4
0

homepage-connect-functions.php 129 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262
  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 = (strpos($GLOBALS['embyURL'], 'jellyfin') !== false) ? $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 = true;
  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. $torrents = array();
  1022. $digest = (empty($GLOBALS['rTorrentURLOverride'])) ? qualifyURL($GLOBALS['rTorrentURL'], true) : qualifyURL(checkOverrideURL($GLOBALS['rTorrentURL'], $GLOBALS['rTorrentURLOverride']), true);
  1023. $passwordInclude = ($GLOBALS['rTorrentUsername'] !== '' && $GLOBALS['rTorrentPassword'] !== '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  1024. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  1025. $extraPath = (empty($GLOBALS['rTorrentURLOverride'])) ? $extraPath : '';
  1026. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  1027. $options = (localURL($url, $GLOBALS['rTorrentDisableCertCheck'])) ? array('verify' => false) : array();
  1028. if ($GLOBALS['rTorrentUsername'] !== '' && decrypt($GLOBALS['rTorrentPassword']) !== '') {
  1029. $credentials = array('auth' => new Requests_Auth_Digest(array($GLOBALS['rTorrentUsername'], decrypt($GLOBALS['rTorrentPassword']))));
  1030. $options = array_merge($options, $credentials);
  1031. }
  1032. $data = xmlrpc_encode_request("d.multicall2", array(
  1033. "",
  1034. "main",
  1035. "d.name=",
  1036. "d.base_path=",
  1037. "d.up.total=",
  1038. "d.size_bytes=",
  1039. "d.down.total=",
  1040. "d.completed_bytes=",
  1041. "d.connection_current=",
  1042. "d.down.rate=",
  1043. "d.up.rate=",
  1044. "d.timestamp.started=",
  1045. "d.state=",
  1046. "d.group.name=",
  1047. "d.hash=",
  1048. "d.complete=",
  1049. "d.ratio=",
  1050. "d.chunk_size=",
  1051. "f.size_bytes=",
  1052. "f.size_chunks=",
  1053. "f.completed_chunks=",
  1054. "d.custom=",
  1055. "d.custom1=",
  1056. "d.custom2=",
  1057. "d.custom3=",
  1058. "d.custom4=",
  1059. "d.custom5=",
  1060. ), array());
  1061. $response = Requests::post($url, array(), $data, $options);
  1062. if ($response->success) {
  1063. $torrentList = xmlrpc_decode(str_replace('i8>', 'string>', $response->body));
  1064. foreach ($torrentList as $key => $value) {
  1065. $tempStatus = rTorrentStatus($value[13], $value[10], $value[6]);
  1066. if ($tempStatus == 'Seeding' && $GLOBALS['rTorrentHideSeeding']) {
  1067. //do nothing
  1068. } elseif ($tempStatus == 'Finished' && $GLOBALS['rTorrentHideCompleted']) {
  1069. //do nothing
  1070. } else {
  1071. $torrents[$key] = array(
  1072. 'name' => $value[0],
  1073. 'base' => $value[1],
  1074. 'upTotal' => $value[2],
  1075. 'size' => $value[3],
  1076. 'downTotal' => $value[4],
  1077. 'downloaded' => $value[5],
  1078. 'connectionState' => $value[6],
  1079. 'leech' => $value[7],
  1080. 'seed' => $value[8],
  1081. 'date' => $value[9],
  1082. 'state' => ($value[10]) ? 'on' : 'off',
  1083. 'group' => $value[11],
  1084. 'hash' => $value[12],
  1085. 'complete' => ($value[13]) ? 'yes' : 'no',
  1086. 'ratio' => $value[14],
  1087. 'label' => $value[20],
  1088. 'status' => $tempStatus,
  1089. 'temp' => $value[16] . ' - ' . $value[17] . ' - ' . $value[18],
  1090. 'custom' => $value[19] . ' - ' . $value[20] . ' - ' . $value[21],
  1091. 'custom2' => $value[22] . ' - ' . $value[23] . ' - ' . $value[24],
  1092. );
  1093. }
  1094. }
  1095. if (count($torrents) !== 0) {
  1096. usort($torrents, function ($a, $b) {
  1097. $direction = substr($GLOBALS['rTorrentSortOrder'], -1);
  1098. $sort = substr($GLOBALS['rTorrentSortOrder'], 0, strlen($GLOBALS['rTorrentSortOrder']) - 1);
  1099. switch ($direction) {
  1100. case 'a':
  1101. return $a[$sort] <=> $b[$sort];
  1102. break;
  1103. case 'd':
  1104. return $b[$sort] <=> $a[$sort];
  1105. break;
  1106. default:
  1107. return $b['date'] <=> $a['date'];
  1108. }
  1109. });
  1110. }
  1111. $api['content']['queueItems'] = $torrents;
  1112. $api['content']['historyItems'] = false;
  1113. }
  1114. } catch
  1115. (Requests_Exception $e) {
  1116. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1117. };
  1118. $api['content'] = isset($api['content']) ? $api['content'] : false;
  1119. return $api;
  1120. }
  1121. return false;
  1122. }
  1123. function qBittorrentConnect()
  1124. {
  1125. if ($GLOBALS['homepageqBittorrentEnabled'] && !empty($GLOBALS['qBittorrentURL']) && qualifyRequest($GLOBALS['homepageqBittorrentAuth'])) {
  1126. $digest = qualifyURL($GLOBALS['qBittorrentURL'], true);
  1127. $data = array('username' => $GLOBALS['qBittorrentUsername'], 'password' => decrypt($GLOBALS['qBittorrentPassword']));
  1128. $apiVersionLogin = ($GLOBALS['qBittorrentApiVersion'] == '1') ? '/login' : '/api/v2/auth/login';
  1129. $apiVersionQuery = ($GLOBALS['qBittorrentApiVersion'] == '1') ? '/query/torrents?sort=' : '/api/v2/torrents/info?sort=';
  1130. $url = $digest['scheme'] . '://' . $digest['host'] . $digest['port'] . $digest['path'] . $apiVersionLogin;
  1131. try {
  1132. $options = (localURL($GLOBALS['qBittorrentURL'])) ? array('verify' => false) : array();
  1133. $response = Requests::post($url, array(), $data, $options);
  1134. $reflection = new ReflectionClass($response->cookies);
  1135. $cookie = $reflection->getProperty("cookies");
  1136. $cookie->setAccessible(true);
  1137. $cookie = $cookie->getValue($response->cookies);
  1138. if ($cookie) {
  1139. $headers = array(
  1140. 'Cookie' => 'SID=' . $cookie['SID']->value
  1141. );
  1142. $reverse = $GLOBALS['qBittorrentReverseSorting'] ? 'true' : 'false';
  1143. $url = $digest['scheme'] . '://' . $digest['host'] . $digest['port'] . $digest['path'] . $apiVersionQuery . $GLOBALS['qBittorrentSortOrder'] . '&reverse=' . $reverse;
  1144. $response = Requests::get($url, $headers, $options);
  1145. if ($response) {
  1146. $torrentList = json_decode($response->body, true);
  1147. if ($GLOBALS['qBittorrentHideSeeding'] || $GLOBALS['qBittorrentHideCompleted']) {
  1148. $filter = array();
  1149. $torrents['arguments']['torrents'] = array();
  1150. if ($GLOBALS['qBittorrentHideSeeding']) {
  1151. array_push($filter, 'uploading', 'stalledUP', 'queuedUP');
  1152. }
  1153. if ($GLOBALS['qBittorrentHideCompleted']) {
  1154. array_push($filter, 'pausedUP');
  1155. }
  1156. foreach ($torrentList as $key => $value) {
  1157. if (!in_array($value['state'], $filter)) {
  1158. $torrents['arguments']['torrents'][] = $value;
  1159. }
  1160. }
  1161. } else {
  1162. $torrents['arguments']['torrents'] = json_decode($response->body, true);
  1163. }
  1164. $api['content']['queueItems'] = $torrents;
  1165. $api['content']['historyItems'] = false;
  1166. }
  1167. } else {
  1168. writeLog('error', 'qBittorrent Connect Function - Error: Could not get session ID', 'SYSTEM');
  1169. }
  1170. } catch (Requests_Exception $e) {
  1171. writeLog('error', 'qBittorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1172. };
  1173. $api['content'] = isset($api['content']) ? $api['content'] : false;
  1174. return $api;
  1175. }
  1176. return false;
  1177. }
  1178. function delugeStatus($queued, $status, $state)
  1179. {
  1180. if ($queued == '-1' && $state == '100' && ($status == 'Seeding' || $status == 'Queued' || $status == 'Paused')) {
  1181. $state = 'Seeding';
  1182. } elseif ($state !== '100') {
  1183. $state = 'Downloading';
  1184. } else {
  1185. $state = 'Finished';
  1186. }
  1187. return ($state) ? $state : $status;
  1188. }
  1189. function delugeConnect()
  1190. {
  1191. if ($GLOBALS['homepageDelugeEnabled'] && !empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword']) && qualifyRequest($GLOBALS['homepageDelugeAuth'])) {
  1192. try {
  1193. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  1194. $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');
  1195. foreach ($torrents as $key => $value) {
  1196. $tempStatus = delugeStatus($value->queue, $value->state, $value->progress);
  1197. if ($tempStatus == 'Seeding' && $GLOBALS['delugeHideSeeding']) {
  1198. //do nothing
  1199. } elseif ($tempStatus == 'Finished' && $GLOBALS['delugeHideCompleted']) {
  1200. //do nothing
  1201. } else {
  1202. $api['content']['queueItems'][] = $value;
  1203. }
  1204. }
  1205. $api['content']['queueItems'] = (empty($api['content']['queueItems'])) ? [] : $api['content']['queueItems'];
  1206. $api['content']['historyItems'] = false;
  1207. } catch (Excecption $e) {
  1208. writeLog('error', 'Deluge Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1209. }
  1210. }
  1211. $api['content'] = isset($api['content']) ? $api['content'] : false;
  1212. return $api;
  1213. }
  1214. function getCalendar()
  1215. {
  1216. $startDate = date('Y-m-d', strtotime("-" . $GLOBALS['calendarStart'] . " days"));
  1217. $endDate = date('Y-m-d', strtotime("+" . $GLOBALS['calendarEnd'] . " days"));
  1218. $icalCalendarSources = array();
  1219. $calendarItems = array();
  1220. // SONARR CONNECT
  1221. if ($GLOBALS['homepageSonarrEnabled'] && qualifyRequest($GLOBALS['homepageSonarrAuth']) && !empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  1222. $sonarrs = array();
  1223. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  1224. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  1225. if (count($sonarrURLList) == count($sonarrTokenList)) {
  1226. foreach ($sonarrURLList as $key => $value) {
  1227. $sonarrs[$key] = array(
  1228. 'url' => $value,
  1229. 'token' => $sonarrTokenList[$key]
  1230. );
  1231. }
  1232. foreach ($sonarrs as $key => $value) {
  1233. try {
  1234. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  1235. $sonarr = $sonarr->getCalendar($startDate, $endDate, $GLOBALS['sonarrUnmonitored']);
  1236. $result = json_decode($sonarr, true);
  1237. if (is_array($result) || is_object($result)) {
  1238. $sonarrCalendar = (array_key_exists('error', $result)) ? '' : getSonarrCalendar($sonarr, $key);
  1239. } else {
  1240. $sonarrCalendar = '';
  1241. }
  1242. } catch (Exception $e) {
  1243. writeLog('error', 'Sonarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1244. }
  1245. if (!empty($sonarrCalendar)) {
  1246. $calendarItems = array_merge($calendarItems, $sonarrCalendar);
  1247. }
  1248. }
  1249. }
  1250. }
  1251. // LIDARR CONNECT
  1252. if ($GLOBALS['homepageLidarrEnabled'] && qualifyRequest($GLOBALS['homepageLidarrAuth']) && !empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  1253. $lidarrs = array();
  1254. $lidarrURLList = explode(',', $GLOBALS['lidarrURL']);
  1255. $lidarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  1256. if (count($lidarrURLList) == count($lidarrTokenList)) {
  1257. foreach ($lidarrURLList as $key => $value) {
  1258. $lidarrs[$key] = array(
  1259. 'url' => $value,
  1260. 'token' => $lidarrTokenList[$key]
  1261. );
  1262. }
  1263. foreach ($lidarrs as $key => $value) {
  1264. try {
  1265. $lidarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  1266. $lidarr = $lidarr->getCalendar($startDate, $endDate);
  1267. $result = json_decode($lidarr, true);
  1268. if (is_array($result) || is_object($result)) {
  1269. $lidarrCalendar = (array_key_exists('error', $result)) ? '' : getLidarrCalendar($lidarr, $key);
  1270. } else {
  1271. $lidarrCalendar = '';
  1272. }
  1273. } catch (Exception $e) {
  1274. writeLog('error', 'Lidarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1275. }
  1276. if (!empty($lidarrCalendar)) {
  1277. $calendarItems = array_merge($calendarItems, $lidarrCalendar);
  1278. }
  1279. }
  1280. }
  1281. }
  1282. // RADARR CONNECT
  1283. if ($GLOBALS['homepageRadarrEnabled'] && qualifyRequest($GLOBALS['homepageRadarrAuth']) && !empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  1284. $radarrs = array();
  1285. $radarrURLList = explode(',', $GLOBALS['radarrURL']);
  1286. $radarrTokenList = explode(',', $GLOBALS['radarrToken']);
  1287. if (count($radarrURLList) == count($radarrTokenList)) {
  1288. foreach ($radarrURLList as $key => $value) {
  1289. $radarrs[$key] = array(
  1290. 'url' => $value,
  1291. 'token' => $radarrTokenList[$key]
  1292. );
  1293. }
  1294. foreach ($radarrs as $key => $value) {
  1295. try {
  1296. $radarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  1297. $radarr = $radarr->getCalendar($startDate, $endDate);
  1298. $result = json_decode($radarr, true);
  1299. if (is_array($result) || is_object($result)) {
  1300. $radarrCalendar = (array_key_exists('error', $result)) ? '' : getRadarrCalendar($radarr, $key, $value['url']);
  1301. } else {
  1302. $radarrCalendar = '';
  1303. }
  1304. } catch (Exception $e) {
  1305. writeLog('error', 'Radarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1306. }
  1307. if (!empty($radarrCalendar)) {
  1308. $calendarItems = array_merge($calendarItems, $radarrCalendar);
  1309. }
  1310. }
  1311. }
  1312. }
  1313. // SICKRAGE/BEARD/MEDUSA CONNECT
  1314. if ($GLOBALS['homepageSickrageEnabled'] && qualifyRequest($GLOBALS['homepageSickrageAuth']) && !empty($GLOBALS['sickrageURL']) && !empty($GLOBALS['sickrageToken'])) {
  1315. $sicks = array();
  1316. $sickURLList = explode(',', $GLOBALS['sickrageURL']);
  1317. $sickTokenList = explode(',', $GLOBALS['sickrageToken']);
  1318. if (count($sickURLList) == count($sickTokenList)) {
  1319. foreach ($sickURLList as $key => $value) {
  1320. $sicks[$key] = array(
  1321. 'url' => $value,
  1322. 'token' => $sickTokenList[$key]
  1323. );
  1324. }
  1325. foreach ($sicks as $key => $value) {
  1326. try {
  1327. $sickrage = new Kryptonit3\SickRage\SickRage($value['url'], $value['token']);
  1328. $sickrageFuture = getSickrageCalendarWanted($sickrage->future(), $key);
  1329. $sickrageHistory = getSickrageCalendarHistory($sickrage->history("100", "downloaded"), $key);
  1330. if (!empty($sickrageFuture)) {
  1331. $calendarItems = array_merge($calendarItems, $sickrageFuture);
  1332. }
  1333. if (!empty($sickrageHistory)) {
  1334. $calendarItems = array_merge($calendarItems, $sickrageHistory);
  1335. }
  1336. } catch (Exception $e) {
  1337. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1338. }
  1339. }
  1340. }
  1341. }
  1342. // COUCHPOTATO CONNECT
  1343. if ($GLOBALS['homepageCouchpotatoEnabled'] && qualifyRequest($GLOBALS['homepageCouchpotatoAuth']) && !empty($GLOBALS['couchpotatoURL']) && !empty($GLOBALS['couchpotatoToken'])) {
  1344. $couchs = array();
  1345. $couchpotatoURLList = explode(',', $GLOBALS['couchpotatoURL']);
  1346. $couchpotatoTokenList = explode(',', $GLOBALS['couchpotatoToken']);
  1347. if (count($couchpotatoURLList) == count($couchpotatoTokenList)) {
  1348. foreach ($couchpotatoURLList as $key => $value) {
  1349. $couchs[$key] = array(
  1350. 'url' => $value,
  1351. 'token' => $couchpotatoTokenList[$key]
  1352. );
  1353. }
  1354. foreach ($couchs as $key => $value) {
  1355. try {
  1356. $couchpotato = new Kryptonit3\CouchPotato\CouchPotato($value['url'], $value['token']);
  1357. $couchCalendar = getCouchCalendar($couchpotato->getMediaList(), $key);
  1358. if (!empty($couchCalendar)) {
  1359. $calendarItems = array_merge($calendarItems, $couchCalendar);
  1360. }
  1361. } catch (Exception $e) {
  1362. writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  1363. }
  1364. }
  1365. }
  1366. }
  1367. // iCal URL
  1368. if ($GLOBALS['homepageCalendarEnabled'] && qualifyRequest($GLOBALS['homepageCalendarAuth']) && !empty($GLOBALS['calendariCal'])) {
  1369. $calendars = array();
  1370. $calendarURLList = explode(',', $GLOBALS['calendariCal']);
  1371. $icalEvents = array();
  1372. foreach ($calendarURLList as $key => $value) {
  1373. $icsEvents = getIcsEventsAsArray($value);
  1374. if (isset($icsEvents) && !empty($icsEvents)) {
  1375. $timeZone = isset($icsEvents [1] ['X-WR-TIMEZONE']) ? trim($icsEvents[1]['X-WR-TIMEZONE']) : date_default_timezone_get();
  1376. $originalTimeZone = isset($icsEvents [1] ['X-WR-TIMEZONE']) ? str_replace('"', '', trim($icsEvents[1]['X-WR-TIMEZONE'])) : false;
  1377. unset($icsEvents [1]);
  1378. foreach ($icsEvents as $icsEvent) {
  1379. $startKeys = array_filter_key($icsEvent, function ($key) {
  1380. return strpos($key, 'DTSTART') === 0;
  1381. });
  1382. $endKeys = array_filter_key($icsEvent, function ($key) {
  1383. return strpos($key, 'DTEND') === 0;
  1384. });
  1385. if (!empty($startKeys) && !empty($endKeys) && isset($icsEvent['SUMMARY'])) {
  1386. /* Getting start date and time */
  1387. $repeat = isset($icsEvent ['RRULE']) ? $icsEvent ['RRULE'] : false;
  1388. if (!$originalTimeZone) {
  1389. $tzKey = array_keys($startKeys);
  1390. if (strpos($tzKey[0], 'TZID=') !== false) {
  1391. $originalTimeZone = explode('TZID=', (string)$tzKey[0]);
  1392. $originalTimeZone = (count($originalTimeZone) >= 2) ? str_replace('"', '', $originalTimeZone[1]) : false;
  1393. }
  1394. }
  1395. $start = reset($startKeys);
  1396. $end = reset($endKeys);
  1397. $totalDays = $GLOBALS['calendarStart'] + $GLOBALS['calendarEnd'];
  1398. if ($repeat) {
  1399. $repeatOverride = getCalenderRepeatCount(trim($icsEvent["RRULE"]));
  1400. switch (trim(strtolower(getCalenderRepeat($repeat)))) {
  1401. case 'daily':
  1402. $repeat = ($repeatOverride) ? $repeatOverride : $totalDays;
  1403. $term = 'days';
  1404. break;
  1405. case 'weekly':
  1406. $repeat = ($repeatOverride) ? $repeatOverride : round($totalDays / 7);
  1407. $term = 'weeks';
  1408. break;
  1409. case 'monthly':
  1410. $repeat = ($repeatOverride) ? $repeatOverride : round($totalDays / 30);
  1411. $term = 'months';
  1412. break;
  1413. case 'yearly':
  1414. $repeat = ($repeatOverride) ? $repeatOverride : round($totalDays / 365);
  1415. $term = 'years';
  1416. break;
  1417. default:
  1418. $repeat = ($repeatOverride) ? $repeatOverride : $totalDays;
  1419. $term = 'days';
  1420. break;
  1421. }
  1422. } else {
  1423. $repeat = 1;
  1424. $term = 'day';
  1425. }
  1426. $calendarTimes = 0;
  1427. while ($calendarTimes < $repeat) {
  1428. $currentDate = new DateTime ($GLOBALS['currentTime']);
  1429. $oldestDay = new DateTime ($GLOBALS['currentTime']);
  1430. $oldestDay->modify('-' . $GLOBALS['calendarStart'] . ' days');
  1431. $newestDay = new DateTime ($GLOBALS['currentTime']);
  1432. $newestDay->modify('+' . $GLOBALS['calendarEnd'] . ' days');
  1433. /* Converting to datetime and apply the timezone to get proper date time */
  1434. $startDt = new DateTime ($start);
  1435. /* Getting end date with time */
  1436. $endDt = new DateTime ($end);
  1437. if ($calendarTimes !== 0) {
  1438. $dateDiff = date_diff($startDt, $currentDate);
  1439. $startDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1440. $startDt->modify('+' . $calendarTimes . ' ' . $term);
  1441. $endDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1442. $endDt->modify('+' . $calendarTimes . ' ' . $term);
  1443. } elseif ($calendarTimes == 0 && $repeat !== 1) {
  1444. $dateDiff = date_diff($startDt, $currentDate);
  1445. $startDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1446. $endDt->modify($dateDiff->format('%R') . (round(($dateDiff->days) / 7)) . ' weeks');
  1447. }
  1448. $calendarStartDiff = date_diff($startDt, $newestDay);
  1449. $calendarEndDiff = date_diff($startDt, $oldestDay);
  1450. if ($originalTimeZone && $originalTimeZone !== 'UTC' && (strpos($start, 'Z') == false)) {
  1451. $originalTimeZone = calendarStandardizeTimezone($originalTimeZone);
  1452. $dateTimeOriginalTZ = new DateTimeZone($originalTimeZone);
  1453. $dateTimeOriginal = new DateTime('now', $dateTimeOriginalTZ);
  1454. $dateTimeUTCTZ = new DateTimeZone(date_default_timezone_get());
  1455. $dateTimeUTC = new DateTime('now', $dateTimeUTCTZ);
  1456. $dateTimeOriginalOffset = $dateTimeOriginal->getOffset() / 3600;
  1457. $dateTimeUTCOffset = $dateTimeUTC->getOffset() / 3600;
  1458. $diff = $dateTimeUTCOffset - $dateTimeOriginalOffset;
  1459. $startDt->modify('+ ' . $diff . ' hour');
  1460. $endDt->modify('+ ' . $diff . ' hour');
  1461. }
  1462. $startDt->setTimeZone(new DateTimezone ($timeZone));
  1463. $endDt->setTimeZone(new DateTimezone ($timeZone));
  1464. $startDate = $startDt->format(DateTime::ATOM);
  1465. $endDate = $endDt->format(DateTime::ATOM);
  1466. if (new DateTime() < $endDt) {
  1467. $extraClass = 'text-info';
  1468. } else {
  1469. $extraClass = 'text-success';
  1470. }
  1471. /* Getting the name of event */
  1472. $eventName = $icsEvent['SUMMARY'];
  1473. if (!calendarDaysCheck($calendarStartDiff->format('%R') . $calendarStartDiff->days, $calendarEndDiff->format('%R') . $calendarEndDiff->days)) {
  1474. break;
  1475. }
  1476. if (isset($icsEvent["RRULE"]) && getCalenderRepeatUntil(trim($icsEvent["RRULE"]))) {
  1477. $untilDate = new DateTime (getCalenderRepeatUntil(trim($icsEvent["RRULE"])));
  1478. $untilDiff = date_diff($currentDate, $untilDate);
  1479. if ($untilDiff->days > 0) {
  1480. break;
  1481. }
  1482. }
  1483. $icalEvents[] = array(
  1484. 'title' => $eventName,
  1485. 'imagetype' => 'calendar-o text-warning text-custom-calendar ' . $extraClass,
  1486. 'imagetypeFilter' => 'ical',
  1487. 'className' => 'bg-calendar calendar-item bg-custom-calendar',
  1488. 'start' => $startDate,
  1489. 'end' => $endDate,
  1490. 'bgColor' => str_replace('text', 'bg', $extraClass),
  1491. );
  1492. $calendarTimes = $calendarTimes + 1;
  1493. }
  1494. }
  1495. }
  1496. }
  1497. }
  1498. $calendarSources['ical'] = $icalEvents;
  1499. }
  1500. $calendarSources['events'] = $calendarItems;
  1501. return ($calendarSources) ? $calendarSources : false;
  1502. }
  1503. function calendarDaysCheck($entryStart, $entryEnd)
  1504. {
  1505. $success = false;
  1506. $entryStart = intval($entryStart);
  1507. $entryEnd = intval($entryEnd);
  1508. if ($entryStart >= 0 && $entryEnd <= 0) {
  1509. $success = true;
  1510. }
  1511. return $success;
  1512. }
  1513. function calendarStandardizeTimezone($timezone)
  1514. {
  1515. switch ($timezone) {
  1516. case('CST'):
  1517. case('Central Time'):
  1518. case('Central Standard Time'):
  1519. $timezone = 'America/Chicago';
  1520. break;
  1521. case('CET'):
  1522. case('Central European Time'):
  1523. $timezone = 'Europe/Berlin';
  1524. break;
  1525. case('EST'):
  1526. case('Eastern Time'):
  1527. case('Eastern Standard Time'):
  1528. $timezone = 'America/New_York';
  1529. break;
  1530. case('PST'):
  1531. case('Pacific Time'):
  1532. case('Pacific Standard Time'):
  1533. $timezone = 'America/Los_Angeles';
  1534. break;
  1535. case('China Time'):
  1536. case('China Standard Time'):
  1537. $timezone = 'Asia/Beijing';
  1538. break;
  1539. case('IST'):
  1540. case('India Time'):
  1541. case('India Standard Time'):
  1542. $timezone = 'Asia/New_Delhi';
  1543. break;
  1544. case('JST');
  1545. case('Japan Time'):
  1546. case('Japan Standard Time'):
  1547. $timezone = 'Asia/Tokyo';
  1548. break;
  1549. }
  1550. return $timezone;
  1551. }
  1552. function getCalenderRepeat($value)
  1553. {
  1554. //FREQ=DAILY
  1555. //RRULE:FREQ=WEEKLY;BYDAY=TH
  1556. $first = explode('=', $value);
  1557. if (count($first) > 1) {
  1558. $second = explode(';', $first[1]);
  1559. } else {
  1560. return $value;
  1561. }
  1562. if ($second) {
  1563. return $second[0];
  1564. } else {
  1565. return $first[1];
  1566. }
  1567. }
  1568. function getCalenderRepeatUntil($value)
  1569. {
  1570. $first = explode('UNTIL=', $value);
  1571. if (count($first) > 1) {
  1572. if (strpos($first[1], ';') !== false) {
  1573. $check = explode(';', $first[1]);
  1574. return $check[0];
  1575. } else {
  1576. return $first[1];
  1577. }
  1578. } else {
  1579. return false;
  1580. }
  1581. }
  1582. function getCalenderRepeatCount($value)
  1583. {
  1584. $first = explode('COUNT=', $value);
  1585. if (count($first) > 1) {
  1586. return $first[1];
  1587. } else {
  1588. return false;
  1589. }
  1590. }
  1591. function getSonarrCalendar($array, $number)
  1592. {
  1593. $array = json_decode($array, true);
  1594. $gotCalendar = array();
  1595. $i = 0;
  1596. foreach ($array as $child) {
  1597. $i++;
  1598. $seriesName = $child['series']['title'];
  1599. $seriesID = $child['series']['tvdbId'];
  1600. $episodeID = $child['series']['tvdbId'];
  1601. $monitored = $child['monitored'];
  1602. if (!isset($episodeID)) {
  1603. $episodeID = "";
  1604. }
  1605. //$episodeName = htmlentities($child['title'], ENT_QUOTES);
  1606. $episodeAirDate = $child['airDateUtc'];
  1607. $episodeAirDate = strtotime($episodeAirDate);
  1608. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1609. if (new DateTime() < new DateTime($episodeAirDate)) {
  1610. $unaired = true;
  1611. }
  1612. if ($child['episodeNumber'] == "1") {
  1613. $episodePremier = "true";
  1614. } else {
  1615. $episodePremier = "false";
  1616. $date = new DateTime($episodeAirDate);
  1617. $date->add(new DateInterval("PT1S"));
  1618. $date->format(DateTime::ATOM);
  1619. $child['airDateUtc'] = gmdate('Y-m-d\TH:i:s\Z', strtotime($date->format(DateTime::ATOM)));
  1620. }
  1621. $downloaded = $child['hasFile'];
  1622. if ($downloaded == "0" && isset($unaired) && $episodePremier == "true") {
  1623. $downloaded = "text-primary animated flash";
  1624. } elseif ($downloaded == "0" && isset($unaired) && $monitored == "0") {
  1625. $downloaded = "text-dark";
  1626. } elseif ($downloaded == "0" && isset($unaired)) {
  1627. $downloaded = "text-info";
  1628. } elseif ($downloaded == "1") {
  1629. $downloaded = "text-success";
  1630. } else {
  1631. $downloaded = "text-danger";
  1632. }
  1633. $fanart = "/plugins/images/cache/no-np.png";
  1634. foreach ($child['series']['images'] as $image) {
  1635. if ($image['coverType'] == "fanart") {
  1636. $fanart = $image['url'];
  1637. }
  1638. }
  1639. if ($fanart !== "/plugins/images/cache/no-np.png" || (strpos($fanart, '://') === false)) {
  1640. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1641. $imageURL = $fanart;
  1642. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1643. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1644. if (!file_exists($cacheFile)) {
  1645. cacheImage($imageURL, $seriesID);
  1646. unset($imageURL);
  1647. unset($cacheFile);
  1648. }
  1649. }
  1650. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  1651. $details = array(
  1652. "seasonCount" => $child['series']['seasonCount'],
  1653. "status" => $child['series']['status'],
  1654. "topTitle" => $seriesName,
  1655. "bottomTitle" => $bottomTitle,
  1656. "overview" => isset($child['overview']) ? $child['overview'] : '',
  1657. "runtime" => $child['series']['runtime'],
  1658. "image" => $fanart,
  1659. "ratings" => $child['series']['ratings']['value'],
  1660. "videoQuality" => $child["hasFile"] && isset($child['episodeFile']['quality']['quality']['name']) ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  1661. "audioChannels" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  1662. "audioCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  1663. "videoCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  1664. "size" => $child["hasFile"] && isset($child['episodeFile']['size']) ? $child['episodeFile']['size'] : "unknown",
  1665. "genres" => $child['series']['genres'],
  1666. );
  1667. array_push($gotCalendar, array(
  1668. "id" => "Sonarr-" . $number . "-" . $i,
  1669. "title" => $seriesName,
  1670. "start" => $child['airDateUtc'],
  1671. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1672. "imagetype" => "tv " . $downloaded,
  1673. "imagetypeFilter" => "tv",
  1674. "downloadFilter" => $downloaded,
  1675. "bgColor" => str_replace('text', 'bg', $downloaded),
  1676. "details" => $details
  1677. ));
  1678. }
  1679. if ($i != 0) {
  1680. return $gotCalendar;
  1681. }
  1682. return false;
  1683. }
  1684. function getLidarrCalendar($array, $number)
  1685. {
  1686. $array = json_decode($array, true);
  1687. $gotCalendar = array();
  1688. $i = 0;
  1689. foreach ($array as $child) {
  1690. $i++;
  1691. $albumName = $child['title'];
  1692. $artistName = $child['artist']['artistName'];
  1693. $albumID = '';
  1694. $releaseDate = $child['releaseDate'];
  1695. $releaseDate = strtotime($releaseDate);
  1696. $releaseDate = date("Y-m-d H:i:s", $releaseDate);
  1697. if (new DateTime() < new DateTime($releaseDate)) {
  1698. $unaired = true;
  1699. }
  1700. if (isset($child['statistics']['percentOfTracks'])) {
  1701. if ($child['statistics']['percentOfTracks'] == '100.0') {
  1702. $downloaded = '1';
  1703. } else {
  1704. $downloaded = '0';
  1705. }
  1706. } else {
  1707. $downloaded = '0';
  1708. }
  1709. if ($downloaded == "0" && isset($unaired)) {
  1710. $downloaded = "text-info";
  1711. } elseif ($downloaded == "1") {
  1712. $downloaded = "text-success";
  1713. } else {
  1714. $downloaded = "text-danger";
  1715. }
  1716. $fanart = "/plugins/images/cache/no-np.png";
  1717. foreach ($child['artist']['images'] as $image) {
  1718. if ($image['coverType'] == "fanart") {
  1719. $fanart = str_replace('http://', 'https://', $image['url']);
  1720. }
  1721. }
  1722. $details = array(
  1723. "seasonCount" => '',
  1724. "status" => '',
  1725. "topTitle" => $albumName,
  1726. "bottomTitle" => $artistName,
  1727. "overview" => isset($child['artist']['overview']) ? $child['artist']['overview'] : '',
  1728. "runtime" => '',
  1729. "image" => $fanart,
  1730. "ratings" => $child['artist']['ratings']['value'],
  1731. "videoQuality" => "unknown",
  1732. "audioChannels" => "unknown",
  1733. "audioCodec" => "unknown",
  1734. "videoCodec" => "unknown",
  1735. "size" => "unknown",
  1736. "genres" => $child['genres'],
  1737. );
  1738. array_push($gotCalendar, array(
  1739. "id" => "Lidarr-" . $number . "-" . $i,
  1740. "title" => $artistName,
  1741. "start" => $child['releaseDate'],
  1742. "className" => "inline-popups bg-calendar calendar-item musicID--",
  1743. "imagetype" => "music " . $downloaded,
  1744. "imagetypeFilter" => "music",
  1745. "downloadFilter" => $downloaded,
  1746. "bgColor" => str_replace('text', 'bg', $downloaded),
  1747. "details" => $details,
  1748. "data" => $child
  1749. ));
  1750. }
  1751. if ($i != 0) {
  1752. return $gotCalendar;
  1753. }
  1754. return false;
  1755. }
  1756. function getRadarrCalendar($array, $number, $url)
  1757. {
  1758. $url = rtrim($url, '/'); //remove trailing slash
  1759. $url = $url . '/api';
  1760. $array = json_decode($array, true);
  1761. $gotCalendar = array();
  1762. $i = 0;
  1763. foreach ($array as $child) {
  1764. if (isset($child['physicalRelease'])) {
  1765. $i++;
  1766. $movieName = $child['title'];
  1767. $movieID = $child['tmdbId'];
  1768. if (!isset($movieID)) {
  1769. $movieID = "";
  1770. }
  1771. $physicalRelease = $child['physicalRelease'];
  1772. $physicalRelease = strtotime($physicalRelease);
  1773. $physicalRelease = date("Y-m-d", $physicalRelease);
  1774. if (new DateTime() < new DateTime($physicalRelease)) {
  1775. $notReleased = "true";
  1776. } else {
  1777. $notReleased = "false";
  1778. }
  1779. $downloaded = $child['hasFile'];
  1780. if ($downloaded == "0" && $notReleased == "true") {
  1781. $downloaded = "text-info";
  1782. } elseif ($downloaded == "1") {
  1783. $downloaded = "text-success";
  1784. } else {
  1785. $downloaded = "text-danger";
  1786. }
  1787. $banner = "/plugins/images/cache/no-np.png";
  1788. foreach ($child['images'] as $image) {
  1789. if ($image['coverType'] == "banner" || $image['coverType'] == "fanart") {
  1790. if (strpos($image['url'], '://') === false) {
  1791. $imageUrl = $image['url'];
  1792. $urlParts = explode("/", $url);
  1793. $imageParts = explode("/", $image['url']);
  1794. if ($imageParts[1] == end($urlParts)) {
  1795. unset($imageParts[1]);
  1796. $imageUrl = implode("/", $imageParts);
  1797. }
  1798. $banner = $url . $imageUrl . '?apikey=' . $GLOBALS['radarrToken'];
  1799. } else {
  1800. $banner = $image['url'];
  1801. }
  1802. }
  1803. }
  1804. if ($banner !== "/plugins/images/cache/no-np.png" || (strpos($banner, 'apikey') !== false)) {
  1805. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1806. $imageURL = $banner;
  1807. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1808. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1809. if (!file_exists($cacheFile)) {
  1810. cacheImage($imageURL, $movieID);
  1811. unset($imageURL);
  1812. unset($cacheFile);
  1813. }
  1814. }
  1815. $alternativeTitles = "";
  1816. foreach ($child['alternativeTitles'] as $alternative) {
  1817. $alternativeTitles .= $alternative['title'] . ', ';
  1818. }
  1819. $alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
  1820. $details = array(
  1821. "topTitle" => $movieName,
  1822. "bottomTitle" => $alternativeTitles,
  1823. "status" => $child['status'],
  1824. "overview" => $child['overview'],
  1825. "runtime" => $child['runtime'],
  1826. "image" => $banner,
  1827. "ratings" => $child['ratings']['value'],
  1828. "videoQuality" => $child["hasFile"] ? @$child['movieFile']['quality']['quality']['name'] : "unknown",
  1829. "audioChannels" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
  1830. "audioCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
  1831. "videoCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
  1832. "size" => $child["hasFile"] ? @$child['movieFile']['size'] : "unknown",
  1833. "genres" => $child['genres'],
  1834. "year" => isset($child['year']) ? $child['year'] : '',
  1835. "studio" => isset($child['studio']) ? $child['studio'] : '',
  1836. );
  1837. array_push($gotCalendar, array(
  1838. "id" => "Radarr-" . $number . "-" . $i,
  1839. "title" => $movieName,
  1840. "start" => $physicalRelease,
  1841. "className" => "inline-popups bg-calendar movieID--" . $movieID,
  1842. "imagetype" => "film " . $downloaded,
  1843. "imagetypeFilter" => "film",
  1844. "downloadFilter" => $downloaded,
  1845. "bgColor" => str_replace('text', 'bg', $downloaded),
  1846. "details" => $details
  1847. ));
  1848. }
  1849. }
  1850. if ($i != 0) {
  1851. return $gotCalendar;
  1852. }
  1853. return false;
  1854. }
  1855. function getCouchCalendar($array, $number)
  1856. {
  1857. $api = json_decode($array, true);
  1858. $gotCalendar = array();
  1859. $i = 0;
  1860. foreach ($api['movies'] as $child) {
  1861. if ($child['status'] == "active" || $child['status'] == "done") {
  1862. $i++;
  1863. $movieName = $child['info']['original_title'];
  1864. $movieID = $child['info']['tmdb_id'];
  1865. if (!isset($movieID)) {
  1866. $movieID = "";
  1867. }
  1868. $physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
  1869. $backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
  1870. $physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
  1871. $physicalRelease = strtotime($physicalRelease);
  1872. $physicalRelease = date("Y-m-d", $physicalRelease);
  1873. if (new DateTime() < new DateTime($physicalRelease)) {
  1874. $notReleased = "true";
  1875. } else {
  1876. $notReleased = "false";
  1877. }
  1878. $downloaded = ($child['status'] == "active") ? "0" : "1";
  1879. if ($downloaded == "0" && $notReleased == "true") {
  1880. $downloaded = "text-info";
  1881. } elseif ($downloaded == "1") {
  1882. $downloaded = "text-success";
  1883. } else {
  1884. $downloaded = "text-danger";
  1885. }
  1886. if (!empty($child['info']['images']['backdrop_original'])) {
  1887. $banner = $child['info']['images']['backdrop_original'][0];
  1888. } elseif (!empty($child['info']['images']['backdrop'])) {
  1889. $banner = $child['info']['images']['backdrop_original'][0];
  1890. } else {
  1891. $banner = "/plugins/images/cache/no-np.png";
  1892. }
  1893. if ($banner !== "/plugins/images/cache/no-np.png") {
  1894. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1895. $imageURL = $banner;
  1896. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1897. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1898. if (!file_exists($cacheFile)) {
  1899. cacheImage($imageURL, $movieID);
  1900. unset($imageURL);
  1901. unset($cacheFile);
  1902. }
  1903. }
  1904. $hasFile = (!empty($child['releases']) && !empty($child['releases'][0]['files']['movie']));
  1905. $details = array(
  1906. "topTitle" => $movieName,
  1907. "bottomTitle" => $child['info']['tagline'],
  1908. "status" => $child['status'],
  1909. "overview" => $child['info']['plot'],
  1910. "runtime" => $child['info']['runtime'],
  1911. "image" => $banner,
  1912. "ratings" => isset($child['info']['rating']['imdb'][0]) ? $child['info']['rating']['imdb'][0] : '',
  1913. "videoQuality" => $hasFile ? $child['releases'][0]['quality'] : "unknown",
  1914. "audioChannels" => "",
  1915. "audioCodec" => "",
  1916. "videoCodec" => "",
  1917. "genres" => $child['info']['genres'],
  1918. "year" => isset($child['info']['year']) ? $child['info']['year'] : '',
  1919. "studio" => isset($child['info']['year']) ? $child['info']['year'] : '',
  1920. );
  1921. array_push($gotCalendar, array(
  1922. "id" => "CouchPotato-" . $number . "-" . $i,
  1923. "title" => $movieName,
  1924. "start" => $physicalRelease,
  1925. "className" => "inline-popups bg-calendar calendar-item movieID--" . $movieID,
  1926. "imagetype" => "film " . $downloaded,
  1927. "imagetypeFilter" => "film",
  1928. "downloadFilter" => $downloaded,
  1929. "bgColor" => str_replace('text', 'bg', $downloaded),
  1930. "details" => $details
  1931. ));
  1932. }
  1933. }
  1934. if ($i != 0) {
  1935. return $gotCalendar;
  1936. }
  1937. return false;
  1938. }
  1939. function getSickrageCalendarWanted($array, $number)
  1940. {
  1941. $array = json_decode($array, true);
  1942. $gotCalendar = array();
  1943. $i = 0;
  1944. foreach ($array['data']['missed'] as $child) {
  1945. $i++;
  1946. $seriesName = $child['show_name'];
  1947. $seriesID = $child['tvdbid'];
  1948. $episodeID = $child['tvdbid'];
  1949. $episodeAirDate = $child['airdate'];
  1950. $episodeAirDateTime = explode(" ", $child['airs']);
  1951. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1952. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1953. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1954. if (new DateTime() < new DateTime($episodeAirDate)) {
  1955. $unaired = true;
  1956. }
  1957. $downloaded = "0";
  1958. if ($downloaded == "0" && isset($unaired)) {
  1959. $downloaded = "text-info";
  1960. } elseif ($downloaded == "1") {
  1961. $downloaded = "text-success";
  1962. } else {
  1963. $downloaded = "text-danger";
  1964. }
  1965. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1966. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1967. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1968. $fanart = "/plugins/images/cache/no-np.png";
  1969. if (file_exists($cacheFile)) {
  1970. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1971. unset($cacheFile);
  1972. }
  1973. $details = array(
  1974. "seasonCount" => "",
  1975. "status" => $child['show_status'],
  1976. "topTitle" => $seriesName,
  1977. "bottomTitle" => $bottomTitle,
  1978. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1979. "runtime" => "",
  1980. "image" => $fanart,
  1981. "ratings" => "",
  1982. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1983. "audioChannels" => "",
  1984. "audioCodec" => "",
  1985. "videoCodec" => "",
  1986. "size" => "",
  1987. "genres" => "",
  1988. );
  1989. array_push($gotCalendar, array(
  1990. "id" => "Sick-" . $number . "-Miss-" . $i,
  1991. "title" => $seriesName,
  1992. "start" => $episodeAirDate,
  1993. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1994. "imagetype" => "tv " . $downloaded,
  1995. "imagetypeFilter" => "tv",
  1996. "downloadFilter" => $downloaded,
  1997. "bgColor" => str_replace('text', 'bg', $downloaded),
  1998. "details" => $details,
  1999. ));
  2000. }
  2001. foreach ($array['data']['today'] as $child) {
  2002. $i++;
  2003. $seriesName = $child['show_name'];
  2004. $seriesID = $child['tvdbid'];
  2005. $episodeID = $child['tvdbid'];
  2006. $episodeAirDate = $child['airdate'];
  2007. $episodeAirDateTime = explode(" ", $child['airs']);
  2008. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  2009. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  2010. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2011. if (new DateTime() < new DateTime($episodeAirDate)) {
  2012. $unaired = true;
  2013. }
  2014. $downloaded = "0";
  2015. if ($downloaded == "0" && isset($unaired)) {
  2016. $downloaded = "text-info";
  2017. } elseif ($downloaded == "1") {
  2018. $downloaded = "text-success";
  2019. } else {
  2020. $downloaded = "text-danger";
  2021. }
  2022. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  2023. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2024. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  2025. $fanart = "/plugins/images/cache/no-np.png";
  2026. if (file_exists($cacheFile)) {
  2027. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  2028. unset($cacheFile);
  2029. }
  2030. $details = array(
  2031. "seasonCount" => "",
  2032. "status" => $child['show_status'],
  2033. "topTitle" => $seriesName,
  2034. "bottomTitle" => $bottomTitle,
  2035. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  2036. "runtime" => "",
  2037. "image" => $fanart,
  2038. "ratings" => "",
  2039. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  2040. "audioChannels" => "",
  2041. "audioCodec" => "",
  2042. "videoCodec" => "",
  2043. "size" => "",
  2044. "genres" => "",
  2045. );
  2046. array_push($gotCalendar, array(
  2047. "id" => "Sick-" . $number . "-Today-" . $i,
  2048. "title" => $seriesName,
  2049. "start" => $episodeAirDate,
  2050. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2051. "imagetype" => "tv " . $downloaded,
  2052. "imagetypeFilter" => "tv",
  2053. "downloadFilter" => $downloaded,
  2054. "bgColor" => str_replace('text', 'bg', $downloaded),
  2055. "details" => $details,
  2056. ));
  2057. }
  2058. foreach ($array['data']['soon'] as $child) {
  2059. $i++;
  2060. $seriesName = $child['show_name'];
  2061. $seriesID = $child['tvdbid'];
  2062. $episodeID = $child['tvdbid'];
  2063. $episodeAirDate = $child['airdate'];
  2064. $episodeAirDateTime = explode(" ", $child['airs']);
  2065. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  2066. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  2067. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2068. if (new DateTime() < new DateTime($episodeAirDate)) {
  2069. $unaired = true;
  2070. }
  2071. $downloaded = "0";
  2072. if ($downloaded == "0" && isset($unaired)) {
  2073. $downloaded = "text-info";
  2074. } elseif ($downloaded == "1") {
  2075. $downloaded = "text-success";
  2076. } else {
  2077. $downloaded = "text-danger";
  2078. }
  2079. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  2080. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2081. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  2082. $fanart = "/plugins/images/cache/no-np.png";
  2083. if (file_exists($cacheFile)) {
  2084. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  2085. unset($cacheFile);
  2086. }
  2087. $details = array(
  2088. "seasonCount" => "",
  2089. "status" => $child['show_status'],
  2090. "topTitle" => $seriesName,
  2091. "bottomTitle" => $bottomTitle,
  2092. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  2093. "runtime" => "",
  2094. "image" => $fanart,
  2095. "ratings" => "",
  2096. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  2097. "audioChannels" => "",
  2098. "audioCodec" => "",
  2099. "videoCodec" => "",
  2100. "size" => "",
  2101. "genres" => "",
  2102. );
  2103. array_push($gotCalendar, array(
  2104. "id" => "Sick-" . $number . "-Soon-" . $i,
  2105. "title" => $seriesName,
  2106. "start" => $episodeAirDate,
  2107. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2108. "imagetype" => "tv " . $downloaded,
  2109. "imagetypeFilter" => "tv",
  2110. "downloadFilter" => $downloaded,
  2111. "bgColor" => str_replace('text', 'bg', $downloaded),
  2112. "details" => $details,
  2113. ));
  2114. }
  2115. foreach ($array['data']['later'] as $child) {
  2116. $i++;
  2117. $seriesName = $child['show_name'];
  2118. $seriesID = $child['tvdbid'];
  2119. $episodeID = $child['tvdbid'];
  2120. $episodeAirDate = $child['airdate'];
  2121. $episodeAirDateTime = explode(" ", $child['airs']);
  2122. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  2123. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  2124. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2125. if (new DateTime() < new DateTime($episodeAirDate)) {
  2126. $unaired = true;
  2127. }
  2128. $downloaded = "0";
  2129. if ($downloaded == "0" && isset($unaired)) {
  2130. $downloaded = "text-info";
  2131. } elseif ($downloaded == "1") {
  2132. $downloaded = "text-success";
  2133. } else {
  2134. $downloaded = "text-danger";
  2135. }
  2136. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  2137. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2138. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  2139. $fanart = "/plugins/images/cache/no-np.png";
  2140. if (file_exists($cacheFile)) {
  2141. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  2142. unset($cacheFile);
  2143. }
  2144. $details = array(
  2145. "seasonCount" => "",
  2146. "status" => $child['show_status'],
  2147. "topTitle" => $seriesName,
  2148. "bottomTitle" => $bottomTitle,
  2149. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  2150. "runtime" => "",
  2151. "image" => $fanart,
  2152. "ratings" => "",
  2153. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  2154. "audioChannels" => "",
  2155. "audioCodec" => "",
  2156. "videoCodec" => "",
  2157. "size" => "",
  2158. "genres" => "",
  2159. );
  2160. array_push($gotCalendar, array(
  2161. "id" => "Sick-" . $number . "-Later-" . $i,
  2162. "title" => $seriesName,
  2163. "start" => $episodeAirDate,
  2164. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2165. "imagetype" => "tv " . $downloaded,
  2166. "imagetypeFilter" => "tv",
  2167. "downloadFilter" => $downloaded,
  2168. "bgColor" => str_replace('text', 'bg', $downloaded),
  2169. "details" => $details,
  2170. ));
  2171. }
  2172. if ($i != 0) {
  2173. return $gotCalendar;
  2174. }
  2175. return false;
  2176. }
  2177. function getSickrageCalendarHistory($array, $number)
  2178. {
  2179. $array = json_decode($array, true);
  2180. $gotCalendar = array();
  2181. $i = 0;
  2182. foreach ($array['data'] as $child) {
  2183. $i++;
  2184. $seriesName = $child['show_name'];
  2185. $seriesID = $child['tvdbid'];
  2186. $episodeID = $child['tvdbid'];
  2187. $episodeAirDate = $child['date'];
  2188. $downloaded = "text-success";
  2189. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']);
  2190. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2191. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  2192. $fanart = "/plugins/images/cache/no-np.png";
  2193. if (file_exists($cacheFile)) {
  2194. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  2195. unset($cacheFile);
  2196. }
  2197. $details = array(
  2198. "seasonCount" => "",
  2199. "status" => $child['status'],
  2200. "topTitle" => $seriesName,
  2201. "bottomTitle" => $bottomTitle,
  2202. "overview" => '',
  2203. "runtime" => isset($child['series']['runtime']) ? $child['series']['runtime'] : 30,
  2204. "image" => $fanart,
  2205. "ratings" => isset($child['series']['ratings']['value']) ? $child['series']['ratings']['value'] : "unknown",
  2206. "videoQuality" => isset($child["quality"]) ? $child['quality'] : "unknown",
  2207. "audioChannels" => "",
  2208. "audioCodec" => "",
  2209. "videoCodec" => "",
  2210. "size" => "",
  2211. "genres" => "",
  2212. );
  2213. array_push($gotCalendar, array(
  2214. "id" => "Sick-" . $number . "-History-" . $i,
  2215. "title" => $seriesName,
  2216. "start" => $episodeAirDate,
  2217. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2218. "imagetype" => "tv " . $downloaded,
  2219. "imagetypeFilter" => "tv",
  2220. "downloadFilter" => $downloaded,
  2221. "bgColor" => str_replace('text', 'bg', $downloaded),
  2222. "details" => $details,
  2223. ));
  2224. }
  2225. if ($i != 0) {
  2226. return $gotCalendar;
  2227. }
  2228. return false;
  2229. }
  2230. function ombiAPI($array)
  2231. {
  2232. return ombiAction($array['data']['id'], $array['data']['action'], $array['data']['type'], $array['data']);
  2233. }
  2234. function ombiImport($type = null)
  2235. {
  2236. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && !empty($type)) {
  2237. try {
  2238. $url = qualifyURL($GLOBALS['ombiURL']);
  2239. $headers = array(
  2240. "Accept" => "application/json",
  2241. "Content-Type" => "application/json",
  2242. "Apikey" => $GLOBALS['ombiToken']
  2243. );
  2244. $options = (localURL($url)) ? array('verify' => false) : array();
  2245. switch ($type) {
  2246. case 'emby':
  2247. case 'emby_local':
  2248. case 'emby_connect':
  2249. case 'emby_all':
  2250. $response = Requests::post($url . "/api/v1/Job/embyuserimporter", $headers, $options);
  2251. break;
  2252. case 'plex':
  2253. $response = Requests::post($url . "/api/v1/Job/plexuserimporter", $headers, $options);
  2254. break;
  2255. default:
  2256. return false;
  2257. break;
  2258. }
  2259. if ($response->success) {
  2260. writeLog('success', 'OMBI Connect Function - Ran User Import', 'SYSTEM');
  2261. return true;
  2262. } else {
  2263. writeLog('error', 'OMBI Connect Function - Error: Connection Unsuccessful', 'SYSTEM');
  2264. return false;
  2265. }
  2266. } catch (Requests_Exception $e) {
  2267. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2268. return false;
  2269. };
  2270. }
  2271. return false;
  2272. }
  2273. function ombiAction($id, $action, $type, $fullArray = null)
  2274. {
  2275. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  2276. $url = qualifyURL($GLOBALS['ombiURL']);
  2277. $headers = array(
  2278. "Accept" => "application/json",
  2279. "Content-Type" => "application/json",
  2280. "Apikey" => $GLOBALS['ombiToken']
  2281. );
  2282. $data = array(
  2283. 'id' => $id,
  2284. );
  2285. switch ($type) {
  2286. case 'season':
  2287. case 'tv':
  2288. $type = 'tv';
  2289. $add = array(
  2290. 'tvDbId' => $id,
  2291. 'requestAll' => ombiTVDefault('all'),
  2292. 'latestSeason' => ombiTVDefault('last'),
  2293. 'firstSeason' => ombiTVDefault('first')
  2294. );
  2295. break;
  2296. default:
  2297. $type = 'movie';
  2298. $add = array("theMovieDbId" => (int)$id);
  2299. break;
  2300. }
  2301. $success['head'] = $headers;
  2302. $success['act'] = $action;
  2303. $success['data'] = $data;
  2304. $success['add'] = $add;
  2305. $success['type'] = $type;
  2306. try {
  2307. $options = (localURL($url)) ? array('verify' => false) : array();
  2308. switch ($action) {
  2309. case 'add':
  2310. if (isset($_COOKIE['Auth'])) {
  2311. $headers = array(
  2312. "Accept" => "application/json",
  2313. "Content-Type" => "application/json",
  2314. "Authorization" => "Bearer " . $_COOKIE['Auth']
  2315. );
  2316. $success['head'] = $headers;
  2317. } else {
  2318. return false;
  2319. }
  2320. $response = Requests::post($url . "/api/v1/Request/" . $type, $headers, json_encode($add), $options);
  2321. break;
  2322. default:
  2323. if (qualifyRequest(1)) {
  2324. switch ($action) {
  2325. case 'approve':
  2326. $response = Requests::post($url . "/api/v1/Request/" . $type . "/approve", $headers, json_encode($data), $options);
  2327. break;
  2328. case 'available':
  2329. $response = Requests::post($url . "/api/v1/Request/" . $type . "/available", $headers, json_encode($data), $options);
  2330. break;
  2331. case 'unavailable':
  2332. $response = Requests::post($url . "/api/v1/Request/" . $type . "/unavailable", $headers, json_encode($data), $options);
  2333. break;
  2334. case 'deny':
  2335. $response = Requests::put($url . "/api/v1/Request/" . $type . "/deny", $headers, json_encode($data), $options);
  2336. break;
  2337. case 'delete':
  2338. $response = Requests::delete($url . "/api/v1/Request/" . $type . "/" . $id, $headers, $options);
  2339. break;
  2340. default:
  2341. return false;
  2342. }
  2343. }
  2344. break;
  2345. }
  2346. $success['api'] = $response;
  2347. $success['bd'] = $response->body;
  2348. $success['hd'] = $response->headers;
  2349. if ($response->success) {
  2350. $success['ok'] = true;
  2351. }
  2352. } catch (Requests_Exception $e) {
  2353. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2354. };
  2355. }
  2356. return isset($success['ok']) ? $success : false;
  2357. }
  2358. function getOmbiRequests($type = "both", $limit = 50)
  2359. {
  2360. $api['count'] = array(
  2361. 'movie' => 0,
  2362. 'tv' => 0,
  2363. 'limit' => (integer)$limit
  2364. );
  2365. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  2366. $url = qualifyURL($GLOBALS['ombiURL']);
  2367. $headers = array(
  2368. "Accept" => "application/json",
  2369. "Apikey" => $GLOBALS['ombiToken'],
  2370. );
  2371. $requests = array();
  2372. try {
  2373. $options = (localURL($url)) ? array('verify' => false) : array();
  2374. switch ($type) {
  2375. case 'movie':
  2376. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  2377. break;
  2378. case 'tv':
  2379. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  2380. break;
  2381. default:
  2382. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  2383. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  2384. break;
  2385. }
  2386. if ($movie->success || $tv->success) {
  2387. if (isset($movie)) {
  2388. $movie = json_decode($movie->body, true);
  2389. //$movie = array_reverse($movie);
  2390. foreach ($movie as $key => $value) {
  2391. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2392. if ($proceed) {
  2393. $api['count']['movie']++;
  2394. $requests[] = array(
  2395. 'id' => $value['theMovieDbId'],
  2396. 'title' => $value['title'],
  2397. 'overview' => $value['overview'],
  2398. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/' . $value['posterPath'] : 'plugins/images/cache/no-list.png',
  2399. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2400. 'approved' => $value['approved'],
  2401. 'available' => $value['available'],
  2402. 'denied' => $value['denied'],
  2403. 'deniedReason' => $value['deniedReason'],
  2404. 'user' => $value['requestedUser']['userName'],
  2405. 'userAlias' => $value['requestedUser']['userAlias'],
  2406. 'request_id' => $value['id'],
  2407. 'request_date' => $value['requestedDate'],
  2408. 'release_date' => $value['releaseDate'],
  2409. 'type' => 'movie',
  2410. 'icon' => 'mdi mdi-filmstrip',
  2411. 'color' => 'palette-Deep-Purple-900 bg white',
  2412. );
  2413. }
  2414. }
  2415. }
  2416. if (isset($tv) && (is_array($tv) || is_object($tv))) {
  2417. $tv = json_decode($tv->body, true);
  2418. foreach ($tv as $key => $value) {
  2419. if (count($value['childRequests']) > 0) {
  2420. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['childRequests'][0]['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2421. if ($proceed) {
  2422. $api['count']['tv']++;
  2423. $requests[] = array(
  2424. 'id' => $value['tvDbId'],
  2425. 'title' => $value['title'],
  2426. 'overview' => $value['overview'],
  2427. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? $value['posterPath'] : 'plugins/images/cache/no-list.png',
  2428. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2429. 'approved' => $value['childRequests'][0]['approved'],
  2430. 'available' => $value['childRequests'][0]['available'],
  2431. 'denied' => $value['childRequests'][0]['denied'],
  2432. 'deniedReason' => $value['childRequests'][0]['deniedReason'],
  2433. 'user' => $value['childRequests'][0]['requestedUser']['userName'],
  2434. 'userAlias' => $value['childRequests'][0]['requestedUser']['userAlias'],
  2435. 'request_id' => $value['id'],
  2436. 'request_date' => $value['childRequests'][0]['requestedDate'],
  2437. 'release_date' => $value['releaseDate'],
  2438. 'type' => 'tv',
  2439. 'icon' => 'mdi mdi-television',
  2440. 'color' => 'grayish-blue-bg',
  2441. );
  2442. }
  2443. }
  2444. }
  2445. }
  2446. //sort here
  2447. usort($requests, function ($item1, $item2) {
  2448. if ($item1['request_date'] == $item2['request_date']) {
  2449. return 0;
  2450. }
  2451. return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
  2452. });
  2453. }
  2454. } catch (Requests_Exception $e) {
  2455. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2456. };
  2457. }
  2458. $api['content'] = isset($requests) ? array_slice($requests, 0, $limit) : false;
  2459. return $api;
  2460. }
  2461. function unifiConnect()
  2462. {
  2463. if ($GLOBALS['homepageUnifiEnabled'] && !empty($GLOBALS['unifiURL']) && !empty($GLOBALS['unifiSiteName']) && !empty($GLOBALS['unifiUsername']) && !empty($GLOBALS['unifiPassword']) && qualifyRequest($GLOBALS['homepageUnifiAuth'])) {
  2464. $api['content']['unifi'] = array();
  2465. $url = qualifyURL($GLOBALS['unifiURL']);
  2466. $urlStat = $url . '/api/s/' . $GLOBALS['unifiSiteName'] . '/stat/health';
  2467. try {
  2468. $options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => false);
  2469. $data = array(
  2470. 'username' => $GLOBALS['unifiUsername'],
  2471. 'password' => decrypt($GLOBALS['unifiPassword']),
  2472. 'remember' => true,
  2473. 'strict' => true
  2474. );
  2475. $response = Requests::post($url . '/api/login', array(), json_encode($data), $options);
  2476. if ($response->success) {
  2477. $cookie['unifises'] = ($response->cookies['unifises']->value) ?? false;
  2478. $cookie['csrf_token'] = ($response->cookies['csrf_token']->value) ?? false;
  2479. } else {
  2480. return false;
  2481. }
  2482. $headers = array(
  2483. 'cookie' => 'unifises=' . $cookie['unifises'] . ';' . 'csrf_token=' . $cookie['csrf_token'] . ';'
  2484. );
  2485. $response = Requests::get($urlStat, $headers, $options);
  2486. if ($response->success) {
  2487. $api['content']['unifi'] = json_decode($response->body, true);
  2488. }
  2489. } catch (Requests_Exception $e) {
  2490. writeLog('error', 'Unifi Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2491. };
  2492. $api['content']['unifi'] = isset($api['content']['unifi']) ? $api['content']['unifi'] : false;
  2493. return $api;
  2494. }
  2495. return false;
  2496. }
  2497. function getTautulli()
  2498. {
  2499. if ($GLOBALS['homepageTautulliEnabled'] && !empty($GLOBALS['tautulliURL']) && !empty($GLOBALS['tautulliApikey']) && qualifyRequest($GLOBALS['homepageTautulliAuth'])) {
  2500. $api = [];
  2501. $url = qualifyURL($GLOBALS['tautulliURL']);
  2502. $apiURL = $url . '/api/v2?apikey=' . $GLOBALS['tautulliApikey'];
  2503. $height = getCacheImageSize('h');
  2504. $width = getCacheImageSize('w');
  2505. $nowPlayingHeight = getCacheImageSize('nph');
  2506. $nowPlayingWidth = getCacheImageSize('npw');
  2507. try {
  2508. $homestatsUrl = $apiURL . '&cmd=get_home_stats&grouping=1';
  2509. $homestats = Requests::get($homestatsUrl, [], []);
  2510. if ($homestats->success) {
  2511. $homestats = json_decode($homestats->body, true);
  2512. $api['homestats'] = $homestats['response'];
  2513. // Cache art & thumb for first result in each tautulli API result
  2514. $categories = ['top_movies', 'top_tv', 'popular_movies', 'popular_tv'];
  2515. foreach ($categories as $cat) {
  2516. $key = array_search($cat, array_column($api['homestats']['data'], 'stat_id'));
  2517. $img = $api['homestats']['data'][$key]['rows'][0];
  2518. cacheImage($url . '/pms_image_proxy?img=' . $img['art'] . '&rating_key=' . $img['rating_key'] . '&width=' . $nowPlayingWidth . '&height=' . $nowPlayingHeight, $img['rating_key'] . '-np');
  2519. cacheImage($url . '/pms_image_proxy?img=' . $img['thumb'] . '&rating_key=' . $img['rating_key'] . '&width=' . $width . '&height=' . $height, $img['rating_key'] . '-list');
  2520. $img['art'] = 'plugins/images/cache/' . $img['rating_key'] . '-np.jpg';
  2521. $img['thumb'] = 'plugins/images/cache/' . $img['rating_key'] . '-list.jpg';
  2522. $api['homestats']['data'][$key]['rows'][0] = $img;
  2523. }
  2524. // Cache the platform icon
  2525. $key = array_search('top_platforms', array_column($api['homestats']['data'], 'stat_id'));
  2526. $platform = $api['homestats']['data'][$key]['rows'][0]['platform_name'];
  2527. cacheImage($url . '/images/platforms/' . $platform . '.svg', 'tautulli-' . $platform, 'svg');
  2528. }
  2529. $libstatsUrl = $apiURL . '&cmd=get_libraries';
  2530. $libstats = Requests::get($libstatsUrl, [], []);
  2531. if ($libstats->success) {
  2532. $libstats = json_decode($libstats->body, true);
  2533. $api['libstats'] = $libstats['response'];
  2534. $categories = ['movie.svg', 'show.svg', 'artist.svg'];
  2535. foreach ($categories as $cat) {
  2536. $parts = explode('.', $cat);
  2537. cacheImage($url . '/images/libraries/' . $cat, 'tautulli-' . $parts[0], $parts[1]);
  2538. }
  2539. }
  2540. $api['options'] = [
  2541. 'url' => $url,
  2542. 'libraries' => $GLOBALS['tautulliLibraries'],
  2543. 'topMovies' => $GLOBALS['tautulliTopMovies'],
  2544. 'topTV' => $GLOBALS['tautulliTopTV'],
  2545. 'topUsers' => $GLOBALS['tautulliTopUsers'],
  2546. 'topPlatforms' => $GLOBALS['tautulliTopPlatforms'],
  2547. 'popularMovies' => $GLOBALS['tautulliPopularMovies'],
  2548. 'popularTV' => $GLOBALS['tautulliPopularTV'],
  2549. 'title' => $GLOBALS['tautulliHeaderToggle'],
  2550. ];
  2551. $ids = []; // Array of stat_ids to remove from the returned array
  2552. if (!qualifyRequest($GLOBALS['homepageTautulliLibraryAuth'])) {
  2553. $api['options']['libraries'] = false;
  2554. unset($api['libstats']);
  2555. }
  2556. if (!qualifyRequest($GLOBALS['homepageTautulliViewsAuth'])) {
  2557. $api['options']['topMovies'] = false;
  2558. $api['options']['topTV'] = false;
  2559. $api['options']['popularMovies'] = false;
  2560. $api['options']['popularTV'] = false;
  2561. $ids = array_merge(['top_movies', 'popular_movies', 'popular_tv', 'top_tv'], $ids);
  2562. $api['homestats']['data'] = array_values($api['homestats']['data']);
  2563. }
  2564. if (!qualifyRequest($GLOBALS['homepageTautulliMiscAuth'])) {
  2565. $api['options']['topUsers'] = false;
  2566. $api['options']['topPlatforms'] = false;
  2567. $ids = array_merge(['top_platforms', 'top_users'], $ids);
  2568. $api['homestats']['data'] = array_values($api['homestats']['data']);
  2569. }
  2570. $ids = array_merge(['top_music', 'popular_music', 'last_watched', 'most_concurrent'], $ids);
  2571. foreach ($ids as $id) {
  2572. if ($key = array_search($id, array_column($api['homestats']['data'], 'stat_id'))) {
  2573. unset($api['homestats']['data'][$key]);
  2574. $api['homestats']['data'] = array_values($api['homestats']['data']);
  2575. }
  2576. }
  2577. } catch (Requests_Exception $e) {
  2578. writeLog('error', 'Tautulli Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2579. };
  2580. $api = isset($api) ? $api : false;
  2581. return $api;
  2582. }
  2583. return false;
  2584. }
  2585. function getMonitorr()
  2586. {
  2587. if ($GLOBALS['homepageMonitorrEnabled'] && !empty($GLOBALS['monitorrURL']) && qualifyRequest($GLOBALS['homepageMonitorrAuth'])) {
  2588. $api = [];
  2589. $url = qualifyURL($GLOBALS['monitorrURL']);
  2590. $dataUrl = $url . '/assets/php/loop.php';
  2591. try {
  2592. $response = Requests::get($dataUrl, ['Token' => $GLOBALS['organizrAPI']], []);
  2593. if ($response->success) {
  2594. $html = html_entity_decode($response->body);
  2595. // This section grabs the names of all services by regex
  2596. $services = [];
  2597. $servicesMatch = [];
  2598. $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>/';
  2599. preg_match_all($servicePattern, $html, $servicesMatch);
  2600. unset($servicesMatch[0]);
  2601. $servicesMatch = array_values($servicesMatch);
  2602. foreach ($servicesMatch as $group) {
  2603. foreach ($group as $service) {
  2604. if ($service !== '') {
  2605. array_push($services, $service);
  2606. }
  2607. }
  2608. }
  2609. // This section then grabs the status and image of that service with regex
  2610. $statuses = [];
  2611. foreach ($services as $service) {
  2612. $statusPattern = '/' . $service . '<\/div><\/div><div class="btnonline">(Online)<\/div>|' . $service . '<\/div><\/div><div class="btnoffline".*>(Offline)<\/div><\/div><\/div>/';
  2613. $status = [];
  2614. preg_match($statusPattern, $html, $status);
  2615. $statuses[$service] = $status;
  2616. foreach ($status as $match) {
  2617. if ($match == 'Online') {
  2618. $statuses[$service] = [
  2619. 'status' => true
  2620. ];
  2621. } else if ($match == 'Offline') {
  2622. $statuses[$service] = [
  2623. 'status' => false
  2624. ];
  2625. }
  2626. }
  2627. $imageMatch = [];
  2628. $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 . '/';
  2629. preg_match($imgPattern, $html, $imageMatch);
  2630. unset($imageMatch[0]);
  2631. $imageMatch = array_values($imageMatch);
  2632. // array_push($api['imagematches'][$service], $imageMatch);
  2633. foreach ($imageMatch as $match) {
  2634. if ($match !== '') {
  2635. $image = $match;
  2636. }
  2637. }
  2638. $ext = explode('.', $image);
  2639. $ext = $ext[key(array_slice($ext, -1, 1, true))];
  2640. $imageUrl = $url . '/assets' . $image;
  2641. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2642. $img = Requests::get($imageUrl, ['Token' => $GLOBALS['organizrAPI']], []);
  2643. if ($img->success) {
  2644. $base64 = 'data:image/' . $ext . ';base64,' . base64_encode($img->body);
  2645. $statuses[$service]['image'] = $base64;
  2646. } else {
  2647. $statuses[$service]['image'] = $cacheDirectory . 'no-list.png';
  2648. }
  2649. $linkMatch = [];
  2650. $linkPattern = '/<a class="servicetile" href="(.*)" target="_blank" style="display: block"><div id="serviceimg"><div><img id="' . strtolower($service) . '-service-img/';
  2651. preg_match($linkPattern, $html, $linkMatch);
  2652. $linkMatch = array_values($linkMatch);
  2653. unset($linkMatch[0]);
  2654. foreach ($linkMatch as $link) {
  2655. if ($link !== '') {
  2656. $statuses[$service]['link'] = $link;
  2657. }
  2658. }
  2659. }
  2660. ksort($statuses);
  2661. $api['services'] = $statuses;
  2662. $api['options'] = [
  2663. 'title' => $GLOBALS['monitorrHeader'],
  2664. 'titleToggle' => $GLOBALS['monitorrHeaderToggle'],
  2665. 'compact' => $GLOBALS['monitorrCompact'],
  2666. ];
  2667. }
  2668. } catch (Requests_Exception $e) {
  2669. writeLog('error', 'Monitorr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2670. };
  2671. $api = isset($api) ? $api : false;
  2672. return $api;
  2673. }
  2674. }
  2675. function getSpeedtest()
  2676. {
  2677. if ($GLOBALS['homepageSpeedtestEnabled'] && !empty($GLOBALS['speedtestURL']) && qualifyRequest($GLOBALS['homepageSpeedtestAuth'])) {
  2678. $api = [];
  2679. $url = qualifyURL($GLOBALS['speedtestURL']);
  2680. $dataUrl = $url . '/api/speedtest/latest';
  2681. try {
  2682. $response = Requests::get($dataUrl);
  2683. if ($response->success) {
  2684. $json = json_decode($response->body, true);
  2685. $api['data'] = [
  2686. 'current' => $json['data'],
  2687. 'average' => $json['average'],
  2688. 'max' => $json['max'],
  2689. ];
  2690. $api['options'] = [
  2691. 'title' => $GLOBALS['speedtestHeader'],
  2692. 'titleToggle' => $GLOBALS['speedtestHeaderToggle'],
  2693. ];
  2694. }
  2695. } catch (Requests_Exception $e) {
  2696. writeLog('error', 'Speedtest Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2697. };
  2698. $api = isset($api) ? $api : false;
  2699. return $api;
  2700. }
  2701. }
  2702. function getNetdata()
  2703. {
  2704. if ($GLOBALS['homepageNetdataEnabled'] && !empty($GLOBALS['netdataURL']) && qualifyRequest($GLOBALS['homepageNetdataAuth'])) {
  2705. require_once('netdata-functions.php');
  2706. $api = [];
  2707. $api['data'] = [];
  2708. $api['url'] = $GLOBALS['netdataURL'];
  2709. $url = qualifyURL($GLOBALS['netdataURL']);
  2710. for($i = 1; $i < 8; $i++) {
  2711. if($GLOBALS['netdata'.($i).'Enabled']) {
  2712. switch($GLOBALS['netdata'.$i.'Data']) {
  2713. case 'disk-read':
  2714. $data = disk('in', $url);
  2715. break;
  2716. case 'disk-write':
  2717. $data = disk('out', $url);
  2718. $data['value'] = abs($data['value']);
  2719. $data['percent'] = abs($data['percent']);
  2720. break;
  2721. case 'cpu':
  2722. $data = cpu($url);
  2723. break;
  2724. case 'net-in':
  2725. $data = net('received', $url);
  2726. break;
  2727. case 'net-out':
  2728. $data = net('sent', $url);
  2729. $data['value'] = abs($data['value']);
  2730. $data['percent'] = abs($data['percent']);
  2731. break;
  2732. case 'ram-used':
  2733. $data = ram($url);
  2734. break;
  2735. case 'swap-used':
  2736. $data = swap($url);
  2737. break;
  2738. case 'disk-avail':
  2739. $data = diskSpace('avail', $url);
  2740. break;
  2741. case 'disk-used':
  2742. $data = diskSpace('used', $url);
  2743. break;
  2744. case 'ipmi-temp-c':
  2745. $data = ipmiTemp($url, 'c');
  2746. break;
  2747. case 'ipmi-temp-f':
  2748. $data = ipmiTemp($url, 'f');
  2749. break;
  2750. case 'cpu-temp-c':
  2751. $data = cpuTemp($url, 'c');
  2752. break;
  2753. case 'cpu-temp-f':
  2754. $data = cpuTemp($url, 'f');
  2755. break;
  2756. case 'custom':
  2757. $data = customNetdata($url, $i);
  2758. break;
  2759. default:
  2760. $data = [
  2761. 'title' => 'DNC',
  2762. 'value' => 0,
  2763. 'units' => 'N/A',
  2764. 'max' => 100,
  2765. ];
  2766. break;
  2767. }
  2768. $data['title'] = $GLOBALS['netdata'.$i.'Title'];
  2769. $data['colour'] = $GLOBALS['netdata'.$i.'Colour'];
  2770. $data['chart'] = $GLOBALS['netdata'.$i.'Chart'];
  2771. $data['size'] = $GLOBALS['netdata'.$i.'Size'];
  2772. $data['lg'] = $GLOBALS['netdata'.($i).'lg'];
  2773. $data['md'] = $GLOBALS['netdata'.($i).'md'];
  2774. $data['sm'] = $GLOBALS['netdata'.($i).'sm'];
  2775. array_push($api['data'], $data);
  2776. }
  2777. }
  2778. $api = isset($api) ? $api : false;
  2779. return $api;
  2780. }
  2781. }
  2782. function testAPIConnection($array)
  2783. {
  2784. switch ($array['data']['action']) {
  2785. case 'unifiSite':
  2786. if (!empty($GLOBALS['unifiURL']) && !empty($GLOBALS['unifiUsername']) && !empty($GLOBALS['unifiPassword'])) {
  2787. $url = qualifyURL($GLOBALS['unifiURL']);
  2788. try {
  2789. $options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => false);
  2790. $data = array(
  2791. 'username' => $GLOBALS['unifiUsername'],
  2792. 'password' => decrypt($GLOBALS['unifiPassword']),
  2793. 'remember' => true,
  2794. 'strict' => true
  2795. );
  2796. $response = Requests::post($url . '/api/login', array(), json_encode($data), $options);
  2797. if ($response->success) {
  2798. $cookie['unifises'] = ($response->cookies['unifises']->value) ?? false;
  2799. $cookie['csrf_token'] = ($response->cookies['csrf_token']->value) ?? false;
  2800. } else {
  2801. return false;
  2802. }
  2803. $headers = array(
  2804. 'cookie' => 'unifises=' . $cookie['unifises'] . ';' . 'csrf_token=' . $cookie['csrf_token'] . ';'
  2805. );
  2806. $response = Requests::get($url . '/api/self/sites', $headers, $options);
  2807. if ($response->success) {
  2808. $body = json_decode($response->body, true);
  2809. return $body;
  2810. } else {
  2811. return false;
  2812. }
  2813. } catch (Requests_Exception $e) {
  2814. writeLog('error', 'Unifi Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2815. };
  2816. }
  2817. break;
  2818. case 'unifi':
  2819. if (!empty($GLOBALS['unifiURL']) && !empty($GLOBALS['unifiUsername']) && !empty($GLOBALS['unifiPassword']) && !empty($GLOBALS['unifiSiteName'])) {
  2820. $url = qualifyURL($GLOBALS['unifiURL']);
  2821. try {
  2822. $options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => false);
  2823. $data = array(
  2824. 'username' => $GLOBALS['unifiUsername'],
  2825. 'password' => decrypt($GLOBALS['unifiPassword']),
  2826. 'remember' => true,
  2827. 'strict' => true
  2828. );
  2829. $response = Requests::post($url . '/api/login', array(), json_encode($data), $options);
  2830. if ($response->success) {
  2831. $cookie['unifises'] = ($response->cookies['unifises']->value) ?? false;
  2832. $cookie['csrf_token'] = ($response->cookies['csrf_token']->value) ?? false;
  2833. } else {
  2834. return 'Failed to Login';
  2835. }
  2836. $headers = array(
  2837. 'cookie' => 'unifises=' . $cookie['unifises'] . ';' . 'csrf_token=' . $cookie['csrf_token'] . ';'
  2838. );
  2839. $response = Requests::get($url . '/api/s/' . $GLOBALS['unifiSiteName'] . '/self', $headers, $options);
  2840. $body = json_decode($response->body, true);
  2841. return ($body['meta']['rc'] == 'ok') ? true : $body['meta']['msg'];
  2842. } catch (Requests_Exception $e) {
  2843. writeLog('error', 'Unifi Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2844. };
  2845. } else {
  2846. return 'Not all data is filled in...';
  2847. }
  2848. break;
  2849. case 'ombi':
  2850. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken'])) {
  2851. $url = qualifyURL($GLOBALS['ombiURL']);
  2852. $url = $url . "/api/v1/Status/info";
  2853. $headers = array(
  2854. "Accept" => "application/json",
  2855. "Content-Type" => "application/json",
  2856. "Apikey" => $GLOBALS['ombiToken']
  2857. );
  2858. try {
  2859. $options = (localURL($url)) ? array('verify' => false) : array();
  2860. $response = Requests::get($url, $headers, $options);
  2861. if ($response->success) {
  2862. return true;
  2863. } else {
  2864. return $response->body;
  2865. }
  2866. } catch (Requests_Exception $e) {
  2867. return $e->getMessage();
  2868. };
  2869. } else {
  2870. return 'URL and/or Token not setup';
  2871. }
  2872. break;
  2873. case 'plex':
  2874. if (!empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken'])) {
  2875. $url = qualifyURL($GLOBALS['plexURL']);
  2876. $url = $url . "/?X-Plex-Token=" . $GLOBALS['plexToken'];
  2877. try {
  2878. $options = (localURL($url)) ? array('verify' => false) : array();
  2879. $response = Requests::get($url, array(), $options);
  2880. libxml_use_internal_errors(true);
  2881. if ($response->success) {
  2882. return true;
  2883. }
  2884. } catch (Requests_Exception $e) {
  2885. return $e->getMessage();
  2886. };
  2887. } else {
  2888. return 'URL and/or Token not setup';
  2889. }
  2890. break;
  2891. case 'emby':
  2892. break;
  2893. case 'sonarr':
  2894. if (!empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  2895. $sonarrs = array();
  2896. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  2897. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  2898. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2899. foreach ($sonarrURLList as $key => $value) {
  2900. $sonarrs[$key] = array(
  2901. 'url' => $value,
  2902. 'token' => $sonarrTokenList[$key]
  2903. );
  2904. }
  2905. foreach ($sonarrs as $key => $value) {
  2906. try {
  2907. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2908. $result = json_decode($sonarr->getSystemStatus(), true);
  2909. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2910. } catch (Exception $e) {
  2911. return strip($e->getMessage());
  2912. }
  2913. }
  2914. }
  2915. } else {
  2916. return 'URL/s and/or Token/s not setup';
  2917. }
  2918. break;
  2919. case 'lidarr':
  2920. if (!empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  2921. $sonarrs = array();
  2922. $sonarrURLList = explode(',', $GLOBALS['lidarrURL']);
  2923. $sonarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  2924. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2925. foreach ($sonarrURLList as $key => $value) {
  2926. $sonarrs[$key] = array(
  2927. 'url' => $value,
  2928. 'token' => $sonarrTokenList[$key]
  2929. );
  2930. }
  2931. foreach ($sonarrs as $key => $value) {
  2932. try {
  2933. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  2934. $result = json_decode($sonarr->getSystemStatus(), true);
  2935. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2936. } catch (Exception $e) {
  2937. return $e->getMessage();
  2938. }
  2939. }
  2940. }
  2941. } else {
  2942. return 'URL/s and/or Token/s not setup';
  2943. }
  2944. break;
  2945. case 'radarr':
  2946. if (!empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  2947. $sonarrs = array();
  2948. $sonarrURLList = explode(',', $GLOBALS['radarrURL']);
  2949. $sonarrTokenList = explode(',', $GLOBALS['radarrToken']);
  2950. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2951. foreach ($sonarrURLList as $key => $value) {
  2952. $sonarrs[$key] = array(
  2953. 'url' => $value,
  2954. 'token' => $sonarrTokenList[$key]
  2955. );
  2956. }
  2957. foreach ($sonarrs as $key => $value) {
  2958. try {
  2959. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2960. $result = json_decode($sonarr->getSystemStatus(), true);
  2961. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2962. } catch (Exception $e) {
  2963. return $e->getMessage();
  2964. }
  2965. }
  2966. }
  2967. } else {
  2968. return 'URL/s and/or Token/s not setup';
  2969. }
  2970. break;
  2971. case 'jdownloader':
  2972. if (!empty($GLOBALS['jdownloaderURL'])) {
  2973. $url = qualifyURL($GLOBALS['jdownloaderURL']);
  2974. try {
  2975. $options = (localURL($url)) ? array('verify' => false, 'timeout' => 30) : array('timeout' => 30);
  2976. $response = Requests::get($url, array(), $options);
  2977. if ($response->success) {
  2978. return true;
  2979. }
  2980. } catch (Requests_Exception $e) {
  2981. return $e->getMessage();
  2982. };
  2983. } else {
  2984. return 'URL and/or Token not setup';
  2985. }
  2986. break;
  2987. case 'sabnzbd':
  2988. if (!empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken'])) {
  2989. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  2990. $url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  2991. try {
  2992. $options = (localURL($url)) ? array('verify' => false) : array();
  2993. $response = Requests::get($url, array(), $options);
  2994. if ($response->success) {
  2995. return true;
  2996. }
  2997. } catch (Requests_Exception $e) {
  2998. return $e->getMessage();
  2999. };
  3000. } else {
  3001. return 'URL and/or Token not setup';
  3002. }
  3003. break;
  3004. case 'nzbget':
  3005. if (!empty($GLOBALS['nzbgetURL'])) {
  3006. $url = qualifyURL($GLOBALS['nzbgetURL']);
  3007. $url = $url . '/jsonrpc/listgroups';
  3008. try {
  3009. $options = (localURL($url)) ? array('verify' => false) : array();
  3010. if ($GLOBALS['nzbgetUsername'] !== '' && decrypt($GLOBALS['nzbgetPassword']) !== '') {
  3011. $credentials = array('auth' => new Requests_Auth_Basic(array($GLOBALS['nzbgetUsername'], decrypt($GLOBALS['nzbgetPassword']))));
  3012. $options = array_merge($options, $credentials);
  3013. }
  3014. $response = Requests::get($url, array(), $options);
  3015. if ($response->success) {
  3016. return true;
  3017. }
  3018. } catch (Requests_Exception $e) {
  3019. return $e->getMessage();
  3020. };
  3021. } else {
  3022. return 'URL and/or Username/Password not setup';
  3023. }
  3024. break;
  3025. case 'deluge':
  3026. if (!empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword'])) {
  3027. try {
  3028. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  3029. $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');
  3030. return true;
  3031. } catch (Exception $e) {
  3032. return $e->getMessage();
  3033. }
  3034. } else {
  3035. return 'URL and/or Password not setup';
  3036. }
  3037. break;
  3038. case 'rtorrent':
  3039. if (!empty($GLOBALS['rTorrentURL']) || !empty($GLOBALS['rTorrentURLOverride'])) {
  3040. try {
  3041. $digest = (empty($GLOBALS['rTorrentURLOverride'])) ? qualifyURL($GLOBALS['rTorrentURL'], true) : qualifyURL(checkOverrideURL($GLOBALS['rTorrentURL'], $GLOBALS['rTorrentURLOverride']), true);
  3042. $passwordInclude = ($GLOBALS['rTorrentUsername'] !== '' && $GLOBALS['rTorrentPassword'] !== '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  3043. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  3044. $extraPath = (empty($GLOBALS['rTorrentURLOverride'])) ? $extraPath : '';
  3045. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  3046. $options = (localURL($url, $GLOBALS['rTorrentDisableCertCheck'])) ? array('verify' => false) : array();
  3047. if ($GLOBALS['rTorrentUsername'] !== '' && decrypt($GLOBALS['rTorrentPassword']) !== '') {
  3048. $credentials = array('auth' => new Requests_Auth_Digest(array($GLOBALS['rTorrentUsername'], decrypt($GLOBALS['rTorrentPassword']))));
  3049. $options = array_merge($options, $credentials);
  3050. }
  3051. $data = xmlrpc_encode_request("system.listMethods", null);
  3052. $response = Requests::post($url, array(), $data, $options);
  3053. if ($response->success) {
  3054. $methods = xmlrpc_decode(str_replace('i8>', 'i4>', $response->body));
  3055. if (count($methods) !== 0) {
  3056. return true;
  3057. }
  3058. }
  3059. return false;
  3060. } catch
  3061. (Requests_Exception $e) {
  3062. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  3063. return $e->getMessage();
  3064. };
  3065. }
  3066. break;
  3067. case 'ldap_login':
  3068. $username = $array['data']['data']['username'];
  3069. $password = $array['data']['data']['password'];
  3070. if (empty($username) || empty($password)) {
  3071. return 'Missing Username or Password';
  3072. }
  3073. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  3074. $ad = new \Adldap\Adldap();
  3075. // Create a configuration array.
  3076. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  3077. $i = 0;
  3078. foreach ($ldapServers as $key => $value) {
  3079. // Calculate parts
  3080. $digest = parse_url(trim($value));
  3081. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  3082. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  3083. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  3084. // Reassign
  3085. $ldapHosts[] = $host;
  3086. $ldapServersNew[$key] = $scheme . '://' . $host . ':' . $port; // May use this later
  3087. if ($i == 0) {
  3088. $ldapPort = $port;
  3089. }
  3090. $i++;
  3091. }
  3092. $config = [
  3093. // Mandatory Configuration Options
  3094. 'hosts' => $ldapHosts,
  3095. 'base_dn' => $GLOBALS['authBaseDN'],
  3096. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  3097. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  3098. // Optional Configuration Options
  3099. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  3100. 'account_prefix' => (empty($GLOBALS['authBackendHostPrefix'])) ? null : $GLOBALS['authBackendHostPrefix'],
  3101. 'account_suffix' => (empty($GLOBALS['authBackendHostSuffix'])) ? null : $GLOBALS['authBackendHostSuffix'],
  3102. 'port' => $ldapPort,
  3103. 'follow_referrals' => false,
  3104. 'use_ssl' => false,
  3105. 'use_tls' => false,
  3106. 'version' => 3,
  3107. 'timeout' => 5,
  3108. // Custom LDAP Options
  3109. 'custom_options' => [
  3110. // See: http://php.net/ldap_set_option
  3111. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  3112. ]
  3113. ];
  3114. // Add a connection provider to Adldap.
  3115. $ad->addProvider($config);
  3116. try {
  3117. // If a successful connection is made to your server, the provider will be returned.
  3118. $provider = $ad->connect();
  3119. //prettyPrint($provider);
  3120. if ($provider->auth()->attempt($username, $password, true)) {
  3121. // Passed.
  3122. $user = $provider->search()->find($username);
  3123. //return $user->getFirstAttribute('cn');
  3124. //return $user->getGroups(['cn']);
  3125. //return $user;
  3126. //return $user->getUserPrincipalName();
  3127. //return $user->getGroups(['cn']);
  3128. return true;
  3129. } else {
  3130. // Failed.
  3131. return 'Username/Password Failed to authenticate';
  3132. }
  3133. } catch (\Adldap\Auth\BindException $e) {
  3134. $detailedError = $e->getDetailedError();
  3135. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  3136. return $detailedError->getErrorMessage();
  3137. // There was an issue binding / connecting to the server.
  3138. } catch (Adldap\Auth\UsernameRequiredException $e) {
  3139. $detailedError = $e->getDetailedError();
  3140. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  3141. return $detailedError->getErrorMessage();
  3142. // The user didn't supply a username.
  3143. } catch (Adldap\Auth\PasswordRequiredException $e) {
  3144. $detailedError = $e->getDetailedError();
  3145. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  3146. return $detailedError->getErrorMessage();
  3147. // The user didn't supply a password.
  3148. }
  3149. }
  3150. break;
  3151. case 'ldap':
  3152. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  3153. $ad = new \Adldap\Adldap();
  3154. // Create a configuration array.
  3155. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  3156. $i = 0;
  3157. foreach ($ldapServers as $key => $value) {
  3158. // Calculate parts
  3159. $digest = parse_url(trim($value));
  3160. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  3161. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  3162. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  3163. // Reassign
  3164. $ldapHosts[] = $host;
  3165. if ($i == 0) {
  3166. $ldapPort = $port;
  3167. }
  3168. $i++;
  3169. }
  3170. $config = [
  3171. // Mandatory Configuration Options
  3172. 'hosts' => $ldapHosts,
  3173. 'base_dn' => $GLOBALS['authBaseDN'],
  3174. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  3175. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  3176. // Optional Configuration Options
  3177. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  3178. 'account_prefix' => '',
  3179. 'account_suffix' => '',
  3180. 'port' => $ldapPort,
  3181. 'follow_referrals' => false,
  3182. 'use_ssl' => false,
  3183. 'use_tls' => false,
  3184. 'version' => 3,
  3185. 'timeout' => 5,
  3186. // Custom LDAP Options
  3187. 'custom_options' => [
  3188. // See: http://php.net/ldap_set_option
  3189. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  3190. ]
  3191. ];
  3192. // Add a connection provider to Adldap.
  3193. $ad->addProvider($config);
  3194. try {
  3195. // If a successful connection is made to your server, the provider will be returned.
  3196. $provider = $ad->connect();
  3197. } catch (\Adldap\Auth\BindException $e) {
  3198. $detailedError = $e->getDetailedError();
  3199. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), 'SYSTEM');
  3200. return $detailedError->getErrorMessage();
  3201. // There was an issue binding / connecting to the server.
  3202. }
  3203. return ($provider) ? true : false;
  3204. }
  3205. return false;
  3206. break;
  3207. default :
  3208. return false;
  3209. }
  3210. return false;
  3211. }