functions.php 47 KB

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