homepage-connect-functions.php 124 KB

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