homepage-connect-functions.php 106 KB

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