homepage-connect-functions.php 107 KB

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