4
0

functions.php 48 KB

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