homepage-connect-functions.php 110 KB

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