homepage-connect-functions.php 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261
  1. <?php
  2. /** @noinspection PhpUndefinedFieldInspection */
  3. function homepageConnect($array)
  4. {
  5. switch ($array['data']['action']) {
  6. case 'getPlexStreams':
  7. return (qualifyRequest($GLOBALS['homepagePlexStreamsAuth'])) ? plexConnect('streams') : false;
  8. break;
  9. case 'getPlexRecent':
  10. return (qualifyRequest($GLOBALS['homepagePlexRecentAuth'])) ? plexConnect('recent') : false;
  11. break;
  12. case 'getPlexMetadata':
  13. return (qualifyRequest($GLOBALS['homepagePlexAuth'])) ? plexConnect('metadata', $array['data']['key']) : false;
  14. break;
  15. case 'getPlexSearch':
  16. return (qualifyRequest($GLOBALS['mediaSearchAuth'])) ? plexConnect('search', $array['data']['query']) : false;
  17. break;
  18. case 'getPlexPlaylists':
  19. return (qualifyRequest($GLOBALS['homepagePlexPlaylistAuth'])) ? getPlexPlaylists() : false;
  20. break;
  21. case 'getEmbyStreams':
  22. return (qualifyRequest($GLOBALS['homepageEmbyStreamsAuth']) && $GLOBALS['homepageEmbyEnabled']) ? embyConnect('streams') : false;
  23. break;
  24. case 'getEmbyRecent':
  25. return (qualifyRequest($GLOBALS['homepageEmbyRecentAuth']) && $GLOBALS['homepageEmbyEnabled']) ? embyConnect('recent') : false;
  26. break;
  27. case 'getEmbyMetadata':
  28. return (qualifyRequest($GLOBALS['homepageEmbyAuth']) && $GLOBALS['homepageEmbyEnabled']) ? embyConnect('metadata', $array['data']['key'], true) : false;
  29. break;
  30. case 'getJdownloader':
  31. return jdownloaderConnect();
  32. break;
  33. case 'getSabnzbd':
  34. return sabnzbdConnect();
  35. break;
  36. case 'getNzbget':
  37. return nzbgetConnect();
  38. break;
  39. case 'getTransmission':
  40. return transmissionConnect();
  41. break;
  42. case 'getqBittorrent':
  43. return qBittorrentConnect();
  44. break;
  45. case 'getrTorrent':
  46. return rTorrentConnect();
  47. break;
  48. case 'getDeluge':
  49. return delugeConnect();
  50. break;
  51. case 'getCalendar':
  52. return getCalendar();
  53. break;
  54. case 'getRequests':
  55. return getOmbiRequests('both', $GLOBALS['ombiLimit']);
  56. break;
  57. case 'getHealthChecks':
  58. return (qualifyRequest($GLOBALS['homepageHealthChecksAuth'])) ? getHealthChecks($array['data']['tags']) : false;
  59. break;
  60. case 'getUnifi':
  61. return unifiConnect();
  62. break;
  63. case 'getTautulli':
  64. return getTautulli();
  65. case 'getPihole':
  66. return getPihole();
  67. break;
  68. case 'getMonitorr':
  69. return getMonitorr();
  70. break;
  71. case 'getWeatherAndAir':
  72. return getWeatherAndAir();
  73. break;
  74. case 'getSpeedtest':
  75. return getSpeedtest();
  76. break;
  77. case 'getNetdata':
  78. return getNetdata();
  79. break;
  80. default:
  81. # code...
  82. break;
  83. }
  84. return false;
  85. }
  86. function healthChecksTags($tags)
  87. {
  88. $return = '?tag=';
  89. if (!$tags) {
  90. return '';
  91. } elseif ($tags == '*') {
  92. return '';
  93. } else {
  94. if (strpos($tags, ',') !== false) {
  95. $list = explode(',', $tags);
  96. return $return . implode("&tag=", $list);
  97. } else {
  98. return $return . $tags;
  99. }
  100. }
  101. }
  102. function getWeatherAndAir()
  103. {
  104. if ($GLOBALS['homepageWeatherAndAirEnabled'] && !empty($GLOBALS['homepageWeatherAndAirLatitude']) && !empty($GLOBALS['homepageWeatherAndAirLongitude']) && qualifyRequest($GLOBALS['homepageWeatherAndAirAuth'])) {
  105. $api['content'] = array(
  106. 'weather' => false,
  107. 'air' => false,
  108. 'pollen' => false
  109. );
  110. $apiURL = qualifyURL('https://api.breezometer.com/');
  111. $info = '&lat=' . $GLOBALS['homepageWeatherAndAirLatitude'] . '&lon=' . $GLOBALS['homepageWeatherAndAirLongitude'] . '&units=' . $GLOBALS['homepageWeatherAndAirUnits'] . '&key=b7401295888443538a7ebe04719c8394';
  112. try {
  113. $headers = array();
  114. $options = array();
  115. if ($GLOBALS['homepageWeatherAndAirWeatherEnabled']) {
  116. $endpoint = '/weather/v1/forecast/hourly?hours=120&metadata=true';
  117. $response = Requests::get($apiURL . $endpoint . $info, $headers, $options);
  118. if ($response->success) {
  119. $apiData = json_decode($response->body, true);
  120. $api['content']['weather'] = ($apiData['error'] === null) ? $apiData : false;
  121. unset($apiData);
  122. }
  123. }
  124. if ($GLOBALS['homepageWeatherAndAirAirQualityEnabled']) {
  125. $endpoint = '/air-quality/v2/current-conditions?features=breezometer_aqi,local_aqi,health_recommendations,sources_and_effects,dominant_pollutant_concentrations,pollutants_concentrations,pollutants_aqi_information&metadata=true';
  126. $response = Requests::get($apiURL . $endpoint . $info, $headers, $options);
  127. if ($response->success) {
  128. $apiData = json_decode($response->body, true);
  129. $api['content']['air'] = ($apiData['error'] === null) ? $apiData : false;
  130. unset($apiData);
  131. }
  132. }
  133. if ($GLOBALS['homepageWeatherAndAirPollenEnabled']) {
  134. $endpoint = '/pollen/v2/forecast/daily/?features=plants_information,types_information&days=1&metadata=true';
  135. $response = Requests::get($apiURL . $endpoint . $info, $headers, $options);
  136. if ($response->success) {
  137. $apiData = json_decode($response->body, true);
  138. $api['content']['pollen'] = ($apiData['error'] === null) ? $apiData : false;
  139. unset($apiData);
  140. }
  141. }
  142. } catch (Requests_Exception $e) {
  143. writeLog('error', 'Weather And Air Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  144. };
  145. $api['content'] = isset($api['content']) ? $api['content'] : false;
  146. return $api;
  147. }
  148. return false;
  149. }
  150. function getHealthChecks($tags = null)
  151. {
  152. if ($GLOBALS['homepageHealthChecksEnabled'] && !empty($GLOBALS['healthChecksToken']) && !empty($GLOBALS['healthChecksURL']) && qualifyRequest($GLOBALS['homepageHealthChecksAuth'])) {
  153. $api['content']['checks'] = array();
  154. $tags = ($tags) ? healthChecksTags($tags) : '';
  155. $healthChecks = explode(',', $GLOBALS['healthChecksToken']);
  156. foreach ($healthChecks as $token) {
  157. $url = qualifyURL($GLOBALS['healthChecksURL']) . '/' . $tags;
  158. try {
  159. $headers = array('X-Api-Key' => $token);
  160. $options = (localURL($url)) ? array('verify' => false) : array();
  161. $response = Requests::get($url, $headers, $options);
  162. if ($response->success) {
  163. $healthResults = json_decode($response->body, true);
  164. $api['content']['checks'] = array_merge($api['content']['checks'], $healthResults['checks']);
  165. }
  166. } catch (Requests_Exception $e) {
  167. writeLog('error', 'HealthChecks Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  168. };
  169. }
  170. usort($api['content']['checks'], function ($a, $b) {
  171. return $a['status'] <=> $b['status'];
  172. });
  173. $api['content']['checks'] = isset($api['content']['checks']) ? $api['content']['checks'] : false;
  174. return $api;
  175. }
  176. return false;
  177. }
  178. function getPihole()
  179. {
  180. if ($GLOBALS['homepagePiholeEnabled'] && !empty($GLOBALS['piholeURL']) && qualifyRequest($GLOBALS['homepagePiholeAuth'])) {
  181. $api = array();
  182. $urls = explode(',', $GLOBALS['piholeURL']);
  183. foreach ($urls as $url) {
  184. $url = $url . '/api.php?';
  185. try {
  186. $response = Requests::get($url, [], []);
  187. if ($response->success) {
  188. $piholeResults = json_decode($response->body, true);
  189. $ip = qualifyURL($url, true)['host'];
  190. $api['data'][$ip] = $piholeResults;
  191. }
  192. } catch (Requests_Exception $e) {
  193. writeLog('error', 'Pi-hole Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  194. };
  195. }
  196. $api['options']['combine'] = $GLOBALS['homepagePiholeCombine'];
  197. $api['options']['title'] = $GLOBALS['piholeHeaderToggle'];
  198. $api = isset($api) ? $api : false;
  199. return $api;
  200. }
  201. return false;
  202. }
  203. function streamType($value)
  204. {
  205. if ($value == "transcode" || $value == "Transcode") {
  206. return "Transcode";
  207. } elseif ($value == "copy" || $value == "DirectStream") {
  208. return "Direct Stream";
  209. } elseif ($value == "directplay" || $value == "DirectPlay") {
  210. return "Direct Play";
  211. } else {
  212. return "Direct Play";
  213. }
  214. }
  215. function resolveEmbyItem($itemDetails)
  216. {
  217. /*
  218. // Grab Each item info from Emby (extra call)
  219. $id = isset($itemDetails['NowPlayingItem']['Id']) ? $itemDetails['NowPlayingItem']['Id'] : $itemDetails['Id'];
  220. $url = qualifyURL($GLOBALS['embyURL']);
  221. $url = $url . '/Items?Ids=' . $id . '&api_key=' . $GLOBALS['embyToken'] . '&Fields=Overview,People,Genres,CriticRating,Studios,Taglines';
  222. try {
  223. $options = (localURL($url)) ? array('verify' => false) : array();
  224. $response = Requests::get($url, array(), $options);
  225. if ($response->success) {
  226. $item = json_decode($response->body, true)['Items'][0];
  227. }
  228. } catch (Requests_Exception $e) {
  229. return false;
  230. };
  231. */
  232. $item = isset($itemDetails['NowPlayingItem']['Id']) ? $itemDetails['NowPlayingItem'] : $itemDetails;
  233. // Static Height & Width
  234. $height = getCacheImageSize('h');
  235. $width = getCacheImageSize('w');
  236. $nowPlayingHeight = getCacheImageSize('nph');
  237. $nowPlayingWidth = getCacheImageSize('npw');
  238. $actorHeight = 450;
  239. $actorWidth = 300;
  240. // Cache Directories
  241. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  242. $cacheDirectoryWeb = 'plugins/images/cache/';
  243. // Types
  244. $embyItem['array-item'] = $item;
  245. $embyItem['array-itemdetails'] = $itemDetails;
  246. switch (@$item['Type']) {
  247. case 'Series':
  248. $embyItem['type'] = 'tv';
  249. $embyItem['title'] = $item['Name'];
  250. $embyItem['secondaryTitle'] = '';
  251. $embyItem['summary'] = '';
  252. $embyItem['ratingKey'] = $item['Id'];
  253. $embyItem['thumb'] = $item['Id'];
  254. $embyItem['key'] = $item['Id'] . "-list";
  255. $embyItem['nowPlayingThumb'] = $item['Id'];
  256. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  257. $embyItem['metadataKey'] = $item['Id'];
  258. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['BackdropImageTags'][0]) ? 'Backdrop' : '');
  259. break;
  260. case 'Episode':
  261. $embyItem['type'] = 'tv';
  262. $embyItem['title'] = $item['SeriesName'];
  263. $embyItem['secondaryTitle'] = '';
  264. $embyItem['summary'] = '';
  265. $embyItem['ratingKey'] = $item['Id'];
  266. $embyItem['thumb'] = (isset($item['SeriesId']) ? $item['SeriesId'] : $item['Id']);
  267. $embyItem['key'] = (isset($item['SeriesId']) ? $item['SeriesId'] : $item['Id']) . "-list";
  268. $embyItem['nowPlayingThumb'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'] : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'] : false);
  269. $embyItem['nowPlayingKey'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'] . '-np' : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'] . '-np' : false);
  270. $embyItem['metadataKey'] = $item['Id'];
  271. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['ParentBackdropImageTags'][0]) ? 'Backdrop' : '');
  272. $embyItem['nowPlayingTitle'] = @$item['SeriesName'] . ' - ' . @$item['Name'];
  273. $embyItem['nowPlayingBottom'] = 'S' . @$item['ParentIndexNumber'] . ' · E' . @$item['IndexNumber'];
  274. break;
  275. case 'MusicAlbum':
  276. case 'Audio':
  277. $embyItem['type'] = 'music';
  278. $embyItem['title'] = $item['Name'];
  279. $embyItem['secondaryTitle'] = '';
  280. $embyItem['summary'] = '';
  281. $embyItem['ratingKey'] = $item['Id'];
  282. $embyItem['thumb'] = $item['Id'];
  283. $embyItem['key'] = $item['Id'] . "-list";
  284. $embyItem['nowPlayingThumb'] = (isset($item['AlbumId']) ? $item['AlbumId'] : @$item['ParentBackdropItemId']);
  285. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  286. $embyItem['metadataKey'] = isset($item['AlbumId']) ? $item['AlbumId'] : $item['Id'];
  287. $embyItem['nowPlayingImageType'] = (isset($item['ParentBackdropItemId']) ? "Primary" : "Backdrop");
  288. $embyItem['nowPlayingTitle'] = @$item['AlbumArtist'] . ' - ' . @$item['Name'];
  289. $embyItem['nowPlayingBottom'] = @$item['Album'];
  290. break;
  291. case 'Movie':
  292. $embyItem['type'] = 'movie';
  293. $embyItem['title'] = $item['Name'];
  294. $embyItem['secondaryTitle'] = '';
  295. $embyItem['summary'] = '';
  296. $embyItem['ratingKey'] = $item['Id'];
  297. $embyItem['thumb'] = $item['Id'];
  298. $embyItem['key'] = $item['Id'] . "-list";
  299. $embyItem['nowPlayingThumb'] = $item['Id'];
  300. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  301. $embyItem['metadataKey'] = $item['Id'];
  302. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
  303. $embyItem['nowPlayingTitle'] = @$item['Name'];
  304. $embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
  305. break;
  306. case 'Video':
  307. $embyItem['type'] = 'video';
  308. $embyItem['title'] = $item['Name'];
  309. $embyItem['secondaryTitle'] = '';
  310. $embyItem['summary'] = '';
  311. $embyItem['ratingKey'] = $item['Id'];
  312. $embyItem['thumb'] = $item['Id'];
  313. $embyItem['key'] = $item['Id'] . "-list";
  314. $embyItem['nowPlayingThumb'] = $item['Id'];
  315. $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
  316. $embyItem['metadataKey'] = $item['Id'];
  317. $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
  318. $embyItem['nowPlayingTitle'] = @$item['Name'];
  319. $embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
  320. break;
  321. default:
  322. return false;
  323. }
  324. $embyItem['uid'] = $item['Id'];
  325. $embyItem['imageType'] = (isset($item['ImageTags']['Primary']) ? "Primary" : false);
  326. $embyItem['elapsed'] = isset($itemDetails['PlayState']['PositionTicks']) && $itemDetails['PlayState']['PositionTicks'] !== '0' ? (int)$itemDetails['PlayState']['PositionTicks'] : null;
  327. $embyItem['duration'] = isset($itemDetails['NowPlayingItem']['RunTimeTicks']) ? (int)$itemDetails['NowPlayingItem']['RunTimeTicks'] : (int)(isset($item['RunTimeTicks']) ? $item['RunTimeTicks'] : '');
  328. $embyItem['watched'] = ($embyItem['elapsed'] && $embyItem['duration'] ? floor(($embyItem['elapsed'] / $embyItem['duration']) * 100) : 0);
  329. $embyItem['transcoded'] = isset($itemDetails['TranscodingInfo']['CompletionPercentage']) ? floor((int)$itemDetails['TranscodingInfo']['CompletionPercentage']) : 100;
  330. $embyItem['stream'] = @$itemDetails['PlayState']['PlayMethod'];
  331. $embyItem['id'] = $item['ServerId'];
  332. $embyItem['session'] = @$itemDetails['DeviceId'];
  333. $embyItem['bandwidth'] = isset($itemDetails['TranscodingInfo']['Bitrate']) ? $itemDetails['TranscodingInfo']['Bitrate'] / 1000 : '';
  334. $embyItem['bandwidthType'] = 'wan';
  335. $embyItem['sessionType'] = (@$itemDetails['PlayState']['PlayMethod'] == 'Transcode') ? 'Transcoding' : 'Direct Playing';
  336. $embyItem['state'] = ((@(string)$itemDetails['PlayState']['IsPaused'] == '1') ? "pause" : "play");
  337. $embyItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? @(string)$itemDetails['UserName'] : "";
  338. $embyItem['userThumb'] = '';
  339. $embyItem['userAddress'] = (isset($itemDetails['RemoteEndPoint']) ? $itemDetails['RemoteEndPoint'] : "x.x.x.x");
  340. $embyURL = ($GLOBALS['homepageJellyfinInstead']) ? $GLOBALS['embyURL'] . '/web/index.html#!/itemdetails.html?id=' : 'https://app.emby.media/#!/item/item.html?id=';
  341. $embyItem['address'] = $GLOBALS['embyTabURL'] ? rtrim($GLOBALS['embyTabURL'], '/') . "/web/#!/item/item.html?id=" . $embyItem['uid'] : $embyURL . $embyItem['uid'] . "&serverId=" . $embyItem['id'];
  342. $embyItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=emby&type=' . $embyItem['nowPlayingImageType'] . '&img=' . $embyItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $embyItem['nowPlayingKey'] . '$' . randString();
  343. $embyItem['originalImage'] = 'api/?v1/image&source=emby&type=' . $embyItem['imageType'] . '&img=' . $embyItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $embyItem['key'] . '$' . randString();
  344. $embyItem['openTab'] = $GLOBALS['embyTabURL'] && $GLOBALS['embyTabName'] ? true : false;
  345. $embyItem['tabName'] = $GLOBALS['embyTabName'] ? $GLOBALS['embyTabName'] : '';
  346. // Stream info
  347. $embyItem['userStream'] = array(
  348. 'platform' => @(string)$itemDetails['Client'],
  349. 'product' => @(string)$itemDetails['Client'],
  350. 'device' => @(string)$itemDetails['DeviceName'],
  351. 'stream' => @$itemDetails['PlayState']['PlayMethod'],
  352. 'videoResolution' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]['Width']) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Width'] : '',
  353. 'throttled' => false,
  354. 'sourceVideoCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : '',
  355. 'videoCodec' => @$itemDetails['TranscodingInfo']['VideoCodec'],
  356. 'audioCodec' => @$itemDetails['TranscodingInfo']['AudioCodec'],
  357. 'sourceAudioCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][1]) ? $itemDetails['NowPlayingItem']['MediaStreams'][1]['Codec'] : (isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : ''),
  358. 'videoDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
  359. 'audioDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
  360. 'container' => isset($itemDetails['NowPlayingItem']['Container']) ? $itemDetails['NowPlayingItem']['Container'] : '',
  361. 'audioChannels' => @$itemDetails['TranscodingInfo']['AudioChannels']
  362. );
  363. // Genre catch all
  364. if (isset($item['Genres'])) {
  365. $genres = array();
  366. foreach ($item['Genres'] as $genre) {
  367. $genres[] = $genre;
  368. }
  369. }
  370. // Actor catch all
  371. if (isset($item['People'])) {
  372. $actors = array();
  373. foreach ($item['People'] as $key => $value) {
  374. if (@$value['PrimaryImageTag'] && @$value['Role']) {
  375. if (file_exists($cacheDirectory . (string)$value['Id'] . '-cast.jpg')) {
  376. $actorImage = $cacheDirectoryWeb . (string)$value['Id'] . '-cast.jpg';
  377. }
  378. if (file_exists($cacheDirectory . (string)$value['Id'] . '-cast.jpg') && (time() - 604800) > filemtime($cacheDirectory . (string)$value['Id'] . '-cast.jpg') || !file_exists($cacheDirectory . (string)$value['Id'] . '-cast.jpg')) {
  379. $actorImage = 'api/?v1/image&source=emby&type=Primary&img=' . (string)$value['Id'] . '&height=' . $actorHeight . '&width=' . $actorWidth . '&key=' . (string)$value['Id'] . '-cast';
  380. }
  381. $actors[] = array(
  382. 'name' => (string)$value['Name'],
  383. 'role' => (string)$value['Role'],
  384. 'thumb' => $actorImage
  385. );
  386. }
  387. }
  388. }
  389. // Metadata information
  390. $embyItem['metadata'] = array(
  391. 'guid' => $item['Id'],
  392. 'summary' => @(string)$item['Overview'],
  393. 'rating' => @(string)$item['CommunityRating'],
  394. 'duration' => @(string)$item['RunTimeTicks'],
  395. 'originallyAvailableAt' => @(string)$item['PremiereDate'],
  396. 'year' => (string)isset($item['ProductionYear']) ? $item['ProductionYear'] : '',
  397. //'studio' => (string)$item['studio'],
  398. 'tagline' => @(string)$item['Taglines'][0],
  399. 'genres' => (isset($item['Genres'])) ? $genres : '',
  400. 'actors' => (isset($item['People'])) ? $actors : ''
  401. );
  402. if (file_exists($cacheDirectory . $embyItem['nowPlayingKey'] . '.jpg')) {
  403. $embyItem['nowPlayingImageURL'] = $cacheDirectoryWeb . $embyItem['nowPlayingKey'] . '.jpg';
  404. }
  405. if (file_exists($cacheDirectory . $embyItem['key'] . '.jpg')) {
  406. $embyItem['imageURL'] = $cacheDirectoryWeb . $embyItem['key'] . '.jpg';
  407. }
  408. if (file_exists($cacheDirectory . $embyItem['nowPlayingKey'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $embyItem['nowPlayingKey'] . '.jpg') || !file_exists($cacheDirectory . $embyItem['nowPlayingKey'] . '.jpg')) {
  409. $embyItem['nowPlayingImageURL'] = 'api/?v1/image&source=emby&type=' . $embyItem['nowPlayingImageType'] . '&img=' . $embyItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $embyItem['nowPlayingKey'] . '';
  410. }
  411. if (file_exists($cacheDirectory . $embyItem['key'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $embyItem['key'] . '.jpg') || !file_exists($cacheDirectory . $embyItem['key'] . '.jpg')) {
  412. $embyItem['imageURL'] = 'api/?v1/image&source=emby&type=' . $embyItem['imageType'] . '&img=' . $embyItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $embyItem['key'] . '';
  413. }
  414. if (!$embyItem['nowPlayingThumb']) {
  415. $embyItem['nowPlayingOriginalImage'] = $embyItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png";
  416. $embyItem['nowPlayingKey'] = "no-np";
  417. }
  418. if (!$embyItem['thumb']) {
  419. $embyItem['originalImage'] = $embyItem['imageURL'] = "plugins/images/cache/no-list.png";
  420. $embyItem['key'] = "no-list";
  421. }
  422. if (isset($useImage)) {
  423. $embyItem['useImage'] = $useImage;
  424. }
  425. return $embyItem;
  426. }
  427. function getCacheImageSize($type)
  428. {
  429. switch ($type) {
  430. case 'height':
  431. case 'h':
  432. return 300 * $GLOBALS['cacheImageSize'];
  433. break;
  434. case 'width':
  435. case 'w':
  436. return 200 * $GLOBALS['cacheImageSize'];
  437. break;
  438. case 'nowPlayingHeight':
  439. case 'nph':
  440. return 675 * $GLOBALS['cacheImageSize'];
  441. break;
  442. case 'nowPlayingWidth':
  443. case 'npw':
  444. return 1200 * $GLOBALS['cacheImageSize'];
  445. break;
  446. }
  447. }
  448. function resolvePlexItem($item)
  449. {
  450. // Static Height & Width
  451. $height = getCacheImageSize('h');
  452. $width = getCacheImageSize('w');
  453. $nowPlayingHeight = getCacheImageSize('nph');
  454. $nowPlayingWidth = getCacheImageSize('npw');
  455. // Cache Directories
  456. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  457. $cacheDirectoryWeb = 'plugins/images/cache/';
  458. // Types
  459. switch ($item['type']) {
  460. case 'show':
  461. $plexItem['type'] = 'tv';
  462. $plexItem['title'] = (string)$item['title'];
  463. $plexItem['secondaryTitle'] = (string)$item['year'];
  464. $plexItem['summary'] = (string)$item['summary'];
  465. $plexItem['ratingKey'] = (string)$item['ratingKey'];
  466. $plexItem['thumb'] = (string)$item['thumb'];
  467. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  468. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  469. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  470. $plexItem['nowPlayingTitle'] = (string)$item['title'];
  471. $plexItem['nowPlayingBottom'] = (string)$item['year'];
  472. $plexItem['metadataKey'] = (string)$item['ratingKey'];
  473. break;
  474. case 'season':
  475. $plexItem['type'] = 'tv';
  476. $plexItem['title'] = (string)$item['parentTitle'];
  477. $plexItem['secondaryTitle'] = (string)$item['title'];
  478. $plexItem['summary'] = (string)$item['parentSummary'];
  479. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  480. $plexItem['thumb'] = (string)$item['thumb'];
  481. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  482. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  483. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  484. $plexItem['metadataKey'] = (string)$item['parentRatingKey'];
  485. break;
  486. case 'episode':
  487. $plexItem['type'] = 'tv';
  488. $plexItem['title'] = (string)$item['grandparentTitle'];
  489. $plexItem['secondaryTitle'] = (string)$item['parentTitle'];
  490. $plexItem['summary'] = (string)$item['title'];
  491. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  492. $plexItem['thumb'] = ($item['parentThumb'] ? (string)$item['parentThumb'] : (string)$item['grandparentThumb']);
  493. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  494. $plexItem['nowPlayingThumb'] = (string)$item['grandparentArt'];
  495. $plexItem['nowPlayingKey'] = (string)$item['grandparentRatingKey'] . "-np";
  496. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'] . ' - ' . (string)$item['title'];
  497. $plexItem['nowPlayingBottom'] = 'S' . (string)$item['parentIndex'] . ' · E' . (string)$item['index'];
  498. $plexItem['metadataKey'] = (string)$item['grandparentRatingKey'];
  499. break;
  500. case 'clip':
  501. $useImage = (isset($item['live']) ? "plugins/images/cache/livetv.png" : null);
  502. $plexItem['type'] = 'clip';
  503. $plexItem['title'] = (isset($item['live']) ? 'Live TV' : (string)$item['title']);
  504. $plexItem['secondaryTitle'] = '';
  505. $plexItem['summary'] = (string)$item['summary'];
  506. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  507. $plexItem['thumb'] = (string)$item['thumb'];
  508. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  509. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  510. $plexItem['nowPlayingKey'] = isset($item['ratingKey']) ? (string)$item['ratingKey'] . "-np" : (isset($item['live']) ? "livetv.png" : ":)");
  511. $plexItem['nowPlayingTitle'] = $plexItem['title'];
  512. $plexItem['nowPlayingBottom'] = isset($item['extraType']) ? "Trailer" : (isset($item['live']) ? "Live TV" : ":)");
  513. break;
  514. case 'album':
  515. case 'track':
  516. $plexItem['type'] = 'music';
  517. $plexItem['title'] = (string)$item['parentTitle'];
  518. $plexItem['secondaryTitle'] = (string)$item['title'];
  519. $plexItem['summary'] = (string)$item['title'];
  520. $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
  521. $plexItem['thumb'] = (string)$item['thumb'];
  522. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  523. $plexItem['nowPlayingThumb'] = ($item['parentThumb']) ? (string)$item['parentThumb'] : (string)$item['art'];
  524. $plexItem['nowPlayingKey'] = (string)$item['parentRatingKey'] . "-np";
  525. $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'] . ' - ' . (string)$item['title'];
  526. $plexItem['nowPlayingBottom'] = (string)$item['parentTitle'];
  527. $plexItem['metadataKey'] = isset($item['grandparentRatingKey']) ? (string)$item['grandparentRatingKey'] : (string)$item['parentRatingKey'];
  528. break;
  529. default:
  530. $plexItem['type'] = 'movie';
  531. $plexItem['title'] = (string)$item['title'];
  532. $plexItem['secondaryTitle'] = (string)$item['year'];
  533. $plexItem['summary'] = (string)$item['summary'];
  534. $plexItem['ratingKey'] = (string)$item['ratingKey'];
  535. $plexItem['thumb'] = (string)$item['thumb'];
  536. $plexItem['key'] = (string)$item['ratingKey'] . "-list";
  537. $plexItem['nowPlayingThumb'] = (string)$item['art'];
  538. $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
  539. $plexItem['nowPlayingTitle'] = (string)$item['title'];
  540. $plexItem['nowPlayingBottom'] = (string)$item['year'];
  541. $plexItem['metadataKey'] = (string)$item['ratingKey'];
  542. }
  543. $plexItem['originalType'] = $item['type'];
  544. $plexItem['uid'] = (string)$item['ratingKey'];
  545. $plexItem['elapsed'] = isset($item['viewOffset']) && $item['viewOffset'] !== '0' ? (int)$item['viewOffset'] : null;
  546. $plexItem['duration'] = isset($item['duration']) ? (int)$item['duration'] : (int)$item->Media['duration'];
  547. $plexItem['addedAt'] = isset($item['addedAt']) ? (int)$item['addedAt'] : null;
  548. $plexItem['watched'] = ($plexItem['elapsed'] && $plexItem['duration'] ? floor(($plexItem['elapsed'] / $plexItem['duration']) * 100) : 0);
  549. $plexItem['transcoded'] = isset($item->TranscodeSession['progress']) ? floor((int)$item->TranscodeSession['progress'] - $plexItem['watched']) : '';
  550. $plexItem['stream'] = isset($item->Media->Part->Stream['decision']) ? (string)$item->Media->Part->Stream['decision'] : '';
  551. $plexItem['id'] = str_replace('"', '', (string)$item->Player['machineIdentifier']);
  552. $plexItem['session'] = (string)$item->Session['id'];
  553. $plexItem['bandwidth'] = (string)$item->Session['bandwidth'];
  554. $plexItem['bandwidthType'] = (string)$item->Session['location'];
  555. $plexItem['sessionType'] = isset($item->TranscodeSession['progress']) ? 'Transcoding' : 'Direct Playing';
  556. $plexItem['state'] = (((string)$item->Player['state'] == "paused") ? "pause" : "play");
  557. $plexItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->User['title'] : "";
  558. $plexItem['userThumb'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->User['thumb'] : "";
  559. $plexItem['userAddress'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->Player['address'] : "x.x.x.x";
  560. $plexItem['address'] = $GLOBALS['plexTabURL'] ? $GLOBALS['plexTabURL'] . "/web/index.html#!/server/" . $GLOBALS['plexID'] . "/details?key=/library/metadata/" . $item['ratingKey'] : "https://app.plex.tv/web/app#!/server/" . $GLOBALS['plexID'] . "/details?key=/library/metadata/" . $item['ratingKey'];
  561. $plexItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=plex&img=' . $plexItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $plexItem['nowPlayingKey'] . '$' . randString();
  562. $plexItem['originalImage'] = 'api/?v1/image&source=plex&img=' . $plexItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $plexItem['key'] . '$' . randString();
  563. $plexItem['openTab'] = $GLOBALS['plexTabURL'] && $GLOBALS['plexTabName'] ? true : false;
  564. $plexItem['tabName'] = $GLOBALS['plexTabName'] ? $GLOBALS['plexTabName'] : '';
  565. // Stream info
  566. $plexItem['userStream'] = array(
  567. 'platform' => (string)$item->Player['platform'],
  568. 'product' => (string)$item->Player['product'],
  569. 'device' => (string)$item->Player['device'],
  570. 'stream' => isset($item->Media) ? (string)$item->Media->Part['decision'] . ($item->TranscodeSession['throttled'] == '1' ? ' (Throttled)' : '') : '',
  571. 'videoResolution' => (string)$item->Media['videoResolution'],
  572. 'throttled' => ($item->TranscodeSession['throttled'] == 1) ? true : false,
  573. 'sourceVideoCodec' => (string)$item->TranscodeSession['sourceVideoCodec'],
  574. 'videoCodec' => (string)$item->TranscodeSession['videoCodec'],
  575. 'audioCodec' => (string)$item->TranscodeSession['audioCodec'],
  576. 'sourceAudioCodec' => (string)$item->TranscodeSession['sourceAudioCodec'],
  577. 'videoDecision' => streamType((string)$item->TranscodeSession['videoDecision']),
  578. 'audioDecision' => streamType((string)$item->TranscodeSession['audioDecision']),
  579. 'container' => (string)$item->TranscodeSession['container'],
  580. 'audioChannels' => (string)$item->TranscodeSession['audioChannels']
  581. );
  582. // Genre catch all
  583. if ($item->Genre) {
  584. $genres = array();
  585. foreach ($item->Genre as $key => $value) {
  586. $genres[] = (string)$value['tag'];
  587. }
  588. }
  589. // Actor catch all
  590. if ($item->Role) {
  591. $actors = array();
  592. foreach ($item->Role as $key => $value) {
  593. if ($value['thumb']) {
  594. $actors[] = array(
  595. 'name' => (string)$value['tag'],
  596. 'role' => (string)$value['role'],
  597. 'thumb' => (string)$value['thumb']
  598. );
  599. }
  600. }
  601. }
  602. // Metadata information
  603. $plexItem['metadata'] = array(
  604. 'guid' => (string)$item['guid'],
  605. 'summary' => (string)$item['summary'],
  606. 'rating' => (string)$item['rating'],
  607. 'duration' => (string)$item['duration'],
  608. 'originallyAvailableAt' => (string)$item['originallyAvailableAt'],
  609. 'year' => (string)$item['year'],
  610. 'studio' => (string)$item['studio'],
  611. 'tagline' => (string)$item['tagline'],
  612. 'genres' => ($item->Genre) ? $genres : '',
  613. 'actors' => ($item->Role) ? $actors : ''
  614. );
  615. if (file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg')) {
  616. $plexItem['nowPlayingImageURL'] = $cacheDirectoryWeb . $plexItem['nowPlayingKey'] . '.jpg';
  617. }
  618. if (file_exists($cacheDirectory . $plexItem['key'] . '.jpg')) {
  619. $plexItem['imageURL'] = $cacheDirectoryWeb . $plexItem['key'] . '.jpg';
  620. }
  621. if (file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg') || !file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg')) {
  622. $plexItem['nowPlayingImageURL'] = 'api/?v1/image&source=plex&img=' . $plexItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $plexItem['nowPlayingKey'] . '';
  623. }
  624. if (file_exists($cacheDirectory . $plexItem['key'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $plexItem['key'] . '.jpg') || !file_exists($cacheDirectory . $plexItem['key'] . '.jpg')) {
  625. $plexItem['imageURL'] = 'api/?v1/image&source=plex&img=' . $plexItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $plexItem['key'] . '';
  626. }
  627. if (!$plexItem['nowPlayingThumb']) {
  628. $plexItem['nowPlayingOriginalImage'] = $plexItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png";
  629. $plexItem['nowPlayingKey'] = "no-np";
  630. }
  631. if (!$plexItem['thumb'] || $plexItem['addedAt'] >= (time() - 300)) {
  632. $plexItem['originalImage'] = $plexItem['imageURL'] = "plugins/images/cache/no-list.png";
  633. $plexItem['key'] = "no-list";
  634. }
  635. if (isset($useImage)) {
  636. $plexItem['useImage'] = $useImage;
  637. }
  638. return $plexItem;
  639. }
  640. function plexConnect($action, $key = null)
  641. {
  642. if ($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']))) {
  643. $url = qualifyURL($GLOBALS['plexURL']);
  644. $multipleURL = false;
  645. $ignore = array();
  646. $resolve = true;
  647. switch ($action) {
  648. case 'streams':
  649. $url = $url . "/status/sessions?X-Plex-Token=" . $GLOBALS['plexToken'];
  650. break;
  651. case 'libraries':
  652. $url = $url . "/library/sections?X-Plex-Token=" . $GLOBALS['plexToken'];
  653. $resolve = false;
  654. break;
  655. case 'recent':
  656. //$url = $url . "/library/recentlyAdded?X-Plex-Token=" . $GLOBALS['plexToken'] . "&limit=" . $GLOBALS['homepageRecentLimit'];
  657. $urls['movie'] = $url . "/hubs/home/recentlyAdded?X-Plex-Token=" . $GLOBALS['plexToken'] . "&X-Plex-Container-Start=0&X-Plex-Container-Size=" . $GLOBALS['homepageRecentLimit'] . "&type=1";
  658. $urls['tv'] = $url . "/hubs/home/recentlyAdded?X-Plex-Token=" . $GLOBALS['plexToken'] . "&X-Plex-Container-Start=0&X-Plex-Container-Size=" . $GLOBALS['homepageRecentLimit'] . "&type=2";
  659. $urls['music'] = $url . "/hubs/home/recentlyAdded?X-Plex-Token=" . $GLOBALS['plexToken'] . "&X-Plex-Container-Start=0&X-Plex-Container-Size=" . $GLOBALS['homepageRecentLimit'] . "&type=8";
  660. $multipleURL = true;
  661. break;
  662. case 'metadata':
  663. $url = $url . "/library/metadata/" . $key . "?X-Plex-Token=" . $GLOBALS['plexToken'];
  664. break;
  665. case 'playlists':
  666. $url = $url . "/playlists?X-Plex-Token=" . $GLOBALS['plexToken'];
  667. break;
  668. case 'search':
  669. $url = $url . "/search?query=" . rawurlencode($key) . "&X-Plex-Token=" . $GLOBALS['plexToken'];
  670. $ignore = array('artist', 'episode');
  671. break;
  672. default:
  673. # code...
  674. break;
  675. }
  676. try {
  677. if (!$multipleURL) {
  678. $options = (localURL($url)) ? array('verify' => false) : array();
  679. $response = Requests::get($url, array(), $options);
  680. libxml_use_internal_errors(true);
  681. if ($response->success) {
  682. $items = array();
  683. $plex = simplexml_load_string($response->body);
  684. foreach ($plex as $child) {
  685. if (!in_array($child['type'], $ignore) && isset($child['librarySectionID'])) {
  686. $items[] = resolvePlexItem($child);
  687. }
  688. }
  689. $api['content'] = ($resolve) ? $items : $plex;
  690. $api['plexID'] = $GLOBALS['plexID'];
  691. $api['showNames'] = true;
  692. $api['group'] = '1';
  693. return $api;
  694. }
  695. } else {
  696. foreach ($urls as $k => $v) {
  697. $options = (localURL($v)) ? array('verify' => false) : array();
  698. $response = Requests::get($v, array(), $options);
  699. libxml_use_internal_errors(true);
  700. if ($response->success) {
  701. $items = array();
  702. $plex = simplexml_load_string($response->body);
  703. foreach ($plex as $child) {
  704. if (!in_array($child['type'], $ignore) && isset($child['librarySectionID'])) {
  705. $items[] = resolvePlexItem($child);
  706. }
  707. }
  708. if (isset($api)) {
  709. $api['content'] = array_merge($api['content'], ($resolve) ? $items : $plex);
  710. } else {
  711. $api['content'] = ($resolve) ? $items : $plex;
  712. }
  713. }
  714. }
  715. if (isset($api['content'])) {
  716. usort($api['content'], function ($a, $b) {
  717. return $b['addedAt'] <=> $a['addedAt'];
  718. });
  719. }
  720. $api['plexID'] = $GLOBALS['plexID'];
  721. $api['showNames'] = true;
  722. $api['group'] = '1';
  723. return $api;
  724. }
  725. } catch (Requests_Exception $e) {
  726. writeLog('error', 'Plex Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  727. };
  728. }
  729. return false;
  730. }
  731. function getPlexPlaylists()
  732. {
  733. if ($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']) && qualifyRequest($GLOBALS['homepagePlexPlaylistAuth']) && $GLOBALS['homepagePlexPlaylist'])) {
  734. $url = qualifyURL($GLOBALS['plexURL']);
  735. $url = $url . "/playlists?X-Plex-Token=" . $GLOBALS['plexToken'];
  736. try {
  737. $options = (localURL($url)) ? array('verify' => false) : array();
  738. $response = Requests::get($url, array(), $options);
  739. libxml_use_internal_errors(true);
  740. if ($response->success) {
  741. $items = array();
  742. $plex = simplexml_load_string($response->body);
  743. foreach ($plex as $child) {
  744. if ($child['playlistType'] == "video" && strpos(strtolower($child['title']), 'private') === false) {
  745. $playlistTitleClean = preg_replace("/(\W)+/", "", (string)$child['title']);
  746. $playlistURL = qualifyURL($GLOBALS['plexURL']);
  747. $playlistURL = $playlistURL . $child['key'] . "?X-Plex-Token=" . $GLOBALS['plexToken'];
  748. $options = (localURL($url)) ? array('verify' => false) : array();
  749. $playlistResponse = Requests::get($playlistURL, array(), $options);
  750. if ($playlistResponse->success) {
  751. $playlistResponse = simplexml_load_string($playlistResponse->body);
  752. $items[$playlistTitleClean]['title'] = (string)$child['title'];
  753. foreach ($playlistResponse->Video as $playlistItem) {
  754. $items[$playlistTitleClean][] = resolvePlexItem($playlistItem);
  755. }
  756. }
  757. }
  758. }
  759. $api['content'] = $items;
  760. $api['plexID'] = $GLOBALS['plexID'];
  761. $api['showNames'] = true;
  762. $api['group'] = '1';
  763. return $api;
  764. }
  765. } catch (Requests_Exception $e) {
  766. writeLog('error', 'Plex Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  767. };
  768. }
  769. return false;
  770. }
  771. function embyConnect($action, $key = 'Latest', $skip = false)
  772. {
  773. if ($GLOBALS['homepageEmbyEnabled'] && !empty($GLOBALS['embyURL']) && !empty($GLOBALS['embyToken']) && qualifyRequest($GLOBALS['homepageEmbyAuth'])) {
  774. $url = qualifyURL($GLOBALS['embyURL']);
  775. switch ($action) {
  776. case 'streams':
  777. $url = $url . '/Sessions?api_key=' . $GLOBALS['embyToken'] . '&Fields=Overview,People,Genres,CriticRating,Studios,Taglines';
  778. break;
  779. case 'recent':
  780. case 'metadata':
  781. $username = false;
  782. if (isset($GLOBALS['organizrUser']['username'])) {
  783. $username = strtolower($GLOBALS['organizrUser']['username']);
  784. }
  785. // Get A User
  786. $userIds = $url . "/Users?api_key=" . $GLOBALS['embyToken'];
  787. $showPlayed = false;
  788. try {
  789. $options = (localURL($userIds)) ? array('verify' => false) : array();
  790. $response = Requests::get($userIds, array(), $options);
  791. if ($response->success) {
  792. $emby = json_decode($response->body, true);
  793. foreach ($emby as $value) { // Scan for admin user
  794. if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
  795. $userId = $value['Id'];
  796. }
  797. if ($username && strtolower($value['Name']) == $username) {
  798. $userId = $value['Id'];
  799. $showPlayed = false;
  800. break;
  801. }
  802. }
  803. $url = $url . '/Users/' . $userId . '/Items/' . $key . '?EnableImages=true&Limit=' . $GLOBALS['homepageRecentLimit'] . '&api_key=' . $GLOBALS['embyToken'] . ($showPlayed ? '' : '&IsPlayed=false') . '&Fields=Overview,People,Genres,CriticRating,Studios,Taglines';
  804. }
  805. } catch (Requests_Exception $e) {
  806. writeLog('error', 'Emby Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  807. };
  808. break;
  809. default:
  810. # code...
  811. break;
  812. }
  813. try {
  814. $options = (localURL($url)) ? array('verify' => false) : array();
  815. $response = Requests::get($url, array(), $options);
  816. if ($response->success) {
  817. $items = array();
  818. $emby = json_decode($response->body, true);
  819. if ($key !== 'Latest') {
  820. if (isset($emby['NowPlayingItem']) || isset($emby['Name'])) {
  821. $items[] = resolveEmbyItem($emby);
  822. }
  823. } else {
  824. foreach ($emby as $child) {
  825. if (isset($child['NowPlayingItem']) || isset($child['Name'])) {
  826. $items[] = resolveEmbyItem($child);
  827. }
  828. }
  829. }
  830. $api['content'] = array_filter($items);
  831. return $api;
  832. }
  833. } catch (Requests_Exception $e) {
  834. writeLog('error', 'Emby Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  835. };
  836. }
  837. return false;
  838. }
  839. function jdownloaderConnect()
  840. {
  841. if ($GLOBALS['homepageJdownloaderEnabled'] && !empty($GLOBALS['jdownloaderURL']) && qualifyRequest($GLOBALS['homepageJdownloaderAuth'])) {
  842. $url = qualifyURL($GLOBALS['jdownloaderURL']);
  843. try {
  844. $options = (localURL($url)) ? array('verify' => false, 'timeout' => 30) : array('timeout' => 30);
  845. $response = Requests::get($url, array(), $options);
  846. if ($response->success) {
  847. $temp = json_decode($response->body, true);
  848. $packages = $temp['packages'];
  849. if ($packages['downloader']) {
  850. $api['content']['queueItems'] = $packages['downloader'];
  851. } else {
  852. $api['content']['queueItems'] = [];
  853. }
  854. if ($packages['linkgrabber_decrypted']) {
  855. $api['content']['grabberItems'] = $packages['linkgrabber_decrypted'];
  856. } else {
  857. $api['content']['grabberItems'] = [];
  858. }
  859. if ($packages['linkgrabber_failed']) {
  860. $api['content']['encryptedItems'] = $packages['linkgrabber_failed'];
  861. } else {
  862. $api['content']['encryptedItems'] = [];
  863. }
  864. if ($packages['linkgrabber_offline']) {
  865. $api['content']['offlineItems'] = $packages['linkgrabber_offline'];
  866. } else {
  867. $api['content']['offlineItems'] = [];
  868. }
  869. $api['content']['$status'] = array($temp['downloader_state'], $temp['grabber_collecting'], $temp['update_ready']);
  870. }
  871. } catch (Requests_Exception $e) {
  872. writeLog('error', 'JDownloader Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  873. };
  874. $api['content'] = isset($api['content']) ? $api['content'] : false;
  875. return $api;
  876. }
  877. return false;
  878. }
  879. function sabnzbdConnect()
  880. {
  881. if ($GLOBALS['homepageSabnzbdEnabled'] && !empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken']) && qualifyRequest($GLOBALS['homepageSabnzbdAuth'])) {
  882. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  883. $url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  884. try {
  885. $options = (localURL($url)) ? array('verify' => false) : array();
  886. $response = Requests::get($url, array(), $options);
  887. if ($response->success) {
  888. $api['content']['queueItems'] = json_decode($response->body, true);
  889. }
  890. } catch (Requests_Exception $e) {
  891. writeLog('error', 'SabNZBd Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  892. };
  893. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  894. $url = $url . '/api?mode=history&output=json&limit=100&apikey=' . $GLOBALS['sabnzbdToken'];
  895. try {
  896. $options = (localURL($url)) ? array('verify' => false) : array();
  897. $response = Requests::get($url, array(), $options);
  898. if ($response->success) {
  899. $api['content']['historyItems'] = json_decode($response->body, true);
  900. }
  901. } catch (Requests_Exception $e) {
  902. writeLog('error', 'SabNZBd Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  903. };
  904. $api['content'] = isset($api['content']) ? $api['content'] : false;
  905. return $api;
  906. }
  907. return false;
  908. }
  909. function nzbgetConnect()
  910. {
  911. if ($GLOBALS['homepageNzbgetEnabled'] && !empty($GLOBALS['nzbgetURL']) && qualifyRequest($GLOBALS['homepageNzbgetAuth'])) {
  912. $url = qualifyURL($GLOBALS['nzbgetURL']);
  913. $url = $url . '/jsonrpc/listgroups';
  914. try {
  915. $options = (localURL($url)) ? array('verify' => false) : array();
  916. if ($GLOBALS['nzbgetUsername'] !== '' && decrypt($GLOBALS['nzbgetPassword']) !== '') {
  917. $credentials = array('auth' => new Requests_Auth_Basic(array($GLOBALS['nzbgetUsername'], decrypt($GLOBALS['nzbgetPassword']))));
  918. $options = array_merge($options, $credentials);
  919. }
  920. $response = Requests::get($url, array(), $options);
  921. if ($response->success) {
  922. $api['content']['queueItems'] = json_decode($response->body, true);
  923. }
  924. } catch (Requests_Exception $e) {
  925. writeLog('error', 'NZBGet Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  926. };
  927. $url = qualifyURL($GLOBALS['nzbgetURL']);
  928. $url = $url . '/jsonrpc/history';
  929. try {
  930. $options = (localURL($url)) ? array('verify' => false) : array();
  931. if ($GLOBALS['nzbgetUsername'] !== '' && decrypt($GLOBALS['nzbgetPassword']) !== '') {
  932. $credentials = array('auth' => new Requests_Auth_Basic(array($GLOBALS['nzbgetUsername'], decrypt($GLOBALS['nzbgetPassword']))));
  933. $options = array_merge($options, $credentials);
  934. }
  935. $response = Requests::get($url, array(), $options);
  936. if ($response->success) {
  937. $api['content']['historyItems'] = json_decode($response->body, true);
  938. }
  939. } catch (Requests_Exception $e) {
  940. writeLog('error', 'NZBGet Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  941. };
  942. $api['content'] = isset($api['content']) ? $api['content'] : false;
  943. return $api;
  944. }
  945. return false;
  946. }
  947. function transmissionConnect()
  948. {
  949. if ($GLOBALS['homepageTransmissionEnabled'] && !empty($GLOBALS['transmissionURL']) && qualifyRequest($GLOBALS['homepageTransmissionAuth'])) {
  950. $digest = qualifyURL($GLOBALS['transmissionURL'], true);
  951. $passwordInclude = ($GLOBALS['transmissionUsername'] != '' && $GLOBALS['transmissionPassword'] != '') ? $GLOBALS['transmissionUsername'] . ':' . decrypt($GLOBALS['transmissionPassword']) . "@" : '';
  952. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . '/rpc';
  953. try {
  954. $options = (localURL($GLOBALS['transmissionURL'])) ? array('verify' => false) : array();
  955. $response = Requests::get($url, array(), $options);
  956. if ($response->headers['x-transmission-session-id']) {
  957. $headers = array(
  958. 'X-Transmission-Session-Id' => $response->headers['x-transmission-session-id'],
  959. 'Content-Type' => 'application/json'
  960. );
  961. $data = array(
  962. 'method' => 'torrent-get',
  963. 'arguments' => array(
  964. 'fields' => array(
  965. "id", "name", "totalSize", "eta", "isFinished", "isStalled", "percentDone", "rateDownload", "status", "downloadDir", "errorString"
  966. ),
  967. ),
  968. 'tags' => ''
  969. );
  970. $response = Requests::post($url, $headers, json_encode($data), $options);
  971. if ($response->success) {
  972. $torrentList = json_decode($response->body, true)['arguments']['torrents'];
  973. if ($GLOBALS['transmissionHideSeeding'] || $GLOBALS['transmissionHideCompleted']) {
  974. $filter = array();
  975. $torrents['arguments']['torrents'] = array();
  976. if ($GLOBALS['transmissionHideSeeding']) {
  977. array_push($filter, 6, 5);
  978. }
  979. if ($GLOBALS['transmissionHideCompleted']) {
  980. array_push($filter, 0);
  981. }
  982. foreach ($torrentList as $key => $value) {
  983. if (!in_array($value['status'], $filter)) {
  984. $torrents['arguments']['torrents'][] = $value;
  985. }
  986. }
  987. } else {
  988. $torrents = json_decode($response->body, true);
  989. }
  990. $api['content']['queueItems'] = $torrents;
  991. $api['content']['historyItems'] = false;
  992. }
  993. } else {
  994. writeLog('error', 'Transmission Connect Function - Error: Could not get session ID', 'SYSTEM');
  995. }
  996. } catch (Requests_Exception $e) {
  997. writeLog('error', 'Transmission Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  998. };
  999. $api['content'] = isset($api['content']) ? $api['content'] : false;
  1000. return $api;
  1001. }
  1002. return false;
  1003. }
  1004. function rTorrentStatus($completed, $state, $status)
  1005. {
  1006. if ($completed && $state && $status == 'seed') {
  1007. $state = 'Seeding';
  1008. } elseif (!$completed && !$state && $status == 'leech') {
  1009. $state = 'Stopped';
  1010. } elseif (!$completed && $state && $status == 'leech') {
  1011. $state = 'Downloading';
  1012. } elseif ($completed && !$state && $status == 'seed') {
  1013. $state = 'Finished';
  1014. }
  1015. return ($state) ? $state : $status;
  1016. }
  1017. function rTorrentConnect()
  1018. {
  1019. if ($GLOBALS['homepagerTorrentEnabled'] && (!empty($GLOBALS['rTorrentURL']) || !empty($GLOBALS['rTorrentURLOverride'])) && qualifyRequest($GLOBALS['homepagerTorrentAuth'])) {
  1020. try {
  1021. if($GLOBALS['rTorrentLimit'] == '0') { $GLOBALS['rTorrentLimit'] = '1000'; }
  1022. $torrents = array();
  1023. $digest = (empty($GLOBALS['rTorrentURLOverride'])) ? qualifyURL($GLOBALS['rTorrentURL'], true) : qualifyURL(checkOverrideURL($GLOBALS['rTorrentURL'], $GLOBALS['rTorrentURLOverride']), true);
  1024. $passwordInclude = ($GLOBALS['rTorrentUsername'] !== '' && $GLOBALS['rTorrentPassword'] !== '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  1025. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  1026. $extraPath = (empty($GLOBALS['rTorrentURLOverride'])) ? $extraPath : '';
  1027. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  1028. $options = (localURL($url, $GLOBALS['rTorrentDisableCertCheck'])) ? array('verify' => false) : array();
  1029. if ($GLOBALS['rTorrentUsername'] !== '' && decrypt($GLOBALS['rTorrentPassword']) !== '') {
  1030. $credentials = array('auth' => new Requests_Auth_Digest(array($GLOBALS['rTorrentUsername'], decrypt($GLOBALS['rTorrentPassword']))));
  1031. $options = array_merge($options, $credentials);
  1032. }
  1033. $data = xmlrpc_encode_request("d.multicall2", array(
  1034. "",
  1035. "main",
  1036. "d.name=",
  1037. "d.base_path=",
  1038. "d.up.total=",
  1039. "d.size_bytes=",
  1040. "d.down.total=",
  1041. "d.completed_bytes=",
  1042. "d.connection_current=",
  1043. "d.down.rate=",
  1044. "d.up.rate=",
  1045. "d.timestamp.started=",
  1046. "d.state=",
  1047. "d.group.name=",
  1048. "d.hash=",
  1049. "d.complete=",
  1050. "d.ratio=",
  1051. "d.chunk_size=",
  1052. "f.size_bytes=",
  1053. "f.size_chunks=",
  1054. "f.completed_chunks=",
  1055. "d.custom=",
  1056. "d.custom1=",
  1057. "d.custom2=",
  1058. "d.custom3=",
  1059. "d.custom4=",
  1060. "d.custom5=",
  1061. ), array());
  1062. $response = Requests::post($url, array(), $data, $options);
  1063. if ($response->success) {
  1064. $torrentList = xmlrpc_decode(str_replace('i8>', 'string>', $response->body));
  1065. foreach ($torrentList as $key => $value) {
  1066. $tempStatus = rTorrentStatus($value[13], $value[10], $value[6]);
  1067. if ($tempStatus == 'Seeding' && $GLOBALS['rTorrentHideSeeding']) {
  1068. //do nothing
  1069. } elseif ($tempStatus == 'Finished' && $GLOBALS['rTorrentHideCompleted']) {
  1070. //do nothing
  1071. } else {
  1072. $torrents[$key] = array(
  1073. 'name' => $value[0],
  1074. 'base' => $value[1],
  1075. 'upTotal' => $value[2],
  1076. 'size' => $value[3],
  1077. 'downTotal' => $value[4],
  1078. 'downloaded' => $value[5],
  1079. 'connectionState' => $value[6],
  1080. 'leech' => $value[7],
  1081. 'seed' => $value[8],
  1082. 'date' => $value[9],
  1083. 'state' => ($value[10]) ? 'on' : 'off',
  1084. 'group' => $value[11],
  1085. 'hash' => $value[12],
  1086. 'complete' => ($value[13]) ? 'yes' : 'no',
  1087. 'ratio' => $value[14],
  1088. 'label' => $value[20],
  1089. 'status' => $tempStatus,
  1090. 'temp' => $value[16] . ' - ' . $value[17] . ' - ' . $value[18],
  1091. 'custom' => $value[19] . ' - ' . $value[20] . ' - ' . $value[21],
  1092. 'custom2' => $value[22] . ' - ' . $value[23] . ' - ' . $value[24],
  1093. );
  1094. }
  1095. }
  1096. if (count($torrents) !== 0) {
  1097. usort($torrents, function ($a, $b) {
  1098. $direction = substr($GLOBALS['rTorrentSortOrder'], -1);
  1099. $sort = substr($GLOBALS['rTorrentSortOrder'], 0, strlen($GLOBALS['rTorrentSortOrder']) - 1);
  1100. switch ($direction) {
  1101. case 'a':
  1102. return $a[$sort] <=> $b[$sort];
  1103. break;
  1104. case 'd':
  1105. return $b[$sort] <=> $a[$sort];
  1106. break;
  1107. default:
  1108. return $b['date'] <=> $a['date'];
  1109. }
  1110. });
  1111. $torrents = array_slice($torrents, 0, $GLOBALS['rTorrentLimit']);
  1112. }
  1113. $api['content']['queueItems'] = $torrents;
  1114. $api['content']['historyItems'] = false;
  1115. }
  1116. } catch
  1117. (Requests_Exception $e) {
  1118. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1119. };
  1120. $api['content'] = isset($api['content']) ? $api['content'] : false;
  1121. return $api;
  1122. }
  1123. return false;
  1124. }
  1125. function qBittorrentConnect()
  1126. {
  1127. if ($GLOBALS['homepageqBittorrentEnabled'] && !empty($GLOBALS['qBittorrentURL']) && qualifyRequest($GLOBALS['homepageqBittorrentAuth'])) {
  1128. $digest = qualifyURL($GLOBALS['qBittorrentURL'], true);
  1129. $data = array('username' => $GLOBALS['qBittorrentUsername'], 'password' => decrypt($GLOBALS['qBittorrentPassword']));
  1130. $apiVersionLogin = ($GLOBALS['qBittorrentApiVersion'] == '1') ? '/login' : '/api/v2/auth/login';
  1131. $apiVersionQuery = ($GLOBALS['qBittorrentApiVersion'] == '1') ? '/query/torrents?sort=' : '/api/v2/torrents/info?sort=';
  1132. $url = $digest['scheme'] . '://' . $digest['host'] . $digest['port'] . $digest['path'] . $apiVersionLogin;
  1133. try {
  1134. $options = (localURL($GLOBALS['qBittorrentURL'])) ? array('verify' => false) : array();
  1135. $response = Requests::post($url, array(), $data, $options);
  1136. $reflection = new ReflectionClass($response->cookies);
  1137. $cookie = $reflection->getProperty("cookies");
  1138. $cookie->setAccessible(true);
  1139. $cookie = $cookie->getValue($response->cookies);
  1140. if ($cookie) {
  1141. $headers = array(
  1142. 'Cookie' => 'SID=' . $cookie['SID']->value
  1143. );
  1144. $reverse = $GLOBALS['qBittorrentReverseSorting'] ? 'true' : 'false';
  1145. $url = $digest['scheme'] . '://' . $digest['host'] . $digest['port'] . $digest['path'] . $apiVersionQuery . $GLOBALS['qBittorrentSortOrder'] . '&reverse=' . $reverse;
  1146. $response = Requests::get($url, $headers, $options);
  1147. if ($response) {
  1148. $torrentList = json_decode($response->body, true);
  1149. if ($GLOBALS['qBittorrentHideSeeding'] || $GLOBALS['qBittorrentHideCompleted']) {
  1150. $filter = array();
  1151. $torrents['arguments']['torrents'] = array();
  1152. if ($GLOBALS['qBittorrentHideSeeding']) {
  1153. array_push($filter, 'uploading', 'stalledUP', 'queuedUP');
  1154. }
  1155. if ($GLOBALS['qBittorrentHideCompleted']) {
  1156. array_push($filter, 'pausedUP');
  1157. }
  1158. foreach ($torrentList as $key => $value) {
  1159. if (!in_array($value['state'], $filter)) {
  1160. $torrents['arguments']['torrents'][] = $value;
  1161. }
  1162. }
  1163. } else {
  1164. $torrents['arguments']['torrents'] = json_decode($response->body, true);
  1165. }
  1166. $api['content']['queueItems'] = $torrents;
  1167. $api['content']['historyItems'] = false;
  1168. }
  1169. } else {
  1170. writeLog('error', 'qBittorrent Connect Function - Error: Could not get session ID', 'SYSTEM');
  1171. }
  1172. } catch (Requests_Exception $e) {
  1173. writeLog('error', 'qBittorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1174. };
  1175. $api['content'] = isset($api['content']) ? $api['content'] : false;
  1176. return $api;
  1177. }
  1178. return false;
  1179. }
  1180. function delugeStatus($queued, $status, $state)
  1181. {
  1182. if ($queued == '-1' && $state == '100' && ($status == 'Seeding' || $status == 'Queued' || $status == 'Paused')) {
  1183. $state = 'Seeding';
  1184. } elseif ($state !== '100') {
  1185. $state = 'Downloading';
  1186. } else {
  1187. $state = 'Finished';
  1188. }
  1189. return ($state) ? $state : $status;
  1190. }
  1191. function delugeConnect()
  1192. {
  1193. if ($GLOBALS['homepageDelugeEnabled'] && !empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword']) && qualifyRequest($GLOBALS['homepageDelugeAuth'])) {
  1194. try {
  1195. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  1196. $torrents = $deluge->getTorrents(null, 'comment, download_payload_rate, eta, hash, is_finished, is_seed, message, name, paused, progress, queue, state, total_size, upload_payload_rate');
  1197. foreach ($torrents as $key => $value) {
  1198. $tempStatus = delugeStatus($value->queue, $value->state, $value->progress);
  1199. if ($tempStatus == 'Seeding' && $GLOBALS['delugeHideSeeding']) {
  1200. //do nothing
  1201. } elseif ($tempStatus == 'Finished' && $GLOBALS['delugeHideCompleted']) {
  1202. //do nothing
  1203. } else {
  1204. $api['content']['queueItems'][] = $value;
  1205. }
  1206. }
  1207. $api['content']['queueItems'] = (empty($api['content']['queueItems'])) ? [] : $api['content']['queueItems'];
  1208. $api['content']['historyItems'] = false;
  1209. } catch (Excecption $e) {
  1210. writeLog('error', 'Deluge Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1211. }
  1212. }
  1213. $api['content'] = isset($api['content']) ? $api['content'] : false;
  1214. return $api;
  1215. }
  1216. function getCalendar()
  1217. {
  1218. $startDate = date('Y-m-d', strtotime("-" . $GLOBALS['calendarStart'] . " days"));
  1219. $endDate = date('Y-m-d', strtotime("+" . $GLOBALS['calendarEnd'] . " days"));
  1220. $icalCalendarSources = array();
  1221. $calendarItems = array();
  1222. // SONARR CONNECT
  1223. if ($GLOBALS['homepageSonarrEnabled'] && qualifyRequest($GLOBALS['homepageSonarrAuth']) && !empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  1224. $sonarrs = array();
  1225. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  1226. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  1227. if (count($sonarrURLList) == count($sonarrTokenList)) {
  1228. foreach ($sonarrURLList as $key => $value) {
  1229. $sonarrs[$key] = array(
  1230. 'url' => $value,
  1231. 'token' => $sonarrTokenList[$key]
  1232. );
  1233. }
  1234. foreach ($sonarrs as $key => $value) {
  1235. try {
  1236. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  1237. $sonarr = $sonarr->getCalendar($startDate, $endDate, $GLOBALS['sonarrUnmonitored']);
  1238. $result = json_decode($sonarr, true);
  1239. if (is_array($result) || is_object($result)) {
  1240. $sonarrCalendar = (array_key_exists('error', $result)) ? '' : getSonarrCalendar($sonarr, $key);
  1241. } else {
  1242. $sonarrCalendar = '';
  1243. }
  1244. } catch (Exception $e) {
  1245. writeLog('error', 'Sonarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1246. }
  1247. if (!empty($sonarrCalendar)) {
  1248. $calendarItems = array_merge($calendarItems, $sonarrCalendar);
  1249. }
  1250. }
  1251. }
  1252. }
  1253. // LIDARR CONNECT
  1254. if ($GLOBALS['homepageLidarrEnabled'] && qualifyRequest($GLOBALS['homepageLidarrAuth']) && !empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  1255. $lidarrs = array();
  1256. $lidarrURLList = explode(',', $GLOBALS['lidarrURL']);
  1257. $lidarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  1258. if (count($lidarrURLList) == count($lidarrTokenList)) {
  1259. foreach ($lidarrURLList as $key => $value) {
  1260. $lidarrs[$key] = array(
  1261. 'url' => $value,
  1262. 'token' => $lidarrTokenList[$key]
  1263. );
  1264. }
  1265. foreach ($lidarrs as $key => $value) {
  1266. try {
  1267. $lidarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  1268. $lidarr = $lidarr->getCalendar($startDate, $endDate);
  1269. $result = json_decode($lidarr, true);
  1270. if (is_array($result) || is_object($result)) {
  1271. $lidarrCalendar = (array_key_exists('error', $result)) ? '' : getLidarrCalendar($lidarr, $key);
  1272. } else {
  1273. $lidarrCalendar = '';
  1274. }
  1275. } catch (Exception $e) {
  1276. writeLog('error', 'Lidarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1277. }
  1278. if (!empty($lidarrCalendar)) {
  1279. $calendarItems = array_merge($calendarItems, $lidarrCalendar);
  1280. }
  1281. }
  1282. }
  1283. }
  1284. // RADARR CONNECT
  1285. if ($GLOBALS['homepageRadarrEnabled'] && qualifyRequest($GLOBALS['homepageRadarrAuth']) && !empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  1286. $radarrs = array();
  1287. $radarrURLList = explode(',', $GLOBALS['radarrURL']);
  1288. $radarrTokenList = explode(',', $GLOBALS['radarrToken']);
  1289. if (count($radarrURLList) == count($radarrTokenList)) {
  1290. foreach ($radarrURLList as $key => $value) {
  1291. $radarrs[$key] = array(
  1292. 'url' => $value,
  1293. 'token' => $radarrTokenList[$key]
  1294. );
  1295. }
  1296. foreach ($radarrs as $key => $value) {
  1297. try {
  1298. $radarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  1299. $radarr = $radarr->getCalendar($startDate, $endDate);
  1300. $result = json_decode($radarr, true);
  1301. if (is_array($result) || is_object($result)) {
  1302. $radarrCalendar = (array_key_exists('error', $result)) ? '' : getRadarrCalendar($radarr, $key, $value['url']);
  1303. } else {
  1304. $radarrCalendar = '';
  1305. }
  1306. } catch (Exception $e) {
  1307. writeLog('error', 'Radarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1308. }
  1309. if (!empty($radarrCalendar)) {
  1310. $calendarItems = array_merge($calendarItems, $radarrCalendar);
  1311. }
  1312. }
  1313. }
  1314. }
  1315. // SICKRAGE/BEARD/MEDUSA CONNECT
  1316. if ($GLOBALS['homepageSickrageEnabled'] && qualifyRequest($GLOBALS['homepageSickrageAuth']) && !empty($GLOBALS['sickrageURL']) && !empty($GLOBALS['sickrageToken'])) {
  1317. $sicks = array();
  1318. $sickURLList = explode(',', $GLOBALS['sickrageURL']);
  1319. $sickTokenList = explode(',', $GLOBALS['sickrageToken']);
  1320. if (count($sickURLList) == count($sickTokenList)) {
  1321. foreach ($sickURLList as $key => $value) {
  1322. $sicks[$key] = array(
  1323. 'url' => $value,
  1324. 'token' => $sickTokenList[$key]
  1325. );
  1326. }
  1327. foreach ($sicks as $key => $value) {
  1328. try {
  1329. $sickrage = new Kryptonit3\SickRage\SickRage($value['url'], $value['token']);
  1330. $sickrageFuture = getSickrageCalendarWanted($sickrage->future(), $key);
  1331. $sickrageHistory = getSickrageCalendarHistory($sickrage->history("100", "downloaded"), $key);
  1332. if (!empty($sickrageFuture)) {
  1333. $calendarItems = array_merge($calendarItems, $sickrageFuture);
  1334. }
  1335. if (!empty($sickrageHistory)) {
  1336. $calendarItems = array_merge($calendarItems, $sickrageHistory);
  1337. }
  1338. } catch (Exception $e) {
  1339. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1340. }
  1341. }
  1342. }
  1343. }
  1344. // COUCHPOTATO CONNECT
  1345. if ($GLOBALS['homepageCouchpotatoEnabled'] && qualifyRequest($GLOBALS['homepageCouchpotatoAuth']) && !empty($GLOBALS['couchpotatoURL']) && !empty($GLOBALS['couchpotatoToken'])) {
  1346. $couchs = array();
  1347. $couchpotatoURLList = explode(',', $GLOBALS['couchpotatoURL']);
  1348. $couchpotatoTokenList = explode(',', $GLOBALS['couchpotatoToken']);
  1349. if (count($couchpotatoURLList) == count($couchpotatoTokenList)) {
  1350. foreach ($couchpotatoURLList as $key => $value) {
  1351. $couchs[$key] = array(
  1352. 'url' => $value,
  1353. 'token' => $couchpotatoTokenList[$key]
  1354. );
  1355. }
  1356. foreach ($couchs as $key => $value) {
  1357. try {
  1358. $couchpotato = new Kryptonit3\CouchPotato\CouchPotato($value['url'], $value['token']);
  1359. $couchCalendar = getCouchCalendar($couchpotato->getMediaList(), $key);
  1360. if (!empty($couchCalendar)) {
  1361. $calendarItems = array_merge($calendarItems, $couchCalendar);
  1362. }
  1363. } catch (Exception $e) {
  1364. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1365. }
  1366. }
  1367. }
  1368. }
  1369. // iCal URL
  1370. if ($GLOBALS['homepageCalendarEnabled'] && qualifyRequest($GLOBALS['homepageCalendarAuth']) && !empty($GLOBALS['calendariCal'])) {
  1371. $calendars = array();
  1372. $calendarURLList = explode(',', $GLOBALS['calendariCal']);
  1373. $icalEvents = array();
  1374. foreach ($calendarURLList as $key => $value) {
  1375. $icsEvents = getIcsEventsAsArray($value);
  1376. if (isset($icsEvents) && !empty($icsEvents)) {
  1377. $timeZone = isset($icsEvents [1] ['X-WR-TIMEZONE']) ? trim($icsEvents[1]['X-WR-TIMEZONE']) : date_default_timezone_get();
  1378. $originalTimeZone = isset($icsEvents [1] ['X-WR-TIMEZONE']) ? str_replace('"', '', trim($icsEvents[1]['X-WR-TIMEZONE'])) : false;
  1379. unset($icsEvents [1]);
  1380. foreach ($icsEvents as $icsEvent) {
  1381. $startKeys = array_filter_key($icsEvent, function ($key) {
  1382. return strpos($key, 'DTSTART') === 0;
  1383. });
  1384. $endKeys = array_filter_key($icsEvent, function ($key) {
  1385. return strpos($key, 'DTEND') === 0;
  1386. });
  1387. if (!empty($startKeys) && !empty($endKeys) && isset($icsEvent['SUMMARY'])) {
  1388. /* Getting start date and time */
  1389. $repeat = isset($icsEvent ['RRULE']) ? $icsEvent ['RRULE'] : false;
  1390. if (!$originalTimeZone) {
  1391. $tzKey = array_keys($startKeys);
  1392. if (strpos($tzKey[0], 'TZID=') !== false) {
  1393. $originalTimeZone = explode('TZID=', (string)$tzKey[0]);
  1394. $originalTimeZone = (count($originalTimeZone) >= 2) ? str_replace('"', '', $originalTimeZone[1]) : false;
  1395. }
  1396. }
  1397. $start = reset($startKeys);
  1398. $end = reset($endKeys);
  1399. $totalDays = $GLOBALS['calendarStart'] + $GLOBALS['calendarEnd'];
  1400. if ($repeat) {
  1401. $repeatOverride = getCalenderRepeatCount(trim($icsEvent["RRULE"]));
  1402. switch (trim(strtolower(getCalenderRepeat($repeat)))) {
  1403. case 'daily':
  1404. $repeat = ($repeatOverride) ? $repeatOverride : $totalDays;
  1405. $term = 'days';
  1406. break;
  1407. case 'weekly':
  1408. $repeat = ($repeatOverride) ? $repeatOverride : round($totalDays / 7);
  1409. $term = 'weeks';
  1410. break;
  1411. case 'monthly':
  1412. $repeat = ($repeatOverride) ? $repeatOverride : round($totalDays / 30);
  1413. $term = 'months';
  1414. break;
  1415. case 'yearly':
  1416. $repeat = ($repeatOverride) ? $repeatOverride : round($totalDays / 365);
  1417. $term = 'years';
  1418. break;
  1419. default:
  1420. $repeat = ($repeatOverride) ? $repeatOverride : $totalDays;
  1421. $term = 'days';
  1422. break;
  1423. }
  1424. } else {
  1425. $repeat = 1;
  1426. $term = 'day';
  1427. }
  1428. $calendarTimes = 0;
  1429. while ($calendarTimes < $repeat) {
  1430. $currentDate = new DateTime ($GLOBALS['currentTime']);
  1431. $oldestDay = new DateTime ($GLOBALS['currentTime']);
  1432. $oldestDay->modify('-' . $GLOBALS['calendarStart'] . ' days');
  1433. $newestDay = new DateTime ($GLOBALS['currentTime']);
  1434. $newestDay->modify('+' . $GLOBALS['calendarEnd'] . ' days');
  1435. /* Converting to datetime and apply the timezone to get proper date time */
  1436. $startDt = new DateTime ($start);
  1437. /* Getting end date with time */
  1438. $endDt = new DateTime ($end);
  1439. if ($calendarTimes !== 0) {
  1440. $dateDiff = date_diff($startDt, $currentDate);
  1441. $startDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1442. $startDt->modify('+' . $calendarTimes . ' ' . $term);
  1443. $endDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1444. $endDt->modify('+' . $calendarTimes . ' ' . $term);
  1445. } elseif ($calendarTimes == 0 && $repeat !== 1) {
  1446. $dateDiff = date_diff($startDt, $currentDate);
  1447. $startDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1448. $endDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1449. }
  1450. $calendarStartDiff = date_diff($startDt, $newestDay);
  1451. $calendarEndDiff = date_diff($startDt, $oldestDay);
  1452. if ($originalTimeZone && $originalTimeZone !== 'UTC' && (strpos($start, 'Z') == false)) {
  1453. $originalTimeZone = calendarStandardizeTimezone($originalTimeZone);
  1454. $dateTimeOriginalTZ = new DateTimeZone($originalTimeZone);
  1455. $dateTimeOriginal = new DateTime('now', $dateTimeOriginalTZ);
  1456. $dateTimeUTCTZ = new DateTimeZone(date_default_timezone_get());
  1457. $dateTimeUTC = new DateTime('now', $dateTimeUTCTZ);
  1458. $dateTimeOriginalOffset = $dateTimeOriginal->getOffset() / 3600;
  1459. $dateTimeUTCOffset = $dateTimeUTC->getOffset() / 3600;
  1460. $diff = $dateTimeUTCOffset - $dateTimeOriginalOffset;
  1461. $startDt->modify('+ ' . $diff . ' hour');
  1462. $endDt->modify('+ ' . $diff . ' hour');
  1463. }
  1464. $startDt->setTimeZone(new DateTimezone ($timeZone));
  1465. $endDt->setTimeZone(new DateTimezone ($timeZone));
  1466. $startDate = $startDt->format(DateTime::ATOM);
  1467. $endDate = $endDt->format(DateTime::ATOM);
  1468. if (new DateTime() < $endDt) {
  1469. $extraClass = 'text-info';
  1470. } else {
  1471. $extraClass = 'text-success';
  1472. }
  1473. /* Getting the name of event */
  1474. $eventName = $icsEvent['SUMMARY'];
  1475. if (!calendarDaysCheck($calendarStartDiff->format('%R') . $calendarStartDiff->days, $calendarEndDiff->format('%R') . $calendarEndDiff->days)) {
  1476. break;
  1477. }
  1478. if (isset($icsEvent["RRULE"]) && getCalenderRepeatUntil(trim($icsEvent["RRULE"]))) {
  1479. $untilDate = new DateTime (getCalenderRepeatUntil(trim($icsEvent["RRULE"])));
  1480. $untilDiff = date_diff($currentDate, $untilDate);
  1481. if ($untilDiff->days > 0) {
  1482. break;
  1483. }
  1484. }
  1485. $icalEvents[] = array(
  1486. 'title' => $eventName,
  1487. 'imagetype' => 'calendar-o text-warning text-custom-calendar ' . $extraClass,
  1488. 'imagetypeFilter' => 'ical',
  1489. 'className' => 'bg-calendar calendar-item bg-custom-calendar',
  1490. 'start' => $startDate,
  1491. 'end' => $endDate,
  1492. 'bgColor' => str_replace('text', 'bg', $extraClass),
  1493. );
  1494. $calendarTimes = $calendarTimes + 1;
  1495. }
  1496. }
  1497. }
  1498. }
  1499. }
  1500. $calendarSources['ical'] = $icalEvents;
  1501. }
  1502. $calendarSources['events'] = $calendarItems;
  1503. return ($calendarSources) ? $calendarSources : false;
  1504. }
  1505. function calendarDaysCheck($entryStart, $entryEnd)
  1506. {
  1507. $success = false;
  1508. $entryStart = intval($entryStart);
  1509. $entryEnd = intval($entryEnd);
  1510. if ($entryStart >= 0 && $entryEnd <= 0) {
  1511. $success = true;
  1512. }
  1513. return $success;
  1514. }
  1515. function calendarStandardizeTimezone($timezone)
  1516. {
  1517. switch ($timezone) {
  1518. case('CST'):
  1519. case('Central Time'):
  1520. case('Central Standard Time'):
  1521. $timezone = 'America/Chicago';
  1522. break;
  1523. case('CET'):
  1524. case('Central European Time'):
  1525. $timezone = 'Europe/Berlin';
  1526. break;
  1527. case('EST'):
  1528. case('Eastern Time'):
  1529. case('Eastern Standard Time'):
  1530. $timezone = 'America/New_York';
  1531. break;
  1532. case('PST'):
  1533. case('Pacific Time'):
  1534. case('Pacific Standard Time'):
  1535. $timezone = 'America/Los_Angeles';
  1536. break;
  1537. case('China Time'):
  1538. case('China Standard Time'):
  1539. $timezone = 'Asia/Beijing';
  1540. break;
  1541. case('IST'):
  1542. case('India Time'):
  1543. case('India Standard Time'):
  1544. $timezone = 'Asia/New_Delhi';
  1545. break;
  1546. case('JST');
  1547. case('Japan Time'):
  1548. case('Japan Standard Time'):
  1549. $timezone = 'Asia/Tokyo';
  1550. break;
  1551. }
  1552. return $timezone;
  1553. }
  1554. function getCalenderRepeat($value)
  1555. {
  1556. //FREQ=DAILY
  1557. //RRULE:FREQ=WEEKLY;BYDAY=TH
  1558. $first = explode('=', $value);
  1559. if (count($first) > 1) {
  1560. $second = explode(';', $first[1]);
  1561. } else {
  1562. return $value;
  1563. }
  1564. if ($second) {
  1565. return $second[0];
  1566. } else {
  1567. return $first[1];
  1568. }
  1569. }
  1570. function getCalenderRepeatUntil($value)
  1571. {
  1572. $first = explode('UNTIL=', $value);
  1573. if (count($first) > 1) {
  1574. if (strpos($first[1], ';') !== false) {
  1575. $check = explode(';', $first[1]);
  1576. return $check[0];
  1577. } else {
  1578. return $first[1];
  1579. }
  1580. } else {
  1581. return false;
  1582. }
  1583. }
  1584. function getCalenderRepeatCount($value)
  1585. {
  1586. $first = explode('COUNT=', $value);
  1587. if (count($first) > 1) {
  1588. return $first[1];
  1589. } else {
  1590. return false;
  1591. }
  1592. }
  1593. function getSonarrCalendar($array, $number)
  1594. {
  1595. $array = json_decode($array, true);
  1596. $gotCalendar = array();
  1597. $i = 0;
  1598. foreach ($array as $child) {
  1599. $i++;
  1600. $seriesName = $child['series']['title'];
  1601. $seriesID = $child['series']['tvdbId'];
  1602. $episodeID = $child['series']['tvdbId'];
  1603. $monitored = $child['monitored'];
  1604. if (!isset($episodeID)) {
  1605. $episodeID = "";
  1606. }
  1607. //$episodeName = htmlentities($child['title'], ENT_QUOTES);
  1608. $episodeAirDate = $child['airDateUtc'];
  1609. $episodeAirDate = strtotime($episodeAirDate);
  1610. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1611. if (new DateTime() < new DateTime($episodeAirDate)) {
  1612. $unaired = true;
  1613. }
  1614. if ($child['episodeNumber'] == "1") {
  1615. $episodePremier = "true";
  1616. } else {
  1617. $episodePremier = "false";
  1618. $date = new DateTime($episodeAirDate);
  1619. $date->add(new DateInterval("PT1S"));
  1620. $date->format(DateTime::ATOM);
  1621. $child['airDateUtc'] = gmdate('Y-m-d\TH:i:s\Z', strtotime($date->format(DateTime::ATOM)));
  1622. }
  1623. $downloaded = $child['hasFile'];
  1624. if ($downloaded == "0" && isset($unaired) && $episodePremier == "true") {
  1625. $downloaded = "text-primary animated flash";
  1626. } elseif ($downloaded == "0" && isset($unaired) && $monitored == "0") {
  1627. $downloaded = "text-dark";
  1628. } elseif ($downloaded == "0" && isset($unaired)) {
  1629. $downloaded = "text-info";
  1630. } elseif ($downloaded == "1") {
  1631. $downloaded = "text-success";
  1632. } else {
  1633. $downloaded = "text-danger";
  1634. }
  1635. $fanart = "/plugins/images/cache/no-np.png";
  1636. foreach ($child['series']['images'] as $image) {
  1637. if ($image['coverType'] == "fanart") {
  1638. $fanart = $image['url'];
  1639. }
  1640. }
  1641. if ($fanart !== "/plugins/images/cache/no-np.png" || (strpos($fanart, '://') === false)) {
  1642. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1643. $imageURL = $fanart;
  1644. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1645. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1646. if (!file_exists($cacheFile)) {
  1647. cacheImage($imageURL, $seriesID);
  1648. unset($imageURL);
  1649. unset($cacheFile);
  1650. }
  1651. }
  1652. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  1653. $details = array(
  1654. "seasonCount" => $child['series']['seasonCount'],
  1655. "status" => $child['series']['status'],
  1656. "topTitle" => $seriesName,
  1657. "bottomTitle" => $bottomTitle,
  1658. "overview" => isset($child['overview']) ? $child['overview'] : '',
  1659. "runtime" => $child['series']['runtime'],
  1660. "image" => $fanart,
  1661. "ratings" => $child['series']['ratings']['value'],
  1662. "videoQuality" => $child["hasFile"] && isset($child['episodeFile']['quality']['quality']['name']) ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  1663. "audioChannels" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  1664. "audioCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  1665. "videoCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  1666. "size" => $child["hasFile"] && isset($child['episodeFile']['size']) ? $child['episodeFile']['size'] : "unknown",
  1667. "genres" => $child['series']['genres'],
  1668. );
  1669. array_push($gotCalendar, array(
  1670. "id" => "Sonarr-" . $number . "-" . $i,
  1671. "title" => $seriesName,
  1672. "start" => $child['airDateUtc'],
  1673. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1674. "imagetype" => "tv " . $downloaded,
  1675. "imagetypeFilter" => "tv",
  1676. "downloadFilter" => $downloaded,
  1677. "bgColor" => str_replace('text', 'bg', $downloaded),
  1678. "details" => $details
  1679. ));
  1680. }
  1681. if ($i != 0) {
  1682. return $gotCalendar;
  1683. }
  1684. return false;
  1685. }
  1686. function getLidarrCalendar($array, $number)
  1687. {
  1688. $array = json_decode($array, true);
  1689. $gotCalendar = array();
  1690. $i = 0;
  1691. foreach ($array as $child) {
  1692. $i++;
  1693. $albumName = $child['title'];
  1694. $artistName = $child['artist']['artistName'];
  1695. $albumID = '';
  1696. $releaseDate = $child['releaseDate'];
  1697. $releaseDate = strtotime($releaseDate);
  1698. $releaseDate = date("Y-m-d H:i:s", $releaseDate);
  1699. if (new DateTime() < new DateTime($releaseDate)) {
  1700. $unaired = true;
  1701. }
  1702. if (isset($child['statistics']['percentOfTracks'])) {
  1703. if ($child['statistics']['percentOfTracks'] == '100.0') {
  1704. $downloaded = '1';
  1705. } else {
  1706. $downloaded = '0';
  1707. }
  1708. } else {
  1709. $downloaded = '0';
  1710. }
  1711. if ($downloaded == "0" && isset($unaired)) {
  1712. $downloaded = "text-info";
  1713. } elseif ($downloaded == "1") {
  1714. $downloaded = "text-success";
  1715. } else {
  1716. $downloaded = "text-danger";
  1717. }
  1718. $fanart = "/plugins/images/cache/no-np.png";
  1719. foreach ($child['artist']['images'] as $image) {
  1720. if ($image['coverType'] == "fanart") {
  1721. $fanart = str_replace('http://', 'https://', $image['url']);
  1722. }
  1723. }
  1724. $details = array(
  1725. "seasonCount" => '',
  1726. "status" => '',
  1727. "topTitle" => $albumName,
  1728. "bottomTitle" => $artistName,
  1729. "overview" => isset($child['artist']['overview']) ? $child['artist']['overview'] : '',
  1730. "runtime" => '',
  1731. "image" => $fanart,
  1732. "ratings" => $child['artist']['ratings']['value'],
  1733. "videoQuality" => "unknown",
  1734. "audioChannels" => "unknown",
  1735. "audioCodec" => "unknown",
  1736. "videoCodec" => "unknown",
  1737. "size" => "unknown",
  1738. "genres" => $child['genres'],
  1739. );
  1740. array_push($gotCalendar, array(
  1741. "id" => "Lidarr-" . $number . "-" . $i,
  1742. "title" => $artistName,
  1743. "start" => $child['releaseDate'],
  1744. "className" => "inline-popups bg-calendar calendar-item musicID--",
  1745. "imagetype" => "music " . $downloaded,
  1746. "imagetypeFilter" => "music",
  1747. "downloadFilter" => $downloaded,
  1748. "bgColor" => str_replace('text', 'bg', $downloaded),
  1749. "details" => $details,
  1750. "data" => $child
  1751. ));
  1752. }
  1753. if ($i != 0) {
  1754. return $gotCalendar;
  1755. }
  1756. return false;
  1757. }
  1758. function getRadarrCalendar($array, $number, $url)
  1759. {
  1760. $url = rtrim($url, '/'); //remove trailing slash
  1761. $url = $url . '/api';
  1762. $array = json_decode($array, true);
  1763. $gotCalendar = array();
  1764. $i = 0;
  1765. foreach ($array as $child) {
  1766. if (isset($child['physicalRelease'])) {
  1767. $i++;
  1768. $movieName = $child['title'];
  1769. $movieID = $child['tmdbId'];
  1770. if (!isset($movieID)) {
  1771. $movieID = "";
  1772. }
  1773. $physicalRelease = $child['physicalRelease'];
  1774. $physicalRelease = strtotime($physicalRelease);
  1775. $physicalRelease = date("Y-m-d", $physicalRelease);
  1776. if (new DateTime() < new DateTime($physicalRelease)) {
  1777. $notReleased = "true";
  1778. } else {
  1779. $notReleased = "false";
  1780. }
  1781. $downloaded = $child['hasFile'];
  1782. if ($downloaded == "0" && $notReleased == "true") {
  1783. $downloaded = "text-info";
  1784. } elseif ($downloaded == "1") {
  1785. $downloaded = "text-success";
  1786. } else {
  1787. $downloaded = "text-danger";
  1788. }
  1789. $banner = "/plugins/images/cache/no-np.png";
  1790. foreach ($child['images'] as $image) {
  1791. if ($image['coverType'] == "banner" || $image['coverType'] == "fanart") {
  1792. if (strpos($image['url'], '://') === false) {
  1793. $imageUrl = $image['url'];
  1794. $urlParts = explode("/", $url);
  1795. $imageParts = explode("/", $image['url']);
  1796. if ($imageParts[1] == end($urlParts)) {
  1797. unset($imageParts[1]);
  1798. $imageUrl = implode("/", $imageParts);
  1799. }
  1800. $banner = $url . $imageUrl . '?apikey=' . $GLOBALS['radarrToken'];
  1801. } else {
  1802. $banner = $image['url'];
  1803. }
  1804. }
  1805. }
  1806. if ($banner !== "/plugins/images/cache/no-np.png" || (strpos($banner, 'apikey') !== false)) {
  1807. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1808. $imageURL = $banner;
  1809. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1810. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1811. if (!file_exists($cacheFile)) {
  1812. cacheImage($imageURL, $movieID);
  1813. unset($imageURL);
  1814. unset($cacheFile);
  1815. }
  1816. }
  1817. $alternativeTitles = "";
  1818. foreach ($child['alternativeTitles'] as $alternative) {
  1819. $alternativeTitles .= $alternative['title'] . ', ';
  1820. }
  1821. $alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
  1822. $details = array(
  1823. "topTitle" => $movieName,
  1824. "bottomTitle" => $alternativeTitles,
  1825. "status" => $child['status'],
  1826. "overview" => $child['overview'],
  1827. "runtime" => $child['runtime'],
  1828. "image" => $banner,
  1829. "ratings" => $child['ratings']['value'],
  1830. "videoQuality" => $child["hasFile"] ? @$child['movieFile']['quality']['quality']['name'] : "unknown",
  1831. "audioChannels" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
  1832. "audioCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
  1833. "videoCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
  1834. "size" => $child["hasFile"] ? @$child['movieFile']['size'] : "unknown",
  1835. "genres" => $child['genres'],
  1836. "year" => isset($child['year']) ? $child['year'] : '',
  1837. "studio" => isset($child['studio']) ? $child['studio'] : '',
  1838. );
  1839. array_push($gotCalendar, array(
  1840. "id" => "Radarr-" . $number . "-" . $i,
  1841. "title" => $movieName,
  1842. "start" => $physicalRelease,
  1843. "className" => "inline-popups bg-calendar movieID--" . $movieID,
  1844. "imagetype" => "film " . $downloaded,
  1845. "imagetypeFilter" => "film",
  1846. "downloadFilter" => $downloaded,
  1847. "bgColor" => str_replace('text', 'bg', $downloaded),
  1848. "details" => $details
  1849. ));
  1850. }
  1851. }
  1852. if ($i != 0) {
  1853. return $gotCalendar;
  1854. }
  1855. return false;
  1856. }
  1857. function getCouchCalendar($array, $number)
  1858. {
  1859. $api = json_decode($array, true);
  1860. $gotCalendar = array();
  1861. $i = 0;
  1862. foreach ($api['movies'] as $child) {
  1863. if ($child['status'] == "active" || $child['status'] == "done") {
  1864. $i++;
  1865. $movieName = $child['info']['original_title'];
  1866. $movieID = $child['info']['tmdb_id'];
  1867. if (!isset($movieID)) {
  1868. $movieID = "";
  1869. }
  1870. $physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
  1871. $backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
  1872. $physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
  1873. $physicalRelease = strtotime($physicalRelease);
  1874. $physicalRelease = date("Y-m-d", $physicalRelease);
  1875. if (new DateTime() < new DateTime($physicalRelease)) {
  1876. $notReleased = "true";
  1877. } else {
  1878. $notReleased = "false";
  1879. }
  1880. $downloaded = ($child['status'] == "active") ? "0" : "1";
  1881. if ($downloaded == "0" && $notReleased == "true") {
  1882. $downloaded = "text-info";
  1883. } elseif ($downloaded == "1") {
  1884. $downloaded = "text-success";
  1885. } else {
  1886. $downloaded = "text-danger";
  1887. }
  1888. if (!empty($child['info']['images']['backdrop_original'])) {
  1889. $banner = $child['info']['images']['backdrop_original'][0];
  1890. } elseif (!empty($child['info']['images']['backdrop'])) {
  1891. $banner = $child['info']['images']['backdrop_original'][0];
  1892. } else {
  1893. $banner = "/plugins/images/cache/no-np.png";
  1894. }
  1895. if ($banner !== "/plugins/images/cache/no-np.png") {
  1896. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1897. $imageURL = $banner;
  1898. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1899. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1900. if (!file_exists($cacheFile)) {
  1901. cacheImage($imageURL, $movieID);
  1902. unset($imageURL);
  1903. unset($cacheFile);
  1904. }
  1905. }
  1906. $hasFile = (!empty($child['releases']) && !empty($child['releases'][0]['files']['movie']));
  1907. $details = array(
  1908. "topTitle" => $movieName,
  1909. "bottomTitle" => $child['info']['tagline'],
  1910. "status" => $child['status'],
  1911. "overview" => $child['info']['plot'],
  1912. "runtime" => $child['info']['runtime'],
  1913. "image" => $banner,
  1914. "ratings" => isset($child['info']['rating']['imdb'][0]) ? $child['info']['rating']['imdb'][0] : '',
  1915. "videoQuality" => $hasFile ? $child['releases'][0]['quality'] : "unknown",
  1916. "audioChannels" => "",
  1917. "audioCodec" => "",
  1918. "videoCodec" => "",
  1919. "genres" => $child['info']['genres'],
  1920. "year" => isset($child['info']['year']) ? $child['info']['year'] : '',
  1921. "studio" => isset($child['info']['year']) ? $child['info']['year'] : '',
  1922. );
  1923. array_push($gotCalendar, array(
  1924. "id" => "CouchPotato-" . $number . "-" . $i,
  1925. "title" => $movieName,
  1926. "start" => $physicalRelease,
  1927. "className" => "inline-popups bg-calendar calendar-item movieID--" . $movieID,
  1928. "imagetype" => "film " . $downloaded,
  1929. "imagetypeFilter" => "film",
  1930. "downloadFilter" => $downloaded,
  1931. "bgColor" => str_replace('text', 'bg', $downloaded),
  1932. "details" => $details
  1933. ));
  1934. }
  1935. }
  1936. if ($i != 0) {
  1937. return $gotCalendar;
  1938. }
  1939. return false;
  1940. }
  1941. function getSickrageCalendarWanted($array, $number)
  1942. {
  1943. $array = json_decode($array, true);
  1944. $gotCalendar = array();
  1945. $i = 0;
  1946. foreach ($array['data']['missed'] as $child) {
  1947. $i++;
  1948. $seriesName = $child['show_name'];
  1949. $seriesID = $child['tvdbid'];
  1950. $episodeID = $child['tvdbid'];
  1951. $episodeAirDate = $child['airdate'];
  1952. $episodeAirDateTime = explode(" ", $child['airs']);
  1953. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1954. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1955. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1956. if (new DateTime() < new DateTime($episodeAirDate)) {
  1957. $unaired = true;
  1958. }
  1959. $downloaded = "0";
  1960. if ($downloaded == "0" && isset($unaired)) {
  1961. $downloaded = "text-info";
  1962. } elseif ($downloaded == "1") {
  1963. $downloaded = "text-success";
  1964. } else {
  1965. $downloaded = "text-danger";
  1966. }
  1967. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1968. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1969. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1970. $fanart = "/plugins/images/cache/no-np.png";
  1971. if (file_exists($cacheFile)) {
  1972. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1973. unset($cacheFile);
  1974. }
  1975. $details = array(
  1976. "seasonCount" => "",
  1977. "status" => $child['show_status'],
  1978. "topTitle" => $seriesName,
  1979. "bottomTitle" => $bottomTitle,
  1980. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1981. "runtime" => "",
  1982. "image" => $fanart,
  1983. "ratings" => "",
  1984. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1985. "audioChannels" => "",
  1986. "audioCodec" => "",
  1987. "videoCodec" => "",
  1988. "size" => "",
  1989. "genres" => "",
  1990. );
  1991. array_push($gotCalendar, array(
  1992. "id" => "Sick-" . $number . "-Miss-" . $i,
  1993. "title" => $seriesName,
  1994. "start" => $episodeAirDate,
  1995. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1996. "imagetype" => "tv " . $downloaded,
  1997. "imagetypeFilter" => "tv",
  1998. "downloadFilter" => $downloaded,
  1999. "bgColor" => str_replace('text', 'bg', $downloaded),
  2000. "details" => $details,
  2001. ));
  2002. }
  2003. foreach ($array['data']['today'] as $child) {
  2004. $i++;
  2005. $seriesName = $child['show_name'];
  2006. $seriesID = $child['tvdbid'];
  2007. $episodeID = $child['tvdbid'];
  2008. $episodeAirDate = $child['airdate'];
  2009. $episodeAirDateTime = explode(" ", $child['airs']);
  2010. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  2011. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  2012. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2013. if (new DateTime() < new DateTime($episodeAirDate)) {
  2014. $unaired = true;
  2015. }
  2016. $downloaded = "0";
  2017. if ($downloaded == "0" && isset($unaired)) {
  2018. $downloaded = "text-info";
  2019. } elseif ($downloaded == "1") {
  2020. $downloaded = "text-success";
  2021. } else {
  2022. $downloaded = "text-danger";
  2023. }
  2024. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  2025. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2026. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  2027. $fanart = "/plugins/images/cache/no-np.png";
  2028. if (file_exists($cacheFile)) {
  2029. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  2030. unset($cacheFile);
  2031. }
  2032. $details = array(
  2033. "seasonCount" => "",
  2034. "status" => $child['show_status'],
  2035. "topTitle" => $seriesName,
  2036. "bottomTitle" => $bottomTitle,
  2037. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  2038. "runtime" => "",
  2039. "image" => $fanart,
  2040. "ratings" => "",
  2041. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  2042. "audioChannels" => "",
  2043. "audioCodec" => "",
  2044. "videoCodec" => "",
  2045. "size" => "",
  2046. "genres" => "",
  2047. );
  2048. array_push($gotCalendar, array(
  2049. "id" => "Sick-" . $number . "-Today-" . $i,
  2050. "title" => $seriesName,
  2051. "start" => $episodeAirDate,
  2052. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2053. "imagetype" => "tv " . $downloaded,
  2054. "imagetypeFilter" => "tv",
  2055. "downloadFilter" => $downloaded,
  2056. "bgColor" => str_replace('text', 'bg', $downloaded),
  2057. "details" => $details,
  2058. ));
  2059. }
  2060. foreach ($array['data']['soon'] as $child) {
  2061. $i++;
  2062. $seriesName = $child['show_name'];
  2063. $seriesID = $child['tvdbid'];
  2064. $episodeID = $child['tvdbid'];
  2065. $episodeAirDate = $child['airdate'];
  2066. $episodeAirDateTime = explode(" ", $child['airs']);
  2067. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  2068. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  2069. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2070. if (new DateTime() < new DateTime($episodeAirDate)) {
  2071. $unaired = true;
  2072. }
  2073. $downloaded = "0";
  2074. if ($downloaded == "0" && isset($unaired)) {
  2075. $downloaded = "text-info";
  2076. } elseif ($downloaded == "1") {
  2077. $downloaded = "text-success";
  2078. } else {
  2079. $downloaded = "text-danger";
  2080. }
  2081. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  2082. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2083. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  2084. $fanart = "/plugins/images/cache/no-np.png";
  2085. if (file_exists($cacheFile)) {
  2086. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  2087. unset($cacheFile);
  2088. }
  2089. $details = array(
  2090. "seasonCount" => "",
  2091. "status" => $child['show_status'],
  2092. "topTitle" => $seriesName,
  2093. "bottomTitle" => $bottomTitle,
  2094. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  2095. "runtime" => "",
  2096. "image" => $fanart,
  2097. "ratings" => "",
  2098. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  2099. "audioChannels" => "",
  2100. "audioCodec" => "",
  2101. "videoCodec" => "",
  2102. "size" => "",
  2103. "genres" => "",
  2104. );
  2105. array_push($gotCalendar, array(
  2106. "id" => "Sick-" . $number . "-Soon-" . $i,
  2107. "title" => $seriesName,
  2108. "start" => $episodeAirDate,
  2109. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2110. "imagetype" => "tv " . $downloaded,
  2111. "imagetypeFilter" => "tv",
  2112. "downloadFilter" => $downloaded,
  2113. "bgColor" => str_replace('text', 'bg', $downloaded),
  2114. "details" => $details,
  2115. ));
  2116. }
  2117. foreach ($array['data']['later'] as $child) {
  2118. $i++;
  2119. $seriesName = $child['show_name'];
  2120. $seriesID = $child['tvdbid'];
  2121. $episodeID = $child['tvdbid'];
  2122. $episodeAirDate = $child['airdate'];
  2123. $episodeAirDateTime = explode(" ", $child['airs']);
  2124. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  2125. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  2126. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2127. if (new DateTime() < new DateTime($episodeAirDate)) {
  2128. $unaired = true;
  2129. }
  2130. $downloaded = "0";
  2131. if ($downloaded == "0" && isset($unaired)) {
  2132. $downloaded = "text-info";
  2133. } elseif ($downloaded == "1") {
  2134. $downloaded = "text-success";
  2135. } else {
  2136. $downloaded = "text-danger";
  2137. }
  2138. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  2139. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2140. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  2141. $fanart = "/plugins/images/cache/no-np.png";
  2142. if (file_exists($cacheFile)) {
  2143. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  2144. unset($cacheFile);
  2145. }
  2146. $details = array(
  2147. "seasonCount" => "",
  2148. "status" => $child['show_status'],
  2149. "topTitle" => $seriesName,
  2150. "bottomTitle" => $bottomTitle,
  2151. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  2152. "runtime" => "",
  2153. "image" => $fanart,
  2154. "ratings" => "",
  2155. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  2156. "audioChannels" => "",
  2157. "audioCodec" => "",
  2158. "videoCodec" => "",
  2159. "size" => "",
  2160. "genres" => "",
  2161. );
  2162. array_push($gotCalendar, array(
  2163. "id" => "Sick-" . $number . "-Later-" . $i,
  2164. "title" => $seriesName,
  2165. "start" => $episodeAirDate,
  2166. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2167. "imagetype" => "tv " . $downloaded,
  2168. "imagetypeFilter" => "tv",
  2169. "downloadFilter" => $downloaded,
  2170. "bgColor" => str_replace('text', 'bg', $downloaded),
  2171. "details" => $details,
  2172. ));
  2173. }
  2174. if ($i != 0) {
  2175. return $gotCalendar;
  2176. }
  2177. return false;
  2178. }
  2179. function getSickrageCalendarHistory($array, $number)
  2180. {
  2181. $array = json_decode($array, true);
  2182. $gotCalendar = array();
  2183. $i = 0;
  2184. foreach ($array['data'] as $child) {
  2185. $i++;
  2186. $seriesName = $child['show_name'];
  2187. $seriesID = $child['tvdbid'];
  2188. $episodeID = $child['tvdbid'];
  2189. $episodeAirDate = $child['date'];
  2190. $downloaded = "text-success";
  2191. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']);
  2192. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2193. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  2194. $fanart = "/plugins/images/cache/no-np.png";
  2195. if (file_exists($cacheFile)) {
  2196. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  2197. unset($cacheFile);
  2198. }
  2199. $details = array(
  2200. "seasonCount" => "",
  2201. "status" => $child['status'],
  2202. "topTitle" => $seriesName,
  2203. "bottomTitle" => $bottomTitle,
  2204. "overview" => '',
  2205. "runtime" => isset($child['series']['runtime']) ? $child['series']['runtime'] : 30,
  2206. "image" => $fanart,
  2207. "ratings" => isset($child['series']['ratings']['value']) ? $child['series']['ratings']['value'] : "unknown",
  2208. "videoQuality" => isset($child["quality"]) ? $child['quality'] : "unknown",
  2209. "audioChannels" => "",
  2210. "audioCodec" => "",
  2211. "videoCodec" => "",
  2212. "size" => "",
  2213. "genres" => "",
  2214. );
  2215. array_push($gotCalendar, array(
  2216. "id" => "Sick-" . $number . "-History-" . $i,
  2217. "title" => $seriesName,
  2218. "start" => $episodeAirDate,
  2219. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2220. "imagetype" => "tv " . $downloaded,
  2221. "imagetypeFilter" => "tv",
  2222. "downloadFilter" => $downloaded,
  2223. "bgColor" => str_replace('text', 'bg', $downloaded),
  2224. "details" => $details,
  2225. ));
  2226. }
  2227. if ($i != 0) {
  2228. return $gotCalendar;
  2229. }
  2230. return false;
  2231. }
  2232. function ombiAPI($array)
  2233. {
  2234. return ombiAction($array['data']['id'], $array['data']['action'], $array['data']['type'], $array['data']);
  2235. }
  2236. function ombiImport($type = null)
  2237. {
  2238. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && !empty($type)) {
  2239. try {
  2240. $url = qualifyURL($GLOBALS['ombiURL']);
  2241. $headers = array(
  2242. "Accept" => "application/json",
  2243. "Content-Type" => "application/json",
  2244. "Apikey" => $GLOBALS['ombiToken']
  2245. );
  2246. $options = (localURL($url)) ? array('verify' => false) : array();
  2247. switch ($type) {
  2248. case 'emby':
  2249. case 'emby_local':
  2250. case 'emby_connect':
  2251. case 'emby_all':
  2252. $response = Requests::post($url . "/api/v1/Job/embyuserimporter", $headers, $options);
  2253. break;
  2254. case 'plex':
  2255. $response = Requests::post($url . "/api/v1/Job/plexuserimporter", $headers, $options);
  2256. break;
  2257. default:
  2258. return false;
  2259. break;
  2260. }
  2261. if ($response->success) {
  2262. writeLog('success', 'OMBI Connect Function - Ran User Import', 'SYSTEM');
  2263. return true;
  2264. } else {
  2265. writeLog('error', 'OMBI Connect Function - Error: Connection Unsuccessful', 'SYSTEM');
  2266. return false;
  2267. }
  2268. } catch (Requests_Exception $e) {
  2269. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2270. return false;
  2271. };
  2272. }
  2273. return false;
  2274. }
  2275. function ombiAction($id, $action, $type, $fullArray = null)
  2276. {
  2277. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  2278. $url = qualifyURL($GLOBALS['ombiURL']);
  2279. $headers = array(
  2280. "Accept" => "application/json",
  2281. "Content-Type" => "application/json",
  2282. "Apikey" => $GLOBALS['ombiToken']
  2283. );
  2284. $data = array(
  2285. 'id' => $id,
  2286. );
  2287. switch ($type) {
  2288. case 'season':
  2289. case 'tv':
  2290. $type = 'tv';
  2291. $add = array(
  2292. 'tvDbId' => $id,
  2293. 'requestAll' => ombiTVDefault('all'),
  2294. 'latestSeason' => ombiTVDefault('last'),
  2295. 'firstSeason' => ombiTVDefault('first')
  2296. );
  2297. break;
  2298. default:
  2299. $type = 'movie';
  2300. $add = array("theMovieDbId" => (int)$id);
  2301. break;
  2302. }
  2303. $success['head'] = $headers;
  2304. $success['act'] = $action;
  2305. $success['data'] = $data;
  2306. $success['add'] = $add;
  2307. $success['type'] = $type;
  2308. try {
  2309. $options = (localURL($url)) ? array('verify' => false) : array();
  2310. switch ($action) {
  2311. case 'add':
  2312. if (isset($_COOKIE['Auth'])) {
  2313. $headers = array(
  2314. "Accept" => "application/json",
  2315. "Content-Type" => "application/json",
  2316. "Authorization" => "Bearer " . $_COOKIE['Auth']
  2317. );
  2318. $success['head'] = $headers;
  2319. } else {
  2320. return false;
  2321. }
  2322. $response = Requests::post($url . "/api/v1/Request/" . $type, $headers, json_encode($add), $options);
  2323. break;
  2324. default:
  2325. if (qualifyRequest(1)) {
  2326. switch ($action) {
  2327. case 'approve':
  2328. $response = Requests::post($url . "/api/v1/Request/" . $type . "/approve", $headers, json_encode($data), $options);
  2329. break;
  2330. case 'available':
  2331. $response = Requests::post($url . "/api/v1/Request/" . $type . "/available", $headers, json_encode($data), $options);
  2332. break;
  2333. case 'unavailable':
  2334. $response = Requests::post($url . "/api/v1/Request/" . $type . "/unavailable", $headers, json_encode($data), $options);
  2335. break;
  2336. case 'deny':
  2337. $response = Requests::put($url . "/api/v1/Request/" . $type . "/deny", $headers, json_encode($data), $options);
  2338. break;
  2339. case 'delete':
  2340. $response = Requests::delete($url . "/api/v1/Request/" . $type . "/" . $id, $headers, $options);
  2341. break;
  2342. default:
  2343. return false;
  2344. }
  2345. }
  2346. break;
  2347. }
  2348. $success['api'] = $response;
  2349. $success['bd'] = $response->body;
  2350. $success['hd'] = $response->headers;
  2351. if ($response->success) {
  2352. $success['ok'] = true;
  2353. }
  2354. } catch (Requests_Exception $e) {
  2355. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2356. };
  2357. }
  2358. return isset($success['ok']) ? $success : false;
  2359. }
  2360. function getOmbiRequests($type = "both", $limit = 50)
  2361. {
  2362. $api['count'] = array(
  2363. 'movie' => 0,
  2364. 'tv' => 0,
  2365. 'limit' => (integer)$limit
  2366. );
  2367. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  2368. $url = qualifyURL($GLOBALS['ombiURL']);
  2369. $headers = array(
  2370. "Accept" => "application/json",
  2371. "Apikey" => $GLOBALS['ombiToken'],
  2372. );
  2373. $requests = array();
  2374. try {
  2375. $options = (localURL($url)) ? array('verify' => false) : array();
  2376. switch ($type) {
  2377. case 'movie':
  2378. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  2379. break;
  2380. case 'tv':
  2381. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  2382. break;
  2383. default:
  2384. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  2385. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  2386. break;
  2387. }
  2388. if ($movie->success || $tv->success) {
  2389. if (isset($movie)) {
  2390. $movie = json_decode($movie->body, true);
  2391. //$movie = array_reverse($movie);
  2392. foreach ($movie as $key => $value) {
  2393. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2394. if ($proceed) {
  2395. $api['count']['movie']++;
  2396. $requests[] = array(
  2397. 'id' => $value['theMovieDbId'],
  2398. 'title' => $value['title'],
  2399. 'overview' => $value['overview'],
  2400. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/' . $value['posterPath'] : 'plugins/images/cache/no-list.png',
  2401. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2402. 'approved' => $value['approved'],
  2403. 'available' => $value['available'],
  2404. 'denied' => $value['denied'],
  2405. 'deniedReason' => $value['deniedReason'],
  2406. 'user' => $value['requestedUser']['userName'],
  2407. 'userAlias' => $value['requestedUser']['userAlias'],
  2408. 'request_id' => $value['id'],
  2409. 'request_date' => $value['requestedDate'],
  2410. 'release_date' => $value['releaseDate'],
  2411. 'type' => 'movie',
  2412. 'icon' => 'mdi mdi-filmstrip',
  2413. 'color' => 'palette-Deep-Purple-900 bg white',
  2414. );
  2415. }
  2416. }
  2417. }
  2418. if (isset($tv) && (is_array($tv) || is_object($tv))) {
  2419. $tv = json_decode($tv->body, true);
  2420. foreach ($tv as $key => $value) {
  2421. if (count($value['childRequests']) > 0) {
  2422. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['childRequests'][0]['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2423. if ($proceed) {
  2424. $api['count']['tv']++;
  2425. $requests[] = array(
  2426. 'id' => $value['tvDbId'],
  2427. 'title' => $value['title'],
  2428. 'overview' => $value['overview'],
  2429. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? $value['posterPath'] : 'plugins/images/cache/no-list.png',
  2430. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2431. 'approved' => $value['childRequests'][0]['approved'],
  2432. 'available' => $value['childRequests'][0]['available'],
  2433. 'denied' => $value['childRequests'][0]['denied'],
  2434. 'deniedReason' => $value['childRequests'][0]['deniedReason'],
  2435. 'user' => $value['childRequests'][0]['requestedUser']['userName'],
  2436. 'userAlias' => $value['childRequests'][0]['requestedUser']['userAlias'],
  2437. 'request_id' => $value['id'],
  2438. 'request_date' => $value['childRequests'][0]['requestedDate'],
  2439. 'release_date' => $value['releaseDate'],
  2440. 'type' => 'tv',
  2441. 'icon' => 'mdi mdi-television',
  2442. 'color' => 'grayish-blue-bg',
  2443. );
  2444. }
  2445. }
  2446. }
  2447. }
  2448. //sort here
  2449. usort($requests, function ($item1, $item2) {
  2450. if ($item1['request_date'] == $item2['request_date']) {
  2451. return 0;
  2452. }
  2453. return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
  2454. });
  2455. }
  2456. } catch (Requests_Exception $e) {
  2457. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2458. };
  2459. }
  2460. $api['content'] = isset($requests) ? array_slice($requests, 0, $limit) : false;
  2461. return $api;
  2462. }
  2463. function unifiConnect()
  2464. {
  2465. if ($GLOBALS['homepageUnifiEnabled'] && !empty($GLOBALS['unifiURL']) && !empty($GLOBALS['unifiSiteName']) && !empty($GLOBALS['unifiUsername']) && !empty($GLOBALS['unifiPassword']) && qualifyRequest($GLOBALS['homepageUnifiAuth'])) {
  2466. $api['content']['unifi'] = array();
  2467. $url = qualifyURL($GLOBALS['unifiURL']);
  2468. $urlStat = $url . '/api/s/' . $GLOBALS['unifiSiteName'] . '/stat/health';
  2469. try {
  2470. $options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => false);
  2471. $data = array(
  2472. 'username' => $GLOBALS['unifiUsername'],
  2473. 'password' => decrypt($GLOBALS['unifiPassword']),
  2474. 'remember' => true,
  2475. 'strict' => true
  2476. );
  2477. $response = Requests::post($url . '/api/login', array(), json_encode($data), $options);
  2478. if ($response->success) {
  2479. $cookie['unifises'] = ($response->cookies['unifises']->value) ?? false;
  2480. $cookie['csrf_token'] = ($response->cookies['csrf_token']->value) ?? false;
  2481. } else {
  2482. return false;
  2483. }
  2484. $headers = array(
  2485. 'cookie' => 'unifises=' . $cookie['unifises'] . ';' . 'csrf_token=' . $cookie['csrf_token'] . ';'
  2486. );
  2487. $response = Requests::get($urlStat, $headers, $options);
  2488. if ($response->success) {
  2489. $api['content']['unifi'] = json_decode($response->body, true);
  2490. }
  2491. } catch (Requests_Exception $e) {
  2492. writeLog('error', 'Unifi Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2493. };
  2494. $api['content']['unifi'] = isset($api['content']['unifi']) ? $api['content']['unifi'] : false;
  2495. return $api;
  2496. }
  2497. return false;
  2498. }
  2499. function getTautulli()
  2500. {
  2501. if ($GLOBALS['homepageTautulliEnabled'] && !empty($GLOBALS['tautulliURL']) && !empty($GLOBALS['tautulliApikey']) && qualifyRequest($GLOBALS['homepageTautulliAuth'])) {
  2502. $api = [];
  2503. $url = qualifyURL($GLOBALS['tautulliURL']);
  2504. $apiURL = $url . '/api/v2?apikey=' . $GLOBALS['tautulliApikey'];
  2505. $height = getCacheImageSize('h');
  2506. $width = getCacheImageSize('w');
  2507. $nowPlayingHeight = getCacheImageSize('nph');
  2508. $nowPlayingWidth = getCacheImageSize('npw');
  2509. try {
  2510. $homestatsUrl = $apiURL . '&cmd=get_home_stats&grouping=1';
  2511. $homestats = Requests::get($homestatsUrl, [], []);
  2512. if ($homestats->success) {
  2513. $homestats = json_decode($homestats->body, true);
  2514. $api['homestats'] = $homestats['response'];
  2515. // Cache art & thumb for first result in each tautulli API result
  2516. $categories = ['top_movies', 'top_tv', 'popular_movies', 'popular_tv'];
  2517. foreach ($categories as $cat) {
  2518. $key = array_search($cat, array_column($api['homestats']['data'], 'stat_id'));
  2519. $img = $api['homestats']['data'][$key]['rows'][0];
  2520. cacheImage($url . '/pms_image_proxy?img=' . $img['art'] . '&rating_key=' . $img['rating_key'] . '&width=' . $nowPlayingWidth . '&height=' . $nowPlayingHeight, $img['rating_key'] . '-np');
  2521. cacheImage($url . '/pms_image_proxy?img=' . $img['thumb'] . '&rating_key=' . $img['rating_key'] . '&width=' . $width . '&height=' . $height, $img['rating_key'] . '-list');
  2522. $img['art'] = 'plugins/images/cache/' . $img['rating_key'] . '-np.jpg';
  2523. $img['thumb'] = 'plugins/images/cache/' . $img['rating_key'] . '-list.jpg';
  2524. $api['homestats']['data'][$key]['rows'][0] = $img;
  2525. }
  2526. // Cache the platform icon
  2527. $key = array_search('top_platforms', array_column($api['homestats']['data'], 'stat_id'));
  2528. $platform = $api['homestats']['data'][$key]['rows'][0]['platform_name'];
  2529. cacheImage($url . '/images/platforms/' . $platform . '.svg', 'tautulli-' . $platform, 'svg');
  2530. }
  2531. $libstatsUrl = $apiURL . '&cmd=get_libraries';
  2532. $libstats = Requests::get($libstatsUrl, [], []);
  2533. if ($libstats->success) {
  2534. $libstats = json_decode($libstats->body, true);
  2535. $api['libstats'] = $libstats['response'];
  2536. $categories = ['movie.svg', 'show.svg', 'artist.svg'];
  2537. foreach ($categories as $cat) {
  2538. $parts = explode('.', $cat);
  2539. cacheImage($url . '/images/libraries/' . $cat, 'tautulli-' . $parts[0], $parts[1]);
  2540. }
  2541. }
  2542. $api['options'] = [
  2543. 'url' => $url,
  2544. 'libraries' => $GLOBALS['tautulliLibraries'],
  2545. 'topMovies' => $GLOBALS['tautulliTopMovies'],
  2546. 'topTV' => $GLOBALS['tautulliTopTV'],
  2547. 'topUsers' => $GLOBALS['tautulliTopUsers'],
  2548. 'topPlatforms' => $GLOBALS['tautulliTopPlatforms'],
  2549. 'popularMovies' => $GLOBALS['tautulliPopularMovies'],
  2550. 'popularTV' => $GLOBALS['tautulliPopularTV'],
  2551. 'title' => $GLOBALS['tautulliHeaderToggle'],
  2552. ];
  2553. $ids = []; // Array of stat_ids to remove from the returned array
  2554. if (!qualifyRequest($GLOBALS['homepageTautulliLibraryAuth'])) {
  2555. $api['options']['libraries'] = false;
  2556. unset($api['libstats']);
  2557. }
  2558. if (!qualifyRequest($GLOBALS['homepageTautulliViewsAuth'])) {
  2559. $api['options']['topMovies'] = false;
  2560. $api['options']['topTV'] = false;
  2561. $api['options']['popularMovies'] = false;
  2562. $api['options']['popularTV'] = false;
  2563. $ids = array_merge(['top_movies', 'popular_movies', 'popular_tv', 'top_tv'], $ids);
  2564. $api['homestats']['data'] = array_values($api['homestats']['data']);
  2565. }
  2566. if (!qualifyRequest($GLOBALS['homepageTautulliMiscAuth'])) {
  2567. $api['options']['topUsers'] = false;
  2568. $api['options']['topPlatforms'] = false;
  2569. $ids = array_merge(['top_platforms', 'top_users'], $ids);
  2570. $api['homestats']['data'] = array_values($api['homestats']['data']);
  2571. }
  2572. $ids = array_merge(['top_music', 'popular_music', 'last_watched', 'most_concurrent'], $ids);
  2573. foreach ($ids as $id) {
  2574. if ($key = array_search($id, array_column($api['homestats']['data'], 'stat_id'))) {
  2575. unset($api['homestats']['data'][$key]);
  2576. $api['homestats']['data'] = array_values($api['homestats']['data']);
  2577. }
  2578. }
  2579. } catch (Requests_Exception $e) {
  2580. writeLog('error', 'Tautulli Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2581. };
  2582. $api = isset($api) ? $api : false;
  2583. return $api;
  2584. }
  2585. return false;
  2586. }
  2587. function getMonitorr()
  2588. {
  2589. if ($GLOBALS['homepageMonitorrEnabled'] && !empty($GLOBALS['monitorrURL']) && qualifyRequest($GLOBALS['homepageMonitorrAuth'])) {
  2590. $api = [];
  2591. $url = qualifyURL($GLOBALS['monitorrURL']);
  2592. $dataUrl = $url . '/assets/php/loop.php';
  2593. try {
  2594. $response = Requests::get($dataUrl, ['Token' => $GLOBALS['organizrAPI']], []);
  2595. if ($response->success) {
  2596. $html = html_entity_decode($response->body);
  2597. // This section grabs the names of all services by regex
  2598. $services = [];
  2599. $servicesMatch = [];
  2600. $servicePattern = '/<div id="servicetitle"><div>(.*)<\/div><\/div><div class="btnonline">Online<\/div><\/a><\/div><\/div>|<div id="servicetitleoffline".*><div>(.*)<\/div><\/div><div class="btnoffline".*>Offline<\/div><\/div><\/div>|<div id="servicetitlenolink".*><div>(.*)<\/div><\/div><div class="btnonline".*>Online<\/div><\/div><\/div>|<div id="servicetitle"><div>(.*)<\/div><\/div><div class="btnunknown">/';
  2601. preg_match_all($servicePattern, $html, $servicesMatch);
  2602. $services = array_filter($servicesMatch[1]) + array_filter($servicesMatch[2]) + array_filter($servicesMatch[3]) + array_filter($servicesMatch[4]);
  2603. $statuses = [];
  2604. foreach ($services as $key => $service) {
  2605. $statusPattern = '/' . $service . '<\/div><\/div><div class="btnonline">(Online)<\/div>|' . $service . '<\/div><\/div><div class="btnoffline".*>(Offline)<\/div><\/div><\/div>|' . $service . '<\/div><\/div><div class="btnunknown">(.*)<\/div><\/a>/';
  2606. $status = [];
  2607. preg_match($statusPattern, $html, $status);
  2608. $statuses[$service] = $status;
  2609. foreach ($status as $match) {
  2610. if ($match == 'Online') {
  2611. $statuses[$service] = [
  2612. 'status' => true
  2613. ];
  2614. } else if ($match == 'Offline') {
  2615. $statuses[$service] = [
  2616. 'status' => false
  2617. ];
  2618. } else if ($match == 'Unresponsive') {
  2619. $statuses[$service] = [
  2620. 'status' => 'unresponsive'
  2621. ];
  2622. }
  2623. }
  2624. $statuses[$service]['sort'] = $key;
  2625. $imageMatch = [];
  2626. $imgPattern = '/assets\/img\/\.\.(.*)" class="serviceimg" alt=.*><\/div><\/div><div id="servicetitle"><div>' . $service . '|assets\/img\/\.\.(.*)" class="serviceimg imgoffline" alt=.*><\/div><\/div><div id="servicetitleoffline".*><div>' . $service . '|assets\/img\/\.\.(.*)" class="serviceimg" alt=.*><\/div><\/div><div id="servicetitlenolink".*><div>' . $service . '/';
  2627. preg_match($imgPattern, $html, $imageMatch);
  2628. unset($imageMatch[0]);
  2629. $imageMatch = array_values($imageMatch);
  2630. // array_push($api['imagematches'][$service], $imageMatch);
  2631. foreach ($imageMatch as $match) {
  2632. if ($match !== '') {
  2633. $image = $match;
  2634. }
  2635. }
  2636. $ext = explode('.', $image);
  2637. $ext = $ext[key(array_slice($ext, -1, 1, true))];
  2638. $imageUrl = $url . '/assets' . $image;
  2639. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2640. $img = Requests::get($imageUrl, ['Token' => $GLOBALS['organizrAPI']], []);
  2641. if ($img->success) {
  2642. $base64 = 'data:image/' . $ext . ';base64,' . base64_encode($img->body);
  2643. $statuses[$service]['image'] = $base64;
  2644. } else {
  2645. $statuses[$service]['image'] = $cacheDirectory . 'no-list.png';
  2646. }
  2647. $linkMatch = [];
  2648. $linkPattern = '/<a class="servicetile" href="(.*)" target="_blank" style="display: block"><div id="serviceimg"><div><img id="' . strtolower($service) . '-service-img/';
  2649. preg_match($linkPattern, $html, $linkMatch);
  2650. $linkMatch = array_values($linkMatch);
  2651. unset($linkMatch[0]);
  2652. foreach ($linkMatch as $link) {
  2653. if ($link !== '') {
  2654. $statuses[$service]['link'] = $link;
  2655. }
  2656. }
  2657. }
  2658. foreach($statuses as $status){
  2659. foreach($status as $key=>$value){
  2660. if(!isset($sortArray[$key])){
  2661. $sortArray[$key] = array();
  2662. }
  2663. $sortArray[$key][] = $value;
  2664. }
  2665. }
  2666. array_multisort($sortArray['status'], SORT_ASC, $sortArray['sort'], SORT_ASC, $statuses);
  2667. $api['services'] = $statuses;
  2668. $api['options'] = [
  2669. 'title' => $GLOBALS['monitorrHeader'],
  2670. 'titleToggle' => $GLOBALS['monitorrHeaderToggle'],
  2671. 'compact' => $GLOBALS['monitorrCompact'],
  2672. ];
  2673. }
  2674. } catch (Requests_Exception $e) {
  2675. writeLog('error', 'Monitorr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2676. $api['error'] = $e->getMessage();
  2677. };
  2678. $api = isset($api) ? $api : false;
  2679. return $api;
  2680. }
  2681. }
  2682. function getSpeedtest()
  2683. {
  2684. if ($GLOBALS['homepageSpeedtestEnabled'] && !empty($GLOBALS['speedtestURL']) && qualifyRequest($GLOBALS['homepageSpeedtestAuth'])) {
  2685. $api = [];
  2686. $url = qualifyURL($GLOBALS['speedtestURL']);
  2687. $dataUrl = $url . '/api/speedtest/latest';
  2688. try {
  2689. $response = Requests::get($dataUrl);
  2690. if ($response->success) {
  2691. $json = json_decode($response->body, true);
  2692. $api['data'] = [
  2693. 'current' => $json['data'],
  2694. 'average' => $json['average'],
  2695. 'max' => $json['max'],
  2696. ];
  2697. $api['options'] = [
  2698. 'title' => $GLOBALS['speedtestHeader'],
  2699. 'titleToggle' => $GLOBALS['speedtestHeaderToggle'],
  2700. ];
  2701. }
  2702. } catch (Requests_Exception $e) {
  2703. writeLog('error', 'Speedtest Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2704. };
  2705. $api = isset($api) ? $api : false;
  2706. return $api;
  2707. }
  2708. }
  2709. function getNetdata()
  2710. {
  2711. if ($GLOBALS['homepageNetdataEnabled'] && !empty($GLOBALS['netdataURL']) && qualifyRequest($GLOBALS['homepageNetdataAuth'])) {
  2712. require_once('netdata-functions.php');
  2713. $api = [];
  2714. $api['data'] = [];
  2715. $api['url'] = $GLOBALS['netdataURL'];
  2716. $url = qualifyURL($GLOBALS['netdataURL']);
  2717. for ($i = 1; $i < 8; $i++) {
  2718. if ($GLOBALS['netdata' . ($i) . 'Enabled']) {
  2719. switch ($GLOBALS['netdata' . $i . 'Data']) {
  2720. case 'disk-read':
  2721. $data = disk('in', $url);
  2722. break;
  2723. case 'disk-write':
  2724. $data = disk('out', $url);
  2725. $data['value'] = abs($data['value']);
  2726. $data['percent'] = abs($data['percent']);
  2727. break;
  2728. case 'cpu':
  2729. $data = cpu($url);
  2730. break;
  2731. case 'net-in':
  2732. $data = net('received', $url);
  2733. break;
  2734. case 'net-out':
  2735. $data = net('sent', $url);
  2736. $data['value'] = abs($data['value']);
  2737. $data['percent'] = abs($data['percent']);
  2738. break;
  2739. case 'ram-used':
  2740. $data = ram($url);
  2741. break;
  2742. case 'swap-used':
  2743. $data = swap($url);
  2744. break;
  2745. case 'disk-avail':
  2746. $data = diskSpace('avail', $url);
  2747. break;
  2748. case 'disk-used':
  2749. $data = diskSpace('used', $url);
  2750. break;
  2751. case 'ipmi-temp-c':
  2752. $data = ipmiTemp($url, 'c');
  2753. break;
  2754. case 'ipmi-temp-f':
  2755. $data = ipmiTemp($url, 'f');
  2756. break;
  2757. case 'cpu-temp-c':
  2758. $data = cpuTemp($url, 'c');
  2759. break;
  2760. case 'cpu-temp-f':
  2761. $data = cpuTemp($url, 'f');
  2762. break;
  2763. case 'custom':
  2764. $data = customNetdata($url, $i);
  2765. break;
  2766. default:
  2767. $data = [
  2768. 'title' => 'DNC',
  2769. 'value' => 0,
  2770. 'units' => 'N/A',
  2771. 'max' => 100,
  2772. ];
  2773. break;
  2774. }
  2775. $data['title'] = $GLOBALS['netdata' . $i . 'Title'];
  2776. $data['colour'] = $GLOBALS['netdata' . $i . 'Colour'];
  2777. $data['chart'] = $GLOBALS['netdata' . $i . 'Chart'];
  2778. $data['size'] = $GLOBALS['netdata' . $i . 'Size'];
  2779. $data['lg'] = $GLOBALS['netdata' . ($i) . 'lg'];
  2780. $data['md'] = $GLOBALS['netdata' . ($i) . 'md'];
  2781. $data['sm'] = $GLOBALS['netdata' . ($i) . 'sm'];
  2782. array_push($api['data'], $data);
  2783. }
  2784. }
  2785. $api = isset($api) ? $api : false;
  2786. return $api;
  2787. }
  2788. }
  2789. function testAPIConnection($array)
  2790. {
  2791. switch ($array['data']['action']) {
  2792. case 'unifiSite':
  2793. if (!empty($GLOBALS['unifiURL']) && !empty($GLOBALS['unifiUsername']) && !empty($GLOBALS['unifiPassword'])) {
  2794. $url = qualifyURL($GLOBALS['unifiURL']);
  2795. try {
  2796. $options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => false);
  2797. $data = array(
  2798. 'username' => $GLOBALS['unifiUsername'],
  2799. 'password' => decrypt($GLOBALS['unifiPassword']),
  2800. 'remember' => true,
  2801. 'strict' => true
  2802. );
  2803. $response = Requests::post($url . '/api/login', array(), json_encode($data), $options);
  2804. if ($response->success) {
  2805. $cookie['unifises'] = ($response->cookies['unifises']->value) ?? false;
  2806. $cookie['csrf_token'] = ($response->cookies['csrf_token']->value) ?? false;
  2807. } else {
  2808. return false;
  2809. }
  2810. $headers = array(
  2811. 'cookie' => 'unifises=' . $cookie['unifises'] . ';' . 'csrf_token=' . $cookie['csrf_token'] . ';'
  2812. );
  2813. $response = Requests::get($url . '/api/self/sites', $headers, $options);
  2814. if ($response->success) {
  2815. $body = json_decode($response->body, true);
  2816. return $body;
  2817. } else {
  2818. return false;
  2819. }
  2820. } catch (Requests_Exception $e) {
  2821. writeLog('error', 'Unifi Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2822. };
  2823. }
  2824. break;
  2825. case 'unifi':
  2826. if (!empty($GLOBALS['unifiURL']) && !empty($GLOBALS['unifiUsername']) && !empty($GLOBALS['unifiPassword']) && !empty($GLOBALS['unifiSiteName'])) {
  2827. $url = qualifyURL($GLOBALS['unifiURL']);
  2828. try {
  2829. $options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => false);
  2830. $data = array(
  2831. 'username' => $GLOBALS['unifiUsername'],
  2832. 'password' => decrypt($GLOBALS['unifiPassword']),
  2833. 'remember' => true,
  2834. 'strict' => true
  2835. );
  2836. $response = Requests::post($url . '/api/login', array(), json_encode($data), $options);
  2837. if ($response->success) {
  2838. $cookie['unifises'] = ($response->cookies['unifises']->value) ?? false;
  2839. $cookie['csrf_token'] = ($response->cookies['csrf_token']->value) ?? false;
  2840. } else {
  2841. return 'Failed to Login';
  2842. }
  2843. $headers = array(
  2844. 'cookie' => 'unifises=' . $cookie['unifises'] . ';' . 'csrf_token=' . $cookie['csrf_token'] . ';'
  2845. );
  2846. $response = Requests::get($url . '/api/s/' . $GLOBALS['unifiSiteName'] . '/self', $headers, $options);
  2847. $body = json_decode($response->body, true);
  2848. return ($body['meta']['rc'] == 'ok') ? true : $body['meta']['msg'];
  2849. } catch (Requests_Exception $e) {
  2850. writeLog('error', 'Unifi Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2851. };
  2852. } else {
  2853. return 'Not all data is filled in...';
  2854. }
  2855. break;
  2856. case 'ombi':
  2857. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken'])) {
  2858. $url = qualifyURL($GLOBALS['ombiURL']);
  2859. $url = $url . "/api/v1/Status/info";
  2860. $headers = array(
  2861. "Accept" => "application/json",
  2862. "Content-Type" => "application/json",
  2863. "Apikey" => $GLOBALS['ombiToken']
  2864. );
  2865. try {
  2866. $options = (localURL($url)) ? array('verify' => false) : array();
  2867. $response = Requests::get($url, $headers, $options);
  2868. if ($response->success) {
  2869. return true;
  2870. } else {
  2871. return $response->body;
  2872. }
  2873. } catch (Requests_Exception $e) {
  2874. return $e->getMessage();
  2875. };
  2876. } else {
  2877. return 'URL and/or Token not setup';
  2878. }
  2879. break;
  2880. case 'plex':
  2881. if (!empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken'])) {
  2882. $url = qualifyURL($GLOBALS['plexURL']);
  2883. $url = $url . "/?X-Plex-Token=" . $GLOBALS['plexToken'];
  2884. try {
  2885. $options = (localURL($url)) ? array('verify' => false) : array();
  2886. $response = Requests::get($url, array(), $options);
  2887. libxml_use_internal_errors(true);
  2888. if ($response->success) {
  2889. return true;
  2890. }
  2891. } catch (Requests_Exception $e) {
  2892. return $e->getMessage();
  2893. };
  2894. } else {
  2895. return 'URL and/or Token not setup';
  2896. }
  2897. break;
  2898. case 'emby':
  2899. break;
  2900. case 'sonarr':
  2901. if (!empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  2902. $sonarrs = array();
  2903. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  2904. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  2905. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2906. foreach ($sonarrURLList as $key => $value) {
  2907. $sonarrs[$key] = array(
  2908. 'url' => $value,
  2909. 'token' => $sonarrTokenList[$key]
  2910. );
  2911. }
  2912. foreach ($sonarrs as $key => $value) {
  2913. try {
  2914. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2915. $result = json_decode($sonarr->getSystemStatus(), true);
  2916. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2917. } catch (Exception $e) {
  2918. return strip($e->getMessage());
  2919. }
  2920. }
  2921. }
  2922. } else {
  2923. return 'URL/s and/or Token/s not setup';
  2924. }
  2925. break;
  2926. case 'lidarr':
  2927. if (!empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  2928. $sonarrs = array();
  2929. $sonarrURLList = explode(',', $GLOBALS['lidarrURL']);
  2930. $sonarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  2931. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2932. foreach ($sonarrURLList as $key => $value) {
  2933. $sonarrs[$key] = array(
  2934. 'url' => $value,
  2935. 'token' => $sonarrTokenList[$key]
  2936. );
  2937. }
  2938. foreach ($sonarrs as $key => $value) {
  2939. try {
  2940. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  2941. $result = json_decode($sonarr->getSystemStatus(), true);
  2942. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2943. } catch (Exception $e) {
  2944. return $e->getMessage();
  2945. }
  2946. }
  2947. }
  2948. } else {
  2949. return 'URL/s and/or Token/s not setup';
  2950. }
  2951. break;
  2952. case 'radarr':
  2953. if (!empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  2954. $sonarrs = array();
  2955. $sonarrURLList = explode(',', $GLOBALS['radarrURL']);
  2956. $sonarrTokenList = explode(',', $GLOBALS['radarrToken']);
  2957. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2958. foreach ($sonarrURLList as $key => $value) {
  2959. $sonarrs[$key] = array(
  2960. 'url' => $value,
  2961. 'token' => $sonarrTokenList[$key]
  2962. );
  2963. }
  2964. foreach ($sonarrs as $key => $value) {
  2965. try {
  2966. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2967. $result = json_decode($sonarr->getSystemStatus(), true);
  2968. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2969. } catch (Exception $e) {
  2970. return $e->getMessage();
  2971. }
  2972. }
  2973. }
  2974. } else {
  2975. return 'URL/s and/or Token/s not setup';
  2976. }
  2977. break;
  2978. case 'jdownloader':
  2979. if (!empty($GLOBALS['jdownloaderURL'])) {
  2980. $url = qualifyURL($GLOBALS['jdownloaderURL']);
  2981. try {
  2982. $options = (localURL($url)) ? array('verify' => false, 'timeout' => 30) : array('timeout' => 30);
  2983. $response = Requests::get($url, array(), $options);
  2984. if ($response->success) {
  2985. return true;
  2986. }
  2987. } catch (Requests_Exception $e) {
  2988. return $e->getMessage();
  2989. };
  2990. } else {
  2991. return 'URL and/or Token not setup';
  2992. }
  2993. break;
  2994. case 'sabnzbd':
  2995. if (!empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken'])) {
  2996. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  2997. $url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  2998. try {
  2999. $options = (localURL($url)) ? array('verify' => false) : array();
  3000. $response = Requests::get($url, array(), $options);
  3001. if ($response->success) {
  3002. return true;
  3003. }
  3004. } catch (Requests_Exception $e) {
  3005. return $e->getMessage();
  3006. };
  3007. } else {
  3008. return 'URL and/or Token not setup';
  3009. }
  3010. break;
  3011. case 'nzbget':
  3012. if (!empty($GLOBALS['nzbgetURL'])) {
  3013. $url = qualifyURL($GLOBALS['nzbgetURL']);
  3014. $url = $url . '/jsonrpc/listgroups';
  3015. try {
  3016. $options = (localURL($url)) ? array('verify' => false) : array();
  3017. if ($GLOBALS['nzbgetUsername'] !== '' && decrypt($GLOBALS['nzbgetPassword']) !== '') {
  3018. $credentials = array('auth' => new Requests_Auth_Basic(array($GLOBALS['nzbgetUsername'], decrypt($GLOBALS['nzbgetPassword']))));
  3019. $options = array_merge($options, $credentials);
  3020. }
  3021. $response = Requests::get($url, array(), $options);
  3022. if ($response->success) {
  3023. return true;
  3024. }
  3025. } catch (Requests_Exception $e) {
  3026. return $e->getMessage();
  3027. };
  3028. } else {
  3029. return 'URL and/or Username/Password not setup';
  3030. }
  3031. break;
  3032. case 'deluge':
  3033. if (!empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword'])) {
  3034. try {
  3035. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  3036. $torrents = $deluge->getTorrents(null, 'comment, download_payload_rate, eta, hash, is_finished, is_seed, message, name, paused, progress, queue, state, total_size, upload_payload_rate');
  3037. return true;
  3038. } catch (Exception $e) {
  3039. return $e->getMessage();
  3040. }
  3041. } else {
  3042. return 'URL and/or Password not setup';
  3043. }
  3044. break;
  3045. case 'rtorrent':
  3046. if (!empty($GLOBALS['rTorrentURL']) || !empty($GLOBALS['rTorrentURLOverride'])) {
  3047. try {
  3048. $digest = (empty($GLOBALS['rTorrentURLOverride'])) ? qualifyURL($GLOBALS['rTorrentURL'], true) : qualifyURL(checkOverrideURL($GLOBALS['rTorrentURL'], $GLOBALS['rTorrentURLOverride']), true);
  3049. $passwordInclude = ($GLOBALS['rTorrentUsername'] !== '' && $GLOBALS['rTorrentPassword'] !== '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  3050. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  3051. $extraPath = (empty($GLOBALS['rTorrentURLOverride'])) ? $extraPath : '';
  3052. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  3053. $options = (localURL($url, $GLOBALS['rTorrentDisableCertCheck'])) ? array('verify' => false) : array();
  3054. if ($GLOBALS['rTorrentUsername'] !== '' && decrypt($GLOBALS['rTorrentPassword']) !== '') {
  3055. $credentials = array('auth' => new Requests_Auth_Digest(array($GLOBALS['rTorrentUsername'], decrypt($GLOBALS['rTorrentPassword']))));
  3056. $options = array_merge($options, $credentials);
  3057. }
  3058. $data = xmlrpc_encode_request("system.listMethods", null);
  3059. $response = Requests::post($url, array(), $data, $options);
  3060. if ($response->success) {
  3061. $methods = xmlrpc_decode(str_replace('i8>', 'i4>', $response->body));
  3062. if (count($methods) !== 0) {
  3063. return true;
  3064. }
  3065. }
  3066. return false;
  3067. } catch
  3068. (Requests_Exception $e) {
  3069. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  3070. return $e->getMessage();
  3071. };
  3072. }
  3073. break;
  3074. case 'ldap_login':
  3075. $username = $array['data']['data']['username'];
  3076. $password = $array['data']['data']['password'];
  3077. if (empty($username) || empty($password)) {
  3078. return 'Missing Username or Password';
  3079. }
  3080. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  3081. $ad = new \Adldap\Adldap();
  3082. // Create a configuration array.
  3083. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  3084. $i = 0;
  3085. foreach ($ldapServers as $key => $value) {
  3086. // Calculate parts
  3087. $digest = parse_url(trim($value));
  3088. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  3089. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  3090. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  3091. // Reassign
  3092. $ldapHosts[] = $host;
  3093. $ldapServersNew[$key] = $scheme . '://' . $host . ':' . $port; // May use this later
  3094. if ($i == 0) {
  3095. $ldapPort = $port;
  3096. }
  3097. $i++;
  3098. }
  3099. $config = [
  3100. // Mandatory Configuration Options
  3101. 'hosts' => $ldapHosts,
  3102. 'base_dn' => $GLOBALS['authBaseDN'],
  3103. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  3104. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  3105. // Optional Configuration Options
  3106. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  3107. 'account_prefix' => (empty($GLOBALS['authBackendHostPrefix'])) ? null : $GLOBALS['authBackendHostPrefix'],
  3108. 'account_suffix' => (empty($GLOBALS['authBackendHostSuffix'])) ? null : $GLOBALS['authBackendHostSuffix'],
  3109. 'port' => $ldapPort,
  3110. 'follow_referrals' => false,
  3111. 'use_ssl' => $GLOBALS['ldapSSL'],
  3112. 'use_tls' => $GLOBALS['ldapTLS'],
  3113. 'version' => 3,
  3114. 'timeout' => 5,
  3115. // Custom LDAP Options
  3116. 'custom_options' => [
  3117. // See: http://php.net/ldap_set_option
  3118. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  3119. ]
  3120. ];
  3121. // Add a connection provider to Adldap.
  3122. $ad->addProvider($config);
  3123. try {
  3124. // If a successful connection is made to your server, the provider will be returned.
  3125. $provider = $ad->connect();
  3126. //prettyPrint($provider);
  3127. if ($provider->auth()->attempt($username, $password, true)) {
  3128. // Passed.
  3129. $user = $provider->search()->find($username);
  3130. //return $user->getFirstAttribute('cn');
  3131. //return $user->getGroups(['cn']);
  3132. //return $user;
  3133. //return $user->getUserPrincipalName();
  3134. //return $user->getGroups(['cn']);
  3135. return true;
  3136. } else {
  3137. // Failed.
  3138. return 'Username/Password Failed to authenticate';
  3139. }
  3140. } catch (\Adldap\Auth\BindException $e) {
  3141. $detailedError = $e->getDetailedError();
  3142. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  3143. return $detailedError->getErrorMessage();
  3144. // There was an issue binding / connecting to the server.
  3145. } catch (Adldap\Auth\UsernameRequiredException $e) {
  3146. $detailedError = $e->getDetailedError();
  3147. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  3148. return $detailedError->getErrorMessage();
  3149. // The user didn't supply a username.
  3150. } catch (Adldap\Auth\PasswordRequiredException $e) {
  3151. $detailedError = $e->getDetailedError();
  3152. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  3153. return $detailedError->getErrorMessage();
  3154. // The user didn't supply a password.
  3155. }
  3156. }
  3157. break;
  3158. case 'ldap':
  3159. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  3160. $ad = new \Adldap\Adldap();
  3161. // Create a configuration array.
  3162. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  3163. $i = 0;
  3164. foreach ($ldapServers as $key => $value) {
  3165. // Calculate parts
  3166. $digest = parse_url(trim($value));
  3167. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  3168. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  3169. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  3170. // Reassign
  3171. $ldapHosts[] = $host;
  3172. if ($i == 0) {
  3173. $ldapPort = $port;
  3174. }
  3175. $i++;
  3176. }
  3177. $config = [
  3178. // Mandatory Configuration Options
  3179. 'hosts' => $ldapHosts,
  3180. 'base_dn' => $GLOBALS['authBaseDN'],
  3181. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  3182. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  3183. // Optional Configuration Options
  3184. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  3185. 'account_prefix' => '',
  3186. 'account_suffix' => '',
  3187. 'port' => $ldapPort,
  3188. 'follow_referrals' => false,
  3189. 'use_ssl' => $GLOBALS['ldapSSL'],
  3190. 'use_tls' => $GLOBALS['ldapTLS'],
  3191. 'version' => 3,
  3192. 'timeout' => 5,
  3193. // Custom LDAP Options
  3194. 'custom_options' => [
  3195. // See: http://php.net/ldap_set_option
  3196. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  3197. ]
  3198. ];
  3199. // Add a connection provider to Adldap.
  3200. $ad->addProvider($config);
  3201. try {
  3202. // If a successful connection is made to your server, the provider will be returned.
  3203. $provider = $ad->connect();
  3204. } catch (\Adldap\Auth\BindException $e) {
  3205. $detailedError = $e->getDetailedError();
  3206. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), 'SYSTEM');
  3207. return $detailedError->getErrorMessage();
  3208. // There was an issue binding / connecting to the server.
  3209. }
  3210. return ($provider) ? true : false;
  3211. }
  3212. return false;
  3213. break;
  3214. default :
  3215. return false;
  3216. }
  3217. return false;
  3218. }