functions.php 37 KB

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