functions.php 58 KB

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