functions.php 46 KB

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