homepage-connect-functions.php 107 KB

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