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