functions.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  1. <?php
  2. // Debugging output functions
  3. function debug_out($variable, $die = false) {
  4. $trace = debug_backtrace()[0];
  5. echo '<pre style="background-color: #f2f2f2; border: 2px solid black; border-radius: 5px; padding: 5px; margin: 5px;">'.$trace['file'].':'.$trace['line']."\n\n".print_r($variable, true).'</pre>';
  6. if ($die) { http_response_code(503); die(); }
  7. }
  8. // ==== Auth Plugins START ====
  9. if (function_exists('ldap_connect')) :
  10. // Pass credentials to LDAP backend
  11. function plugin_auth_ldap($username, $password) {
  12. // returns true or false
  13. $ldap = ldap_connect(AUTHBACKENDHOST.(AUTHBACKENDPORT?':'.AUTHBACKENDPORT:'389'));
  14. if ($bind = ldap_bind($ldap, AUTHBACKENDDOMAIN.'\\'.$username, $password)) {
  15. return true;
  16. } else {
  17. return false;
  18. }
  19. return false;
  20. }
  21. endif;
  22. // Pass credentials to FTP backend
  23. function plugin_auth_ftp($username, $password) {
  24. // returns true or false
  25. // Connect to FTP
  26. $conn_id = ftp_ssl_connect(AUTHBACKENDHOST, (AUTHBACKENDPORT?AUTHBACKENDPORT:21), 20); // 20 Second Timeout
  27. // Check if valid FTP connection
  28. if ($conn_id) {
  29. // Attempt login
  30. @$login_result = ftp_login($conn_id, $username, $password);
  31. // Return Result
  32. if ($login_result) {
  33. return true;
  34. } else {
  35. return false;
  36. }
  37. } else {
  38. return false;
  39. }
  40. return false;
  41. }
  42. // Pass credentials to Emby Backend
  43. function plugin_auth_emby_local($username, $password) {
  44. $urlCheck = stripos(AUTHBACKENDHOST, "http");
  45. if ($urlCheck === false) {
  46. $embyAddress = "http://" . AUTHBACKENDHOST;
  47. } else {
  48. $embyAddress = AUTHBACKENDHOST;
  49. }
  50. if(AUTHBACKENDPORT !== ""){ $embyAddress .= ":" . AUTHBACKENDPORT; }
  51. $headers = array(
  52. 'Authorization'=> 'MediaBrowser UserId="e8837bc1-ad67-520e-8cd2-f629e3155721", Client="None", Device="Organizr", DeviceId="xxx", Version="1.0.0.0"',
  53. 'Content-Type' => 'application/json',
  54. );
  55. $body = array(
  56. 'Username' => $username,
  57. 'Password' => sha1($password),
  58. 'PasswordMd5' => md5($password),
  59. );
  60. $response = post_router($embyAddress.'/Users/AuthenticateByName', $body, $headers);
  61. if (isset($response['content'])) {
  62. $json = json_decode($response['content'], true);
  63. if (is_array($json) && isset($json['SessionInfo']) && isset($json['User']) && $json['User']['HasPassword'] == true) {
  64. // Login Success - Now Logout Emby Session As We No Longer Need It
  65. $headers = array(
  66. 'X-Mediabrowser-Token' => $json['AccessToken'],
  67. );
  68. $response = post_router($embyAddress.'/Sessions/Logout', array(), $headers);
  69. return true;
  70. }
  71. }
  72. return false;
  73. }
  74. if (function_exists('curl_version')) :
  75. // Authenticate Against Emby Local (first) and Emby Connect
  76. function plugin_auth_emby_all($username, $password) {
  77. return plugin_auth_emby_local($username, $password) || plugin_auth_emby_connect($username, $password);
  78. }
  79. // Authenicate against emby connect
  80. function plugin_auth_emby_connect($username, $password) {
  81. $urlCheck = stripos(AUTHBACKENDHOST, "http");
  82. if ($urlCheck === false) {
  83. $embyAddress = "http://" . AUTHBACKENDHOST;
  84. } else {
  85. $embyAddress = AUTHBACKENDHOST;
  86. }
  87. if(AUTHBACKENDPORT !== "") { $embyAddress .= ":" . AUTHBACKENDPORT; }
  88. // Get A User
  89. $connectId = '';
  90. $userIds = json_decode(file_get_contents($embyAddress.'/Users?api_key='.EMBYTOKEN),true);
  91. if (is_array($userIds)) {
  92. foreach ($userIds as $key => $value) { // Scan for this user
  93. if (isset($value['ConnectUserName']) && isset($value['ConnectUserId'])) { // Qualifty as connect account
  94. if ($value['ConnectUserName'] == $username || $value['Name'] == $username) {
  95. $connectId = $value['ConnectUserId'];
  96. break;
  97. }
  98. }
  99. }
  100. if ($connectId) {
  101. $connectURL = 'https://connect.emby.media/service/user/authenticate';
  102. $headers = array(
  103. 'Accept'=> 'application/json',
  104. 'Content-Type' => 'application/x-www-form-urlencoded',
  105. );
  106. $body = array(
  107. 'nameOrEmail' => $username,
  108. 'rawpw' => $password,
  109. );
  110. $result = curl_post($connectURL, $body, $headers);
  111. if (isset($result['content'])) {
  112. $json = json_decode($result['content'], true);
  113. if (is_array($json) && isset($json['AccessToken']) && isset($json['User']) && $json['User']['Id'] == $connectId) {
  114. return true;
  115. }
  116. }
  117. }
  118. }
  119. return false;
  120. }
  121. // Pass credentials to Plex Backend
  122. function plugin_auth_plex($username, $password) {
  123. // Quick out
  124. if ((strtolower(PLEXUSERNAME) == strtolower($username)) && $password == PLEXPASSWORD) {
  125. return true;
  126. }
  127. //Get User List
  128. $approvedUsers = array();
  129. $userURL = 'https://plex.tv/pms/friends/all';
  130. $userHeaders = array(
  131. 'Authorization' => 'Basic '.base64_encode(PLEXUSERNAME.':'.PLEXPASSWORD),
  132. );
  133. $userXML = simplexml_load_string(curl_get($userURL, $userHeaders));
  134. if (is_array($userXML) || is_object($userXML)) {
  135. //Build User List array
  136. $isUser = false;
  137. $usernameLower = strtolower($username);
  138. foreach($userXML AS $child) {
  139. if(isset($child['username']) && strtolower($child['username']) == $usernameLower) {
  140. $isUser = true;
  141. break;
  142. }
  143. }
  144. if ($isUser) {
  145. //Login User
  146. $connectURL = 'https://plex.tv/users/sign_in.json';
  147. $headers = array(
  148. 'Accept'=> 'application/json',
  149. 'Content-Type' => 'application/x-www-form-urlencoded',
  150. 'X-Plex-Product' => 'Organizr',
  151. 'X-Plex-Version' => '1.0',
  152. 'X-Plex-Client-Identifier' => '01010101-10101010',
  153. );
  154. $body = array(
  155. 'user[login]' => $username,
  156. 'user[password]' => $password,
  157. );
  158. $result = curl_post($connectURL, $body, $headers);
  159. if (isset($result['content'])) {
  160. $json = json_decode($result['content'], true);
  161. if (is_array($json) && isset($json['user']) && isset($json['user']['username']) && $json['user']['username'] == $username) {
  162. return true;
  163. }
  164. }
  165. }
  166. }
  167. return false;
  168. }
  169. endif;
  170. // ==== Auth Plugins END ====
  171. // ==== General Class Definitions START ====
  172. class setLanguage {
  173. private $language = null;
  174. private $langCode = null;
  175. function __construct($language = false) {
  176. // Default
  177. if (!$language) {
  178. $language = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) : "en";
  179. }
  180. $this->langCode = $language;
  181. if (file_exists("lang/{$language}.ini")) {
  182. $this->language = parse_ini_file("lang/{$language}.ini", false, INI_SCANNER_RAW);
  183. } else {
  184. $this->language = parse_ini_file("lang/en.ini", false, INI_SCANNER_RAW);
  185. }
  186. }
  187. public function getLang() {
  188. return $this->langCode;
  189. }
  190. public function translate($originalWord) {
  191. $getArg = func_num_args();
  192. if ($getArg > 1) {
  193. $allWords = func_get_args();
  194. array_shift($allWords);
  195. } else {
  196. $allWords = array();
  197. }
  198. $translatedWord = isset($this->language[$originalWord]) ? $this->language[$originalWord] : null;
  199. if (!$translatedWord) {
  200. echo ("Translation not found for: $originalWord");
  201. }
  202. $translatedWord = htmlspecialchars($translatedWord, ENT_QUOTES);
  203. return vsprintf($translatedWord, $allWords);
  204. }
  205. }
  206. $language = new setLanguage;
  207. // ==== General Class Definitions END ====
  208. // Direct request to curl if it exists, otherwise handle if not HTTPS
  209. function post_router($url, $data, $headers = array(), $referer='') {
  210. if (function_exists('curl_version')) {
  211. return curl_post($url, $data, $headers, $referer);
  212. } else {
  213. return post_request($url, $data, $headers, $referer);
  214. }
  215. }
  216. if (function_exists('curl_version')) :
  217. // Curl Post
  218. function curl_post($url, $data, $headers = array(), $referer='') {
  219. // Initiate cURL
  220. $curlReq = curl_init($url);
  221. // As post request
  222. curl_setopt($curlReq, CURLOPT_CUSTOMREQUEST, "POST");
  223. curl_setopt($curlReq, CURLOPT_RETURNTRANSFER, true);
  224. // Format Data
  225. switch (isset($headers['Content-Type'])?$headers['Content-Type']:'') {
  226. case 'application/json':
  227. curl_setopt($curlReq, CURLOPT_POSTFIELDS, json_encode($data));
  228. break;
  229. case 'application/x-www-form-urlencoded';
  230. curl_setopt($curlReq, CURLOPT_POSTFIELDS, http_build_query($data));
  231. break;
  232. default:
  233. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  234. curl_setopt($curlReq, CURLOPT_POSTFIELDS, http_build_query($data));
  235. }
  236. // Format Headers
  237. $cHeaders = array();
  238. foreach ($headers as $k => $v) {
  239. $cHeaders[] = $k.': '.$v;
  240. }
  241. if (count($cHeaders)) {
  242. curl_setopt($curlReq, CURLOPT_HTTPHEADER, $cHeaders);
  243. }
  244. // Execute
  245. $result = curl_exec($curlReq);
  246. // Close
  247. curl_close($curlReq);
  248. // Return
  249. return array('content'=>$result);
  250. }
  251. //Curl Get Function
  252. function curl_get($url, $headers = array()) {
  253. // Initiate cURL
  254. $curlReq = curl_init($url);
  255. // As post request
  256. curl_setopt($curlReq, CURLOPT_CUSTOMREQUEST, "GET");
  257. curl_setopt($curlReq, CURLOPT_RETURNTRANSFER, true);
  258. // Format Headers
  259. $cHeaders = array();
  260. foreach ($headers as $k => $v) {
  261. $cHeaders[] = $k.': '.$v;
  262. }
  263. if (count($cHeaders)) {
  264. curl_setopt($curlReq, CURLOPT_HTTPHEADER, $cHeaders);
  265. }
  266. // Execute
  267. $result = curl_exec($curlReq);
  268. // Close
  269. curl_close($curlReq);
  270. // Return
  271. return $result;
  272. }
  273. endif;
  274. //Case-Insensitive Function
  275. function in_arrayi($needle, $haystack) {
  276. return in_array(strtolower($needle), array_map('strtolower', $haystack));
  277. }
  278. // HTTP post request (Removes need for curl, probably useless)
  279. function post_request($url, $data, $headers = array(), $referer='') {
  280. // Adapted from http://stackoverflow.com/a/28387011/6810513
  281. // Convert the data array into URL Parameters like a=b&foo=bar etc.
  282. if (isset($headers['Content-Type'])) {
  283. switch ($headers['Content-Type']) {
  284. case 'application/json':
  285. $data = json_encode($data);
  286. break;
  287. case 'application/x-www-form-urlencoded':
  288. $data = http_build_query($data);
  289. break;
  290. }
  291. } else {
  292. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  293. $data = http_build_query($data);
  294. }
  295. // parse the given URL
  296. $urlDigest = parse_url($url);
  297. // extract host and path:
  298. $host = $urlDigest['host'].(isset($urlDigest['port'])?':'.$urlDigest['port']:'');
  299. $path = $urlDigest['path'];
  300. if ($urlDigest['scheme'] != 'http') {
  301. die('Error: Only HTTP request are supported, please use cURL to add HTTPS support! ('.$urlDigest['scheme'].'://'.$host.')');
  302. }
  303. // open a socket connection on port 80 - timeout: 30 sec
  304. $fp = fsockopen($host, 80, $errno, $errstr, 30);
  305. if ($fp){
  306. // send the request headers:
  307. fputs($fp, "POST $path HTTP/1.1\r\n");
  308. fputs($fp, "Host: $host\r\n");
  309. if ($referer != '')
  310. fputs($fp, "Referer: $referer\r\n");
  311. fputs($fp, "Content-length: ". strlen($data) ."\r\n");
  312. foreach($headers as $k => $v) {
  313. fputs($fp, $k.": ".$v."\r\n");
  314. }
  315. fputs($fp, "Connection: close\r\n\r\n");
  316. fputs($fp, $data);
  317. $result = '';
  318. while(!feof($fp)) {
  319. // receive the results of the request
  320. $result .= fgets($fp, 128);
  321. }
  322. }
  323. else {
  324. return array(
  325. 'status' => 'err',
  326. 'error' => "$errstr ($errno)"
  327. );
  328. }
  329. // close the socket connection:
  330. fclose($fp);
  331. // split the result header from the content
  332. $result = explode("\r\n\r\n", $result, 2);
  333. $header = isset($result[0]) ? $result[0] : '';
  334. $content = isset($result[1]) ? $result[1] : '';
  335. // return as structured array:
  336. return array(
  337. 'status' => 'ok',
  338. 'header' => $header,
  339. 'content' => $content,
  340. );
  341. }
  342. // Format item from Emby for Carousel
  343. function resolveEmbyItem($address, $token, $item) {
  344. // Static Height
  345. $height = 150;
  346. // Get Item Details
  347. $itemDetails = json_decode(file_get_contents($address.'/Items?Ids='.$item['Id'].'&Fields=Overview&api_key='.$token),true)['Items'][0];
  348. switch ($item['Type']) {
  349. case 'Episode':
  350. $title = $item['SeriesName'].': '.$item['Name'].' (Season '.$item['ParentIndexNumber'].': Episode '.$item['IndexNumber'].')';
  351. $imageId = $itemDetails['SeriesId'];
  352. $width = 100;
  353. $image = 'carousel-image season';
  354. $style = '';
  355. break;
  356. case 'MusicAlbum':
  357. $title = $item['Name'];
  358. $imageId = $itemDetails['Id'];
  359. $width = 150;
  360. $image = 'music';
  361. $style = 'left: 160px !important;';
  362. break;
  363. default:
  364. $title = $item['Name'];
  365. $imageId = $item['Id'];
  366. $width = 100;
  367. $image = 'carousel-image movie';
  368. $style = '';
  369. }
  370. // If No Overview
  371. if (!isset($itemDetails['Overview'])) {
  372. $itemDetails['Overview'] = '';
  373. }
  374. // Assemble Item And Cache Into Array
  375. return '<div class="item"><a href="'.$address.'/web/itemdetails.html?id='.$item['Id'].'" target="_blank"><img alt="'.$item['Name'].'" class="'.$image.'" src="ajax.php?a=emby-image&img='.$imageId.'&height='.$height.'&width='.$width.'"></a><div class="carousel-caption" style="'.$style.'"><h4>'.$title.'</h4><small><em>'.$itemDetails['Overview'].'</em></small></div></div>';
  376. }
  377. // Format item from Plex for Carousel
  378. function resolvePlexItem($server, $token, $item) {
  379. // Static Height
  380. $height = 150;
  381. $address = "https://app.plex.tv/web/app#!/server/$server/details?key=/library/metadata/".$item['ratingKey'];
  382. switch ($item['type']) {
  383. case 'season':
  384. $title = $item['parentTitle'];
  385. $summary = $item['parentSummary'];
  386. $width = 100;
  387. $image = 'carousel-image season';
  388. $style = '';
  389. break;
  390. case 'album':
  391. $title = $item['parentTitle'];
  392. $summary = $item['title'];
  393. $width = 150;
  394. $image = 'album';
  395. $style = 'left: 160px !important;';
  396. break;
  397. default:
  398. $title = $item['title'];
  399. $summary = $item['summary'];
  400. $width = 100;
  401. $image = 'carousel-image movie';
  402. $style = '';
  403. }
  404. // If No Overview
  405. if (!isset($itemDetails['Overview'])) {
  406. $itemDetails['Overview'] = '';
  407. }
  408. // Assemble Item And Cache Into Array
  409. return '<div class="item"><a href="'.$address.'" target="_blank"><img alt="'.$item['Name'].'" class="'.$image.'" src="image.php?a=plex-image&img='.$item['thumb'].'&height='.$height.'&width='.$width.'"></a><div class="carousel-caption" style="'.$style.'"><h4>'.$title.'</h4><small><em>'.$summary.'</em></small></div></div>';
  410. }
  411. // Create Carousel
  412. function outputCarousel($header, $size, $type, $items) {
  413. // If None Populate Empty Item
  414. if (!count($items)) {
  415. $items = array('<div class="item"><img alt="nada" class="carousel-image movie" src="images/nadaplaying.jpg"><div class="carousel-caption"><h4>Nothing To Show</h4><small><em>Get Some Stuff Going!</em></small></div></div>');
  416. }
  417. // Set First As Active
  418. $items[0] = preg_replace('/^<div class="item ?">/','<div class="item active">', $items[0]);
  419. // Add Buttons
  420. $buttons = '';
  421. if (count($items) > 1) {
  422. $buttons = '
  423. <a class="left carousel-control '.$type.'" href="#carousel-'.$type.'" role="button" data-slide="prev"><span class="fa fa-chevron-left" aria-hidden="true"></span><span class="sr-only">Previous</span></a>
  424. <a class="right carousel-control '.$type.'" href="#carousel-'.$type.'" role="button" data-slide="next"><span class="fa fa-chevron-right" aria-hidden="true"></span><span class="sr-only">Next</span></a>';
  425. }
  426. return '
  427. <div class="col-lg-'.$size.'">
  428. <h5 class="text-center">'.$header.'</h5>
  429. <div id="carousel-'.$type.'" class="carousel slide box-shadow white-bg" data-ride="carousel"><div class="carousel-inner" role="listbox">
  430. '.implode('',$items).'
  431. </div>'.$buttons.'
  432. </div></div>';
  433. }
  434. // Get Now Playing Streams From Emby
  435. function getEmbyStreams($size) {
  436. $address = qualifyURL(EMBYURL);
  437. $api = json_decode(file_get_contents($address.'/Sessions?api_key='.EMBYTOKEN),true);
  438. $playingItems = array();
  439. foreach($api as $key => $value) {
  440. if (isset($value['NowPlayingItem'])) {
  441. $playingItems[] = resolveEmbyItem($address, EMBYTOKEN, $value['NowPlayingItem']);
  442. }
  443. }
  444. return outputCarousel(translate('PLAYING_NOW_ON_EMBY'), $size, 'streams-emby', $playingItems);
  445. }
  446. // Get Now Playing Streams From Plex
  447. function getPlexStreams($size){
  448. $address = qualifyURL(PLEXURL);
  449. // Perform API requests
  450. $api = file_get_contents($address."/status/sessions?X-Plex-Token=".PLEXTOKEN);
  451. $api = simplexml_load_string($api);
  452. $getServer = simplexml_load_string(file_get_contents($address."/?X-Plex-Token=".PLEXTOKEN));
  453. // Identify the local machine
  454. $gotServer = $getServer['machineIdentifier'];
  455. $items = array();
  456. foreach($api AS $child) {
  457. $items[] = resolvePlexItem($gotServer, PLEXTOKEN, $child);
  458. }
  459. return outputCarousel(translate('PLAYING_NOW_ON_PLEX'), $size, 'streams-plex', $items);
  460. }
  461. // Get Recent Content From Emby
  462. function getEmbyRecent($type, $size) {
  463. $address = qualifyURL(EMBYURL);
  464. // Resolve Types
  465. switch ($type) {
  466. case 'movie':
  467. $embyTypeQuery = 'IncludeItemTypes=Movie&';
  468. $header = translate('MOVIES');
  469. break;
  470. case 'season':
  471. $embyTypeQuery = 'IncludeItemTypes=Episode&';
  472. $header = translate('TV_SHOWS');
  473. break;
  474. case 'album':
  475. $embyTypeQuery = 'IncludeItemTypes=MusicAlbum&';
  476. $header = translate('MUSIC');
  477. break;
  478. default:
  479. $embyTypeQuery = '';
  480. $header = translate('RECENT_CONTENT');
  481. }
  482. // Get A User
  483. $userIds = json_decode(file_get_contents($address.'/Users?api_key='.EMBYTOKEN),true);
  484. foreach ($userIds as $value) { // Scan for admin user
  485. $userId = $value['Id'];
  486. if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
  487. break;
  488. }
  489. }
  490. // Get the latest Items
  491. $latest = json_decode(file_get_contents($address.'/Users/'.$userId.'/Items/Latest?'.$embyTypeQuery.'EnableImages=false&api_key='.EMBYTOKEN),true);
  492. // For Each Item In Category
  493. $items = array();
  494. foreach ($latest as $k => $v) {
  495. $items[] = resolveEmbyItem($address, EMBYTOKEN, $v);
  496. }
  497. return outputCarousel($header, $size, $type.'-emby', $items);
  498. }
  499. // Get Recent Content From Plex
  500. function getPlexRecent($type, $size){
  501. $address = qualifyURL(PLEXURL);
  502. // Resolve Types
  503. switch ($type) {
  504. case 'movie':
  505. $header = translate('MOVIES');
  506. break;
  507. case 'season':
  508. $header = translate('TV_SHOWS');
  509. break;
  510. case 'album':
  511. $header = translate('MUSIC');
  512. break;
  513. default:
  514. $header = translate('RECENT_CONTENT');
  515. }
  516. // Perform Requests
  517. $api = file_get_contents($address."/library/recentlyAdded?X-Plex-Token=".PLEXTOKEN);
  518. $api = simplexml_load_string($api);
  519. $getServer = simplexml_load_string(file_get_contents($address."/?X-Plex-Token=".PLEXTOKEN));
  520. // Identify the local machine
  521. $gotServer = $getServer['machineIdentifier'];
  522. $items = array();
  523. foreach($api AS $child) {
  524. if($child['type'] == $type){
  525. $items[] = resolvePlexItem($gotServer, PLEXTOKEN, $child);
  526. }
  527. }
  528. return outputCarousel($header, $size, $type.'-plex', $items);
  529. }
  530. // Get Image From Emby
  531. function getEmbyImage() {
  532. $embyAddress = qualifyURL(EMBYURL);
  533. $itemId = $_GET['img'];
  534. $imgParams = array();
  535. if (isset($_GET['height'])) { $imgParams['height'] = 'maxHeight='.$_GET['height']; }
  536. if (isset($_GET['width'])) { $imgParams['width'] = 'maxWidth='.$_GET['width']; }
  537. if(isset($itemId)) {
  538. $image_src = $embyAddress . '/Items/'.$itemId.'/Images/Primary?'.implode('&', $imgParams);
  539. header('Content-type: image/jpeg');
  540. readfile($image_src);
  541. } else {
  542. debug_out('Invalid Request',1);
  543. }
  544. }
  545. // Get Image From Plex
  546. function getPlexImage() {
  547. $plexAddress = qualifyURL(PLEXURL);
  548. $image_url = $_GET['img'];
  549. $image_height = $_GET['height'];
  550. $image_width = $_GET['width'];
  551. if(isset($image_url) && isset($image_height) && isset($image_width)) {
  552. $image_src = $plexAddress . '/photo/:/transcode?height='.$image_height.'&width='.$image_width.'&upscale=1&url=' . $image_url . '&X-Plex-Token=' . PLEXTOKEN;
  553. header('Content-type: image/jpeg');
  554. readfile($image_src);
  555. } else {
  556. echo "Invalid Plex Request";
  557. }
  558. }
  559. // Simplier access to class
  560. function translate($string) {
  561. if (isset($GLOBALS['language'])) {
  562. return $GLOBALS['language']->translate($string);
  563. } else {
  564. return '!Translations Not Loaded!';
  565. }
  566. }
  567. // Generate Random string
  568. function randString($length = 10) {
  569. $tmp = '';
  570. $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  571. for ($i = 0; $i < $length; $i++) {
  572. $tmp .= substr(str_shuffle($chars), 0, 1);
  573. }
  574. return $tmp;
  575. }
  576. // Create config file in the return syntax
  577. function createConfig($array, $path = 'config/config.php', $nest = 0) {
  578. $output = array();
  579. foreach ($array as $k => $v) {
  580. $allowCommit = true;
  581. switch (gettype($v)) {
  582. case 'boolean':
  583. $item = ($v?'true':'false');
  584. break;
  585. case 'integer':
  586. case 'double':
  587. case 'integer':
  588. case 'NULL':
  589. $item = $v;
  590. break;
  591. case 'string':
  592. $item = '"'.addslashes($v).'"';
  593. break;
  594. case 'array':
  595. $item = createConfig($v, false, $nest+1);
  596. break;
  597. default:
  598. $allowCommit = false;
  599. }
  600. if($allowCommit) {
  601. $output[] = str_repeat("\t",$nest+1).'"'.$k.'" => '.$item;
  602. }
  603. }
  604. $output = (!$nest?"<?php\nreturn ":'')."array(\n".implode(",\n",$output)."\n".str_repeat("\t",$nest).')'.(!$nest?';':'');
  605. if (!$nest && $path) {
  606. $pathDigest = pathinfo($path);
  607. @mkdir($pathDigest['dirname'], 0770, true);
  608. if (file_exists($path)) {
  609. rename($path, $path.'.bak');
  610. }
  611. $file = fopen($path, 'w');
  612. fwrite($file, $output);
  613. fclose($file);
  614. if (file_exists($path)) {
  615. @unlink($path.'.bak');
  616. return true;
  617. }
  618. return false;
  619. } else {
  620. return $output;
  621. }
  622. }
  623. // Load a config file written in the return syntax
  624. function loadConfig($path = 'config/config.php') {
  625. // Adapted from http://stackoverflow.com/a/14173339/6810513
  626. if (!is_file($path)) {
  627. return null;
  628. } else {
  629. return (array) call_user_func(function() use($path) {
  630. return include($path);
  631. });
  632. }
  633. }
  634. // Commit new values to the configuration
  635. function updateConfig($new, $current = false) {
  636. // Get config if not supplied
  637. if (!$current) {
  638. $current = loadConfig();
  639. }
  640. // Inject Parts
  641. foreach ($new as $k => $v) {
  642. $current[$k] = $v;
  643. }
  644. // Return Create
  645. return createConfig($current);
  646. }
  647. // Inject Defaults As Needed
  648. function fillDefaultConfig($array, $path = 'config/configDefaults.php') {
  649. if (is_string($path)) {
  650. $loadedDefaults = loadConfig($path);
  651. } else {
  652. $loadedDefaults = $path;
  653. }
  654. return (is_array($loadedDefaults) ? fillDefaultConfig_recurse($array, $loadedDefaults) : false);
  655. }
  656. // support function for fillDefaultConfig()
  657. function fillDefaultConfig_recurse($current, $defaults) {
  658. foreach($defaults as $k => $v) {
  659. if (!isset($current[$k])) {
  660. $current[$k] = $v;
  661. } else if (is_array($current[$k]) && is_array($v)) {
  662. $current[$k] = fillDefaultConfig_recurse($current[$k], $v);
  663. }
  664. }
  665. return $current;
  666. };
  667. // Define Scalar Variables (nest non-secular with underscores)
  668. function defineConfig($array, $anyCase = true, $nest_prefix = false) {
  669. foreach($array as $k => $v) {
  670. if (is_scalar($v) && !defined($nest_prefix.$k)) {
  671. define($nest_prefix.$k, $v, $anyCase);
  672. } else if (is_array($v)) {
  673. defineConfig($v, $anyCase, $nest_prefix.$k.'_');
  674. }
  675. }
  676. }
  677. // This function exists only because I am lazy
  678. function configLazy($path) {
  679. $config = fillDefaultConfig(loadConfig($path));
  680. if (is_array($config)) {
  681. defineConfig($config);
  682. }
  683. return $config;
  684. }
  685. // Qualify URL
  686. function qualifyURL($url) {
  687. // Get Digest
  688. $digest = parse_url($url);
  689. // http/https
  690. if (!isset($digest['scheme'])) {
  691. if (isset($digest['port']) && in_array($digest['port'], array(80,8080,8096))) {
  692. $scheme = 'http';
  693. } else {
  694. $scheme = 'https';
  695. }
  696. } else {
  697. $scheme = $digest['scheme'];
  698. }
  699. // Host
  700. $host = (isset($digest['host'])?$digest['host']:'');
  701. // Port
  702. $port = (isset($digest['port'])?':'.$digest['port']:'');
  703. // Path
  704. $path = (isset($digest['path'])?$digest['path']:'');
  705. // Output
  706. return $scheme.'://'.$host.$port.$path;
  707. }
  708. // Function to be called at top of each to allow upgrading environment as the spec changes
  709. function upgradeCheck() {
  710. // Upgrade to 1.31
  711. if (file_exists('homepageSettings.ini.php')) {
  712. $databaseConfig = parse_ini_file('databaseLocation.ini.php', true);
  713. $homepageConfig = parse_ini_file('homepageSettings.ini.php', true);
  714. $databaseConfig = array_merge($databaseConfig, $homepageConfig);
  715. $databaseData = '; <?php die("Access denied"); ?>' . "\r\n";
  716. foreach($databaseConfig as $k => $v) {
  717. if(substr($v, -1) == "/") : $v = rtrim($v, "/"); endif;
  718. $databaseData .= $k . " = \"" . $v . "\"\r\n";
  719. }
  720. write_ini_file($databaseData, 'databaseLocation.ini.php');
  721. unlink('homepageSettings.ini.php');
  722. unset($databaseData);
  723. unset($homepageConfig);
  724. }
  725. // Upgrade to 1.32
  726. if (file_exists('databaseLocation.ini.php')) {
  727. // Load Existing
  728. $config = parse_ini_file('databaseLocation.ini.php', true);
  729. // Refactor
  730. $config['database_Location'] = str_replace('//','/',$config['databaseLocation'].'/');
  731. $config['user_home'] = $config['databaseLocation'].'users/';
  732. unset($config['databaseLocation']);
  733. $createConfigSuccess = createConfig($config, 'config/config.php', $nest = 0);
  734. // Create new config
  735. if ($createConfigSuccess) {
  736. // Make Config Dir (this should never happen as the dir and defaults file should be there);
  737. @mkdir('config', 0775, true);
  738. // Remove Old ini file
  739. unlink('databaseLocation.ini.php');
  740. }
  741. }
  742. return true;
  743. }
  744. // Check if all software dependancies are met
  745. function dependCheck() {
  746. return true;
  747. }
  748. // Process file uploads
  749. function uploadFiles($path, $ext_mask = null) {
  750. if (isset($_FILES) && count($_FILES)) {
  751. require_once('class.uploader.php');
  752. $uploader = new Uploader();
  753. $data = $uploader->upload($_FILES['files'], array(
  754. 'limit' => 10,
  755. 'maxSize' => 10,
  756. 'extensions' => $ext_mask,
  757. 'required' => false,
  758. 'uploadDir' => str_replace('//','/',$path.'/'),
  759. 'title' => array('name'),
  760. 'removeFiles' => true,
  761. 'replace' => true,
  762. ));
  763. if($data['isComplete']){
  764. $files = $data['data'];
  765. echo json_encode($files['metas'][0]['name']);
  766. }
  767. if($data['hasErrors']){
  768. $errors = $data['errors'];
  769. echo json_encode($errors);
  770. }
  771. } else {
  772. echo json_encode('No files submitted!');
  773. }
  774. }
  775. // Remove file
  776. function removeFiles($path) {
  777. if(is_file($path)) {
  778. unlink($path);
  779. } else {
  780. echo json_encode('No file specified for removal!');
  781. }
  782. }
  783. // ==============
  784. function clean($strin) {
  785. $strout = null;
  786. for ($i = 0; $i < strlen($strin); $i++) {
  787. $ord = ord($strin[$i]);
  788. if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
  789. $strout .= "&amp;#{$ord};";
  790. }
  791. else {
  792. switch ($strin[$i]) {
  793. case '<':
  794. $strout .= '&lt;';
  795. break;
  796. case '>':
  797. $strout .= '&gt;';
  798. break;
  799. case '&':
  800. $strout .= '&amp;';
  801. break;
  802. case '"':
  803. $strout .= '&quot;';
  804. break;
  805. default:
  806. $strout .= $strin[$i];
  807. }
  808. }
  809. }
  810. return $strout;
  811. }
  812. function registration_callback($username, $email, $userdir){
  813. global $data;
  814. $data = array($username, $email, $userdir);
  815. }
  816. function printArray($arrayName){
  817. $messageCount = count($arrayName);
  818. $i = 0;
  819. foreach ( $arrayName as $item ) :
  820. $i++;
  821. if($i < $messageCount) :
  822. echo "<small class='text-uppercase'>" . $item . "</small> & ";
  823. elseif($i = $messageCount) :
  824. echo "<small class='text-uppercase'>" . $item . "</small>";
  825. endif;
  826. endforeach;
  827. }
  828. function write_ini_file($content, $path) {
  829. if (!$handle = fopen($path, 'w')) {
  830. return false;
  831. }
  832. $success = fwrite($handle, trim($content));
  833. fclose($handle);
  834. return $success;
  835. }
  836. function gotTimezone(){
  837. $regions = array(
  838. 'Africa' => DateTimeZone::AFRICA,
  839. 'America' => DateTimeZone::AMERICA,
  840. 'Antarctica' => DateTimeZone::ANTARCTICA,
  841. 'Arctic' => DateTimeZone::ARCTIC,
  842. 'Asia' => DateTimeZone::ASIA,
  843. 'Atlantic' => DateTimeZone::ATLANTIC,
  844. 'Australia' => DateTimeZone::AUSTRALIA,
  845. 'Europe' => DateTimeZone::EUROPE,
  846. 'Indian' => DateTimeZone::INDIAN,
  847. 'Pacific' => DateTimeZone::PACIFIC
  848. );
  849. $timezones = array();
  850. foreach ($regions as $name => $mask) {
  851. $zones = DateTimeZone::listIdentifiers($mask);
  852. foreach($zones as $timezone) {
  853. $time = new DateTime(NULL, new DateTimeZone($timezone));
  854. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  855. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  856. }
  857. }
  858. print '<select name="timezone" id="timezone" class="form-control material input-sm" required>';
  859. foreach($timezones as $region => $list) {
  860. print '<optgroup label="' . $region . '">' . "\n";
  861. foreach($list as $timezone => $name) {
  862. if($timezone == TIMEZONE) : $selected = " selected"; else : $selected = ""; endif;
  863. print '<option value="' . $timezone . '"' . $selected . '>' . $name . '</option>' . "\n";
  864. }
  865. print '</optgroup>' . "\n";
  866. }
  867. print '</select>';
  868. }
  869. function getTimezone(){
  870. $regions = array(
  871. 'Africa' => DateTimeZone::AFRICA,
  872. 'America' => DateTimeZone::AMERICA,
  873. 'Antarctica' => DateTimeZone::ANTARCTICA,
  874. 'Arctic' => DateTimeZone::ARCTIC,
  875. 'Asia' => DateTimeZone::ASIA,
  876. 'Atlantic' => DateTimeZone::ATLANTIC,
  877. 'Australia' => DateTimeZone::AUSTRALIA,
  878. 'Europe' => DateTimeZone::EUROPE,
  879. 'Indian' => DateTimeZone::INDIAN,
  880. 'Pacific' => DateTimeZone::PACIFIC
  881. );
  882. $timezones = array();
  883. foreach ($regions as $name => $mask) {
  884. $zones = DateTimeZone::listIdentifiers($mask);
  885. foreach($zones as $timezone) {
  886. $time = new DateTime(NULL, new DateTimeZone($timezone));
  887. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  888. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  889. }
  890. }
  891. print '<select name="timezone" id="timezone" class="form-control material" required>';
  892. foreach($timezones as $region => $list) {
  893. print '<optgroup label="' . $region . '">' . "\n";
  894. foreach($list as $timezone => $name) {
  895. print '<option value="' . $timezone . '">' . $name . '</option>' . "\n";
  896. }
  897. print '</optgroup>' . "\n";
  898. }
  899. print '</select>';
  900. }
  901. function explosion($string, $position){
  902. $getWord = explode("|", $string);
  903. return $getWord[$position];
  904. }
  905. function getServerPath() {
  906. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  907. $protocol = "https://";
  908. } else {
  909. $protocol = "http://";
  910. }
  911. return $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
  912. }
  913. function get_browser_name() {
  914. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  915. if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
  916. elseif (strpos($user_agent, 'Edge')) return 'Edge';
  917. elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
  918. elseif (strpos($user_agent, 'Safari')) return 'Safari';
  919. elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
  920. elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
  921. return 'Other';
  922. }
  923. function getSickrageCalendarWanted($array){
  924. $array = json_decode($array, true);
  925. $gotCalendar = "";
  926. $i = 0;
  927. foreach($array['data']['missed'] AS $child) {
  928. $i++;
  929. $seriesName = $child['show_name'];
  930. $episodeID = $child['tvdbid'];
  931. $episodeAirDate = $child['airdate'];
  932. $episodeAirDateTime = explode(" ",$child['airs']);
  933. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  934. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  935. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  936. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  937. $downloaded = "0";
  938. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  939. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  940. }
  941. foreach($array['data']['today'] AS $child) {
  942. $i++;
  943. $seriesName = $child['show_name'];
  944. $episodeID = $child['tvdbid'];
  945. $episodeAirDate = $child['airdate'];
  946. $episodeAirDateTime = explode(" ",$child['airs']);
  947. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  948. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  949. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  950. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  951. $downloaded = "0";
  952. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  953. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  954. }
  955. foreach($array['data']['soon'] AS $child) {
  956. $i++;
  957. $seriesName = $child['show_name'];
  958. $episodeID = $child['tvdbid'];
  959. $episodeAirDate = $child['airdate'];
  960. $episodeAirDateTime = explode(" ",$child['airs']);
  961. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  962. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  963. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  964. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  965. $downloaded = "0";
  966. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  967. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  968. }
  969. foreach($array['data']['later'] AS $child) {
  970. $i++;
  971. $seriesName = $child['show_name'];
  972. $episodeID = $child['tvdbid'];
  973. $episodeAirDate = $child['airdate'];
  974. $episodeAirDateTime = explode(" ",$child['airs']);
  975. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  976. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  977. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  978. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  979. $downloaded = "0";
  980. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  981. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  982. }
  983. if ($i != 0){ return $gotCalendar; }
  984. }
  985. function getSickrageCalendarHistory($array){
  986. $array = json_decode($array, true);
  987. $gotCalendar = "";
  988. $i = 0;
  989. foreach($array['data'] AS $child) {
  990. $i++;
  991. $seriesName = $child['show_name'];
  992. $episodeID = $child['tvdbid'];
  993. $episodeAirDate = $child['date'];
  994. $downloaded = "green-bg";
  995. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  996. }
  997. if ($i != 0){ return $gotCalendar; }
  998. }
  999. function getSonarrCalendar($array){
  1000. $array = json_decode($array, true);
  1001. $gotCalendar = "";
  1002. $i = 0;
  1003. foreach($array AS $child) {
  1004. $i++;
  1005. $seriesName = $child['series']['title'];
  1006. $episodeID = $child['series']['tvdbId'];
  1007. if(!isset($episodeID)){ $episodeID = ""; }
  1008. $episodeName = htmlentities($child['title'], ENT_QUOTES);
  1009. if($child['episodeNumber'] == "1"){ $episodePremier = "true"; }else{ $episodePremier = "false"; }
  1010. $episodeAirDate = $child['airDateUtc'];
  1011. $episodeAirDate = strtotime($episodeAirDate);
  1012. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1013. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1014. $downloaded = $child['hasFile'];
  1015. if($downloaded == "0" && isset($unaired) && $episodePremier == "true"){ $downloaded = "light-blue-bg"; }elseif($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  1016. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1017. }
  1018. if ($i != 0){ return $gotCalendar; }
  1019. }
  1020. function getRadarrCalendar($array){
  1021. $array = json_decode($array, true);
  1022. $gotCalendar = "";
  1023. $i = 0;
  1024. foreach($array AS $child) {
  1025. if(isset($child['inCinemas'])){
  1026. $i++;
  1027. $movieName = $child['title'];
  1028. $movieID = $child['tmdbId'];
  1029. if(!isset($movieID)){ $movieID = ""; }
  1030. if(isset($child['inCinemas']) && isset($child['physicalRelease'])){
  1031. $physicalRelease = $child['physicalRelease'];
  1032. $physicalRelease = strtotime($physicalRelease);
  1033. $physicalRelease = date("Y-m-d", $physicalRelease);
  1034. if (new DateTime() < new DateTime($physicalRelease)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  1035. $downloaded = $child['hasFile'];
  1036. if($downloaded == "0" && $notReleased == "true"){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg"; }else{ $downloaded = "red-bg"; }
  1037. }else{
  1038. $physicalRelease = $child['inCinemas'];
  1039. $downloaded = "light-blue-bg";
  1040. }
  1041. $gotCalendar .= "{ title: \"$movieName\", start: \"$physicalRelease\", className: \"$downloaded\", imagetype: \"film\", url: \"https://www.themoviedb.org/movie/$movieID\" }, \n";
  1042. }
  1043. }
  1044. if ($i != 0){ return $gotCalendar; }
  1045. }
  1046. function nzbgetConnect($url, $port, $username, $password, $list){
  1047. $urlCheck = stripos($url, "http");
  1048. if ($urlCheck === false) {
  1049. $url = "http://" . $url;
  1050. }
  1051. if($port !== ""){ $url = $url . ":" . $port; }
  1052. $address = $url;
  1053. $api = file_get_contents("$url/$username:$password/jsonrpc/$list");
  1054. $api = json_decode($api, true);
  1055. $i = 0;
  1056. $gotNZB = "";
  1057. foreach ($api['result'] AS $child) {
  1058. $i++;
  1059. //echo '<pre>' . var_export($child, true) . '</pre>';
  1060. $downloadName = htmlentities($child['NZBName'], ENT_QUOTES);
  1061. $downloadStatus = $child['Status'];
  1062. $downloadCategory = $child['Category'];
  1063. if($list == "history"){ $downloadPercent = "100"; $progressBar = ""; }
  1064. if($list == "listgroups"){ $downloadPercent = (($child['FileSizeMB'] - $child['RemainingSizeMB']) / $child['FileSizeMB']) * 100; $progressBar = "progress-bar-striped active"; }
  1065. if($child['Health'] <= "750"){
  1066. $downloadHealth = "danger";
  1067. }elseif($child['Health'] <= "900"){
  1068. $downloadHealth = "warning";
  1069. }elseif($child['Health'] <= "1000"){
  1070. $downloadHealth = "success";
  1071. }
  1072. $gotNZB .= '<tr>
  1073. <td>'.$downloadName.'</td>
  1074. <td>'.$downloadStatus.'</td>
  1075. <td>'.$downloadCategory.'</td>
  1076. <td>
  1077. <div class="progress">
  1078. <div class="progress-bar progress-bar-'.$downloadHealth.' '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  1079. <p class="text-center">'.round($downloadPercent).'%</p>
  1080. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  1081. </div>
  1082. </div>
  1083. </td>
  1084. </tr>';
  1085. }
  1086. if($i > 0){ return $gotNZB; }
  1087. if($i == 0){ echo '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>'; }
  1088. }
  1089. function sabnzbdConnect($url, $port, $key, $list){
  1090. $urlCheck = stripos($url, "http");
  1091. if ($urlCheck === false) {
  1092. $url = "http://" . $url;
  1093. }
  1094. if($port !== ""){ $url = $url . ":" . $port; }
  1095. $address = $url;
  1096. $api = file_get_contents("$url/api?mode=$list&output=json&apikey=$key");
  1097. $api = json_decode($api, true);
  1098. $i = 0;
  1099. $gotNZB = "";
  1100. foreach ($api[$list]['slots'] AS $child) {
  1101. $i++;
  1102. if($list == "queue"){ $downloadName = $child['filename']; $downloadCategory = $child['cat']; $downloadPercent = (($child['mb'] - $child['mbleft']) / $child['mb']) * 100; $progressBar = "progress-bar-striped active"; }
  1103. if($list == "history"){ $downloadName = $child['name']; $downloadCategory = $child['category']; $downloadPercent = "100"; $progressBar = ""; }
  1104. $downloadStatus = $child['status'];
  1105. $gotNZB .= '<tr>
  1106. <td>'.$downloadName.'</td>
  1107. <td>'.$downloadStatus.'</td>
  1108. <td>'.$downloadCategory.'</td>
  1109. <td>
  1110. <div class="progress">
  1111. <div class="progress-bar progress-bar-success '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  1112. <p class="text-center">'.round($downloadPercent).'%</p>
  1113. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  1114. </div>
  1115. </div>
  1116. </td>
  1117. </tr>';
  1118. }
  1119. if($i > 0){ return $gotNZB; }
  1120. if($i == 0){ echo '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>'; }
  1121. }
  1122. function getHeadphonesCalendar($url, $port, $key, $list){
  1123. $urlCheck = stripos($url, "http");
  1124. if ($urlCheck === false) {
  1125. $url = "http://" . $url;
  1126. }
  1127. if($port !== ""){ $url = $url . ":" . $port; }
  1128. $address = $url;
  1129. $api = file_get_contents($address."/api?apikey=".$key."&cmd=$list");
  1130. $api = json_decode($api, true);
  1131. $i = 0;
  1132. $gotCalendar = "";
  1133. foreach($api AS $child) {
  1134. if($child['Status'] == "Wanted"){
  1135. $i++;
  1136. $albumName = addslashes($child['AlbumTitle']);
  1137. $albumArtist = htmlentities($child['ArtistName'], ENT_QUOTES);
  1138. $albumDate = $child['ReleaseDate'];
  1139. $albumID = $child['AlbumID'];
  1140. $albumDate = strtotime($albumDate);
  1141. $albumDate = date("Y-m-d", $albumDate);
  1142. $albumStatus = $child['Status'];
  1143. if (new DateTime() < new DateTime($albumDate)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  1144. if($albumStatus == "Wanted" && $notReleased == "true"){ $albumStatusColor = "indigo-bg"; }elseif($albumStatus == "Downloaded"){ $albumStatusColor = "green-bg"; }else{ $albumStatusColor = "red-bg"; }
  1145. $gotCalendar .= "{ title: \"$albumArtist - $albumName\", start: \"$albumDate\", className: \"$albumStatusColor\", imagetype: \"music\", url: \"https://musicbrainz.org/release-group/$albumID\" }, \n";
  1146. }
  1147. }
  1148. if ($i != 0){ return $gotCalendar; }
  1149. }
  1150. ?>