functions.php 46 KB

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