functions.php 54 KB

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