homepage-connect-functions.php 124 KB

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