homepage-connect-functions.php 107 KB

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