functions.php 46 KB

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