functions.php 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  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. // Turn Off Emby And Plex Recent
  734. $config["plexRecentMovie"] = "false";
  735. $config["plexRecentTV"] = "false";
  736. $config["plexRecentMusic"] = "false";
  737. $config["plexPlayingNow"] = "false";
  738. $config["embyRecentMovie"] = "true";
  739. $config["embyRecentTV"] = "true";
  740. $config["embyRecentMusic"] = "false";
  741. $config["embyPlayingNow"] = "true";
  742. $createConfigSuccess = createConfig($config, 'config/config.php', $nest = 0);
  743. // Create new config
  744. if ($createConfigSuccess) {
  745. // Make Config Dir (this should never happen as the dir and defaults file should be there);
  746. @mkdir('config', 0775, true);
  747. // Remove Old ini file
  748. unlink('databaseLocation.ini.php');
  749. }
  750. }
  751. return true;
  752. }
  753. // Check if all software dependancies are met
  754. function dependCheck() {
  755. return true;
  756. }
  757. // Process file uploads
  758. function uploadFiles($path, $ext_mask = null) {
  759. if (isset($_FILES) && count($_FILES)) {
  760. require_once('class.uploader.php');
  761. $uploader = new Uploader();
  762. $data = $uploader->upload($_FILES['files'], array(
  763. 'limit' => 10,
  764. 'maxSize' => 10,
  765. 'extensions' => $ext_mask,
  766. 'required' => false,
  767. 'uploadDir' => str_replace('//','/',$path.'/'),
  768. 'title' => array('name'),
  769. 'removeFiles' => true,
  770. 'replace' => true,
  771. ));
  772. if($data['isComplete']){
  773. $files = $data['data'];
  774. echo json_encode($files['metas'][0]['name']);
  775. }
  776. if($data['hasErrors']){
  777. $errors = $data['errors'];
  778. echo json_encode($errors);
  779. }
  780. } else {
  781. echo json_encode('No files submitted!');
  782. }
  783. }
  784. // Remove file
  785. function removeFiles($path) {
  786. if(is_file($path)) {
  787. unlink($path);
  788. } else {
  789. echo json_encode('No file specified for removal!');
  790. }
  791. }
  792. // ==============
  793. function clean($strin) {
  794. $strout = null;
  795. for ($i = 0; $i < strlen($strin); $i++) {
  796. $ord = ord($strin[$i]);
  797. if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
  798. $strout .= "&amp;#{$ord};";
  799. }
  800. else {
  801. switch ($strin[$i]) {
  802. case '<':
  803. $strout .= '&lt;';
  804. break;
  805. case '>':
  806. $strout .= '&gt;';
  807. break;
  808. case '&':
  809. $strout .= '&amp;';
  810. break;
  811. case '"':
  812. $strout .= '&quot;';
  813. break;
  814. default:
  815. $strout .= $strin[$i];
  816. }
  817. }
  818. }
  819. return $strout;
  820. }
  821. function registration_callback($username, $email, $userdir){
  822. global $data;
  823. $data = array($username, $email, $userdir);
  824. }
  825. function printArray($arrayName){
  826. $messageCount = count($arrayName);
  827. $i = 0;
  828. foreach ( $arrayName as $item ) :
  829. $i++;
  830. if($i < $messageCount) :
  831. echo "<small class='text-uppercase'>" . $item . "</small> & ";
  832. elseif($i = $messageCount) :
  833. echo "<small class='text-uppercase'>" . $item . "</small>";
  834. endif;
  835. endforeach;
  836. }
  837. function write_ini_file($content, $path) {
  838. if (!$handle = fopen($path, 'w')) {
  839. return false;
  840. }
  841. $success = fwrite($handle, trim($content));
  842. fclose($handle);
  843. return $success;
  844. }
  845. function gotTimezone(){
  846. $regions = array(
  847. 'Africa' => DateTimeZone::AFRICA,
  848. 'America' => DateTimeZone::AMERICA,
  849. 'Antarctica' => DateTimeZone::ANTARCTICA,
  850. 'Arctic' => DateTimeZone::ARCTIC,
  851. 'Asia' => DateTimeZone::ASIA,
  852. 'Atlantic' => DateTimeZone::ATLANTIC,
  853. 'Australia' => DateTimeZone::AUSTRALIA,
  854. 'Europe' => DateTimeZone::EUROPE,
  855. 'Indian' => DateTimeZone::INDIAN,
  856. 'Pacific' => DateTimeZone::PACIFIC
  857. );
  858. $timezones = array();
  859. foreach ($regions as $name => $mask) {
  860. $zones = DateTimeZone::listIdentifiers($mask);
  861. foreach($zones as $timezone) {
  862. $time = new DateTime(NULL, new DateTimeZone($timezone));
  863. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  864. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  865. }
  866. }
  867. print '<select name="timezone" id="timezone" class="form-control material input-sm" required>';
  868. foreach($timezones as $region => $list) {
  869. print '<optgroup label="' . $region . '">' . "\n";
  870. foreach($list as $timezone => $name) {
  871. if($timezone == TIMEZONE) : $selected = " selected"; else : $selected = ""; endif;
  872. print '<option value="' . $timezone . '"' . $selected . '>' . $name . '</option>' . "\n";
  873. }
  874. print '</optgroup>' . "\n";
  875. }
  876. print '</select>';
  877. }
  878. function getTimezone(){
  879. $regions = array(
  880. 'Africa' => DateTimeZone::AFRICA,
  881. 'America' => DateTimeZone::AMERICA,
  882. 'Antarctica' => DateTimeZone::ANTARCTICA,
  883. 'Arctic' => DateTimeZone::ARCTIC,
  884. 'Asia' => DateTimeZone::ASIA,
  885. 'Atlantic' => DateTimeZone::ATLANTIC,
  886. 'Australia' => DateTimeZone::AUSTRALIA,
  887. 'Europe' => DateTimeZone::EUROPE,
  888. 'Indian' => DateTimeZone::INDIAN,
  889. 'Pacific' => DateTimeZone::PACIFIC
  890. );
  891. $timezones = array();
  892. foreach ($regions as $name => $mask) {
  893. $zones = DateTimeZone::listIdentifiers($mask);
  894. foreach($zones as $timezone) {
  895. $time = new DateTime(NULL, new DateTimeZone($timezone));
  896. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  897. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  898. }
  899. }
  900. print '<select name="timezone" id="timezone" class="form-control material" required>';
  901. foreach($timezones as $region => $list) {
  902. print '<optgroup label="' . $region . '">' . "\n";
  903. foreach($list as $timezone => $name) {
  904. print '<option value="' . $timezone . '">' . $name . '</option>' . "\n";
  905. }
  906. print '</optgroup>' . "\n";
  907. }
  908. print '</select>';
  909. }
  910. function explosion($string, $position){
  911. $getWord = explode("|", $string);
  912. return $getWord[$position];
  913. }
  914. function getServerPath() {
  915. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  916. $protocol = "https://";
  917. } else {
  918. $protocol = "http://";
  919. }
  920. return $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
  921. }
  922. function get_browser_name() {
  923. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  924. if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
  925. elseif (strpos($user_agent, 'Edge')) return 'Edge';
  926. elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
  927. elseif (strpos($user_agent, 'Safari')) return 'Safari';
  928. elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
  929. elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
  930. return 'Other';
  931. }
  932. function getSickrageCalendarWanted($array){
  933. $array = json_decode($array, true);
  934. $gotCalendar = "";
  935. $i = 0;
  936. foreach($array['data']['missed'] AS $child) {
  937. $i++;
  938. $seriesName = $child['show_name'];
  939. $episodeID = $child['tvdbid'];
  940. $episodeAirDate = $child['airdate'];
  941. $episodeAirDateTime = explode(" ",$child['airs']);
  942. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  943. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  944. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  945. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  946. $downloaded = "0";
  947. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  948. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  949. }
  950. foreach($array['data']['today'] AS $child) {
  951. $i++;
  952. $seriesName = $child['show_name'];
  953. $episodeID = $child['tvdbid'];
  954. $episodeAirDate = $child['airdate'];
  955. $episodeAirDateTime = explode(" ",$child['airs']);
  956. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  957. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  958. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  959. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  960. $downloaded = "0";
  961. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  962. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  963. }
  964. foreach($array['data']['soon'] AS $child) {
  965. $i++;
  966. $seriesName = $child['show_name'];
  967. $episodeID = $child['tvdbid'];
  968. $episodeAirDate = $child['airdate'];
  969. $episodeAirDateTime = explode(" ",$child['airs']);
  970. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  971. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  972. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  973. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  974. $downloaded = "0";
  975. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  976. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  977. }
  978. foreach($array['data']['later'] AS $child) {
  979. $i++;
  980. $seriesName = $child['show_name'];
  981. $episodeID = $child['tvdbid'];
  982. $episodeAirDate = $child['airdate'];
  983. $episodeAirDateTime = explode(" ",$child['airs']);
  984. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  985. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  986. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  987. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  988. $downloaded = "0";
  989. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  990. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  991. }
  992. if ($i != 0){ return $gotCalendar; }
  993. }
  994. function getSickrageCalendarHistory($array){
  995. $array = json_decode($array, true);
  996. $gotCalendar = "";
  997. $i = 0;
  998. foreach($array['data'] AS $child) {
  999. $i++;
  1000. $seriesName = $child['show_name'];
  1001. $episodeID = $child['tvdbid'];
  1002. $episodeAirDate = $child['date'];
  1003. $downloaded = "green-bg";
  1004. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1005. }
  1006. if ($i != 0){ return $gotCalendar; }
  1007. }
  1008. function getSonarrCalendar($array){
  1009. $array = json_decode($array, true);
  1010. $gotCalendar = "";
  1011. $i = 0;
  1012. foreach($array AS $child) {
  1013. $i++;
  1014. $seriesName = $child['series']['title'];
  1015. $episodeID = $child['series']['tvdbId'];
  1016. if(!isset($episodeID)){ $episodeID = ""; }
  1017. $episodeName = htmlentities($child['title'], ENT_QUOTES);
  1018. if($child['episodeNumber'] == "1"){ $episodePremier = "true"; }else{ $episodePremier = "false"; }
  1019. $episodeAirDate = $child['airDateUtc'];
  1020. $episodeAirDate = strtotime($episodeAirDate);
  1021. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1022. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1023. $downloaded = $child['hasFile'];
  1024. 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"; }
  1025. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1026. }
  1027. if ($i != 0){ return $gotCalendar; }
  1028. }
  1029. function getRadarrCalendar($array){
  1030. $array = json_decode($array, true);
  1031. $gotCalendar = "";
  1032. $i = 0;
  1033. foreach($array AS $child) {
  1034. if(isset($child['inCinemas'])){
  1035. $i++;
  1036. $movieName = $child['title'];
  1037. $movieID = $child['tmdbId'];
  1038. if(!isset($movieID)){ $movieID = ""; }
  1039. if(isset($child['inCinemas']) && isset($child['physicalRelease'])){
  1040. $physicalRelease = $child['physicalRelease'];
  1041. $physicalRelease = strtotime($physicalRelease);
  1042. $physicalRelease = date("Y-m-d", $physicalRelease);
  1043. if (new DateTime() < new DateTime($physicalRelease)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  1044. $downloaded = $child['hasFile'];
  1045. if($downloaded == "0" && $notReleased == "true"){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg"; }else{ $downloaded = "red-bg"; }
  1046. }else{
  1047. $physicalRelease = $child['inCinemas'];
  1048. $downloaded = "light-blue-bg";
  1049. }
  1050. $gotCalendar .= "{ title: \"$movieName\", start: \"$physicalRelease\", className: \"$downloaded\", imagetype: \"film\", url: \"https://www.themoviedb.org/movie/$movieID\" }, \n";
  1051. }
  1052. }
  1053. if ($i != 0){ return $gotCalendar; }
  1054. }
  1055. function nzbgetConnect($url, $port, $username, $password, $list){
  1056. $urlCheck = stripos($url, "http");
  1057. if ($urlCheck === false) {
  1058. $url = "http://" . $url;
  1059. }
  1060. if($port !== ""){ $url = $url . ":" . $port; }
  1061. $address = $url;
  1062. $api = file_get_contents("$url/$username:$password/jsonrpc/$list");
  1063. $api = json_decode($api, true);
  1064. $i = 0;
  1065. $gotNZB = "";
  1066. foreach ($api['result'] AS $child) {
  1067. $i++;
  1068. //echo '<pre>' . var_export($child, true) . '</pre>';
  1069. $downloadName = htmlentities($child['NZBName'], ENT_QUOTES);
  1070. $downloadStatus = $child['Status'];
  1071. $downloadCategory = $child['Category'];
  1072. if($list == "history"){ $downloadPercent = "100"; $progressBar = ""; }
  1073. if($list == "listgroups"){ $downloadPercent = (($child['FileSizeMB'] - $child['RemainingSizeMB']) / $child['FileSizeMB']) * 100; $progressBar = "progress-bar-striped active"; }
  1074. if($child['Health'] <= "750"){
  1075. $downloadHealth = "danger";
  1076. }elseif($child['Health'] <= "900"){
  1077. $downloadHealth = "warning";
  1078. }elseif($child['Health'] <= "1000"){
  1079. $downloadHealth = "success";
  1080. }
  1081. $gotNZB .= '<tr>
  1082. <td>'.$downloadName.'</td>
  1083. <td>'.$downloadStatus.'</td>
  1084. <td>'.$downloadCategory.'</td>
  1085. <td>
  1086. <div class="progress">
  1087. <div class="progress-bar progress-bar-'.$downloadHealth.' '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  1088. <p class="text-center">'.round($downloadPercent).'%</p>
  1089. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  1090. </div>
  1091. </div>
  1092. </td>
  1093. </tr>';
  1094. }
  1095. if($i > 0){ return $gotNZB; }
  1096. if($i == 0){ echo '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>'; }
  1097. }
  1098. function sabnzbdConnect($url, $port, $key, $list){
  1099. $urlCheck = stripos($url, "http");
  1100. if ($urlCheck === false) {
  1101. $url = "http://" . $url;
  1102. }
  1103. if($port !== ""){ $url = $url . ":" . $port; }
  1104. $address = $url;
  1105. $api = file_get_contents("$url/api?mode=$list&output=json&apikey=$key");
  1106. $api = json_decode($api, true);
  1107. $i = 0;
  1108. $gotNZB = "";
  1109. foreach ($api[$list]['slots'] AS $child) {
  1110. $i++;
  1111. if($list == "queue"){ $downloadName = $child['filename']; $downloadCategory = $child['cat']; $downloadPercent = (($child['mb'] - $child['mbleft']) / $child['mb']) * 100; $progressBar = "progress-bar-striped active"; }
  1112. if($list == "history"){ $downloadName = $child['name']; $downloadCategory = $child['category']; $downloadPercent = "100"; $progressBar = ""; }
  1113. $downloadStatus = $child['status'];
  1114. $gotNZB .= '<tr>
  1115. <td>'.$downloadName.'</td>
  1116. <td>'.$downloadStatus.'</td>
  1117. <td>'.$downloadCategory.'</td>
  1118. <td>
  1119. <div class="progress">
  1120. <div class="progress-bar progress-bar-success '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  1121. <p class="text-center">'.round($downloadPercent).'%</p>
  1122. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  1123. </div>
  1124. </div>
  1125. </td>
  1126. </tr>';
  1127. }
  1128. if($i > 0){ return $gotNZB; }
  1129. if($i == 0){ echo '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>'; }
  1130. }
  1131. function getHeadphonesCalendar($url, $port, $key, $list){
  1132. $urlCheck = stripos($url, "http");
  1133. if ($urlCheck === false) {
  1134. $url = "http://" . $url;
  1135. }
  1136. if($port !== ""){ $url = $url . ":" . $port; }
  1137. $address = $url;
  1138. $api = file_get_contents($address."/api?apikey=".$key."&cmd=$list");
  1139. $api = json_decode($api, true);
  1140. $i = 0;
  1141. $gotCalendar = "";
  1142. foreach($api AS $child) {
  1143. if($child['Status'] == "Wanted"){
  1144. $i++;
  1145. $albumName = addslashes($child['AlbumTitle']);
  1146. $albumArtist = htmlentities($child['ArtistName'], ENT_QUOTES);
  1147. $albumDate = $child['ReleaseDate'];
  1148. $albumID = $child['AlbumID'];
  1149. $albumDate = strtotime($albumDate);
  1150. $albumDate = date("Y-m-d", $albumDate);
  1151. $albumStatus = $child['Status'];
  1152. if (new DateTime() < new DateTime($albumDate)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  1153. if($albumStatus == "Wanted" && $notReleased == "true"){ $albumStatusColor = "indigo-bg"; }elseif($albumStatus == "Downloaded"){ $albumStatusColor = "green-bg"; }else{ $albumStatusColor = "red-bg"; }
  1154. $gotCalendar .= "{ title: \"$albumArtist - $albumName\", start: \"$albumDate\", className: \"$albumStatusColor\", imagetype: \"music\", url: \"https://musicbrainz.org/release-group/$albumID\" }, \n";
  1155. }
  1156. }
  1157. if ($i != 0){ return $gotCalendar; }
  1158. }
  1159. ?>