functions.php 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810
  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. if (is_array($value)) {
  867. if (isset($value['optgroup'])) {
  868. $output[] = '<optgroup label="'.$key.'">';
  869. foreach($value['optgroup'] as $k => $v) {
  870. $output[] = '<option value="'.$v['value'].'"'.($selected===$v['value']?' selected':'').(isset($v['disabled']) && $v['disabled']?' disabled':'').'>'.$k.'</option>';
  871. }
  872. } else {
  873. $output[] = '<option value="'.$value['value'].'"'.($selected===$value['value']?' selected':'').(isset($value['disabled']) && $value['disabled']?' disabled':'').'>'.$key.'</option>';
  874. }
  875. } else {
  876. $output[] = '<option value="'.$value.'"'.($selected===$value?' selected':'').'>'.$key.'</option>';
  877. }
  878. }
  879. return implode('',$output);
  880. }
  881. // Check if user is allowed to continue
  882. function qualifyUser($type, $errOnFail = false) {
  883. if (!isset($GLOBALS['USER'])) {
  884. require_once("user.php");
  885. $GLOBALS['USER'] = new User('registration_callback');
  886. }
  887. if (is_bool($type)) {
  888. if ($type === true) {
  889. $authorized = ($GLOBALS['USER']->authenticated == true);
  890. } else {
  891. $authorized = true;
  892. }
  893. } elseif (is_string($type)) {
  894. if ($type !== 'false') {
  895. $type = explode('|',$type);
  896. $authorized = ($GLOBALS['USER']->authenticated && in_array($GLOBALS['USER']->role,$type));
  897. } else {
  898. $authorized = true;
  899. }
  900. } else {
  901. debug_out('Invalid Syntax!',1);
  902. }
  903. if (!$authorized && $errOnFail) {
  904. debug_out('Not Authorized' ,1);
  905. } else {
  906. return $authorized;
  907. }
  908. }
  909. // Build an (optionally) tabbed settings page.
  910. function buildSettings($array) {
  911. /*
  912. array(
  913. 'title' => '',
  914. 'id' => '',
  915. 'fields' => array( See buildField() ),
  916. 'tabs' => array(
  917. array(
  918. 'title' => '',
  919. 'id' => '',
  920. 'image' => '',
  921. 'fields' => array( See buildField() ),
  922. ),
  923. ),
  924. );
  925. */
  926. $fieldFunc = function($fieldArr) {
  927. $fields = '<div class="row">';
  928. foreach($fieldArr as $key => $value) {
  929. $isSingle = isset($value['type']);
  930. if ($isSingle) { $value = array($value); }
  931. $tmpField = '';
  932. foreach($value as $k => $v) {
  933. $tmpField .= '<div class="form-group">'.buildField($v).'</div>';
  934. }
  935. $fields .= ($isSingle?$tmpField:'<div class="content-form form-inline">'.$tmpField.'</div>');
  936. }
  937. $fields .= '</div>';
  938. return $fields;
  939. };
  940. $fields = (isset($array['fields'])?$fieldFunc($array['fields']):'');
  941. $tabSelectors = array();
  942. $tabContent = array();
  943. if (isset($array['tabs'])) {
  944. foreach($array['tabs'] as $key => $value) {
  945. $id = (isset($value['id'])?$value['id']:randString(32));
  946. $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>';
  947. $tabContent[$key] = '<div class="tab-pane big-box fade'.($tabContent?'':' active in').'" id="tab-'.$id.'">'.$fieldFunc($value['fields']).'</div>';
  948. }
  949. }
  950. $pageID = (isset($array['id'])?$array['id']:str_replace(array(' ','"',"'"),array('_'),strtolower($array['id'])));
  951. return '
  952. <div class="email-body">
  953. <div class="email-header gray-bg">
  954. <button type="button" class="btn btn-danger btn-sm waves close-button"><i class="fa fa-close"></i></button>
  955. <h1>'.$array['title'].'</h1>
  956. </div>
  957. <div class="email-inner small-box">
  958. <div class="email-inner-section">
  959. <div class="small-box fade in" id="'.$pageID.'_frame">
  960. <div class="row">
  961. <div class="col-lg-12">
  962. <form class="content-form" name="'.$pageID.'" id="'.$pageID.'_form" onsubmit="return false;">
  963. <div style="position: relative; left: 2.5%; width: 95%;">
  964. '.$fields.'
  965. </div>
  966. <div class="tabbable tabs-with-bg" id="'.$pageID.'_tabs">
  967. <ul class="nav nav-tabs apps">
  968. '.implode('', $tabSelectors).'
  969. </ul>
  970. <div class="clearfix"></div>
  971. <div class="tab-content">
  972. '.implode('', $tabContent).'
  973. </div>
  974. </div>
  975. <button type="submit" class="btn waves btn-labeled btn-success btn btn-sm pull-right text-uppercase waves-effect waves-float">
  976. <span class="btn-label"><i class="fa fa-floppy-o"></i></span>Save
  977. </button>
  978. </form>
  979. </div>
  980. </div>
  981. </div>
  982. </div>
  983. </div>
  984. </div>
  985. <script>
  986. $(document).ready(function() {
  987. $(\'#'.$pageID.'_form\').find(\'input, select, textarea\').on(\'change\', function() {
  988. $(this).attr(\'data-changed\', \'true\');
  989. });
  990. $(\'#'.$pageID.'_form\').submit(function () {
  991. var newVals = {};
  992. $(\'#'.$pageID.'_form\').find(\'[data-changed=true]\').each(function() {
  993. if (this.type == \'checkbox\') {
  994. newVals[this.name] = this.checked;
  995. } else {
  996. newVals[this.name] = $(this).val();
  997. }
  998. });
  999. $.post(\'ajax.php?a=update-config\', newVals, function(data) {
  1000. console.log(data);
  1001. parent.notify(data.html, data.icon, data.type, data.length, data.layout, data.effect);
  1002. }, \'json\');
  1003. return false;
  1004. });
  1005. '.(isset($array['onready'])?$array['onready']:'').'
  1006. });
  1007. </script>
  1008. ';
  1009. }
  1010. // Build Settings Fields
  1011. function buildField($params) {
  1012. /*
  1013. array(
  1014. 'type' => '',
  1015. 'placeholder' => '',
  1016. 'label' => '',
  1017. 'labelTranslate' => '',
  1018. 'assist' => '',
  1019. 'name' => '',
  1020. 'pattern' => '',
  1021. 'options' => array( // For SELECT only
  1022. 'Display' => 'value',
  1023. ),
  1024. )
  1025. */
  1026. // Tags
  1027. $tags = array();
  1028. foreach(array('placeholder','style','disabled','readonly','pattern','min','max','required','onkeypress','onchange','onfocus','onleave') as $value) {
  1029. $tags[] = (isset($params[$value])?$value.'="'.$params[$value].'"':'');
  1030. }
  1031. $name = (isset($params['name'])?$params['name']:(isset($params['id'])?$params['id']:''));
  1032. $id = (isset($params['id'])?$params['id']:(isset($params['name'])?$params['name'].'_id':randString(32)));
  1033. $val = (isset($params['value'])?$params['value']:'');
  1034. $class = (isset($params['class'])?' '.$params['class']:'');
  1035. $assist = (isset($params['assist'])?' - i.e. '.$params['assist']:'');
  1036. $label = (isset($params['labelTranslate'])?translate($params['labelTranslate']):(isset($params['label'])?$params['label']:''));
  1037. switch ($params['type']) {
  1038. case 'text':
  1039. case 'number':
  1040. case 'password':
  1041. $field = '
  1042. <input id="'.$id.'" name="'.$name.'" type="'.$params['type'].'" class="form-control material input-sm'.$class.'" '.implode(' ',$tags).' autocorrect="off" autocapitalize="off" value="'.$val.'">
  1043. ';
  1044. break;
  1045. case 'select':
  1046. case 'dropdown':
  1047. $field = '<select id="'.$id.'" name="'.$name.'" class="form-control material input-sm" '.implode(' ',$tags).'>
  1048. '.resolveSelectOptions($params['options'], $val).'
  1049. </select>';
  1050. break;
  1051. case 'check':
  1052. case 'checkbox':
  1053. case 'toggle':
  1054. $checked = ((is_bool($val) && $val) || trim($val) === 'true'?' checked':'');
  1055. return '
  1056. <input id="'.$id.'" name="'.$name.'" type="checkbox" class="switcher switcher-success'.$class.'" '.implode(' ',$tags).' value="'.$val.'"'.$checked.'><label for="'.$id.'"></label>'.$label.'
  1057. ';
  1058. case 'date':
  1059. $field = '
  1060. ';
  1061. break;
  1062. case 'hidden':
  1063. return '<input id="'.$id.'" name="'.$name.'" type="hidden" class="'.$class.'" '.implode(' ',$tags).' value="'.$val.'">';
  1064. case 'header':
  1065. return '<h3 class="'.$class.'" '.implode(' ',$tags).'>'.$val.'</h3>';
  1066. case 'button':
  1067. 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>';
  1068. default:
  1069. $field = '';
  1070. }
  1071. $labelOut = '<p class="help-text">'.$label.$assist.'</p>';
  1072. return $field.$labelOut;
  1073. }
  1074. // Timezone array
  1075. function timezoneOptions() {
  1076. $output = array();
  1077. $timezones = array();
  1078. $regions = array(
  1079. 'Africa' => DateTimeZone::AFRICA,
  1080. 'America' => DateTimeZone::AMERICA,
  1081. 'Antarctica' => DateTimeZone::ANTARCTICA,
  1082. 'Arctic' => DateTimeZone::ARCTIC,
  1083. 'Asia' => DateTimeZone::ASIA,
  1084. 'Atlantic' => DateTimeZone::ATLANTIC,
  1085. 'Australia' => DateTimeZone::AUSTRALIA,
  1086. 'Europe' => DateTimeZone::EUROPE,
  1087. 'Indian' => DateTimeZone::INDIAN,
  1088. 'Pacific' => DateTimeZone::PACIFIC
  1089. );
  1090. foreach ($regions as $name => $mask) {
  1091. $zones = DateTimeZone::listIdentifiers($mask);
  1092. foreach($zones as $timezone) {
  1093. $time = new DateTime(NULL, new DateTimeZone($timezone));
  1094. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  1095. $output[$name]['optgroup'][substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm]['value'] = $timezone;
  1096. }
  1097. }
  1098. return $output;
  1099. }
  1100. // ==============
  1101. function clean($strin) {
  1102. $strout = null;
  1103. for ($i = 0; $i < strlen($strin); $i++) {
  1104. $ord = ord($strin[$i]);
  1105. if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
  1106. $strout .= "&amp;#{$ord};";
  1107. }
  1108. else {
  1109. switch ($strin[$i]) {
  1110. case '<':
  1111. $strout .= '&lt;';
  1112. break;
  1113. case '>':
  1114. $strout .= '&gt;';
  1115. break;
  1116. case '&':
  1117. $strout .= '&amp;';
  1118. break;
  1119. case '"':
  1120. $strout .= '&quot;';
  1121. break;
  1122. default:
  1123. $strout .= $strin[$i];
  1124. }
  1125. }
  1126. }
  1127. return $strout;
  1128. }
  1129. function registration_callback($username, $email, $userdir){
  1130. global $data;
  1131. $data = array($username, $email, $userdir);
  1132. }
  1133. function printArray($arrayName){
  1134. $messageCount = count($arrayName);
  1135. $i = 0;
  1136. foreach ( $arrayName as $item ) :
  1137. $i++;
  1138. if($i < $messageCount) :
  1139. echo "<small class='text-uppercase'>" . $item . "</small> & ";
  1140. elseif($i = $messageCount) :
  1141. echo "<small class='text-uppercase'>" . $item . "</small>";
  1142. endif;
  1143. endforeach;
  1144. }
  1145. function write_ini_file($content, $path) {
  1146. if (!$handle = fopen($path, 'w')) {
  1147. return false;
  1148. }
  1149. $success = fwrite($handle, trim($content));
  1150. fclose($handle);
  1151. return $success;
  1152. }
  1153. function gotTimezone(){
  1154. $regions = array(
  1155. 'Africa' => DateTimeZone::AFRICA,
  1156. 'America' => DateTimeZone::AMERICA,
  1157. 'Antarctica' => DateTimeZone::ANTARCTICA,
  1158. 'Arctic' => DateTimeZone::ARCTIC,
  1159. 'Asia' => DateTimeZone::ASIA,
  1160. 'Atlantic' => DateTimeZone::ATLANTIC,
  1161. 'Australia' => DateTimeZone::AUSTRALIA,
  1162. 'Europe' => DateTimeZone::EUROPE,
  1163. 'Indian' => DateTimeZone::INDIAN,
  1164. 'Pacific' => DateTimeZone::PACIFIC
  1165. );
  1166. $timezones = array();
  1167. foreach ($regions as $name => $mask) {
  1168. $zones = DateTimeZone::listIdentifiers($mask);
  1169. foreach($zones as $timezone) {
  1170. $time = new DateTime(NULL, new DateTimeZone($timezone));
  1171. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  1172. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  1173. }
  1174. }
  1175. print '<select name="timezone" id="timezone" class="form-control material input-sm" required>';
  1176. foreach($timezones as $region => $list) {
  1177. print '<optgroup label="' . $region . '">' . "\n";
  1178. foreach($list as $timezone => $name) {
  1179. if($timezone == TIMEZONE) : $selected = " selected"; else : $selected = ""; endif;
  1180. print '<option value="' . $timezone . '"' . $selected . '>' . $name . '</option>' . "\n";
  1181. }
  1182. print '</optgroup>' . "\n";
  1183. }
  1184. print '</select>';
  1185. }
  1186. function getTimezone(){
  1187. $regions = array(
  1188. 'Africa' => DateTimeZone::AFRICA,
  1189. 'America' => DateTimeZone::AMERICA,
  1190. 'Antarctica' => DateTimeZone::ANTARCTICA,
  1191. 'Arctic' => DateTimeZone::ARCTIC,
  1192. 'Asia' => DateTimeZone::ASIA,
  1193. 'Atlantic' => DateTimeZone::ATLANTIC,
  1194. 'Australia' => DateTimeZone::AUSTRALIA,
  1195. 'Europe' => DateTimeZone::EUROPE,
  1196. 'Indian' => DateTimeZone::INDIAN,
  1197. 'Pacific' => DateTimeZone::PACIFIC
  1198. );
  1199. $timezones = array();
  1200. foreach ($regions as $name => $mask) {
  1201. $zones = DateTimeZone::listIdentifiers($mask);
  1202. foreach($zones as $timezone) {
  1203. $time = new DateTime(NULL, new DateTimeZone($timezone));
  1204. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  1205. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  1206. }
  1207. }
  1208. print '<select name="timezone" id="timezone" class="form-control material" required>';
  1209. foreach($timezones as $region => $list) {
  1210. print '<optgroup label="' . $region . '">' . "\n";
  1211. foreach($list as $timezone => $name) {
  1212. print '<option value="' . $timezone . '">' . $name . '</option>' . "\n";
  1213. }
  1214. print '</optgroup>' . "\n";
  1215. }
  1216. print '</select>';
  1217. }
  1218. function explosion($string, $position){
  1219. $getWord = explode("|", $string);
  1220. return $getWord[$position];
  1221. }
  1222. function getServerPath() {
  1223. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  1224. $protocol = "https://";
  1225. } else {
  1226. $protocol = "http://";
  1227. }
  1228. return $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
  1229. }
  1230. function get_browser_name() {
  1231. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  1232. if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
  1233. elseif (strpos($user_agent, 'Edge')) return 'Edge';
  1234. elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
  1235. elseif (strpos($user_agent, 'Safari')) return 'Safari';
  1236. elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
  1237. elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
  1238. return 'Other';
  1239. }
  1240. function getSickrageCalendarWanted($array){
  1241. $array = json_decode($array, true);
  1242. $gotCalendar = "";
  1243. $i = 0;
  1244. foreach($array['data']['missed'] AS $child) {
  1245. $i++;
  1246. $seriesName = $child['show_name'];
  1247. $episodeID = $child['tvdbid'];
  1248. $episodeAirDate = $child['airdate'];
  1249. $episodeAirDateTime = explode(" ",$child['airs']);
  1250. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1251. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1252. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1253. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1254. $downloaded = "0";
  1255. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  1256. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1257. }
  1258. foreach($array['data']['today'] AS $child) {
  1259. $i++;
  1260. $seriesName = $child['show_name'];
  1261. $episodeID = $child['tvdbid'];
  1262. $episodeAirDate = $child['airdate'];
  1263. $episodeAirDateTime = explode(" ",$child['airs']);
  1264. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1265. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1266. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1267. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1268. $downloaded = "0";
  1269. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  1270. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1271. }
  1272. foreach($array['data']['soon'] AS $child) {
  1273. $i++;
  1274. $seriesName = $child['show_name'];
  1275. $episodeID = $child['tvdbid'];
  1276. $episodeAirDate = $child['airdate'];
  1277. $episodeAirDateTime = explode(" ",$child['airs']);
  1278. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1279. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1280. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1281. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1282. $downloaded = "0";
  1283. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  1284. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1285. }
  1286. foreach($array['data']['later'] 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. if ($i != 0){ return $gotCalendar; }
  1301. }
  1302. function getSickrageCalendarHistory($array){
  1303. $array = json_decode($array, true);
  1304. $gotCalendar = "";
  1305. $i = 0;
  1306. foreach($array['data'] AS $child) {
  1307. $i++;
  1308. $seriesName = $child['show_name'];
  1309. $episodeID = $child['tvdbid'];
  1310. $episodeAirDate = $child['date'];
  1311. $downloaded = "green-bg";
  1312. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1313. }
  1314. if ($i != 0){ return $gotCalendar; }
  1315. }
  1316. function getSonarrCalendar($array){
  1317. $array = json_decode($array, true);
  1318. $gotCalendar = "";
  1319. $i = 0;
  1320. foreach($array AS $child) {
  1321. $i++;
  1322. $seriesName = $child['series']['title'];
  1323. $episodeID = $child['series']['tvdbId'];
  1324. if(!isset($episodeID)){ $episodeID = ""; }
  1325. $episodeName = htmlentities($child['title'], ENT_QUOTES);
  1326. if($child['episodeNumber'] == "1"){ $episodePremier = "true"; }else{ $episodePremier = "false"; }
  1327. $episodeAirDate = $child['airDateUtc'];
  1328. $episodeAirDate = strtotime($episodeAirDate);
  1329. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1330. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1331. $downloaded = $child['hasFile'];
  1332. 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"; }
  1333. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1334. }
  1335. if ($i != 0){ return $gotCalendar; }
  1336. }
  1337. function getRadarrCalendar($array){
  1338. $array = json_decode($array, true);
  1339. $gotCalendar = "";
  1340. $i = 0;
  1341. foreach($array AS $child) {
  1342. if(isset($child['inCinemas'])){
  1343. $i++;
  1344. $movieName = $child['title'];
  1345. $movieID = $child['tmdbId'];
  1346. if(!isset($movieID)){ $movieID = ""; }
  1347. if(isset($child['inCinemas']) && isset($child['physicalRelease'])){
  1348. $physicalRelease = $child['physicalRelease'];
  1349. $physicalRelease = strtotime($physicalRelease);
  1350. $physicalRelease = date("Y-m-d", $physicalRelease);
  1351. if (new DateTime() < new DateTime($physicalRelease)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  1352. $downloaded = $child['hasFile'];
  1353. if($downloaded == "0" && $notReleased == "true"){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg"; }else{ $downloaded = "red-bg"; }
  1354. }else{
  1355. $physicalRelease = $child['inCinemas'];
  1356. $downloaded = "light-blue-bg";
  1357. }
  1358. $gotCalendar .= "{ title: \"$movieName\", start: \"$physicalRelease\", className: \"$downloaded\", imagetype: \"film\", url: \"https://www.themoviedb.org/movie/$movieID\" }, \n";
  1359. }
  1360. }
  1361. if ($i != 0){ return $gotCalendar; }
  1362. }
  1363. function nzbgetConnect($url, $username, $password, $list){
  1364. $url = qualifyURL(NZBGETURL);
  1365. $api = file_get_contents("$url/$username:$password/jsonrpc/$list");
  1366. $api = json_decode($api, true);
  1367. $i = 0;
  1368. $gotNZB = "";
  1369. foreach ($api['result'] AS $child) {
  1370. $i++;
  1371. //echo '<pre>' . var_export($child, true) . '</pre>';
  1372. $downloadName = htmlentities($child['NZBName'], ENT_QUOTES);
  1373. $downloadStatus = $child['Status'];
  1374. $downloadCategory = $child['Category'];
  1375. if($list == "history"){ $downloadPercent = "100"; $progressBar = ""; }
  1376. if($list == "listgroups"){ $downloadPercent = (($child['FileSizeMB'] - $child['RemainingSizeMB']) / $child['FileSizeMB']) * 100; $progressBar = "progress-bar-striped active"; }
  1377. if($child['Health'] <= "750"){
  1378. $downloadHealth = "danger";
  1379. }elseif($child['Health'] <= "900"){
  1380. $downloadHealth = "warning";
  1381. }elseif($child['Health'] <= "1000"){
  1382. $downloadHealth = "success";
  1383. }
  1384. $gotNZB .= '<tr>
  1385. <td>'.$downloadName.'</td>
  1386. <td>'.$downloadStatus.'</td>
  1387. <td>'.$downloadCategory.'</td>
  1388. <td>
  1389. <div class="progress">
  1390. <div class="progress-bar progress-bar-'.$downloadHealth.' '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  1391. <p class="text-center">'.round($downloadPercent).'%</p>
  1392. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  1393. </div>
  1394. </div>
  1395. </td>
  1396. </tr>';
  1397. }
  1398. if($i > 0){ return $gotNZB; }
  1399. if($i == 0){ echo '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>'; }
  1400. }
  1401. function sabnzbdConnect($url, $key, $list){
  1402. $url = qualifyURL(SABNZBDURL);
  1403. $api = file_get_contents("$url/api?mode=$list&output=json&apikey=$key");
  1404. $api = json_decode($api, true);
  1405. $i = 0;
  1406. $gotNZB = "";
  1407. foreach ($api[$list]['slots'] AS $child) {
  1408. $i++;
  1409. if($list == "queue"){ $downloadName = $child['filename']; $downloadCategory = $child['cat']; $downloadPercent = (($child['mb'] - $child['mbleft']) / $child['mb']) * 100; $progressBar = "progress-bar-striped active"; }
  1410. if($list == "history"){ $downloadName = $child['name']; $downloadCategory = $child['category']; $downloadPercent = "100"; $progressBar = ""; }
  1411. $downloadStatus = $child['status'];
  1412. $gotNZB .= '<tr>
  1413. <td>'.$downloadName.'</td>
  1414. <td>'.$downloadStatus.'</td>
  1415. <td>'.$downloadCategory.'</td>
  1416. <td>
  1417. <div class="progress">
  1418. <div class="progress-bar progress-bar-success '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  1419. <p class="text-center">'.round($downloadPercent).'%</p>
  1420. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  1421. </div>
  1422. </div>
  1423. </td>
  1424. </tr>';
  1425. }
  1426. if($i > 0){ return $gotNZB; }
  1427. if($i == 0){ echo '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>'; }
  1428. }
  1429. function getHeadphonesCalendar($url, $key, $list){
  1430. $url = qualifyURL(HEADPHONESURL);
  1431. $api = file_get_contents($url."/api?apikey=".$key."&cmd=$list");
  1432. $api = json_decode($api, true);
  1433. $i = 0;
  1434. $gotCalendar = "";
  1435. foreach($api AS $child) {
  1436. if($child['Status'] == "Wanted"){
  1437. $i++;
  1438. $albumName = addslashes($child['AlbumTitle']);
  1439. $albumArtist = htmlentities($child['ArtistName'], ENT_QUOTES);
  1440. $albumDate = $child['ReleaseDate'];
  1441. $albumID = $child['AlbumID'];
  1442. $albumDate = strtotime($albumDate);
  1443. $albumDate = date("Y-m-d", $albumDate);
  1444. $albumStatus = $child['Status'];
  1445. if (new DateTime() < new DateTime($albumDate)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  1446. if($albumStatus == "Wanted" && $notReleased == "true"){ $albumStatusColor = "indigo-bg"; }elseif($albumStatus == "Downloaded"){ $albumStatusColor = "green-bg"; }else{ $albumStatusColor = "red-bg"; }
  1447. $gotCalendar .= "{ title: \"$albumArtist - $albumName\", start: \"$albumDate\", className: \"$albumStatusColor\", imagetype: \"music\", url: \"https://musicbrainz.org/release-group/$albumID\" }, \n";
  1448. }
  1449. }
  1450. if ($i != 0){ return $gotCalendar; }
  1451. }
  1452. ?>