homepage-connect-functions.php 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129
  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 'getNetdata':
  75. return getNetdata();
  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. if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
  2318. $url = qualifyURL($GLOBALS['ombiURL']);
  2319. $headers = array(
  2320. "Accept" => "application/json",
  2321. "Apikey" => $GLOBALS['ombiToken'],
  2322. );
  2323. $requests = array();
  2324. try {
  2325. $options = (localURL($url)) ? array('verify' => false) : array();
  2326. switch ($type) {
  2327. case 'movie':
  2328. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  2329. break;
  2330. case 'tv':
  2331. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  2332. break;
  2333. default:
  2334. $movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
  2335. $tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
  2336. break;
  2337. }
  2338. if ($movie->success || $tv->success) {
  2339. if (isset($movie)) {
  2340. $movie = json_decode($movie->body, true);
  2341. //$movie = array_reverse($movie);
  2342. foreach ($movie as $key => $value) {
  2343. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2344. if ($proceed) {
  2345. $requests[] = array(
  2346. 'test' => $value,
  2347. 'id' => $value['theMovieDbId'],
  2348. 'title' => $value['title'],
  2349. 'overview' => $value['overview'],
  2350. 'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/' . $value['posterPath'] : '',
  2351. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2352. 'approved' => $value['approved'],
  2353. 'available' => $value['available'],
  2354. 'denied' => $value['denied'],
  2355. 'deniedReason' => $value['deniedReason'],
  2356. 'user' => $value['requestedUser']['userName'],
  2357. 'userAlias' => $value['requestedUser']['userAlias'],
  2358. 'request_id' => $value['id'],
  2359. 'request_date' => $value['requestedDate'],
  2360. 'release_date' => $value['releaseDate'],
  2361. 'type' => 'movie',
  2362. 'icon' => 'mdi mdi-filmstrip',
  2363. 'color' => 'palette-Deep-Purple-900 bg white',
  2364. );
  2365. }
  2366. }
  2367. }
  2368. if (isset($tv) && (is_array($tv) || is_object($tv))) {
  2369. $tv = json_decode($tv->body, true);
  2370. foreach ($tv as $key => $value) {
  2371. if (count($value['childRequests']) > 0) {
  2372. $proceed = (($GLOBALS['ombiLimitUser']) && strtolower($GLOBALS['organizrUser']['username']) == strtolower($value['childRequests'][0]['requestedUser']['userName'])) || (!$GLOBALS['ombiLimitUser']) || qualifyRequest(1) ? true : false;
  2373. if ($proceed) {
  2374. $requests[] = array(
  2375. 'test' => $value,
  2376. 'id' => $value['tvDbId'],
  2377. 'title' => $value['title'],
  2378. 'overview' => $value['overview'],
  2379. 'poster' => $value['posterPath'],
  2380. 'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
  2381. 'approved' => $value['childRequests'][0]['approved'],
  2382. 'available' => $value['childRequests'][0]['available'],
  2383. 'denied' => $value['childRequests'][0]['denied'],
  2384. 'deniedReason' => $value['childRequests'][0]['deniedReason'],
  2385. 'user' => $value['childRequests'][0]['requestedUser']['userName'],
  2386. 'userAlias' => $value['childRequests'][0]['requestedUser']['userAlias'],
  2387. 'request_id' => $value['id'],
  2388. 'request_date' => $value['childRequests'][0]['requestedDate'],
  2389. 'release_date' => $value['releaseDate'],
  2390. 'type' => 'tv',
  2391. 'icon' => 'mdi mdi-television',
  2392. 'color' => 'grayish-blue-bg',
  2393. );
  2394. }
  2395. }
  2396. }
  2397. }
  2398. //sort here
  2399. usort($requests, function ($item1, $item2) {
  2400. if ($item1['request_date'] == $item2['request_date']) {
  2401. return 0;
  2402. }
  2403. return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
  2404. });
  2405. }
  2406. } catch (Requests_Exception $e) {
  2407. writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2408. };
  2409. }
  2410. $api['content'] = isset($requests) ? array_slice($requests, 0, $limit) : false;
  2411. return $api;
  2412. }
  2413. function unifiConnect()
  2414. {
  2415. if ($GLOBALS['homepageUnifiEnabled'] && !empty($GLOBALS['unifiURL']) && !empty($GLOBALS['unifiSiteName']) && !empty($GLOBALS['unifiUsername']) && !empty($GLOBALS['unifiPassword']) && qualifyRequest($GLOBALS['homepageUnifiAuth'])) {
  2416. $api['content']['unifi'] = array();
  2417. $url = qualifyURL($GLOBALS['unifiURL']);
  2418. $urlStat = $url . '/api/s/' . $GLOBALS['unifiSiteName'] . '/stat/health';
  2419. try {
  2420. $options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => false);
  2421. $data = array(
  2422. 'username' => $GLOBALS['unifiUsername'],
  2423. 'password' => decrypt($GLOBALS['unifiPassword']),
  2424. 'remember' => true,
  2425. 'strict' => true
  2426. );
  2427. $response = Requests::post($url . '/api/login', array(), json_encode($data), $options);
  2428. if ($response->success) {
  2429. $cookie['unifises'] = ($response->cookies['unifises']->value) ?? false;
  2430. $cookie['csrf_token'] = ($response->cookies['csrf_token']->value) ?? false;
  2431. } else {
  2432. return false;
  2433. }
  2434. $headers = array(
  2435. 'cookie' => 'unifises=' . $cookie['unifises'] . ';' . 'csrf_token=' . $cookie['csrf_token'] . ';'
  2436. );
  2437. $response = Requests::get($urlStat, $headers, $options);
  2438. if ($response->success) {
  2439. $api['content']['unifi'] = json_decode($response->body, true);
  2440. }
  2441. } catch (Requests_Exception $e) {
  2442. writeLog('error', 'Unifi Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2443. };
  2444. $api['content']['unifi'] = isset($api['content']['unifi']) ? $api['content']['unifi'] : false;
  2445. return $api;
  2446. }
  2447. return false;
  2448. }
  2449. function getTautulli()
  2450. {
  2451. if ($GLOBALS['homepageTautulliEnabled'] && !empty($GLOBALS['tautulliURL']) && !empty($GLOBALS['tautulliApikey']) && qualifyRequest($GLOBALS['homepageTautulliAuth'])) {
  2452. $api = [];
  2453. $url = qualifyURL($GLOBALS['tautulliURL']);
  2454. $apiURL = $url . '/api/v2?apikey=' . $GLOBALS['tautulliApikey'];
  2455. $height = getCacheImageSize('h');
  2456. $width = getCacheImageSize('w');
  2457. $nowPlayingHeight = getCacheImageSize('nph');
  2458. $nowPlayingWidth = getCacheImageSize('npw');
  2459. try {
  2460. $homestatsUrl = $apiURL . '&cmd=get_home_stats&grouping=1';
  2461. $homestats = Requests::get($homestatsUrl, [], []);
  2462. if ($homestats->success) {
  2463. $homestats = json_decode($homestats->body, true);
  2464. $api['homestats'] = $homestats['response'];
  2465. // Cache art & thumb for first result in each tautulli API result
  2466. $categories = ['top_movies', 'top_tv', 'popular_movies', 'popular_tv'];
  2467. foreach ($categories as $cat) {
  2468. $key = array_search($cat, array_column($api['homestats']['data'], 'stat_id'));
  2469. $img = $api['homestats']['data'][$key]['rows'][0];
  2470. cacheImage($url . '/pms_image_proxy?img=' . $img['art'] . '&rating_key=' . $img['rating_key'] . '&width=' . $nowPlayingWidth . '&height=' . $nowPlayingHeight, $img['rating_key'] . '-np');
  2471. cacheImage($url . '/pms_image_proxy?img=' . $img['thumb'] . '&rating_key=' . $img['rating_key'] . '&width=' . $width . '&height=' . $height, $img['rating_key'] . '-list');
  2472. $img['art'] = 'plugins/images/cache/' . $img['rating_key'] . '-np.jpg';
  2473. $img['thumb'] = 'plugins/images/cache/' . $img['rating_key'] . '-list.jpg';
  2474. $api['homestats']['data'][$key]['rows'][0] = $img;
  2475. }
  2476. // Cache the platform icon
  2477. $key = array_search('top_platforms', array_column($api['homestats']['data'], 'stat_id'));
  2478. $platform = $api['homestats']['data'][$key]['rows'][0]['platform_name'];
  2479. cacheImage($url . '/images/platforms/' . $platform . '.svg', 'tautulli-' . $platform, 'svg');
  2480. }
  2481. $libstatsUrl = $apiURL . '&cmd=get_libraries';
  2482. $libstats = Requests::get($libstatsUrl, [], []);
  2483. if ($libstats->success) {
  2484. $libstats = json_decode($libstats->body, true);
  2485. $api['libstats'] = $libstats['response'];
  2486. $categories = ['movie.svg', 'show.svg', 'artist.svg'];
  2487. foreach ($categories as $cat) {
  2488. $parts = explode('.', $cat);
  2489. cacheImage($url . '/images/libraries/' . $cat, 'tautulli-' . $parts[0], $parts[1]);
  2490. }
  2491. }
  2492. $api['options'] = [
  2493. 'url' => $url,
  2494. 'libraries' => $GLOBALS['tautulliLibraries'],
  2495. 'topMovies' => $GLOBALS['tautulliTopMovies'],
  2496. 'topTV' => $GLOBALS['tautulliTopTV'],
  2497. 'topUsers' => $GLOBALS['tautulliTopUsers'],
  2498. 'topPlatforms' => $GLOBALS['tautulliTopPlatforms'],
  2499. 'popularMovies' => $GLOBALS['tautulliPopularMovies'],
  2500. 'popularTV' => $GLOBALS['tautulliPopularTV'],
  2501. 'title' => $GLOBALS['tautulliHeaderToggle'],
  2502. ];
  2503. $ids = []; // Array of stat_ids to remove from the returned array
  2504. if (!qualifyRequest($GLOBALS['homepageTautulliLibraryAuth'])) {
  2505. $api['options']['libraries'] = false;
  2506. unset($api['libstats']);
  2507. }
  2508. if (!qualifyRequest($GLOBALS['homepageTautulliViewsAuth'])) {
  2509. $api['options']['topMovies'] = false;
  2510. $api['options']['topTV'] = false;
  2511. $api['options']['popularMovies'] = false;
  2512. $api['options']['popularTV'] = false;
  2513. $ids = array_merge(['top_movies', 'popular_movies', 'popular_tv', 'top_tv'], $ids);
  2514. $api['homestats']['data'] = array_values($api['homestats']['data']);
  2515. }
  2516. if (!qualifyRequest($GLOBALS['homepageTautulliMiscAuth'])) {
  2517. $api['options']['topUsers'] = false;
  2518. $api['options']['topPlatforms'] = false;
  2519. $ids = array_merge(['top_platforms', 'top_users'], $ids);
  2520. $api['homestats']['data'] = array_values($api['homestats']['data']);
  2521. }
  2522. $ids = array_merge(['top_music', 'popular_music', 'last_watched', 'most_concurrent'], $ids);
  2523. foreach ($ids as $id) {
  2524. if ($key = array_search($id, array_column($api['homestats']['data'], 'stat_id'))) {
  2525. unset($api['homestats']['data'][$key]);
  2526. $api['homestats']['data'] = array_values($api['homestats']['data']);
  2527. }
  2528. }
  2529. } catch (Requests_Exception $e) {
  2530. writeLog('error', 'Tautulli Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2531. };
  2532. $api = isset($api) ? $api : false;
  2533. return $api;
  2534. }
  2535. return false;
  2536. }
  2537. function getMonitorr()
  2538. {
  2539. if ($GLOBALS['homepageMonitorrEnabled'] && !empty($GLOBALS['monitorrURL']) && qualifyRequest($GLOBALS['homepageMonitorrAuth'])) {
  2540. $api = [];
  2541. $url = qualifyURL($GLOBALS['monitorrURL']);
  2542. $dataUrl = $url . '/assets/php/loop.php';
  2543. try {
  2544. $response = Requests::get($dataUrl, ['Token' => $GLOBALS['organizrAPI']], []);
  2545. if ($response->success) {
  2546. $html = html_entity_decode($response->body);
  2547. // This section grabs the names of all services by regex
  2548. $services = [];
  2549. $servicesMatch = [];
  2550. $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>/';
  2551. preg_match_all($servicePattern, $html, $servicesMatch);
  2552. unset($servicesMatch[0]);
  2553. $servicesMatch = array_values($servicesMatch);
  2554. foreach ($servicesMatch as $group) {
  2555. foreach ($group as $service) {
  2556. if ($service !== '') {
  2557. array_push($services, $service);
  2558. }
  2559. }
  2560. }
  2561. // This section then grabs the status and image of that service with regex
  2562. $statuses = [];
  2563. foreach ($services as $service) {
  2564. $statusPattern = '/' . $service . '<\/div><\/div><div class="btnonline">(Online)<\/div>|' . $service . '<\/div><\/div><div class="btnoffline".*>(Offline)<\/div><\/div><\/div>/';
  2565. $status = [];
  2566. preg_match($statusPattern, $html, $status);
  2567. $statuses[$service] = $status;
  2568. foreach ($status as $match) {
  2569. if ($match == 'Online') {
  2570. $statuses[$service] = [
  2571. 'status' => true
  2572. ];
  2573. } else if ($match == 'Offline') {
  2574. $statuses[$service] = [
  2575. 'status' => false
  2576. ];
  2577. }
  2578. }
  2579. $imageMatch = [];
  2580. $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 . '/';
  2581. preg_match($imgPattern, $html, $imageMatch);
  2582. unset($imageMatch[0]);
  2583. $imageMatch = array_values($imageMatch);
  2584. // array_push($api['imagematches'][$service], $imageMatch);
  2585. foreach ($imageMatch as $match) {
  2586. if ($match !== '') {
  2587. $image = $match;
  2588. }
  2589. }
  2590. $ext = explode('.', $image);
  2591. $ext = $ext[key(array_slice($ext, -1, 1, true))];
  2592. $imageUrl = $url . '/assets' . $image;
  2593. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  2594. $img = Requests::get($imageUrl, ['Token' => $GLOBALS['organizrAPI']], []);
  2595. if ($img->success) {
  2596. $base64 = 'data:image/' . $ext . ';base64,' . base64_encode($img->body);
  2597. $statuses[$service]['image'] = $base64;
  2598. } else {
  2599. $statuses[$service]['image'] = $cacheDirectory . 'no-list.png';
  2600. }
  2601. $linkMatch = [];
  2602. $linkPattern = '/<a class="servicetile" href="(.*)" target="_blank" style="display: block"><div id="serviceimg"><div><img id="' . strtolower($service) . '-service-img/';
  2603. preg_match($linkPattern, $html, $linkMatch);
  2604. $linkMatch = array_values($linkMatch);
  2605. unset($linkMatch[0]);
  2606. foreach ($linkMatch as $link) {
  2607. if ($link !== '') {
  2608. $statuses[$service]['link'] = $link;
  2609. }
  2610. }
  2611. }
  2612. ksort($statuses);
  2613. $api['services'] = $statuses;
  2614. $api['options'] = [
  2615. 'title' => $GLOBALS['monitorrHeader'],
  2616. 'titleToggle' => $GLOBALS['monitorrHeaderToggle'],
  2617. 'compact' => $GLOBALS['monitorrCompact'],
  2618. ];
  2619. }
  2620. } catch (Requests_Exception $e) {
  2621. writeLog('error', 'Monitorr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2622. };
  2623. $api = isset($api) ? $api : false;
  2624. return $api;
  2625. }
  2626. }
  2627. function getNetdata()
  2628. {
  2629. if ($GLOBALS['homepageNetdataEnabled'] && !empty($GLOBALS['netdataURL']) && qualifyRequest($GLOBALS['homepageNetdataAuth'])) {
  2630. $api = [];
  2631. $url = qualifyURL($GLOBALS['netdataURL']);
  2632. try {
  2633. $response = Requests::get($url);
  2634. if ($response->success) {
  2635. $html = json_decode($response->body, true);
  2636. $api['url'] = $GLOBALS['netdataURL'];
  2637. $api['options'] = [];
  2638. for($i = 0; $i < 5; $i++) {
  2639. if($GLOBALS['netdata'.($i + 1).'Data'] != '') {
  2640. array_push($api['options'], [
  2641. 'title' => $GLOBALS['netdata'.($i + 1).'Title'],
  2642. 'chart' => $GLOBALS['netdata'.($i + 1).'Chart'],
  2643. 'data' => $GLOBALS['netdata'.($i + 1).'Data'],
  2644. 'units' => $GLOBALS['netdata'.($i + 1).'Units'],
  2645. 'dimensions' => $GLOBALS['netdata'.($i + 1).'Dimensions'],
  2646. 'max' => $GLOBALS['netdata'.($i + 1).'Max'],
  2647. ]);
  2648. }
  2649. }
  2650. }
  2651. } catch (Requests_Exception $e) {
  2652. writeLog('error', 'Monitorr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2653. };
  2654. $api = isset($api) ? $api : false;
  2655. return $api;
  2656. }
  2657. }
  2658. function testAPIConnection($array)
  2659. {
  2660. switch ($array['data']['action']) {
  2661. case 'unifiSite':
  2662. if (!empty($GLOBALS['unifiURL']) && !empty($GLOBALS['unifiUsername']) && !empty($GLOBALS['unifiPassword'])) {
  2663. $url = qualifyURL($GLOBALS['unifiURL']);
  2664. try {
  2665. $options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => false);
  2666. $data = array(
  2667. 'username' => $GLOBALS['unifiUsername'],
  2668. 'password' => decrypt($GLOBALS['unifiPassword']),
  2669. 'remember' => true,
  2670. 'strict' => true
  2671. );
  2672. $response = Requests::post($url . '/api/login', array(), json_encode($data), $options);
  2673. if ($response->success) {
  2674. $cookie['unifises'] = ($response->cookies['unifises']->value) ?? false;
  2675. $cookie['csrf_token'] = ($response->cookies['csrf_token']->value) ?? false;
  2676. } else {
  2677. return false;
  2678. }
  2679. $headers = array(
  2680. 'cookie' => 'unifises=' . $cookie['unifises'] . ';' . 'csrf_token=' . $cookie['csrf_token'] . ';'
  2681. );
  2682. $response = Requests::get($url . '/api/self/sites', $headers, $options);
  2683. if ($response->success) {
  2684. $body = json_decode($response->body, true);
  2685. return $body;
  2686. } else {
  2687. return false;
  2688. }
  2689. } catch (Requests_Exception $e) {
  2690. writeLog('error', 'Unifi Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2691. };
  2692. }
  2693. break;
  2694. case 'unifi':
  2695. if (!empty($GLOBALS['unifiURL']) && !empty($GLOBALS['unifiUsername']) && !empty($GLOBALS['unifiPassword']) && !empty($GLOBALS['unifiSiteName'])) {
  2696. $url = qualifyURL($GLOBALS['unifiURL']);
  2697. try {
  2698. $options = array('verify' => false, 'verifyname' => false, 'follow_redirects' => false);
  2699. $data = array(
  2700. 'username' => $GLOBALS['unifiUsername'],
  2701. 'password' => decrypt($GLOBALS['unifiPassword']),
  2702. 'remember' => true,
  2703. 'strict' => true
  2704. );
  2705. $response = Requests::post($url . '/api/login', array(), json_encode($data), $options);
  2706. if ($response->success) {
  2707. $cookie['unifises'] = ($response->cookies['unifises']->value) ?? false;
  2708. $cookie['csrf_token'] = ($response->cookies['csrf_token']->value) ?? false;
  2709. } else {
  2710. return 'Failed to Login';
  2711. }
  2712. $headers = array(
  2713. 'cookie' => 'unifises=' . $cookie['unifises'] . ';' . 'csrf_token=' . $cookie['csrf_token'] . ';'
  2714. );
  2715. $response = Requests::get($url . '/api/s/' . $GLOBALS['unifiSiteName'] . '/self', $headers, $options);
  2716. $body = json_decode($response->body, true);
  2717. return ($body['meta']['rc'] == 'ok') ? true : $body['meta']['msg'];
  2718. } catch (Requests_Exception $e) {
  2719. writeLog('error', 'Unifi Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2720. };
  2721. } else {
  2722. return 'Not all data is filled in...';
  2723. }
  2724. break;
  2725. case 'ombi':
  2726. if (!empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken'])) {
  2727. $url = qualifyURL($GLOBALS['ombiURL']);
  2728. $url = $url . "/api/v1/Status/info";
  2729. $headers = array(
  2730. "Accept" => "application/json",
  2731. "Content-Type" => "application/json",
  2732. "Apikey" => $GLOBALS['ombiToken']
  2733. );
  2734. try {
  2735. $options = (localURL($url)) ? array('verify' => false) : array();
  2736. $response = Requests::get($url, $headers, $options);
  2737. if ($response->success) {
  2738. return true;
  2739. } else {
  2740. return $response->body;
  2741. }
  2742. } catch (Requests_Exception $e) {
  2743. return $e->getMessage();
  2744. };
  2745. } else {
  2746. return 'URL and/or Token not setup';
  2747. }
  2748. break;
  2749. case 'plex':
  2750. if (!empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken'])) {
  2751. $url = qualifyURL($GLOBALS['plexURL']);
  2752. $url = $url . "/?X-Plex-Token=" . $GLOBALS['plexToken'];
  2753. try {
  2754. $options = (localURL($url)) ? array('verify' => false) : array();
  2755. $response = Requests::get($url, array(), $options);
  2756. libxml_use_internal_errors(true);
  2757. if ($response->success) {
  2758. return true;
  2759. }
  2760. } catch (Requests_Exception $e) {
  2761. return $e->getMessage();
  2762. };
  2763. } else {
  2764. return 'URL and/or Token not setup';
  2765. }
  2766. break;
  2767. case 'emby':
  2768. break;
  2769. case 'sonarr':
  2770. if (!empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
  2771. $sonarrs = array();
  2772. $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
  2773. $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
  2774. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2775. foreach ($sonarrURLList as $key => $value) {
  2776. $sonarrs[$key] = array(
  2777. 'url' => $value,
  2778. 'token' => $sonarrTokenList[$key]
  2779. );
  2780. }
  2781. foreach ($sonarrs as $key => $value) {
  2782. try {
  2783. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2784. $result = json_decode($sonarr->getSystemStatus(), true);
  2785. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2786. } catch (Exception $e) {
  2787. return strip($e->getMessage());
  2788. }
  2789. }
  2790. }
  2791. } else {
  2792. return 'URL/s and/or Token/s not setup';
  2793. }
  2794. break;
  2795. case 'lidarr':
  2796. if (!empty($GLOBALS['lidarrURL']) && !empty($GLOBALS['lidarrToken'])) {
  2797. $sonarrs = array();
  2798. $sonarrURLList = explode(',', $GLOBALS['lidarrURL']);
  2799. $sonarrTokenList = explode(',', $GLOBALS['lidarrToken']);
  2800. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2801. foreach ($sonarrURLList as $key => $value) {
  2802. $sonarrs[$key] = array(
  2803. 'url' => $value,
  2804. 'token' => $sonarrTokenList[$key]
  2805. );
  2806. }
  2807. foreach ($sonarrs as $key => $value) {
  2808. try {
  2809. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token'], true);
  2810. $result = json_decode($sonarr->getSystemStatus(), true);
  2811. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2812. } catch (Exception $e) {
  2813. return $e->getMessage();
  2814. }
  2815. }
  2816. }
  2817. } else {
  2818. return 'URL/s and/or Token/s not setup';
  2819. }
  2820. break;
  2821. case 'radarr':
  2822. if (!empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
  2823. $sonarrs = array();
  2824. $sonarrURLList = explode(',', $GLOBALS['radarrURL']);
  2825. $sonarrTokenList = explode(',', $GLOBALS['radarrToken']);
  2826. if (count($sonarrURLList) == count($sonarrTokenList)) {
  2827. foreach ($sonarrURLList as $key => $value) {
  2828. $sonarrs[$key] = array(
  2829. 'url' => $value,
  2830. 'token' => $sonarrTokenList[$key]
  2831. );
  2832. }
  2833. foreach ($sonarrs as $key => $value) {
  2834. try {
  2835. $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
  2836. $result = json_decode($sonarr->getSystemStatus(), true);
  2837. return (array_key_exists('error', $result)) ? $result['error']['msg'] : true;
  2838. } catch (Exception $e) {
  2839. return $e->getMessage();
  2840. }
  2841. }
  2842. }
  2843. } else {
  2844. return 'URL/s and/or Token/s not setup';
  2845. }
  2846. break;
  2847. case 'jdownloader':
  2848. if (!empty($GLOBALS['jdownloaderURL'])) {
  2849. $url = qualifyURL($GLOBALS['jdownloaderURL']);
  2850. try {
  2851. $options = (localURL($url)) ? array('verify' => false, 'timeout' => 30) : array('timeout' => 30);
  2852. $response = Requests::get($url, array(), $options);
  2853. if ($response->success) {
  2854. return true;
  2855. }
  2856. } catch (Requests_Exception $e) {
  2857. return $e->getMessage();
  2858. };
  2859. } else {
  2860. return 'URL and/or Token not setup';
  2861. }
  2862. break;
  2863. case 'sabnzbd':
  2864. if (!empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken'])) {
  2865. $url = qualifyURL($GLOBALS['sabnzbdURL']);
  2866. $url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
  2867. try {
  2868. $options = (localURL($url)) ? array('verify' => false) : array();
  2869. $response = Requests::get($url, array(), $options);
  2870. if ($response->success) {
  2871. return true;
  2872. }
  2873. } catch (Requests_Exception $e) {
  2874. return $e->getMessage();
  2875. };
  2876. } else {
  2877. return 'URL and/or Token not setup';
  2878. }
  2879. break;
  2880. case 'nzbget':
  2881. if (!empty($GLOBALS['nzbgetURL'])) {
  2882. $url = qualifyURL($GLOBALS['nzbgetURL']);
  2883. $url = $url . '/jsonrpc/listgroups';
  2884. try {
  2885. $options = (localURL($url)) ? array('verify' => false) : array();
  2886. if ($GLOBALS['nzbgetUsername'] !== '' && decrypt($GLOBALS['nzbgetPassword']) !== '') {
  2887. $credentials = array('auth' => new Requests_Auth_Basic(array($GLOBALS['nzbgetUsername'], decrypt($GLOBALS['nzbgetPassword']))));
  2888. $options = array_merge($options, $credentials);
  2889. }
  2890. $response = Requests::get($url, array(), $options);
  2891. if ($response->success) {
  2892. return true;
  2893. }
  2894. } catch (Requests_Exception $e) {
  2895. return $e->getMessage();
  2896. };
  2897. } else {
  2898. return 'URL and/or Username/Password not setup';
  2899. }
  2900. break;
  2901. case 'deluge':
  2902. if (!empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword'])) {
  2903. try {
  2904. $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
  2905. $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');
  2906. return true;
  2907. } catch (Exception $e) {
  2908. return $e->getMessage();
  2909. }
  2910. } else {
  2911. return 'URL and/or Password not setup';
  2912. }
  2913. break;
  2914. case 'rtorrent':
  2915. if (!empty($GLOBALS['rTorrentURL']) || !empty($GLOBALS['rTorrentURLOverride'])) {
  2916. try {
  2917. $digest = (empty($GLOBALS['rTorrentURLOverride'])) ? qualifyURL($GLOBALS['rTorrentURL'], true) : qualifyURL(checkOverrideURL($GLOBALS['rTorrentURL'], $GLOBALS['rTorrentURLOverride']), true);
  2918. $passwordInclude = ($GLOBALS['rTorrentUsername'] !== '' && $GLOBALS['rTorrentPassword'] !== '') ? $GLOBALS['rTorrentUsername'] . ':' . decrypt($GLOBALS['rTorrentPassword']) . "@" : '';
  2919. $extraPath = (strpos($GLOBALS['rTorrentURL'], '.php') !== false) ? '' : '/RPC2';
  2920. $extraPath = (empty($GLOBALS['rTorrentURLOverride'])) ? $extraPath : '';
  2921. $url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . $extraPath;
  2922. $options = (localURL($url, $GLOBALS['rTorrentDisableCertCheck'])) ? array('verify' => false) : array();
  2923. if ($GLOBALS['rTorrentUsername'] !== '' && decrypt($GLOBALS['rTorrentPassword']) !== '') {
  2924. $credentials = array('auth' => new Requests_Auth_Digest(array($GLOBALS['rTorrentUsername'], decrypt($GLOBALS['rTorrentPassword']))));
  2925. $options = array_merge($options, $credentials);
  2926. }
  2927. $data = xmlrpc_encode_request("system.listMethods", null);
  2928. $response = Requests::post($url, array(), $data, $options);
  2929. if ($response->success) {
  2930. $methods = xmlrpc_decode(str_replace('i8>', 'i4>', $response->body));
  2931. if (count($methods) !== 0) {
  2932. return true;
  2933. }
  2934. }
  2935. return false;
  2936. } catch
  2937. (Requests_Exception $e) {
  2938. writeLog('error', 'rTorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  2939. return $e->getMessage();
  2940. };
  2941. }
  2942. break;
  2943. case 'ldap_login':
  2944. $username = $array['data']['data']['username'];
  2945. $password = $array['data']['data']['password'];
  2946. if (empty($username) || empty($password)) {
  2947. return 'Missing Username or Password';
  2948. }
  2949. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  2950. $ad = new \Adldap\Adldap();
  2951. // Create a configuration array.
  2952. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  2953. $i = 0;
  2954. foreach ($ldapServers as $key => $value) {
  2955. // Calculate parts
  2956. $digest = parse_url(trim($value));
  2957. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  2958. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  2959. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  2960. // Reassign
  2961. $ldapHosts[] = $host;
  2962. $ldapServersNew[$key] = $scheme . '://' . $host . ':' . $port; // May use this later
  2963. if ($i == 0) {
  2964. $ldapPort = $port;
  2965. }
  2966. $i++;
  2967. }
  2968. $config = [
  2969. // Mandatory Configuration Options
  2970. 'hosts' => $ldapHosts,
  2971. 'base_dn' => $GLOBALS['authBaseDN'],
  2972. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  2973. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  2974. // Optional Configuration Options
  2975. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  2976. 'account_prefix' => (empty($GLOBALS['authBackendHostPrefix'])) ? null : $GLOBALS['authBackendHostPrefix'],
  2977. 'account_suffix' => (empty($GLOBALS['authBackendHostSuffix'])) ? null : $GLOBALS['authBackendHostSuffix'],
  2978. 'port' => $ldapPort,
  2979. 'follow_referrals' => false,
  2980. 'use_ssl' => false,
  2981. 'use_tls' => false,
  2982. 'version' => 3,
  2983. 'timeout' => 5,
  2984. // Custom LDAP Options
  2985. 'custom_options' => [
  2986. // See: http://php.net/ldap_set_option
  2987. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  2988. ]
  2989. ];
  2990. // Add a connection provider to Adldap.
  2991. $ad->addProvider($config);
  2992. try {
  2993. // If a successful connection is made to your server, the provider will be returned.
  2994. $provider = $ad->connect();
  2995. //prettyPrint($provider);
  2996. if ($provider->auth()->attempt($username, $password, true)) {
  2997. // Passed.
  2998. $user = $provider->search()->find($username);
  2999. //return $user->getFirstAttribute('cn');
  3000. //return $user->getGroups(['cn']);
  3001. //return $user;
  3002. //return $user->getUserPrincipalName();
  3003. //return $user->getGroups(['cn']);
  3004. return true;
  3005. } else {
  3006. // Failed.
  3007. return 'Username/Password Failed to authenticate';
  3008. }
  3009. } catch (\Adldap\Auth\BindException $e) {
  3010. $detailedError = $e->getDetailedError();
  3011. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  3012. return $detailedError->getErrorMessage();
  3013. // There was an issue binding / connecting to the server.
  3014. } catch (Adldap\Auth\UsernameRequiredException $e) {
  3015. $detailedError = $e->getDetailedError();
  3016. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  3017. return $detailedError->getErrorMessage();
  3018. // The user didn't supply a username.
  3019. } catch (Adldap\Auth\PasswordRequiredException $e) {
  3020. $detailedError = $e->getDetailedError();
  3021. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), $username);
  3022. return $detailedError->getErrorMessage();
  3023. // The user didn't supply a password.
  3024. }
  3025. }
  3026. break;
  3027. case 'ldap':
  3028. if (!empty($GLOBALS['authBaseDN']) && !empty($GLOBALS['authBackendHost'])) {
  3029. $ad = new \Adldap\Adldap();
  3030. // Create a configuration array.
  3031. $ldapServers = explode(',', $GLOBALS['authBackendHost']);
  3032. $i = 0;
  3033. foreach ($ldapServers as $key => $value) {
  3034. // Calculate parts
  3035. $digest = parse_url(trim($value));
  3036. $scheme = strtolower((isset($digest['scheme']) ? $digest['scheme'] : 'ldap'));
  3037. $host = (isset($digest['host']) ? $digest['host'] : (isset($digest['path']) ? $digest['path'] : ''));
  3038. $port = (isset($digest['port']) ? $digest['port'] : (strtolower($scheme) == 'ldap' ? 389 : 636));
  3039. // Reassign
  3040. $ldapHosts[] = $host;
  3041. if ($i == 0) {
  3042. $ldapPort = $port;
  3043. }
  3044. $i++;
  3045. }
  3046. $config = [
  3047. // Mandatory Configuration Options
  3048. 'hosts' => $ldapHosts,
  3049. 'base_dn' => $GLOBALS['authBaseDN'],
  3050. 'username' => (empty($GLOBALS['ldapBindUsername'])) ? null : $GLOBALS['ldapBindUsername'],
  3051. 'password' => (empty($GLOBALS['ldapBindPassword'])) ? null : decrypt($GLOBALS['ldapBindPassword']),
  3052. // Optional Configuration Options
  3053. 'schema' => (($GLOBALS['ldapType'] == '1') ? Adldap\Schemas\ActiveDirectory::class : (($GLOBALS['ldapType'] == '2') ? Adldap\Schemas\OpenLDAP::class : Adldap\Schemas\FreeIPA::class)),
  3054. 'account_prefix' => '',
  3055. 'account_suffix' => '',
  3056. 'port' => $ldapPort,
  3057. 'follow_referrals' => false,
  3058. 'use_ssl' => false,
  3059. 'use_tls' => false,
  3060. 'version' => 3,
  3061. 'timeout' => 5,
  3062. // Custom LDAP Options
  3063. 'custom_options' => [
  3064. // See: http://php.net/ldap_set_option
  3065. //LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD
  3066. ]
  3067. ];
  3068. // Add a connection provider to Adldap.
  3069. $ad->addProvider($config);
  3070. try {
  3071. // If a successful connection is made to your server, the provider will be returned.
  3072. $provider = $ad->connect();
  3073. } catch (\Adldap\Auth\BindException $e) {
  3074. $detailedError = $e->getDetailedError();
  3075. writeLog('error', 'LDAP Function - Error: ' . $detailedError->getErrorMessage(), 'SYSTEM');
  3076. return $detailedError->getErrorMessage();
  3077. // There was an issue binding / connecting to the server.
  3078. }
  3079. return ($provider) ? true : false;
  3080. }
  3081. return false;
  3082. break;
  3083. default :
  3084. return false;
  3085. }
  3086. return false;
  3087. }