functions.php 47 KB

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