homepage-connect-functions.php 126 KB

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