homepage-connect-functions.php 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169
  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. $dateTimeOriginalTZ = new DateTimeZone($originalTimeZone);
  1452. $dateTimeOriginal = new DateTime('now', $dateTimeOriginalTZ);
  1453. $dateTimeUTCTZ = new DateTimeZone(date_default_timezone_get());
  1454. $dateTimeUTC = new DateTime('now', $dateTimeUTCTZ);
  1455. $dateTimeOriginalOffset = $dateTimeOriginal->getOffset() / 3600;
  1456. $dateTimeUTCOffset = $dateTimeUTC->getOffset() / 3600;
  1457. $diff = $dateTimeUTCOffset - $dateTimeOriginalOffset;
  1458. $startDt->modify('+ ' . $diff . ' hour');
  1459. $endDt->modify('+ ' . $diff . ' hour');
  1460. }
  1461. $startDt->setTimeZone(new DateTimezone ($timeZone));
  1462. $endDt->setTimeZone(new DateTimezone ($timeZone));
  1463. $startDate = $startDt->format(DateTime::ATOM);
  1464. $endDate = $endDt->format(DateTime::ATOM);
  1465. if (new DateTime() < $endDt) {
  1466. $extraClass = 'text-info';
  1467. } else {
  1468. $extraClass = 'text-success';
  1469. }
  1470. /* Getting the name of event */
  1471. $eventName = $icsEvent['SUMMARY'];
  1472. if (!calendarDaysCheck($calendarStartDiff->format('%R') . $calendarStartDiff->days, $calendarEndDiff->format('%R') . $calendarEndDiff->days)) {
  1473. break;
  1474. }
  1475. if (isset($icsEvent["RRULE"]) && getCalenderRepeatUntil(trim($icsEvent["RRULE"]))) {
  1476. $untilDate = new DateTime (getCalenderRepeatUntil(trim($icsEvent["RRULE"])));
  1477. $untilDiff = date_diff($currentDate, $untilDate);
  1478. if ($untilDiff->days > 0) {
  1479. break;
  1480. }
  1481. }
  1482. $icalEvents[] = array(
  1483. 'title' => $eventName,
  1484. 'imagetype' => 'calendar-o text-warning text-custom-calendar ' . $extraClass,
  1485. 'imagetypeFilter' => 'ical',
  1486. 'className' => 'bg-calendar calendar-item bg-custom-calendar',
  1487. 'start' => $startDate,
  1488. 'end' => $endDate,
  1489. 'bgColor' => str_replace('text', 'bg', $extraClass),
  1490. );
  1491. $calendarTimes = $calendarTimes + 1;
  1492. }
  1493. }
  1494. }
  1495. }
  1496. }
  1497. $calendarSources['ical'] = $icalEvents;
  1498. }
  1499. $calendarSources['events'] = $calendarItems;
  1500. return ($calendarSources) ? $calendarSources : false;
  1501. }
  1502. function calendarDaysCheck($entryStart, $entryEnd)
  1503. {
  1504. $success = false;
  1505. $entryStart = intval($entryStart);
  1506. $entryEnd = intval($entryEnd);
  1507. if ($entryStart >= 0 && $entryEnd <= 0) {
  1508. $success = true;
  1509. }
  1510. return $success;
  1511. }
  1512. function getCalenderRepeat($value)
  1513. {
  1514. //FREQ=DAILY
  1515. //RRULE:FREQ=WEEKLY;BYDAY=TH
  1516. $first = explode('=', $value);
  1517. if (count($first) > 1) {
  1518. $second = explode(';', $first[1]);
  1519. } else {
  1520. return $value;
  1521. }
  1522. if ($second) {
  1523. return $second[0];
  1524. } else {
  1525. return $first[1];
  1526. }
  1527. }
  1528. function getCalenderRepeatUntil($value)
  1529. {
  1530. $first = explode('UNTIL=', $value);
  1531. if (count($first) > 1) {
  1532. if (strpos($first[1], ';') !== false) {
  1533. $check = explode(';', $first[1]);
  1534. return $check[0];
  1535. } else {
  1536. return $first[1];
  1537. }
  1538. } else {
  1539. return false;
  1540. }
  1541. }
  1542. function getCalenderRepeatCount($value)
  1543. {
  1544. $first = explode('COUNT=', $value);
  1545. if (count($first) > 1) {
  1546. return $first[1];
  1547. } else {
  1548. return false;
  1549. }
  1550. }
  1551. function getSonarrCalendar($array, $number)
  1552. {
  1553. $array = json_decode($array, true);
  1554. $gotCalendar = array();
  1555. $i = 0;
  1556. foreach ($array as $child) {
  1557. $i++;
  1558. $seriesName = $child['series']['title'];
  1559. $seriesID = $child['series']['tvdbId'];
  1560. $episodeID = $child['series']['tvdbId'];
  1561. $monitored = $child['monitored'];
  1562. if (!isset($episodeID)) {
  1563. $episodeID = "";
  1564. }
  1565. //$episodeName = htmlentities($child['title'], ENT_QUOTES);
  1566. $episodeAirDate = $child['airDateUtc'];
  1567. $episodeAirDate = strtotime($episodeAirDate);
  1568. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1569. if (new DateTime() < new DateTime($episodeAirDate)) {
  1570. $unaired = true;
  1571. }
  1572. if ($child['episodeNumber'] == "1") {
  1573. $episodePremier = "true";
  1574. } else {
  1575. $episodePremier = "false";
  1576. $date = new DateTime($episodeAirDate);
  1577. $date->add(new DateInterval("PT1S"));
  1578. $date->format(DateTime::ATOM);
  1579. $child['airDateUtc'] = gmdate('Y-m-d\TH:i:s\Z', strtotime($date->format(DateTime::ATOM)));
  1580. }
  1581. $downloaded = $child['hasFile'];
  1582. if ($downloaded == "0" && isset($unaired) && $episodePremier == "true") {
  1583. $downloaded = "text-primary animated flash";
  1584. } elseif ($downloaded == "0" && isset($unaired) && $monitored == "0") {
  1585. $downloaded = "text-dark";
  1586. } elseif ($downloaded == "0" && isset($unaired)) {
  1587. $downloaded = "text-info";
  1588. } elseif ($downloaded == "1") {
  1589. $downloaded = "text-success";
  1590. } else {
  1591. $downloaded = "text-danger";
  1592. }
  1593. $fanart = "/plugins/images/cache/no-np.png";
  1594. foreach ($child['series']['images'] as $image) {
  1595. if ($image['coverType'] == "fanart") {
  1596. $fanart = $image['url'];
  1597. }
  1598. }
  1599. if ($fanart !== "/plugins/images/cache/no-np.png" || (strpos($fanart, '://') === false)) {
  1600. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1601. $imageURL = $fanart;
  1602. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1603. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1604. if (!file_exists($cacheFile)) {
  1605. cacheImage($imageURL, $seriesID);
  1606. unset($imageURL);
  1607. unset($cacheFile);
  1608. }
  1609. }
  1610. $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
  1611. $details = array(
  1612. "seasonCount" => $child['series']['seasonCount'],
  1613. "status" => $child['series']['status'],
  1614. "topTitle" => $seriesName,
  1615. "bottomTitle" => $bottomTitle,
  1616. "overview" => isset($child['overview']) ? $child['overview'] : '',
  1617. "runtime" => $child['series']['runtime'],
  1618. "image" => $fanart,
  1619. "ratings" => $child['series']['ratings']['value'],
  1620. "videoQuality" => $child["hasFile"] && isset($child['episodeFile']['quality']['quality']['name']) ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
  1621. "audioChannels" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
  1622. "audioCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
  1623. "videoCodec" => $child["hasFile"] && isset($child['episodeFile']['mediaInfo']) ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
  1624. "size" => $child["hasFile"] && isset($child['episodeFile']['size']) ? $child['episodeFile']['size'] : "unknown",
  1625. "genres" => $child['series']['genres'],
  1626. );
  1627. array_push($gotCalendar, array(
  1628. "id" => "Sonarr-" . $number . "-" . $i,
  1629. "title" => $seriesName,
  1630. "start" => $child['airDateUtc'],
  1631. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1632. "imagetype" => "tv " . $downloaded,
  1633. "imagetypeFilter" => "tv",
  1634. "downloadFilter" => $downloaded,
  1635. "bgColor" => str_replace('text', 'bg', $downloaded),
  1636. "details" => $details
  1637. ));
  1638. }
  1639. if ($i != 0) {
  1640. return $gotCalendar;
  1641. }
  1642. return false;
  1643. }
  1644. function getLidarrCalendar($array, $number)
  1645. {
  1646. $array = json_decode($array, true);
  1647. $gotCalendar = array();
  1648. $i = 0;
  1649. foreach ($array as $child) {
  1650. $i++;
  1651. $albumName = $child['title'];
  1652. $artistName = $child['artist']['artistName'];
  1653. $albumID = '';
  1654. $releaseDate = $child['releaseDate'];
  1655. $releaseDate = strtotime($releaseDate);
  1656. $releaseDate = date("Y-m-d H:i:s", $releaseDate);
  1657. if (new DateTime() < new DateTime($releaseDate)) {
  1658. $unaired = true;
  1659. }
  1660. if (isset($child['statistics']['percentOfTracks'])) {
  1661. if ($child['statistics']['percentOfTracks'] == '100.0') {
  1662. $downloaded = '1';
  1663. } else {
  1664. $downloaded = '0';
  1665. }
  1666. } else {
  1667. $downloaded = '0';
  1668. }
  1669. if ($downloaded == "0" && isset($unaired)) {
  1670. $downloaded = "text-info";
  1671. } elseif ($downloaded == "1") {
  1672. $downloaded = "text-success";
  1673. } else {
  1674. $downloaded = "text-danger";
  1675. }
  1676. $fanart = "/plugins/images/cache/no-np.png";
  1677. foreach ($child['artist']['images'] as $image) {
  1678. if ($image['coverType'] == "fanart") {
  1679. $fanart = str_replace('http://', 'https://', $image['url']);
  1680. }
  1681. }
  1682. $details = array(
  1683. "seasonCount" => '',
  1684. "status" => '',
  1685. "topTitle" => $albumName,
  1686. "bottomTitle" => $artistName,
  1687. "overview" => isset($child['artist']['overview']) ? $child['artist']['overview'] : '',
  1688. "runtime" => '',
  1689. "image" => $fanart,
  1690. "ratings" => $child['artist']['ratings']['value'],
  1691. "videoQuality" => "unknown",
  1692. "audioChannels" => "unknown",
  1693. "audioCodec" => "unknown",
  1694. "videoCodec" => "unknown",
  1695. "size" => "unknown",
  1696. "genres" => $child['genres'],
  1697. );
  1698. array_push($gotCalendar, array(
  1699. "id" => "Lidarr-" . $number . "-" . $i,
  1700. "title" => $artistName,
  1701. "start" => $child['releaseDate'],
  1702. "className" => "inline-popups bg-calendar calendar-item musicID--",
  1703. "imagetype" => "music " . $downloaded,
  1704. "imagetypeFilter" => "music",
  1705. "downloadFilter" => $downloaded,
  1706. "bgColor" => str_replace('text', 'bg', $downloaded),
  1707. "details" => $details,
  1708. "data" => $child
  1709. ));
  1710. }
  1711. if ($i != 0) {
  1712. return $gotCalendar;
  1713. }
  1714. return false;
  1715. }
  1716. function getRadarrCalendar($array, $number, $url)
  1717. {
  1718. $url = rtrim($url, '/'); //remove trailing slash
  1719. $url = $url . '/api';
  1720. $array = json_decode($array, true);
  1721. $gotCalendar = array();
  1722. $i = 0;
  1723. foreach ($array as $child) {
  1724. if (isset($child['physicalRelease'])) {
  1725. $i++;
  1726. $movieName = $child['title'];
  1727. $movieID = $child['tmdbId'];
  1728. if (!isset($movieID)) {
  1729. $movieID = "";
  1730. }
  1731. $physicalRelease = $child['physicalRelease'];
  1732. $physicalRelease = strtotime($physicalRelease);
  1733. $physicalRelease = date("Y-m-d", $physicalRelease);
  1734. if (new DateTime() < new DateTime($physicalRelease)) {
  1735. $notReleased = "true";
  1736. } else {
  1737. $notReleased = "false";
  1738. }
  1739. $downloaded = $child['hasFile'];
  1740. if ($downloaded == "0" && $notReleased == "true") {
  1741. $downloaded = "text-info";
  1742. } elseif ($downloaded == "1") {
  1743. $downloaded = "text-success";
  1744. } else {
  1745. $downloaded = "text-danger";
  1746. }
  1747. $banner = "/plugins/images/cache/no-np.png";
  1748. foreach ($child['images'] as $image) {
  1749. if ($image['coverType'] == "banner" || $image['coverType'] == "fanart") {
  1750. if (strpos($image['url'], '://') === false) {
  1751. $imageUrl = $image['url'];
  1752. $urlParts = explode("/", $url);
  1753. $imageParts = explode("/", $image['url']);
  1754. if ($imageParts[1] == end($urlParts)) {
  1755. unset($imageParts[1]);
  1756. $imageUrl = implode("/", $imageParts);
  1757. }
  1758. $banner = $url . $imageUrl . '?apikey=' . $GLOBALS['radarrToken'];
  1759. } else {
  1760. $banner = $image['url'];
  1761. }
  1762. }
  1763. }
  1764. if ($banner !== "/plugins/images/cache/no-np.png" || (strpos($banner, 'apikey') !== false)) {
  1765. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1766. $imageURL = $banner;
  1767. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1768. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1769. if (!file_exists($cacheFile)) {
  1770. cacheImage($imageURL, $movieID);
  1771. unset($imageURL);
  1772. unset($cacheFile);
  1773. }
  1774. }
  1775. $alternativeTitles = "";
  1776. foreach ($child['alternativeTitles'] as $alternative) {
  1777. $alternativeTitles .= $alternative['title'] . ', ';
  1778. }
  1779. $alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
  1780. $details = array(
  1781. "topTitle" => $movieName,
  1782. "bottomTitle" => $alternativeTitles,
  1783. "status" => $child['status'],
  1784. "overview" => $child['overview'],
  1785. "runtime" => $child['runtime'],
  1786. "image" => $banner,
  1787. "ratings" => $child['ratings']['value'],
  1788. "videoQuality" => $child["hasFile"] ? @$child['movieFile']['quality']['quality']['name'] : "unknown",
  1789. "audioChannels" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
  1790. "audioCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
  1791. "videoCodec" => $child["hasFile"] ? @$child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
  1792. "size" => $child["hasFile"] ? @$child['movieFile']['size'] : "unknown",
  1793. "genres" => $child['genres'],
  1794. "year" => isset($child['year']) ? $child['year'] : '',
  1795. "studio" => isset($child['studio']) ? $child['studio'] : '',
  1796. );
  1797. array_push($gotCalendar, array(
  1798. "id" => "Radarr-" . $number . "-" . $i,
  1799. "title" => $movieName,
  1800. "start" => $physicalRelease,
  1801. "className" => "inline-popups bg-calendar movieID--" . $movieID,
  1802. "imagetype" => "film " . $downloaded,
  1803. "imagetypeFilter" => "film",
  1804. "downloadFilter" => $downloaded,
  1805. "bgColor" => str_replace('text', 'bg', $downloaded),
  1806. "details" => $details
  1807. ));
  1808. }
  1809. }
  1810. if ($i != 0) {
  1811. return $gotCalendar;
  1812. }
  1813. return false;
  1814. }
  1815. function getCouchCalendar($array, $number)
  1816. {
  1817. $api = json_decode($array, true);
  1818. $gotCalendar = array();
  1819. $i = 0;
  1820. foreach ($api['movies'] as $child) {
  1821. if ($child['status'] == "active" || $child['status'] == "done") {
  1822. $i++;
  1823. $movieName = $child['info']['original_title'];
  1824. $movieID = $child['info']['tmdb_id'];
  1825. if (!isset($movieID)) {
  1826. $movieID = "";
  1827. }
  1828. $physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
  1829. $backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
  1830. $physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
  1831. $physicalRelease = strtotime($physicalRelease);
  1832. $physicalRelease = date("Y-m-d", $physicalRelease);
  1833. if (new DateTime() < new DateTime($physicalRelease)) {
  1834. $notReleased = "true";
  1835. } else {
  1836. $notReleased = "false";
  1837. }
  1838. $downloaded = ($child['status'] == "active") ? "0" : "1";
  1839. if ($downloaded == "0" && $notReleased == "true") {
  1840. $downloaded = "text-info";
  1841. } elseif ($downloaded == "1") {
  1842. $downloaded = "text-success";
  1843. } else {
  1844. $downloaded = "text-danger";
  1845. }
  1846. if (!empty($child['info']['images']['backdrop_original'])) {
  1847. $banner = $child['info']['images']['backdrop_original'][0];
  1848. } elseif (!empty($child['info']['images']['backdrop'])) {
  1849. $banner = $child['info']['images']['backdrop_original'][0];
  1850. } else {
  1851. $banner = "/plugins/images/cache/no-np.png";
  1852. }
  1853. if ($banner !== "/plugins/images/cache/no-np.png") {
  1854. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1855. $imageURL = $banner;
  1856. $cacheFile = $cacheDirectory . $movieID . '.jpg';
  1857. $banner = 'plugins/images/cache/' . $movieID . '.jpg';
  1858. if (!file_exists($cacheFile)) {
  1859. cacheImage($imageURL, $movieID);
  1860. unset($imageURL);
  1861. unset($cacheFile);
  1862. }
  1863. }
  1864. $hasFile = (!empty($child['releases']) && !empty($child['releases'][0]['files']['movie']));
  1865. $details = array(
  1866. "topTitle" => $movieName,
  1867. "bottomTitle" => $child['info']['tagline'],
  1868. "status" => $child['status'],
  1869. "overview" => $child['info']['plot'],
  1870. "runtime" => $child['info']['runtime'],
  1871. "image" => $banner,
  1872. "ratings" => isset($child['info']['rating']['imdb'][0]) ? $child['info']['rating']['imdb'][0] : '',
  1873. "videoQuality" => $hasFile ? $child['releases'][0]['quality'] : "unknown",
  1874. "audioChannels" => "",
  1875. "audioCodec" => "",
  1876. "videoCodec" => "",
  1877. "genres" => $child['info']['genres'],
  1878. "year" => isset($child['info']['year']) ? $child['info']['year'] : '',
  1879. "studio" => isset($child['info']['year']) ? $child['info']['year'] : '',
  1880. );
  1881. array_push($gotCalendar, array(
  1882. "id" => "CouchPotato-" . $number . "-" . $i,
  1883. "title" => $movieName,
  1884. "start" => $physicalRelease,
  1885. "className" => "inline-popups bg-calendar calendar-item movieID--" . $movieID,
  1886. "imagetype" => "film " . $downloaded,
  1887. "imagetypeFilter" => "film",
  1888. "downloadFilter" => $downloaded,
  1889. "bgColor" => str_replace('text', 'bg', $downloaded),
  1890. "details" => $details
  1891. ));
  1892. }
  1893. }
  1894. if ($i != 0) {
  1895. return $gotCalendar;
  1896. }
  1897. return false;
  1898. }
  1899. function getSickrageCalendarWanted($array, $number)
  1900. {
  1901. $array = json_decode($array, true);
  1902. $gotCalendar = array();
  1903. $i = 0;
  1904. foreach ($array['data']['missed'] as $child) {
  1905. $i++;
  1906. $seriesName = $child['show_name'];
  1907. $seriesID = $child['tvdbid'];
  1908. $episodeID = $child['tvdbid'];
  1909. $episodeAirDate = $child['airdate'];
  1910. $episodeAirDateTime = explode(" ", $child['airs']);
  1911. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1912. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1913. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1914. if (new DateTime() < new DateTime($episodeAirDate)) {
  1915. $unaired = true;
  1916. }
  1917. $downloaded = "0";
  1918. if ($downloaded == "0" && isset($unaired)) {
  1919. $downloaded = "text-info";
  1920. } elseif ($downloaded == "1") {
  1921. $downloaded = "text-success";
  1922. } else {
  1923. $downloaded = "text-danger";
  1924. }
  1925. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1926. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1927. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1928. $fanart = "/plugins/images/cache/no-np.png";
  1929. if (file_exists($cacheFile)) {
  1930. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1931. unset($cacheFile);
  1932. }
  1933. $details = array(
  1934. "seasonCount" => "",
  1935. "status" => $child['show_status'],
  1936. "topTitle" => $seriesName,
  1937. "bottomTitle" => $bottomTitle,
  1938. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1939. "runtime" => "",
  1940. "image" => $fanart,
  1941. "ratings" => "",
  1942. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  1943. "audioChannels" => "",
  1944. "audioCodec" => "",
  1945. "videoCodec" => "",
  1946. "size" => "",
  1947. "genres" => "",
  1948. );
  1949. array_push($gotCalendar, array(
  1950. "id" => "Sick-" . $number . "-Miss-" . $i,
  1951. "title" => $seriesName,
  1952. "start" => $episodeAirDate,
  1953. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  1954. "imagetype" => "tv " . $downloaded,
  1955. "imagetypeFilter" => "tv",
  1956. "downloadFilter" => $downloaded,
  1957. "bgColor" => str_replace('text', 'bg', $downloaded),
  1958. "details" => $details,
  1959. ));
  1960. }
  1961. foreach ($array['data']['today'] as $child) {
  1962. $i++;
  1963. $seriesName = $child['show_name'];
  1964. $seriesID = $child['tvdbid'];
  1965. $episodeID = $child['tvdbid'];
  1966. $episodeAirDate = $child['airdate'];
  1967. $episodeAirDateTime = explode(" ", $child['airs']);
  1968. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  1969. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  1970. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1971. if (new DateTime() < new DateTime($episodeAirDate)) {
  1972. $unaired = true;
  1973. }
  1974. $downloaded = "0";
  1975. if ($downloaded == "0" && isset($unaired)) {
  1976. $downloaded = "text-info";
  1977. } elseif ($downloaded == "1") {
  1978. $downloaded = "text-success";
  1979. } else {
  1980. $downloaded = "text-danger";
  1981. }
  1982. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  1983. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  1984. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  1985. $fanart = "/plugins/images/cache/no-np.png";
  1986. if (file_exists($cacheFile)) {
  1987. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  1988. unset($cacheFile);
  1989. }
  1990. $details = array(
  1991. "seasonCount" => "",
  1992. "status" => $child['show_status'],
  1993. "topTitle" => $seriesName,
  1994. "bottomTitle" => $bottomTitle,
  1995. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  1996. "runtime" => "",
  1997. "image" => $fanart,
  1998. "ratings" => "",
  1999. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  2000. "audioChannels" => "",
  2001. "audioCodec" => "",
  2002. "videoCodec" => "",
  2003. "size" => "",
  2004. "genres" => "",
  2005. );
  2006. array_push($gotCalendar, array(
  2007. "id" => "Sick-" . $number . "-Today-" . $i,
  2008. "title" => $seriesName,
  2009. "start" => $episodeAirDate,
  2010. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2011. "imagetype" => "tv " . $downloaded,
  2012. "imagetypeFilter" => "tv",
  2013. "downloadFilter" => $downloaded,
  2014. "bgColor" => str_replace('text', 'bg', $downloaded),
  2015. "details" => $details,
  2016. ));
  2017. }
  2018. foreach ($array['data']['soon'] as $child) {
  2019. $i++;
  2020. $seriesName = $child['show_name'];
  2021. $seriesID = $child['tvdbid'];
  2022. $episodeID = $child['tvdbid'];
  2023. $episodeAirDate = $child['airdate'];
  2024. $episodeAirDateTime = explode(" ", $child['airs']);
  2025. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  2026. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  2027. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2028. if (new DateTime() < new DateTime($episodeAirDate)) {
  2029. $unaired = true;
  2030. }
  2031. $downloaded = "0";
  2032. if ($downloaded == "0" && isset($unaired)) {
  2033. $downloaded = "text-info";
  2034. } elseif ($downloaded == "1") {
  2035. $downloaded = "text-success";
  2036. } else {
  2037. $downloaded = "text-danger";
  2038. }
  2039. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  2040. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2041. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  2042. $fanart = "/plugins/images/cache/no-np.png";
  2043. if (file_exists($cacheFile)) {
  2044. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  2045. unset($cacheFile);
  2046. }
  2047. $details = array(
  2048. "seasonCount" => "",
  2049. "status" => $child['show_status'],
  2050. "topTitle" => $seriesName,
  2051. "bottomTitle" => $bottomTitle,
  2052. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  2053. "runtime" => "",
  2054. "image" => $fanart,
  2055. "ratings" => "",
  2056. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  2057. "audioChannels" => "",
  2058. "audioCodec" => "",
  2059. "videoCodec" => "",
  2060. "size" => "",
  2061. "genres" => "",
  2062. );
  2063. array_push($gotCalendar, array(
  2064. "id" => "Sick-" . $number . "-Soon-" . $i,
  2065. "title" => $seriesName,
  2066. "start" => $episodeAirDate,
  2067. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2068. "imagetype" => "tv " . $downloaded,
  2069. "imagetypeFilter" => "tv",
  2070. "downloadFilter" => $downloaded,
  2071. "bgColor" => str_replace('text', 'bg', $downloaded),
  2072. "details" => $details,
  2073. ));
  2074. }
  2075. foreach ($array['data']['later'] as $child) {
  2076. $i++;
  2077. $seriesName = $child['show_name'];
  2078. $seriesID = $child['tvdbid'];
  2079. $episodeID = $child['tvdbid'];
  2080. $episodeAirDate = $child['airdate'];
  2081. $episodeAirDateTime = explode(" ", $child['airs']);
  2082. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
  2083. $episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
  2084. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2085. if (new DateTime() < new DateTime($episodeAirDate)) {
  2086. $unaired = true;
  2087. }
  2088. $downloaded = "0";
  2089. if ($downloaded == "0" && isset($unaired)) {
  2090. $downloaded = "text-info";
  2091. } elseif ($downloaded == "1") {
  2092. $downloaded = "text-success";
  2093. } else {
  2094. $downloaded = "text-danger";
  2095. }
  2096. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
  2097. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2098. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  2099. $fanart = "/plugins/images/cache/no-np.png";
  2100. if (file_exists($cacheFile)) {
  2101. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  2102. unset($cacheFile);
  2103. }
  2104. $details = array(
  2105. "seasonCount" => "",
  2106. "status" => $child['show_status'],
  2107. "topTitle" => $seriesName,
  2108. "bottomTitle" => $bottomTitle,
  2109. "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
  2110. "runtime" => "",
  2111. "image" => $fanart,
  2112. "ratings" => "",
  2113. "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
  2114. "audioChannels" => "",
  2115. "audioCodec" => "",
  2116. "videoCodec" => "",
  2117. "size" => "",
  2118. "genres" => "",
  2119. );
  2120. array_push($gotCalendar, array(
  2121. "id" => "Sick-" . $number . "-Later-" . $i,
  2122. "title" => $seriesName,
  2123. "start" => $episodeAirDate,
  2124. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2125. "imagetype" => "tv " . $downloaded,
  2126. "imagetypeFilter" => "tv",
  2127. "downloadFilter" => $downloaded,
  2128. "bgColor" => str_replace('text', 'bg', $downloaded),
  2129. "details" => $details,
  2130. ));
  2131. }
  2132. if ($i != 0) {
  2133. return $gotCalendar;
  2134. }
  2135. return false;
  2136. }
  2137. function getSickrageCalendarHistory($array, $number)
  2138. {
  2139. $array = json_decode($array, true);
  2140. $gotCalendar = array();
  2141. $i = 0;
  2142. foreach ($array['data'] as $child) {
  2143. $i++;
  2144. $seriesName = $child['show_name'];
  2145. $seriesID = $child['tvdbid'];
  2146. $episodeID = $child['tvdbid'];
  2147. $episodeAirDate = $child['date'];
  2148. $downloaded = "text-success";
  2149. $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']);
  2150. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2151. $cacheFile = $cacheDirectory . $seriesID . '.jpg';
  2152. $fanart = "/plugins/images/cache/no-np.png";
  2153. if (file_exists($cacheFile)) {
  2154. $fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
  2155. unset($cacheFile);
  2156. }
  2157. $details = array(
  2158. "seasonCount" => "",
  2159. "status" => $child['status'],
  2160. "topTitle" => $seriesName,
  2161. "bottomTitle" => $bottomTitle,
  2162. "overview" => '',
  2163. "runtime" => isset($child['series']['runtime']) ? $child['series']['runtime'] : 30,
  2164. "image" => $fanart,
  2165. "ratings" => isset($child['series']['ratings']['value']) ? $child['series']['ratings']['value'] : "unknown",
  2166. "videoQuality" => isset($child["quality"]) ? $child['quality'] : "unknown",
  2167. "audioChannels" => "",
  2168. "audioCodec" => "",
  2169. "videoCodec" => "",
  2170. "size" => "",
  2171. "genres" => "",
  2172. );
  2173. array_push($gotCalendar, array(
  2174. "id" => "Sick-" . $number . "-History-" . $i,
  2175. "title" => $seriesName,
  2176. "start" => $episodeAirDate,
  2177. "className" => "inline-popups bg-calendar calendar-item tvID--" . $episodeID,
  2178. "imagetype" => "tv " . $downloaded,
  2179. "imagetypeFilter" => "tv",
  2180. "downloadFilter" => $downloaded,
  2181. "bgColor" => str_replace('text', 'bg', $downloaded),
  2182. "details" => $details,
  2183. ));
  2184. }
  2185. if ($i != 0) {
  2186. return $gotCalendar;
  2187. }
  2188. return false;
  2189. }
  2190. function ombiAPI($array)
  2191. {
  2192. return ombiAction($array['data']['id'], $array['data']['action'], $array['data']['type'], $array['data']);
  2193. }
  2194. function ombiImport($type = null)
  2195. {
  2196. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && !empty($type)) {
  2197. try {
  2198. $url = qualifyURL($GLOBALS['ombiURL']);
  2199. $headers = array(
  2200. "Accept" => "application/json",
  2201. "Content-Type" => "application/json",
  2202. "Apikey" => $GLOBALS['ombiToken']
  2203. );
  2204. $options = (localURL($url)) ? array('verify' => false) : array();
  2205. switch ($type) {
  2206. case 'emby':
  2207. case 'emby_local':
  2208. case 'emby_connect':
  2209. case 'emby_all':
  2210. $response = Requests::post($url . "/api/v1/Job/embyuserimporter", $headers, $options);
  2211. break;
  2212. case 'plex':
  2213. $response = Requests::post($url . "/api/v1/Job/plexuserimporter", $headers, $options);
  2214. break;
  2215. default:
  2216. return false;
  2217. break;
  2218. }
  2219. if ($response->success) {
  2220. writeLog('success', 'OMBI Connect Function - Ran User Import', 'SYSTEM');
  2221. return true;
  2222. } else {
  2223. writeLog('error', 'OMBI Connect Function - Error: Connection Unsuccessful', 'SYSTEM');
  2224. return false;
  2225. }
  2226. } catch (Requests_Exception $e) {
  2227. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2228. return false;
  2229. };
  2230. }
  2231. return false;
  2232. }
  2233. function ombiAction($id, $action, $type, $fullArray = null)
  2234. {
  2235. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  2236. $url = qualifyURL($GLOBALS['ombiURL']);
  2237. $headers = array(
  2238. "Accept" => "application/json",
  2239. "Content-Type" => "application/json",
  2240. "Apikey" => $GLOBALS['ombiToken']
  2241. );
  2242. $data = array(
  2243. 'id' => $id,
  2244. );
  2245. switch ($type) {
  2246. case 'season':
  2247. case 'tv':
  2248. $type = 'tv';
  2249. $add = array(
  2250. 'tvDbId' => $id,
  2251. 'requestAll' => ombiTVDefault('all'),
  2252. 'latestSeason' => ombiTVDefault('last'),
  2253. 'firstSeason' => ombiTVDefault('first')
  2254. );
  2255. break;
  2256. default:
  2257. $type = 'movie';
  2258. $add = array("theMovieDbId" => (int)$id);
  2259. break;
  2260. }
  2261. $success['head'] = $headers;
  2262. $success['act'] = $action;
  2263. $success['data'] = $data;
  2264. $success['add'] = $add;
  2265. $success['type'] = $type;
  2266. try {
  2267. $options = (localURL($url)) ? array('verify' => false) : array();
  2268. switch ($action) {
  2269. case 'add':
  2270. if (isset($_COOKIE['Auth'])) {
  2271. $headers = array(
  2272. "Accept" => "application/json",
  2273. "Content-Type" => "application/json",
  2274. "Authorization" => "Bearer " . $_COOKIE['Auth']
  2275. );
  2276. $success['head'] = $headers;
  2277. } else {
  2278. return false;
  2279. }
  2280. $response = Requests::post($url . "/api/v1/Request/" . $type, $headers, json_encode($add), $options);
  2281. break;
  2282. default:
  2283. if (qualifyRequest(1)) {
  2284. switch ($action) {
  2285. case 'approve':
  2286. $response = Requests::post($url . "/api/v1/Request/" . $type . "/approve", $headers, json_encode($data), $options);
  2287. break;
  2288. case 'available':
  2289. $response = Requests::post($url . "/api/v1/Request/" . $type . "/available", $headers, json_encode($data), $options);
  2290. break;
  2291. case 'unavailable':
  2292. $response = Requests::post($url . "/api/v1/Request/" . $type . "/unavailable", $headers, json_encode($data), $options);
  2293. break;
  2294. case 'deny':
  2295. $response = Requests::put($url . "/api/v1/Request/" . $type . "/deny", $headers, json_encode($data), $options);
  2296. break;
  2297. case 'delete':
  2298. $response = Requests::delete($url . "/api/v1/Request/" . $type . "/" . $id, $headers, $options);
  2299. break;
  2300. default:
  2301. return false;
  2302. }
  2303. }
  2304. break;
  2305. }
  2306. $success['api'] = $response;
  2307. $success['bd'] = $response->body;
  2308. $success['hd'] = $response->headers;
  2309. if ($response->success) {
  2310. $success['ok'] = true;
  2311. }
  2312. } catch (Requests_Exception $e) {
  2313. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2314. };
  2315. }
  2316. return isset($success['ok']) ? $success : false;
  2317. }
  2318. function getOmbiRequests($type = "both", $limit = 50)
  2319. {
  2320. $api['count'] = array(
  2321. 'movie' => 0,
  2322. 'tv' => 0,
  2323. 'limit' => (integer)$limit
  2324. );
  2325. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  2326. $url = qualifyURL($GLOBALS['ombiURL']);
  2327. $headers = array(
  2328. "Accept" => "application/json",
  2329. "Apikey" => $GLOBALS['ombiToken'],
  2330. );
  2331. $requests = array();
  2332. try {
  2333. $options = (localURL($url)) ? array('verify' => false) : array();
  2334. switch ($type) {
  2335. case 'movie':
  2336. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  2337. break;
  2338. case 'tv':
  2339. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  2340. break;
  2341. default:
  2342. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  2343. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  2344. break;
  2345. }
  2346. if ($movie->success || $tv->success) {
  2347. if (isset($movie)) {
  2348. $movie = json_decode($movie->body, true);
  2349. //$movie = array_reverse($movie);
  2350. foreach ($movie as $key => $value) {
  2351. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2352. if ($proceed) {
  2353. $api['count']['movie']++;
  2354. $requests[] = array(
  2355. 'id' => $value['theMovieDbId'],
  2356. 'title' => $value['title'],
  2357. 'overview' => $value['overview'],
  2358. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/' . $value['posterPath'] : 'plugins/images/cache/no-list.png',
  2359. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2360. 'approved' => $value['approved'],
  2361. 'available' => $value['available'],
  2362. 'denied' => $value['denied'],
  2363. 'deniedReason' => $value['deniedReason'],
  2364. 'user' => $value['requestedUser']['userName'],
  2365. 'userAlias' => $value['requestedUser']['userAlias'],
  2366. 'request_id' => $value['id'],
  2367. 'request_date' => $value['requestedDate'],
  2368. 'release_date' => $value['releaseDate'],
  2369. 'type' => 'movie',
  2370. 'icon' => 'mdi mdi-filmstrip',
  2371. 'color' => 'palette-Deep-Purple-900 bg white',
  2372. );
  2373. }
  2374. }
  2375. }
  2376. if (isset($tv) && (is_array($tv) || is_object($tv))) {
  2377. $tv = json_decode($tv->body, true);
  2378. foreach ($tv as $key => $value) {
  2379. if (count($value['childRequests']) > 0) {
  2380. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['childRequests'][0]['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2381. if ($proceed) {
  2382. $api['count']['tv']++;
  2383. $requests[] = array(
  2384. 'id' => $value['tvDbId'],
  2385. 'title' => $value['title'],
  2386. 'overview' => $value['overview'],
  2387. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? $value['posterPath'] : 'plugins/images/cache/no-list.png',
  2388. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2389. 'approved' => $value['childRequests'][0]['approved'],
  2390. 'available' => $value['childRequests'][0]['available'],
  2391. 'denied' => $value['childRequests'][0]['denied'],
  2392. 'deniedReason' => $value['childRequests'][0]['deniedReason'],
  2393. 'user' => $value['childRequests'][0]['requestedUser']['userName'],
  2394. 'userAlias' => $value['childRequests'][0]['requestedUser']['userAlias'],
  2395. 'request_id' => $value['id'],
  2396. 'request_date' => $value['childRequests'][0]['requestedDate'],
  2397. 'release_date' => $value['releaseDate'],
  2398. 'type' => 'tv',
  2399. 'icon' => 'mdi mdi-television',
  2400. 'color' => 'grayish-blue-bg',
  2401. );
  2402. }
  2403. }
  2404. }
  2405. }
  2406. //sort here
  2407. usort($requests, function ($item1, $item2) {
  2408. if ($item1['request_date'] == $item2['request_date']) {
  2409. return 0;
  2410. }
  2411. return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
  2412. });
  2413. }
  2414. } catch (Requests_Exception $e) {
  2415. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2416. };
  2417. }
  2418. $api['content'] = isset($requests) ? array_slice($requests, 0, $limit) : false;
  2419. return $api;
  2420. }
  2421. function unifiConnect()
  2422. {
  2423. if ($GLOBALS['homepageUnifiEnabled'] && !empty($GLOBALS['unifiURL']) && !empty($GLOBALS['unifiSiteName']) && !empty($GLOBALS['unifiUsername']) && !empty($GLOBALS['unifiPassword']) && qualifyRequest($GLOBALS['homepageUnifiAuth'])) {
  2424. $api['content']['unifi'] = array();
  2425. $url = qualifyURL($GLOBALS['unifiURL']);
  2426. $urlStat = $url . '/api/s/' . $GLOBALS['unifiSiteName'] . '/stat/health';
  2427. try {
  2428. $options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => false);
  2429. $data = array(
  2430. 'username' => $GLOBALS['unifiUsername'],
  2431. 'password' => decrypt($GLOBALS['unifiPassword']),
  2432. 'remember' => true,
  2433. 'strict' => true
  2434. );
  2435. $response = Requests::post($url . '/api/login', array(), json_encode($data), $options);
  2436. if ($response->success) {
  2437. $cookie['unifises'] = ($response->cookies['unifises']->value) ?? false;
  2438. $cookie['csrf_token'] = ($response->cookies['csrf_token']->value) ?? false;
  2439. } else {
  2440. return false;
  2441. }
  2442. $headers = array(
  2443. 'cookie' => 'unifises=' . $cookie['unifises'] . ';' . 'csrf_token=' . $cookie['csrf_token'] . ';'
  2444. );
  2445. $response = Requests::get($urlStat, $headers, $options);
  2446. if ($response->success) {
  2447. $api['content']['unifi'] = json_decode($response->body, true);
  2448. }
  2449. } catch (Requests_Exception $e) {
  2450. writeLog('error', 'Unifi Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2451. };
  2452. $api['content']['unifi'] = isset($api['content']['unifi']) ? $api['content']['unifi'] : false;
  2453. return $api;
  2454. }
  2455. return false;
  2456. }
  2457. function getTautulli()
  2458. {
  2459. if ($GLOBALS['homepageTautulliEnabled'] && !empty($GLOBALS['tautulliURL']) && !empty($GLOBALS['tautulliApikey']) && qualifyRequest($GLOBALS['homepageTautulliAuth'])) {
  2460. $api = [];
  2461. $url = qualifyURL($GLOBALS['tautulliURL']);
  2462. $apiURL = $url . '/api/v2?apikey=' . $GLOBALS['tautulliApikey'];
  2463. $height = getCacheImageSize('h');
  2464. $width = getCacheImageSize('w');
  2465. $nowPlayingHeight = getCacheImageSize('nph');
  2466. $nowPlayingWidth = getCacheImageSize('npw');
  2467. try {
  2468. $homestatsUrl = $apiURL . '&cmd=get_home_stats&grouping=1';
  2469. $homestats = Requests::get($homestatsUrl, [], []);
  2470. if ($homestats->success) {
  2471. $homestats = json_decode($homestats->body, true);
  2472. $api['homestats'] = $homestats['response'];
  2473. // Cache art & thumb for first result in each tautulli API result
  2474. $categories = ['top_movies', 'top_tv', 'popular_movies', 'popular_tv'];
  2475. foreach ($categories as $cat) {
  2476. $key = array_search($cat, array_column($api['homestats']['data'], 'stat_id'));
  2477. $img = $api['homestats']['data'][$key]['rows'][0];
  2478. cacheImage($url . '/pms_image_proxy?img=' . $img['art'] . '&rating_key=' . $img['rating_key'] . '&width=' . $nowPlayingWidth . '&height=' . $nowPlayingHeight, $img['rating_key'] . '-np');
  2479. cacheImage($url . '/pms_image_proxy?img=' . $img['thumb'] . '&rating_key=' . $img['rating_key'] . '&width=' . $width . '&height=' . $height, $img['rating_key'] . '-list');
  2480. $img['art'] = 'plugins/images/cache/' . $img['rating_key'] . '-np.jpg';
  2481. $img['thumb'] = 'plugins/images/cache/' . $img['rating_key'] . '-list.jpg';
  2482. $api['homestats']['data'][$key]['rows'][0] = $img;
  2483. }
  2484. // Cache the platform icon
  2485. $key = array_search('top_platforms', array_column($api['homestats']['data'], 'stat_id'));
  2486. $platform = $api['homestats']['data'][$key]['rows'][0]['platform_name'];
  2487. cacheImage($url . '/images/platforms/' . $platform . '.svg', 'tautulli-' . $platform, 'svg');
  2488. }
  2489. $libstatsUrl = $apiURL . '&cmd=get_libraries';
  2490. $libstats = Requests::get($libstatsUrl, [], []);
  2491. if ($libstats->success) {
  2492. $libstats = json_decode($libstats->body, true);
  2493. $api['libstats'] = $libstats['response'];
  2494. $categories = ['movie.svg', 'show.svg', 'artist.svg'];
  2495. foreach ($categories as $cat) {
  2496. $parts = explode('.', $cat);
  2497. cacheImage($url . '/images/libraries/' . $cat, 'tautulli-' . $parts[0], $parts[1]);
  2498. }
  2499. }
  2500. $api['options'] = [
  2501. 'url' => $url,
  2502. 'libraries' => $GLOBALS['tautulliLibraries'],
  2503. 'topMovies' => $GLOBALS['tautulliTopMovies'],
  2504. 'topTV' => $GLOBALS['tautulliTopTV'],
  2505. 'topUsers' => $GLOBALS['tautulliTopUsers'],
  2506. 'topPlatforms' => $GLOBALS['tautulliTopPlatforms'],
  2507. 'popularMovies' => $GLOBALS['tautulliPopularMovies'],
  2508. 'popularTV' => $GLOBALS['tautulliPopularTV'],
  2509. 'title' => $GLOBALS['tautulliHeaderToggle'],
  2510. ];
  2511. $ids = []; // Array of stat_ids to remove from the returned array
  2512. if (!qualifyRequest($GLOBALS['homepageTautulliLibraryAuth'])) {
  2513. $api['options']['libraries'] = false;
  2514. unset($api['libstats']);
  2515. }
  2516. if (!qualifyRequest($GLOBALS['homepageTautulliViewsAuth'])) {
  2517. $api['options']['topMovies'] = false;
  2518. $api['options']['topTV'] = false;
  2519. $api['options']['popularMovies'] = false;
  2520. $api['options']['popularTV'] = false;
  2521. $ids = array_merge(['top_movies', 'popular_movies', 'popular_tv', 'top_tv'], $ids);
  2522. $api['homestats']['data'] = array_values($api['homestats']['data']);
  2523. }
  2524. if (!qualifyRequest($GLOBALS['homepageTautulliMiscAuth'])) {
  2525. $api['options']['topUsers'] = false;
  2526. $api['options']['topPlatforms'] = false;
  2527. $ids = array_merge(['top_platforms', 'top_users'], $ids);
  2528. $api['homestats']['data'] = array_values($api['homestats']['data']);
  2529. }
  2530. $ids = array_merge(['top_music', 'popular_music', 'last_watched', 'most_concurrent'], $ids);
  2531. foreach ($ids as $id) {
  2532. if ($key = array_search($id, array_column($api['homestats']['data'], 'stat_id'))) {
  2533. unset($api['homestats']['data'][$key]);
  2534. $api['homestats']['data'] = array_values($api['homestats']['data']);
  2535. }
  2536. }
  2537. } catch (Requests_Exception $e) {
  2538. writeLog('error', 'Tautulli Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2539. };
  2540. $api = isset($api) ? $api : false;
  2541. return $api;
  2542. }
  2543. return false;
  2544. }
  2545. function getMonitorr()
  2546. {
  2547. if ($GLOBALS['homepageMonitorrEnabled'] && !empty($GLOBALS['monitorrURL']) && qualifyRequest($GLOBALS['homepageMonitorrAuth'])) {
  2548. $api = [];
  2549. $url = qualifyURL($GLOBALS['monitorrURL']);
  2550. $dataUrl = $url . '/assets/php/loop.php';
  2551. try {
  2552. $response = Requests::get($dataUrl, ['Token' => $GLOBALS['organizrAPI']], []);
  2553. if ($response->success) {
  2554. $html = html_entity_decode($response->body);
  2555. // This section grabs the names of all services by regex
  2556. $services = [];
  2557. $servicesMatch = [];
  2558. $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>/';
  2559. preg_match_all($servicePattern, $html, $servicesMatch);
  2560. unset($servicesMatch[0]);
  2561. $servicesMatch = array_values($servicesMatch);
  2562. foreach ($servicesMatch as $group) {
  2563. foreach ($group as $service) {
  2564. if ($service !== '') {
  2565. array_push($services, $service);
  2566. }
  2567. }
  2568. }
  2569. // This section then grabs the status and image of that service with regex
  2570. $statuses = [];
  2571. foreach ($services as $service) {
  2572. $statusPattern = '/' . $service . '<\/div><\/div><div class="btnonline">(Online)<\/div>|' . $service . '<\/div><\/div><div class="btnoffline".*>(Offline)<\/div><\/div><\/div>/';
  2573. $status = [];
  2574. preg_match($statusPattern, $html, $status);
  2575. $statuses[$service] = $status;
  2576. foreach ($status as $match) {
  2577. if ($match == 'Online') {
  2578. $statuses[$service] = [
  2579. 'status' => true
  2580. ];
  2581. } else if ($match == 'Offline') {
  2582. $statuses[$service] = [
  2583. 'status' => false
  2584. ];
  2585. }
  2586. }
  2587. $imageMatch = [];
  2588. $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 . '/';
  2589. preg_match($imgPattern, $html, $imageMatch);
  2590. unset($imageMatch[0]);
  2591. $imageMatch = array_values($imageMatch);
  2592. // array_push($api['imagematches'][$service], $imageMatch);
  2593. foreach ($imageMatch as $match) {
  2594. if ($match !== '') {
  2595. $image = $match;
  2596. }
  2597. }
  2598. $ext = explode('.', $image);
  2599. $ext = $ext[key(array_slice($ext, -1, 1, true))];
  2600. $imageUrl = $url . '/assets' . $image;
  2601. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2602. $img = Requests::get($imageUrl, ['Token' => $GLOBALS['organizrAPI']], []);
  2603. if ($img->success) {
  2604. $base64 = 'data:image/' . $ext . ';base64,' . base64_encode($img->body);
  2605. $statuses[$service]['image'] = $base64;
  2606. } else {
  2607. $statuses[$service]['image'] = $cacheDirectory . 'no-list.png';
  2608. }
  2609. $linkMatch = [];
  2610. $linkPattern = '/<a class="servicetile" href="(.*)" target="_blank" style="display: block"><div id="serviceimg"><div><img id="' . strtolower($service) . '-service-img/';
  2611. preg_match($linkPattern, $html, $linkMatch);
  2612. $linkMatch = array_values($linkMatch);
  2613. unset($linkMatch[0]);
  2614. foreach ($linkMatch as $link) {
  2615. if ($link !== '') {
  2616. $statuses[$service]['link'] = $link;
  2617. }
  2618. }
  2619. }
  2620. ksort($statuses);
  2621. $api['services'] = $statuses;
  2622. $api['options'] = [
  2623. 'title' => $GLOBALS['monitorrHeader'],
  2624. 'titleToggle' => $GLOBALS['monitorrHeaderToggle'],
  2625. 'compact' => $GLOBALS['monitorrCompact'],
  2626. ];
  2627. }
  2628. } catch (Requests_Exception $e) {
  2629. writeLog('error', 'Monitorr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2630. };
  2631. $api = isset($api) ? $api : false;
  2632. return $api;
  2633. }
  2634. }
  2635. function getSpeedtest()
  2636. {
  2637. if ($GLOBALS['homepageSpeedtestEnabled'] && !empty($GLOBALS['speedtestURL']) && qualifyRequest($GLOBALS['homepageSpeedtestAuth'])) {
  2638. $api = [];
  2639. $url = qualifyURL($GLOBALS['speedtestURL']);
  2640. $dataUrl = $url . '/api/speedtest/latest';
  2641. try {
  2642. $response = Requests::get($dataUrl);
  2643. if ($response->success) {
  2644. $json = json_decode($response->body, true);
  2645. $api['data'] = [
  2646. 'current' => $json['data'],
  2647. 'average' => $json['average'],
  2648. 'max' => $json['max'],
  2649. ];
  2650. $api['options'] = [
  2651. 'title' => $GLOBALS['speedtestHeader'],
  2652. 'titleToggle' => $GLOBALS['speedtestHeaderToggle'],
  2653. ];
  2654. }
  2655. } catch (Requests_Exception $e) {
  2656. writeLog('error', 'Speedtest Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2657. };
  2658. $api = isset($api) ? $api : false;
  2659. return $api;
  2660. }
  2661. }
  2662. function getNetdata()
  2663. {
  2664. if ($GLOBALS['homepageNetdataEnabled'] && !empty($GLOBALS['netdataURL']) && qualifyRequest($GLOBALS['homepageNetdataAuth'])) {
  2665. $api = [];
  2666. $url = qualifyURL($GLOBALS['netdataURL']);
  2667. try {
  2668. $response = Requests::get($url);
  2669. if ($response->success) {
  2670. $html = json_decode($response->body, true);
  2671. $api['url'] = $GLOBALS['netdataURL'];
  2672. $api['options'] = [];
  2673. for($i = 0; $i < 5; $i++) {
  2674. if($GLOBALS['netdata'.($i + 1).'Data'] != '') {
  2675. array_push($api['options'], [
  2676. 'title' => $GLOBALS['netdata'.($i + 1).'Title'],
  2677. 'chart' => $GLOBALS['netdata'.($i + 1).'Chart'],
  2678. 'data' => $GLOBALS['netdata'.($i + 1).'Data'],
  2679. 'units' => $GLOBALS['netdata'.($i + 1).'Units'],
  2680. 'commonUnits' => $GLOBALS['netdata'.($i + 1).'CommonUnits'],
  2681. 'dimensions' => $GLOBALS['netdata'.($i + 1).'Dimensions'],
  2682. 'max' => $GLOBALS['netdata'.($i + 1).'Max'],
  2683. 'appendOptions' => $GLOBALS['netdata'.($i + 1).'AppendOptions'],
  2684. ]);
  2685. }
  2686. }
  2687. }
  2688. } catch (Requests_Exception $e) {
  2689. writeLog('error', 'Monitorr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2690. };
  2691. $api = isset($api) ? $api : false;
  2692. return $api;
  2693. }
  2694. }
  2695. function testAPIConnection($array)
  2696. {
  2697. switch ($array['data']['action']) {
  2698. case 'unifiSite':
  2699. if (!empty($GLOBALS['unifiURL']) && !empty($GLOBALS['unifiUsername']) && !empty($GLOBALS['unifiPassword'])) {
  2700. $url = qualifyURL($GLOBALS['unifiURL']);
  2701. try {
  2702. $options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => false);
  2703. $data = array(
  2704. 'username' => $GLOBALS['unifiUsername'],
  2705. 'password' => decrypt($GLOBALS['unifiPassword']),
  2706. 'remember' => true,
  2707. 'strict' => true
  2708. );
  2709. $response = Requests::post($url . '/api/login', array(), json_encode($data), $options);
  2710. if ($response->success) {
  2711. $cookie['unifises'] = ($response->cookies['unifises']->value) ?? false;
  2712. $cookie['csrf_token'] = ($response->cookies['csrf_token']->value) ?? false;
  2713. } else {
  2714. return false;
  2715. }
  2716. $headers = array(
  2717. 'cookie' => 'unifises=' . $cookie['unifises'] . ';' . 'csrf_token=' . $cookie['csrf_token'] . ';'
  2718. );
  2719. $response = Requests::get($url . '/api/self/sites', $headers, $options);
  2720. if ($response->success) {
  2721. $body = json_decode($response->body, true);
  2722. return $body;
  2723. } else {
  2724. return false;
  2725. }
  2726. } catch (Requests_Exception $e) {
  2727. writeLog('error', 'Unifi Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2728. };
  2729. }
  2730. break;
  2731. case 'unifi':
  2732. if (!empty($GLOBALS['unifiURL']) && !empty($GLOBALS['unifiUsername']) && !empty($GLOBALS['unifiPassword']) && !empty($GLOBALS['unifiSiteName'])) {
  2733. $url = qualifyURL($GLOBALS['unifiURL']);
  2734. try {
  2735. $options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => false);
  2736. $data = array(
  2737. 'username' => $GLOBALS['unifiUsername'],
  2738. 'password' => decrypt($GLOBALS['unifiPassword']),
  2739. 'remember' => true,
  2740. 'strict' => true
  2741. );
  2742. $response = Requests::post($url . '/api/login', array(), json_encode($data), $options);
  2743. if ($response->success) {
  2744. $cookie['unifises'] = ($response->cookies['unifises']->value) ?? false;
  2745. $cookie['csrf_token'] = ($response->cookies['csrf_token']->value) ?? false;
  2746. } else {
  2747. return 'Failed to Login';
  2748. }
  2749. $headers = array(
  2750. 'cookie' => 'unifises=' . $cookie['unifises'] . ';' . 'csrf_token=' . $cookie['csrf_token'] . ';'
  2751. );
  2752. $response = Requests::get($url . '/api/s/' . $GLOBALS['unifiSiteName'] . '/self', $headers, $options);
  2753. $body = json_decode($response->body, true);
  2754. return ($body['meta']['rc'] == 'ok') ? true : $body['meta']['msg'];
  2755. } catch (Requests_Exception $e) {
  2756. writeLog('error', 'Unifi Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2757. };
  2758. } else {
  2759. return 'Not all data is filled in...';
  2760. }
  2761. break;
  2762. case 'ombi':
  2763. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken'])) {
  2764. $url = qualifyURL($GLOBALS['ombiURL']);
  2765. $url = $url . "/api/v1/Status/info";
  2766. $headers = array(
  2767. "Accept" => "application/json",
  2768. "Content-Type" => "application/json",
  2769. "Apikey" => $GLOBALS['ombiToken']
  2770. );
  2771. try {
  2772. $options = (localURL($url)) ? array('verify' => false) : array();
  2773. $response = Requests::get($url, $headers, $options);
  2774. if ($response->success) {
  2775. return true;
  2776. } else {
  2777. return $response->body;
  2778. }
  2779. } catch (Requests_Exception $e) {
  2780. return $e->getMessage();
  2781. };
  2782. } else {
  2783. return 'URL and/or Token not setup';
  2784. }
  2785. break;
  2786. case 'plex':
  2787. if (!empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken'])) {
  2788. $url = qualifyURL($GLOBALS['plexURL']);
  2789. $url = $url . "/?X-Plex-Token=" . $GLOBALS['plexToken'];
  2790. try {
  2791. $options = (localURL($url)) ? array('verify' => false) : array();
  2792. $response = Requests::get($url, array(), $options);
  2793. libxml_use_internal_errors(true);
  2794. if ($response->success) {
  2795. return true;
  2796. }
  2797. } catch (Requests_Exception $e) {
  2798. return $e->getMessage();
  2799. };
  2800. } else {
  2801. return 'URL and/or Token not setup';
  2802. }
  2803. break;
  2804. case 'emby':
  2805. break;
  2806. case 'sonarr':
  2807. if (!empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  2808. $sonarrs = array();
  2809. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  2810. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  2811. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2812. foreach ($sonarrURLList as $key => $value) {
  2813. $sonarrs[$key] = array(
  2814. 'url' => $value,
  2815. 'token' => $sonarrTokenList[$key]
  2816. );
  2817. }
  2818. foreach ($sonarrs as $key => $value) {
  2819. try {
  2820. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2821. $result = json_decode($sonarr->getSystemStatus(), true);
  2822. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2823. } catch (Exception $e) {
  2824. return strip($e->getMessage());
  2825. }
  2826. }
  2827. }
  2828. } else {
  2829. return 'URL/s and/or Token/s not setup';
  2830. }
  2831. break;
  2832. case 'lidarr':
  2833. if (!empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  2834. $sonarrs = array();
  2835. $sonarrURLList = explode(',', $GLOBALS['lidarrURL']);
  2836. $sonarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  2837. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2838. foreach ($sonarrURLList as $key => $value) {
  2839. $sonarrs[$key] = array(
  2840. 'url' => $value,
  2841. 'token' => $sonarrTokenList[$key]
  2842. );
  2843. }
  2844. foreach ($sonarrs as $key => $value) {
  2845. try {
  2846. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  2847. $result = json_decode($sonarr->getSystemStatus(), true);
  2848. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2849. } catch (Exception $e) {
  2850. return $e->getMessage();
  2851. }
  2852. }
  2853. }
  2854. } else {
  2855. return 'URL/s and/or Token/s not setup';
  2856. }
  2857. break;
  2858. case 'radarr':
  2859. if (!empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  2860. $sonarrs = array();
  2861. $sonarrURLList = explode(',', $GLOBALS['radarrURL']);
  2862. $sonarrTokenList = explode(',', $GLOBALS['radarrToken']);
  2863. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2864. foreach ($sonarrURLList as $key => $value) {
  2865. $sonarrs[$key] = array(
  2866. 'url' => $value,
  2867. 'token' => $sonarrTokenList[$key]
  2868. );
  2869. }
  2870. foreach ($sonarrs as $key => $value) {
  2871. try {
  2872. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2873. $result = json_decode($sonarr->getSystemStatus(), true);
  2874. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2875. } catch (Exception $e) {
  2876. return $e->getMessage();
  2877. }
  2878. }
  2879. }
  2880. } else {
  2881. return 'URL/s and/or Token/s not setup';
  2882. }
  2883. break;
  2884. case 'jdownloader':
  2885. if (!empty($GLOBALS['jdownloaderURL'])) {
  2886. $url = qualifyURL($GLOBALS['jdownloaderURL']);
  2887. try {
  2888. $options = (localURL($url)) ? array('verify' => false, 'timeout' => 30) : array('timeout' => 30);
  2889. $response = Requests::get($url, array(), $options);
  2890. if ($response->success) {
  2891. return true;
  2892. }
  2893. } catch (Requests_Exception $e) {
  2894. return $e->getMessage();
  2895. };
  2896. } else {
  2897. return 'URL and/or Token not setup';
  2898. }
  2899. break;
  2900. case 'sabnzbd':
  2901. if (!empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken'])) {
  2902. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  2903. $url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  2904. try {
  2905. $options = (localURL($url)) ? array('verify' => false) : array();
  2906. $response = Requests::get($url, array(), $options);
  2907. if ($response->success) {
  2908. return true;
  2909. }
  2910. } catch (Requests_Exception $e) {
  2911. return $e->getMessage();
  2912. };
  2913. } else {
  2914. return 'URL and/or Token not setup';
  2915. }
  2916. break;
  2917. case 'nzbget':
  2918. if (!empty($GLOBALS['nzbgetURL'])) {
  2919. $url = qualifyURL($GLOBALS['nzbgetURL']);
  2920. $url = $url . '/jsonrpc/listgroups';
  2921. try {
  2922. $options = (localURL($url)) ? array('verify' => false) : array();
  2923. if ($GLOBALS['nzbgetUsername'] !== '' && decrypt($GLOBALS['nzbgetPassword']) !== '') {
  2924. $credentials = array('auth' => new Requests_Auth_Basic(array($GLOBALS['nzbgetUsername'], decrypt($GLOBALS['nzbgetPassword']))));
  2925. $options = array_merge($options, $credentials);
  2926. }
  2927. $response = Requests::get($url, array(), $options);
  2928. if ($response->success) {
  2929. return true;
  2930. }
  2931. } catch (Requests_Exception $e) {
  2932. return $e->getMessage();
  2933. };
  2934. } else {
  2935. return 'URL and/or Username/Password not setup';
  2936. }
  2937. break;
  2938. case 'deluge':
  2939. if (!empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword'])) {
  2940. try {
  2941. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  2942. $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');
  2943. return true;
  2944. } catch (Exception $e) {
  2945. return $e->getMessage();
  2946. }
  2947. } else {
  2948. return 'URL and/or Password not setup';
  2949. }
  2950. break;
  2951. case 'rtorrent':
  2952. if (!empty($GLOBALS['rTorrentURL']) || !empty($GLOBALS['rTorrentURLOverride'])) {
  2953. try {
  2954. $digest = (empty($GLOBALS['rTorrentURLOverride'])) ? qualifyURL($GLOBALS['rTorrentURL'], true) : qualifyURL(checkOverrideURL($GLOBALS['rTorrentURL'], $GLOBALS['rTorrentURLOverride']), true);
  2955. $passwordInclude = ($GLOBALS['rTorrentUsername'] !== '' && $GLOBALS['rTorrentPassword'] !== '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  2956. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  2957. $extraPath = (empty($GLOBALS['rTorrentURLOverride'])) ? $extraPath : '';
  2958. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  2959. $options = (localURL($url, $GLOBALS['rTorrentDisableCertCheck'])) ? array('verify' => false) : array();
  2960. if ($GLOBALS['rTorrentUsername'] !== '' && decrypt($GLOBALS['rTorrentPassword']) !== '') {
  2961. $credentials = array('auth' => new Requests_Auth_Digest(array($GLOBALS['rTorrentUsername'], decrypt($GLOBALS['rTorrentPassword']))));
  2962. $options = array_merge($options, $credentials);
  2963. }
  2964. $data = xmlrpc_encode_request("system.listMethods", null);
  2965. $response = Requests::post($url, array(), $data, $options);
  2966. if ($response->success) {
  2967. $methods = xmlrpc_decode(str_replace('i8>', 'i4>', $response->body));
  2968. if (count($methods) !== 0) {
  2969. return true;
  2970. }
  2971. }
  2972. return false;
  2973. } catch
  2974. (Requests_Exception $e) {
  2975. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2976. return $e->getMessage();
  2977. };
  2978. }
  2979. break;
  2980. case 'ldap_login':
  2981. $username = $array['data']['data']['username'];
  2982. $password = $array['data']['data']['password'];
  2983. if (empty($username) || empty($password)) {
  2984. return 'Missing Username or Password';
  2985. }
  2986. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  2987. $ad = new \Adldap\Adldap();
  2988. // Create a configuration array.
  2989. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  2990. $i = 0;
  2991. foreach ($ldapServers as $key => $value) {
  2992. // Calculate parts
  2993. $digest = parse_url(trim($value));
  2994. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  2995. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  2996. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  2997. // Reassign
  2998. $ldapHosts[] = $host;
  2999. $ldapServersNew[$key] = $scheme . '://' . $host . ':' . $port; // May use this later
  3000. if ($i == 0) {
  3001. $ldapPort = $port;
  3002. }
  3003. $i++;
  3004. }
  3005. $config = [
  3006. // Mandatory Configuration Options
  3007. 'hosts' => $ldapHosts,
  3008. 'base_dn' => $GLOBALS['authBaseDN'],
  3009. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  3010. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  3011. // Optional Configuration Options
  3012. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  3013. 'account_prefix' => (empty($GLOBALS['authBackendHostPrefix'])) ? null : $GLOBALS['authBackendHostPrefix'],
  3014. 'account_suffix' => (empty($GLOBALS['authBackendHostSuffix'])) ? null : $GLOBALS['authBackendHostSuffix'],
  3015. 'port' => $ldapPort,
  3016. 'follow_referrals' => false,
  3017. 'use_ssl' => false,
  3018. 'use_tls' => false,
  3019. 'version' => 3,
  3020. 'timeout' => 5,
  3021. // Custom LDAP Options
  3022. 'custom_options' => [
  3023. // See: http://php.net/ldap_set_option
  3024. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  3025. ]
  3026. ];
  3027. // Add a connection provider to Adldap.
  3028. $ad->addProvider($config);
  3029. try {
  3030. // If a successful connection is made to your server, the provider will be returned.
  3031. $provider = $ad->connect();
  3032. //prettyPrint($provider);
  3033. if ($provider->auth()->attempt($username, $password, true)) {
  3034. // Passed.
  3035. $user = $provider->search()->find($username);
  3036. //return $user->getFirstAttribute('cn');
  3037. //return $user->getGroups(['cn']);
  3038. //return $user;
  3039. //return $user->getUserPrincipalName();
  3040. //return $user->getGroups(['cn']);
  3041. return true;
  3042. } else {
  3043. // Failed.
  3044. return 'Username/Password Failed to authenticate';
  3045. }
  3046. } catch (\Adldap\Auth\BindException $e) {
  3047. $detailedError = $e->getDetailedError();
  3048. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  3049. return $detailedError->getErrorMessage();
  3050. // There was an issue binding / connecting to the server.
  3051. } catch (Adldap\Auth\UsernameRequiredException $e) {
  3052. $detailedError = $e->getDetailedError();
  3053. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  3054. return $detailedError->getErrorMessage();
  3055. // The user didn't supply a username.
  3056. } catch (Adldap\Auth\PasswordRequiredException $e) {
  3057. $detailedError = $e->getDetailedError();
  3058. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  3059. return $detailedError->getErrorMessage();
  3060. // The user didn't supply a password.
  3061. }
  3062. }
  3063. break;
  3064. case 'ldap':
  3065. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  3066. $ad = new \Adldap\Adldap();
  3067. // Create a configuration array.
  3068. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  3069. $i = 0;
  3070. foreach ($ldapServers as $key => $value) {
  3071. // Calculate parts
  3072. $digest = parse_url(trim($value));
  3073. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  3074. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  3075. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  3076. // Reassign
  3077. $ldapHosts[] = $host;
  3078. if ($i == 0) {
  3079. $ldapPort = $port;
  3080. }
  3081. $i++;
  3082. }
  3083. $config = [
  3084. // Mandatory Configuration Options
  3085. 'hosts' => $ldapHosts,
  3086. 'base_dn' => $GLOBALS['authBaseDN'],
  3087. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  3088. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  3089. // Optional Configuration Options
  3090. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  3091. 'account_prefix' => '',
  3092. 'account_suffix' => '',
  3093. 'port' => $ldapPort,
  3094. 'follow_referrals' => false,
  3095. 'use_ssl' => false,
  3096. 'use_tls' => false,
  3097. 'version' => 3,
  3098. 'timeout' => 5,
  3099. // Custom LDAP Options
  3100. 'custom_options' => [
  3101. // See: http://php.net/ldap_set_option
  3102. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  3103. ]
  3104. ];
  3105. // Add a connection provider to Adldap.
  3106. $ad->addProvider($config);
  3107. try {
  3108. // If a successful connection is made to your server, the provider will be returned.
  3109. $provider = $ad->connect();
  3110. } catch (\Adldap\Auth\BindException $e) {
  3111. $detailedError = $e->getDetailedError();
  3112. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), 'SYSTEM');
  3113. return $detailedError->getErrorMessage();
  3114. // There was an issue binding / connecting to the server.
  3115. }
  3116. return ($provider) ? true : false;
  3117. }
  3118. return false;
  3119. break;
  3120. default :
  3121. return false;
  3122. }
  3123. return false;
  3124. }