functions.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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. // Pass credentials to LDAP backend
  10. function plugin_auth_ldap($username, $password) {
  11. // returns true or false
  12. $ldap = ldap_connect(AUTHBACKENDHOST.(AUTHBACKENDPORT?':'.AUTHBACKENDPORT:'389'));
  13. if ($bind = ldap_bind($ldap, AUTHBACKENDDOMAIN.'\\'.$username, $password)) {
  14. return true;
  15. } else {
  16. return false;
  17. }
  18. return false;
  19. }
  20. // Pass credentials to FTP backend
  21. function plugin_auth_ftp($username, $password) {
  22. // returns true or false
  23. // Connect to FTP
  24. $conn_id = ftp_ssl_connect(AUTHBACKENDHOST, (AUTHBACKENDPORT?AUTHBACKENDPORT:21), 20); // 20 Second Timeout
  25. // Check if valid FTP connection
  26. if ($conn_id) {
  27. // Attempt login
  28. @$login_result = ftp_login($conn_id, $username, $password);
  29. // Return Result
  30. if ($login_result) {
  31. return true;
  32. } else {
  33. return false;
  34. }
  35. } else {
  36. return false;
  37. }
  38. return false;
  39. }
  40. // Authenticate Against Emby Local (first) and Emby Connect
  41. function plugin_auth_emby_all($username, $password) {
  42. return plugin_auth_emby($username, $password) || plugin_auth_emby_connect($username, $password);
  43. }
  44. // Authenicate against emby connect
  45. function plugin_auth_emby_connect($username, $password) {
  46. $urlCheck = stripos(AUTHBACKENDHOST, "http");
  47. if ($urlCheck === false) {
  48. $embyAddress = "http://" . AUTHBACKENDHOST;
  49. } else {
  50. $embyAddress = AUTHBACKENDHOST;
  51. }
  52. if(AUTHBACKENDPORT !== "") { $embyAddress .= ":" . AUTHBACKENDPORT; }
  53. // Get A User
  54. $connectId = '';
  55. $userIds = json_decode(file_get_contents($embyAddress.'/Users?api_key='.EMBYTOKEN),true);
  56. foreach ($userIds as $value) { // Scan for this user
  57. if (isset($value['ConnectUserName']) && isset($value['ConnectUserId'])) { // Qualifty as connect account
  58. if ($value['ConnectUserName'] == $username || $value['Name'] == $username) {
  59. $connectId = $value['ConnectUserId'];
  60. }
  61. break;
  62. }
  63. }
  64. if ($connectId) {
  65. $connectURL = 'https://connect.emby.media/service/user/authenticate';
  66. $headers = array(
  67. 'Accept'=> 'application/json',
  68. 'Content-Type' => 'application/x-www-form-urlencoded',
  69. );
  70. $body = array(
  71. 'nameOrEmail' => $username,
  72. 'rawpw' => $password,
  73. );
  74. $result = json_decode(curl_post($connectURL, $body, $headers),true);
  75. if (isset($response['content'])) {
  76. $json = json_decode($response['content'], true);
  77. if (is_array($json) && isset($json['SessionInfo']) && isset($json['User']) && $json['User']['Id'] == $connectId) {
  78. return true;
  79. }
  80. }
  81. }
  82. return false;
  83. }
  84. // Pass credentials to Emby Backend
  85. function plugin_auth_emby_local($username, $password) {
  86. $urlCheck = stripos(AUTHBACKENDHOST, "http");
  87. if ($urlCheck === false) {
  88. $embyAddress = "http://" . AUTHBACKENDHOST;
  89. } else {
  90. $embyAddress = AUTHBACKENDHOST;
  91. }
  92. if(AUTHBACKENDPORT !== ""){ $embyAddress .= ":" . AUTHBACKENDPORT; }
  93. $headers = array(
  94. 'Authorization'=> 'MediaBrowser UserId="e8837bc1-ad67-520e-8cd2-f629e3155721", Client="None", Device="Organizr", DeviceId="xxx", Version="1.0.0.0"',
  95. 'Content-Type' => 'application/json',
  96. );
  97. $body = array(
  98. 'Username' => $username,
  99. 'Password' => sha1($password),
  100. 'PasswordMd5' => md5($password),
  101. );
  102. $response = post_router($embyAddress.'/Users/AuthenticateByName', $body, $headers);
  103. if (isset($response['content'])) {
  104. $json = json_decode($response['content'], true);
  105. if (is_array($json) && isset($json['SessionInfo']) && isset($json['User']) && $json['User']['HasPassword'] == true) {
  106. // Login Success - Now Logout Emby Session As We No Longer Need It
  107. $headers = array(
  108. 'X-Mediabrowser-Token' => $json['AccessToken'],
  109. );
  110. $response = post_router($embyAddress.'/Sessions/Logout', array(), $headers);
  111. return true;
  112. }
  113. }
  114. return false;
  115. }
  116. // ==== Auth Plugins END ====
  117. // ==== General Class Definitions START ====
  118. class setLanguage {
  119. private $language = null;
  120. function __construct($language = false) {
  121. // Default
  122. if (!$language) {
  123. $language = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) : "en";
  124. }
  125. if (file_exists("lang/{$language}.ini")) {
  126. $this->language = parse_ini_file("lang/{$language}.ini", false, INI_SCANNER_RAW);
  127. } else {
  128. $this->language = parse_ini_file("lang/en.ini", false, INI_SCANNER_RAW);
  129. }
  130. }
  131. public function translate($originalWord) {
  132. $getArg = func_num_args();
  133. if ($getArg > 1) {
  134. $allWords = func_get_args();
  135. array_shift($allWords);
  136. } else {
  137. $allWords = array();
  138. }
  139. $translatedWord = isset($this->language[$originalWord]) ? $this->language[$originalWord] : null;
  140. if (!$translatedWord) {
  141. echo ("Translation not found for: $originalWord");
  142. }
  143. $translatedWord = htmlspecialchars($translatedWord, ENT_QUOTES);
  144. return vsprintf($translatedWord, $allWords);
  145. }
  146. }
  147. $language = new setLanguage;
  148. // ==== General Class Definitions END ====
  149. // Direct request to curl if it exists, otherwise handle if not HTTPS
  150. function post_router($url, $data, $headers = array(), $referer='') {
  151. if (function_exists('curl_version')) {
  152. return curl_post($url, $data, $headers, $referer);
  153. } else {
  154. return post_request($url, $data, $headers, $referer);
  155. }
  156. }
  157. // Curl Post
  158. function curl_post($url, $data, $headers = array(), $referer='') {
  159. // Initiate cURL
  160. $curlReq = curl_init($url);
  161. // As post request
  162. curl_setopt($curlReq, CURLOPT_CUSTOMREQUEST, "POST");
  163. curl_setopt($curlReq, CURLOPT_RETURNTRANSFER, true);
  164. // Format Data
  165. switch ($headers['Content-Type']) {
  166. case 'application/json':
  167. curl_setopt($curlReq, CURLOPT_POSTFIELDS, json_encode($data));
  168. break;
  169. case 'application/x-www-form-urlencoded';
  170. curl_setopt($curlReq, CURLOPT_POSTFIELDS, http_build_query($data));
  171. break;
  172. default:
  173. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  174. curl_setopt($curlReq, CURLOPT_POSTFIELDS, http_build_query($data));
  175. }
  176. // Format Headers
  177. $cHeaders = array();
  178. foreach ($headers as $k => $v) {
  179. $cHeaders[] = $k.': '.$v;
  180. }
  181. if (count($cHeaders)) {
  182. curl_setopt($curlReq, CURLOPT_HTTPHEADER, $cHeaders);
  183. }
  184. // Execute
  185. $result = curl_exec($curlReq);
  186. // Close
  187. curl_close($curlReq);
  188. // Return
  189. return array('content'=>$result);
  190. }
  191. // HTTP post request (Removes need for curl, probably useless)
  192. function post_request($url, $data, $headers = array(), $referer='') {
  193. // Adapted from http://stackoverflow.com/a/28387011/6810513
  194. // Convert the data array into URL Parameters like a=b&foo=bar etc.
  195. if (isset($headers['Content-Type'])) {
  196. switch ($headers['Content-Type']) {
  197. case 'application/json':
  198. $data = json_encode($data);
  199. break;
  200. case 'application/x-www-form-urlencoded':
  201. $data = http_build_query($data);
  202. break;
  203. }
  204. } else {
  205. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  206. $data = http_build_query($data);
  207. }
  208. // parse the given URL
  209. $urlDigest = parse_url($url);
  210. // extract host and path:
  211. $host = $urlDigest['host'].(isset($urlDigest['port'])?':'.$urlDigest['port']:'');
  212. $path = $urlDigest['path'];
  213. if ($urlDigest['scheme'] != 'http') {
  214. die('Error: Only HTTP request are supported, please use cURL to add HTTPS support! ('.$urlDigest['scheme'].'://'.$host.')');
  215. }
  216. // open a socket connection on port 80 - timeout: 30 sec
  217. $fp = fsockopen($host, 80, $errno, $errstr, 30);
  218. if ($fp){
  219. // send the request headers:
  220. fputs($fp, "POST $path HTTP/1.1\r\n");
  221. fputs($fp, "Host: $host\r\n");
  222. if ($referer != '')
  223. fputs($fp, "Referer: $referer\r\n");
  224. fputs($fp, "Content-length: ". strlen($data) ."\r\n");
  225. foreach($headers as $k => $v) {
  226. fputs($fp, $k.": ".$v."\r\n");
  227. }
  228. fputs($fp, "Connection: close\r\n\r\n");
  229. fputs($fp, $data);
  230. $result = '';
  231. while(!feof($fp)) {
  232. // receive the results of the request
  233. $result .= fgets($fp, 128);
  234. }
  235. }
  236. else {
  237. return array(
  238. 'status' => 'err',
  239. 'error' => "$errstr ($errno)"
  240. );
  241. }
  242. // close the socket connection:
  243. fclose($fp);
  244. // split the result header from the content
  245. $result = explode("\r\n\r\n", $result, 2);
  246. $header = isset($result[0]) ? $result[0] : '';
  247. $content = isset($result[1]) ? $result[1] : '';
  248. // return as structured array:
  249. return array(
  250. 'status' => 'ok',
  251. 'header' => $header,
  252. 'content' => $content,
  253. );
  254. }
  255. // Format item from Emby for Carousel
  256. function resolveEmbyItem($address, $token, $item) {
  257. // Static Height
  258. $height = 150;
  259. // Get Item Details
  260. $itemDetails = json_decode(file_get_contents($address.'/Items?Ids='.$item['Id'].'&Fields=Overview&api_key='.$token),true)['Items'][0];
  261. switch ($item['Type']) {
  262. case 'Episode':
  263. $title = $item['SeriesName'].': '.$item['Name'].' (Season '.$item['ParentIndexNumber'].': Episode '.$item['IndexNumber'].')';
  264. $imageId = $itemDetails['SeriesId'];
  265. $width = 100;
  266. $image = 'carousel-image season';
  267. $style = '';
  268. break;
  269. case 'MusicAlbum':
  270. $title = $item['Name'];
  271. $imageId = $itemDetails['Id'];
  272. $width = 150;
  273. $image = 'music';
  274. $style = 'left: 160px !important;';
  275. break;
  276. default:
  277. $title = $item['Name'];
  278. $imageId = $item['Id'];
  279. $width = 100;
  280. $image = 'carousel-image movie';
  281. $style = '';
  282. }
  283. // If No Overview
  284. if (!isset($itemDetails['Overview'])) {
  285. $itemDetails['Overview'] = '';
  286. }
  287. // Assemble Item And Cache Into Array
  288. return '<div class="item"><a href="'.$address.'/web/itemdetails.html?id='.$item['Id'].'" target="_blank"><img alt="'.$item['Name'].'" class="'.$image.'" src="image.php?source=emby&img='.$imageId.'&height='.$height.'&width='.$width.'"></a><div class="carousel-caption" style="'.$style.'"><h4>'.$title.'</h4><small><em>'.$itemDetails['Overview'].'</em></small></div></div>';
  289. }
  290. // Format item from Plex for Carousel
  291. function resolvePlexItem($server, $token, $item) {
  292. // Static Height
  293. $height = 150;
  294. $address = "https://app.plex.tv/web/app#!/server/$server/details?key=/library/metadata/".$item['ratingKey'];
  295. switch ($item['Type']) {
  296. case 'season':
  297. $title = $item['parentTitle'];
  298. $summary = $item['parentSummary'];
  299. $width = 100;
  300. $image = 'carousel-image season';
  301. $style = '';
  302. break;
  303. case 'album':
  304. $title = $item['parentTitle'];
  305. $summary = $item['title'];
  306. $width = 150;
  307. $image = 'album';
  308. $style = 'left: 160px !important;';
  309. break;
  310. default:
  311. $title = $item['title'];
  312. $summary = $item['summary'];
  313. $width = 100;
  314. $image = 'carousel-image movie';
  315. $style = '';
  316. }
  317. // If No Overview
  318. if (!isset($itemDetails['Overview'])) {
  319. $itemDetails['Overview'] = '';
  320. }
  321. // Assemble Item And Cache Into Array
  322. return '<div class="item"><a href="'.$address.'" target="_blank"><img alt="'.$item['Name'].'" class="'.$image.'" src="image.php?source=plex&img='.$item['thumb'].'&height='.$height.'&width='.$width.'"></a><div class="carousel-caption" style="'.$style.'"><h4>'.$title.'</h4><small><em>'.$summary.'</em></small></div></div>';
  323. }
  324. // Create Carousel
  325. function outputCarousel($header, $size, $type, $items) {
  326. // If None Populate Empty Item
  327. if (!count($items)) {
  328. $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>');
  329. }
  330. // Set First As Active
  331. $items[0] = preg_replace('/^<div class="item ?">/','<div class="item active">', $items[0]);
  332. // Add Buttons
  333. $buttons = '';
  334. if (count($items) > 1) {
  335. $buttons = '
  336. <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>
  337. <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>';
  338. }
  339. return '
  340. <div class="col-lg-'.$size.'">
  341. <h5 class="text-center">'.$header.'</h5>
  342. <div id="carousel-'.$type.'" class="carousel slide box-shadow white-bg" data-ride="carousel"><div class="carousel-inner" role="listbox">
  343. '.implode('',$items).'
  344. </div>'.$buttons.'
  345. </div></div>';
  346. }
  347. // Get Now Playing Streams From Emby
  348. function getEmbyStreams($url, $port, $token, $size, $header) {
  349. if (stripos($url, "http") === false) {
  350. $url = "http://" . $url;
  351. }
  352. if ($port !== "") {
  353. $url = $url . ":" . $port;
  354. }
  355. $address = $url;
  356. $api = json_decode(file_get_contents($address.'/Sessions?api_key='.$token),true);
  357. $playingItems = array();
  358. foreach($api as $key => $value) {
  359. if (isset($value['NowPlayingItem'])) {
  360. $playingItems[] = resolveEmbyItem($address, $token, $value['NowPlayingItem']);
  361. }
  362. }
  363. return outputCarousel($header, $size, 'streams-emby', $playingItems);
  364. }
  365. // Get Now Playing Streams From Plex
  366. function getPlexStreams($url, $port, $token, $size, $header){
  367. if (stripos($url, "http") === false) {
  368. $url = "http://" . $url;
  369. }
  370. if ($port !== "") {
  371. $url = $url . ":" . $port;
  372. }
  373. $address = $url;
  374. // Perform API requests
  375. $api = file_get_contents($address."/status/sessions?X-Plex-Token=".$token);
  376. $api = simplexml_load_string($api);
  377. $getServer = file_get_contents($address."/servers?X-Plex-Token=".$token);
  378. $getServer = simplexml_load_string($getServer);
  379. // Identify the local machine
  380. foreach($getServer AS $child) {
  381. $gotServer = $child['machineIdentifier'];
  382. }
  383. $items = array();
  384. foreach($api AS $child) {
  385. $items[] = resolvePlexItem($gotServer, $token, $child);
  386. }
  387. return outputCarousel($header, $size, 'streams-plex', $items);
  388. }
  389. // Get Recent Content From Emby
  390. function getEmbyRecent($url, $port, $type, $token, $size, $header) {
  391. if (stripos($url, "http") === false) {
  392. $url = "http://" . $url;
  393. }
  394. if ($port !== "") {
  395. $url = $url . ":" . $port;
  396. }
  397. $address = $url;
  398. // Resolve Types
  399. switch ($type) {
  400. case 'movie':
  401. $embyTypeQuery = 'IncludeItemTypes=Movie&';
  402. break;
  403. case 'season':
  404. $embyTypeQuery = 'IncludeItemTypes=Episode&';
  405. break;
  406. case 'album':
  407. $embyTypeQuery = 'IncludeItemTypes=MusicAlbum&';
  408. break;
  409. default:
  410. $embyTypeQuery = '';
  411. }
  412. // Get A User
  413. $userIds = json_decode(file_get_contents($address.'/Users?api_key='.$token),true);
  414. foreach ($userIds as $value) { // Scan for admin user
  415. $userId = $value['Id'];
  416. if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
  417. break;
  418. }
  419. }
  420. // Get the latest Items
  421. $latest = json_decode(file_get_contents($address.'/Users/'.$userId.'/Items/Latest?'.$embyTypeQuery.'EnableImages=false&api_key='.$token),true);
  422. // For Each Item In Category
  423. $items = array();
  424. foreach ($latest as $k => $v) {
  425. $items[] = resolveEmbyItem($address, $token, $v);
  426. }
  427. return outputCarousel($header, $size, $type.'-emby', $items);
  428. }
  429. // Get Recent Content From Plex
  430. function getPlexRecent($url, $port, $type, $token, $size, $header){
  431. if (stripos($url, "http") === false) {
  432. $url = "http://" . $url;
  433. }
  434. if ($port !== "") {
  435. $url = $url . ":" . $port;
  436. }
  437. $address = $url;
  438. // Perform Requests
  439. $api = file_get_contents($address."/library/recentlyAdded?X-Plex-Token=".$token);
  440. $api = simplexml_load_string($api);
  441. $getServer = file_get_contents($address."/servers?X-Plex-Token=".$token);
  442. $getServer = simplexml_load_string($getServer);
  443. // Identify the local machine
  444. foreach($getServer AS $child) {
  445. $gotServer = $child['machineIdentifier'];
  446. }
  447. $items = array();
  448. foreach($api AS $child) {
  449. if($child['type'] == $type){
  450. $items[] = resolvePlexItem($gotServer, $token, $child);
  451. }
  452. }
  453. return outputCarousel($header, $size, $type.'-plex', $items);
  454. }
  455. // Simplier access to class
  456. function translate($string) {
  457. if (isset($GLOBALS['language'])) {
  458. return $GLOBALS['language']->translate($string);
  459. } else {
  460. return '!Translations Not Loaded!';
  461. }
  462. }
  463. // Generate Random string
  464. function randString($length = 10) {
  465. $tmp = '';
  466. $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  467. for ($i = 0; $i < $length; $i++) {
  468. $tmp .= substr(str_shuffle($chars), 0, 1);
  469. }
  470. return $tmp;
  471. }
  472. // ==============
  473. function clean($strin) {
  474. $strout = null;
  475. for ($i = 0; $i < strlen($strin); $i++) {
  476. $ord = ord($strin[$i]);
  477. if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
  478. $strout .= "&amp;#{$ord};";
  479. }
  480. else {
  481. switch ($strin[$i]) {
  482. case '<':
  483. $strout .= '&lt;';
  484. break;
  485. case '>':
  486. $strout .= '&gt;';
  487. break;
  488. case '&':
  489. $strout .= '&amp;';
  490. break;
  491. case '"':
  492. $strout .= '&quot;';
  493. break;
  494. default:
  495. $strout .= $strin[$i];
  496. }
  497. }
  498. }
  499. return $strout;
  500. }
  501. function registration_callback($username, $email, $userdir){
  502. global $data;
  503. $data = array($username, $email, $userdir);
  504. }
  505. function printArray($arrayName){
  506. $messageCount = count($arrayName);
  507. $i = 0;
  508. foreach ( $arrayName as $item ) :
  509. $i++;
  510. if($i < $messageCount) :
  511. echo "<small class='text-uppercase'>" . $item . "</small> & ";
  512. elseif($i = $messageCount) :
  513. echo "<small class='text-uppercase'>" . $item . "</small>";
  514. endif;
  515. endforeach;
  516. }
  517. function write_ini_file($content, $path) {
  518. if (!$handle = fopen($path, 'w')) {
  519. return false;
  520. }
  521. $success = fwrite($handle, trim($content));
  522. fclose($handle);
  523. return $success;
  524. }
  525. function gotTimezone(){
  526. $regions = array(
  527. 'Africa' => DateTimeZone::AFRICA,
  528. 'America' => DateTimeZone::AMERICA,
  529. 'Antarctica' => DateTimeZone::ANTARCTICA,
  530. 'Arctic' => DateTimeZone::ARCTIC,
  531. 'Asia' => DateTimeZone::ASIA,
  532. 'Atlantic' => DateTimeZone::ATLANTIC,
  533. 'Australia' => DateTimeZone::AUSTRALIA,
  534. 'Europe' => DateTimeZone::EUROPE,
  535. 'Indian' => DateTimeZone::INDIAN,
  536. 'Pacific' => DateTimeZone::PACIFIC
  537. );
  538. $timezones = array();
  539. foreach ($regions as $name => $mask) {
  540. $zones = DateTimeZone::listIdentifiers($mask);
  541. foreach($zones as $timezone) {
  542. $time = new DateTime(NULL, new DateTimeZone($timezone));
  543. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  544. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  545. }
  546. }
  547. print '<select name="timezone" id="timezone" class="form-control material input-sm" required>';
  548. foreach($timezones as $region => $list) {
  549. print '<optgroup label="' . $region . '">' . "\n";
  550. foreach($list as $timezone => $name) {
  551. if($timezone == TIMEZONE) : $selected = " selected"; else : $selected = ""; endif;
  552. print '<option value="' . $timezone . '"' . $selected . '>' . $name . '</option>' . "\n";
  553. }
  554. print '</optgroup>' . "\n";
  555. }
  556. print '</select>';
  557. }
  558. function getTimezone(){
  559. $regions = array(
  560. 'Africa' => DateTimeZone::AFRICA,
  561. 'America' => DateTimeZone::AMERICA,
  562. 'Antarctica' => DateTimeZone::ANTARCTICA,
  563. 'Arctic' => DateTimeZone::ARCTIC,
  564. 'Asia' => DateTimeZone::ASIA,
  565. 'Atlantic' => DateTimeZone::ATLANTIC,
  566. 'Australia' => DateTimeZone::AUSTRALIA,
  567. 'Europe' => DateTimeZone::EUROPE,
  568. 'Indian' => DateTimeZone::INDIAN,
  569. 'Pacific' => DateTimeZone::PACIFIC
  570. );
  571. $timezones = array();
  572. foreach ($regions as $name => $mask) {
  573. $zones = DateTimeZone::listIdentifiers($mask);
  574. foreach($zones as $timezone) {
  575. $time = new DateTime(NULL, new DateTimeZone($timezone));
  576. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  577. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  578. }
  579. }
  580. print '<select name="timezone" id="timezone" class="form-control material" required>';
  581. foreach($timezones as $region => $list) {
  582. print '<optgroup label="' . $region . '">' . "\n";
  583. foreach($list as $timezone => $name) {
  584. print '<option value="' . $timezone . '">' . $name . '</option>' . "\n";
  585. }
  586. print '</optgroup>' . "\n";
  587. }
  588. print '</select>';
  589. }
  590. function explosion($string, $position){
  591. $getWord = explode("|", $string);
  592. return $getWord[$position];
  593. }
  594. function getServerPath() {
  595. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  596. $protocol = "https://";
  597. } else {
  598. $protocol = "http://";
  599. }
  600. return $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
  601. }
  602. function get_browser_name() {
  603. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  604. if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
  605. elseif (strpos($user_agent, 'Edge')) return 'Edge';
  606. elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
  607. elseif (strpos($user_agent, 'Safari')) return 'Safari';
  608. elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
  609. elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
  610. return 'Other';
  611. }
  612. function getSickrageCalendarWanted($array){
  613. $array = json_decode($array, true);
  614. $gotCalendar = "";
  615. $i = 0;
  616. foreach($array['data']['missed'] AS $child) {
  617. $i++;
  618. $seriesName = $child['show_name'];
  619. $episodeID = $child['tvdbid'];
  620. $episodeAirDate = $child['airdate'];
  621. $episodeAirDateTime = explode(" ",$child['airs']);
  622. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  623. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  624. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  625. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  626. $downloaded = "0";
  627. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  628. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  629. }
  630. foreach($array['data']['today'] AS $child) {
  631. $i++;
  632. $seriesName = $child['show_name'];
  633. $episodeID = $child['tvdbid'];
  634. $episodeAirDate = $child['airdate'];
  635. $episodeAirDateTime = explode(" ",$child['airs']);
  636. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  637. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  638. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  639. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  640. $downloaded = "0";
  641. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  642. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  643. }
  644. foreach($array['data']['soon'] AS $child) {
  645. $i++;
  646. $seriesName = $child['show_name'];
  647. $episodeID = $child['tvdbid'];
  648. $episodeAirDate = $child['airdate'];
  649. $episodeAirDateTime = explode(" ",$child['airs']);
  650. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  651. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  652. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  653. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  654. $downloaded = "0";
  655. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  656. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  657. }
  658. foreach($array['data']['later'] AS $child) {
  659. $i++;
  660. $seriesName = $child['show_name'];
  661. $episodeID = $child['tvdbid'];
  662. $episodeAirDate = $child['airdate'];
  663. $episodeAirDateTime = explode(" ",$child['airs']);
  664. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  665. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  666. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  667. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  668. $downloaded = "0";
  669. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  670. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  671. }
  672. if ($i != 0){ return $gotCalendar; }
  673. }
  674. function getSickrageCalendarHistory($array){
  675. $array = json_decode($array, true);
  676. $gotCalendar = "";
  677. $i = 0;
  678. foreach($array['data'] AS $child) {
  679. $i++;
  680. $seriesName = $child['show_name'];
  681. $episodeID = $child['tvdbid'];
  682. $episodeAirDate = $child['date'];
  683. $downloaded = "green-bg";
  684. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  685. }
  686. if ($i != 0){ return $gotCalendar; }
  687. }
  688. function getSonarrCalendar($array){
  689. $array = json_decode($array, true);
  690. $gotCalendar = "";
  691. $i = 0;
  692. foreach($array AS $child) {
  693. $i++;
  694. $seriesName = $child['series']['title'];
  695. $episodeID = $child['series']['imdbId'];
  696. if(!isset($episodeID)){ $episodeID = ""; }
  697. $episodeName = htmlentities($child['title'], ENT_QUOTES);
  698. if($child['episodeNumber'] == "1"){ $episodePremier = "true"; }else{ $episodePremier = "false"; }
  699. $episodeAirDate = $child['airDateUtc'];
  700. $episodeAirDate = strtotime($episodeAirDate);
  701. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  702. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  703. $downloaded = $child['hasFile'];
  704. 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"; }
  705. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"http://www.imdb.com/title/$episodeID\" }, \n";
  706. }
  707. if ($i != 0){ return $gotCalendar; }
  708. }
  709. function getRadarrCalendar($array){
  710. $array = json_decode($array, true);
  711. $gotCalendar = "";
  712. $i = 0;
  713. foreach($array AS $child) {
  714. if(isset($child['inCinemas'])){
  715. $i++;
  716. $movieName = $child['title'];
  717. $movieID = $child['imdbId'];
  718. if(!isset($movieID)){ $movieID = ""; }
  719. if(isset($child['inCinemas']) && isset($child['physicalRelease'])){
  720. $physicalRelease = $child['physicalRelease'];
  721. $physicalRelease = strtotime($physicalRelease);
  722. $physicalRelease = date("Y-m-d", $physicalRelease);
  723. if (new DateTime() < new DateTime($physicalRelease)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  724. $downloaded = $child['hasFile'];
  725. if($downloaded == "0" && $notReleased == "true"){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg"; }else{ $downloaded = "red-bg"; }
  726. }else{
  727. $physicalRelease = $child['inCinemas'];
  728. $downloaded = "light-blue-bg";
  729. }
  730. $gotCalendar .= "{ title: \"$movieName\", start: \"$physicalRelease\", className: \"$downloaded\", imagetype: \"film\", url: \"http://www.imdb.com/title/$movieID\" }, \n";
  731. }
  732. }
  733. if ($i != 0){ return $gotCalendar; }
  734. }
  735. function nzbgetConnect($url, $port, $username, $password, $list){
  736. $urlCheck = stripos($url, "http");
  737. if ($urlCheck === false) {
  738. $url = "http://" . $url;
  739. }
  740. if($port !== ""){ $url = $url . ":" . $port; }
  741. $address = $url;
  742. $api = file_get_contents("$url/$username:$password/jsonrpc/$list");
  743. $api = json_decode($api, true);
  744. $i = 0;
  745. $gotNZB = "";
  746. foreach ($api['result'] AS $child) {
  747. $i++;
  748. //echo '<pre>' . var_export($child, true) . '</pre>';
  749. $downloadName = htmlentities($child['NZBName'], ENT_QUOTES);
  750. $downloadStatus = $child['Status'];
  751. $downloadCategory = $child['Category'];
  752. if($list == "history"){ $downloadPercent = "100"; $progressBar = ""; }
  753. if($list == "listgroups"){ $downloadPercent = (($child['FileSizeMB'] - $child['RemainingSizeMB']) / $child['FileSizeMB']) * 100; $progressBar = "progress-bar-striped active"; }
  754. if($child['Health'] <= "750"){
  755. $downloadHealth = "danger";
  756. }elseif($child['Health'] <= "900"){
  757. $downloadHealth = "warning";
  758. }elseif($child['Health'] <= "1000"){
  759. $downloadHealth = "success";
  760. }
  761. $gotNZB .= '<tr>
  762. <td>'.$downloadName.'</td>
  763. <td>'.$downloadStatus.'</td>
  764. <td>'.$downloadCategory.'</td>
  765. <td>
  766. <div class="progress">
  767. <div class="progress-bar progress-bar-'.$downloadHealth.' '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  768. <p class="text-center">'.round($downloadPercent).'%</p>
  769. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  770. </div>
  771. </div>
  772. </td>
  773. </tr>';
  774. }
  775. if($i > 0){ return $gotNZB; }
  776. if($i == 0){ echo '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>'; }
  777. }
  778. function sabnzbdConnect($url, $port, $key, $list){
  779. $urlCheck = stripos($url, "http");
  780. if ($urlCheck === false) {
  781. $url = "http://" . $url;
  782. }
  783. if($port !== ""){ $url = $url . ":" . $port; }
  784. $address = $url;
  785. $api = file_get_contents("$url/api?mode=$list&output=json&apikey=$key");
  786. $api = json_decode($api, true);
  787. $i = 0;
  788. $gotNZB = "";
  789. foreach ($api[$list]['slots'] AS $child) {
  790. $i++;
  791. if($list == "queue"){ $downloadName = $child['filename']; $downloadCategory = $child['cat']; $downloadPercent = (($child['mb'] - $child['mbleft']) / $child['mb']) * 100; $progressBar = "progress-bar-striped active"; }
  792. if($list == "history"){ $downloadName = $child['name']; $downloadCategory = $child['category']; $downloadPercent = "100"; $progressBar = ""; }
  793. $downloadStatus = $child['status'];
  794. $gotNZB .= '<tr>
  795. <td>'.$downloadName.'</td>
  796. <td>'.$downloadStatus.'</td>
  797. <td>'.$downloadCategory.'</td>
  798. <td>
  799. <div class="progress">
  800. <div class="progress-bar progress-bar-success '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  801. <p class="text-center">'.round($downloadPercent).'%</p>
  802. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  803. </div>
  804. </div>
  805. </td>
  806. </tr>';
  807. }
  808. if($i > 0){ return $gotNZB; }
  809. if($i == 0){ echo '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>'; }
  810. }
  811. function getHeadphonesCalendar($url, $port, $key, $list){
  812. $urlCheck = stripos($url, "http");
  813. if ($urlCheck === false) {
  814. $url = "http://" . $url;
  815. }
  816. if($port !== ""){ $url = $url . ":" . $port; }
  817. $address = $url;
  818. $api = file_get_contents($address."/api?apikey=".$key."&cmd=$list");
  819. $api = json_decode($api, true);
  820. $i = 0;
  821. $gotCalendar = "";
  822. foreach($api AS $child) {
  823. if($child['Status'] == "Wanted"){
  824. $i++;
  825. $albumName = addslashes($child['AlbumTitle']);
  826. $albumArtist = htmlentities($child['ArtistName'], ENT_QUOTES);
  827. $albumDate = $child['ReleaseDate'];
  828. $albumID = $child['AlbumID'];
  829. $albumDate = strtotime($albumDate);
  830. $albumDate = date("Y-m-d", $albumDate);
  831. $albumStatus = $child['Status'];
  832. if (new DateTime() < new DateTime($albumDate)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  833. if($albumStatus == "Wanted" && $notReleased == "true"){ $albumStatusColor = "indigo-bg"; }elseif($albumStatus == "Downloaded"){ $albumStatusColor = "green-bg"; }else{ $albumStatusColor = "red-bg"; }
  834. $gotCalendar .= "{ title: \"$albumArtist - $albumName\", start: \"$albumDate\", className: \"$albumStatusColor\", imagetype: \"music\", url: \"https://musicbrainz.org/release-group/$albumID\" }, \n";
  835. }
  836. }
  837. if ($i != 0){ return $gotCalendar; }
  838. }
  839. ?>