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