homepage-connect-functions.php 111 KB

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