functions.php 42 KB

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