homepage-connect-functions.php 107 KB

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