functions.php 46 KB

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