functions.php 46 KB

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