4
0

functions.php 70 KB

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