functions.php 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241
  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'];
  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, (isset($urlDigest['port'])?':'.$urlDigest['port']: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. // Currently Logged In User
  536. $username = false;
  537. if (isset($GLOBALS['USER'])) {
  538. $username = strtolower($GLOBALS['USER']->username);
  539. }
  540. // Resolve Types
  541. switch ($type) {
  542. case 'movie':
  543. $embyTypeQuery = 'IncludeItemTypes=Movie&';
  544. $header = translate('MOVIES');
  545. break;
  546. case 'season':
  547. $embyTypeQuery = 'IncludeItemTypes=Episode&';
  548. $header = translate('TV_SHOWS');
  549. break;
  550. case 'album':
  551. $embyTypeQuery = 'IncludeItemTypes=MusicAlbum&';
  552. $header = translate('MUSIC');
  553. break;
  554. default:
  555. $embyTypeQuery = '';
  556. $header = translate('RECENT_CONTENT');
  557. }
  558. // Get A User
  559. $userIds = json_decode(file_get_contents($address.'/Users?api_key='.EMBYTOKEN),true);
  560. $showPlayed = true;
  561. foreach ($userIds as $value) { // Scan for admin user
  562. if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
  563. $userId = $value['Id'];
  564. }
  565. if ($username && strtolower($value['Name']) == $username) {
  566. $userId = $value['Id'];
  567. $showPlayed = false;
  568. break;
  569. }
  570. }
  571. // Get the latest Items
  572. $latest = json_decode(file_get_contents($address.'/Users/'.$userId.'/Items/Latest?'.$embyTypeQuery.'EnableImages=false&api_key='.EMBYTOKEN.($showPlayed?'':'&IsPlayed=false')),true);
  573. // For Each Item In Category
  574. $items = array();
  575. foreach ($latest as $k => $v) {
  576. $items[] = resolveEmbyItem($address, EMBYTOKEN, $v);
  577. }
  578. return outputCarousel($header, $size, $type.'-emby', $items);
  579. }
  580. // Get Recent Content From Plex
  581. function getPlexRecent($type, $size){
  582. $address = qualifyURL(PLEXURL);
  583. // Resolve Types
  584. switch ($type) {
  585. case 'movie':
  586. $header = translate('MOVIES');
  587. break;
  588. case 'season':
  589. $header = translate('TV_SHOWS');
  590. break;
  591. case 'album':
  592. $header = translate('MUSIC');
  593. break;
  594. default:
  595. $header = translate('RECENT_CONTENT');
  596. }
  597. // Perform Requests
  598. $api = file_get_contents($address."/library/recentlyAdded?X-Plex-Token=".PLEXTOKEN);
  599. $api = simplexml_load_string($api);
  600. $getServer = simplexml_load_string(file_get_contents($address."/?X-Plex-Token=".PLEXTOKEN));
  601. // Identify the local machine
  602. $gotServer = $getServer['machineIdentifier'];
  603. $items = array();
  604. foreach($api AS $child) {
  605. if($child['type'] == $type){
  606. $items[] = resolvePlexItem($gotServer, PLEXTOKEN, $child);
  607. }
  608. }
  609. return outputCarousel($header, $size, $type.'-plex', $items);
  610. }
  611. // Get Image From Emby
  612. function getEmbyImage() {
  613. $embyAddress = qualifyURL(EMBYURL);
  614. $itemId = $_GET['img'];
  615. $imgParams = array();
  616. if (isset($_GET['height'])) { $imgParams['height'] = 'maxHeight='.$_GET['height']; }
  617. if (isset($_GET['width'])) { $imgParams['width'] = 'maxWidth='.$_GET['width']; }
  618. if(isset($itemId)) {
  619. $image_src = $embyAddress . '/Items/'.$itemId.'/Images/Primary?'.implode('&', $imgParams);
  620. header('Content-type: image/jpeg');
  621. readfile($image_src);
  622. die();
  623. } else {
  624. debug_out('Invalid Request',1);
  625. }
  626. }
  627. // Get Image From Plex
  628. function getPlexImage() {
  629. $plexAddress = qualifyURL(PLEXURL);
  630. $image_url = $_GET['img'];
  631. $image_height = $_GET['height'];
  632. $image_width = $_GET['width'];
  633. if(isset($image_url) && isset($image_height) && isset($image_width)) {
  634. $image_src = $plexAddress . '/photo/:/transcode?height='.$image_height.'&width='.$image_width.'&upscale=1&url=' . $image_url . '&X-Plex-Token=' . PLEXTOKEN;
  635. header('Content-type: image/jpeg');
  636. readfile($image_src);
  637. die();
  638. } else {
  639. echo "Invalid Plex Request";
  640. }
  641. }
  642. // Simplier access to class
  643. function translate($string) {
  644. if (isset($GLOBALS['language'])) {
  645. return $GLOBALS['language']->translate($string);
  646. } else {
  647. return '!Translations Not Loaded!';
  648. }
  649. }
  650. // Generate Random string
  651. function randString($length = 10, $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
  652. $tmp = '';
  653. for ($i = 0; $i < $length; $i++) {
  654. $tmp .= substr(str_shuffle($chars), 0, 1);
  655. }
  656. return $tmp;
  657. }
  658. // Create config file in the return syntax
  659. function createConfig($array, $path = 'config/config.php', $nest = 0) {
  660. // Define Initial Value
  661. $output = array();
  662. // Sort Items
  663. ksort($array);
  664. // Unset the current version
  665. unset($array['CONFIG_VERSION']);
  666. // Process Settings
  667. foreach ($array as $k => $v) {
  668. $allowCommit = true;
  669. switch (gettype($v)) {
  670. case 'boolean':
  671. $item = ($v?'true':'false');
  672. break;
  673. case 'integer':
  674. case 'double':
  675. case 'integer':
  676. case 'NULL':
  677. $item = $v;
  678. break;
  679. case 'string':
  680. $item = "'".str_replace(array('\\',"'"),array('\\\\',"\'"),$v)."'";
  681. break;
  682. case 'array':
  683. $item = createConfig($v, false, $nest+1);
  684. break;
  685. default:
  686. $allowCommit = false;
  687. }
  688. if($allowCommit) {
  689. $output[] = str_repeat("\t",$nest+1)."'$k' => $item";
  690. }
  691. }
  692. if (!$nest && !isset($array['CONFIG_VERSION'])) {
  693. // Inject Current Version
  694. $output[] = "\t'CONFIG_VERSION' => '".INSTALLEDVERSION."'";
  695. }
  696. // Build output
  697. $output = (!$nest?"<?php\nreturn ":'')."array(\n".implode(",\n",$output)."\n".str_repeat("\t",$nest).')'.(!$nest?';':'');
  698. if (!$nest && $path) {
  699. $pathDigest = pathinfo($path);
  700. @mkdir($pathDigest['dirname'], 0770, true);
  701. if (file_exists($path)) {
  702. rename($path, $pathDigest['dirname'].'/'.$pathDigest['filename'].'.bak.php');
  703. }
  704. $file = fopen($path, 'w');
  705. fwrite($file, $output);
  706. fclose($file);
  707. if (file_exists($path)) {
  708. return true;
  709. }
  710. return false;
  711. } else {
  712. return $output;
  713. }
  714. }
  715. // Load a config file written in the return syntax
  716. function loadConfig($path = 'config/config.php') {
  717. // Adapted from http://stackoverflow.com/a/14173339/6810513
  718. if (!is_file($path)) {
  719. return null;
  720. } else {
  721. return (array) call_user_func(function() use($path) {
  722. return include($path);
  723. });
  724. }
  725. }
  726. // Commit new values to the configuration
  727. function updateConfig($new, $current = false) {
  728. // Get config if not supplied
  729. if (!$current) {
  730. $current = loadConfig();
  731. }
  732. // Inject Parts
  733. foreach ($new as $k => $v) {
  734. $current[$k] = $v;
  735. }
  736. // Return Create
  737. return createConfig($current);
  738. }
  739. // Inject Defaults As Needed
  740. function fillDefaultConfig($array, $path = 'config/configDefaults.php') {
  741. if (is_string($path)) {
  742. $loadedDefaults = loadConfig($path);
  743. } else {
  744. $loadedDefaults = $path;
  745. }
  746. return (is_array($loadedDefaults) ? fillDefaultConfig_recurse($array, $loadedDefaults) : false);
  747. }
  748. // support function for fillDefaultConfig()
  749. function fillDefaultConfig_recurse($current, $defaults) {
  750. foreach($defaults as $k => $v) {
  751. if (!isset($current[$k])) {
  752. $current[$k] = $v;
  753. } else if (is_array($current[$k]) && is_array($v)) {
  754. $current[$k] = fillDefaultConfig_recurse($current[$k], $v);
  755. }
  756. }
  757. return $current;
  758. };
  759. // Define Scalar Variables (nest non-secular with underscores)
  760. function defineConfig($array, $anyCase = true, $nest_prefix = false) {
  761. foreach($array as $k => $v) {
  762. if (is_scalar($v) && !defined($nest_prefix.$k)) {
  763. define($nest_prefix.$k, $v, $anyCase);
  764. } else if (is_array($v)) {
  765. defineConfig($v, $anyCase, $nest_prefix.$k.'_');
  766. }
  767. }
  768. }
  769. // This function exists only because I am lazy
  770. function configLazy($path = 'config/config.php') {
  771. // Load config or default
  772. if (file_exists($path)) {
  773. $config = fillDefaultConfig(loadConfig($path));
  774. } else {
  775. $config = loadConfig('config/configDefaults.php');
  776. }
  777. if (is_array($config)) {
  778. defineConfig($config);
  779. }
  780. return $config;
  781. }
  782. // Qualify URL
  783. function qualifyURL($url) {
  784. // Get Digest
  785. $digest = parse_url($url);
  786. // http/https
  787. if (!isset($digest['scheme'])) {
  788. if (isset($digest['port']) && in_array($digest['port'], array(80,8080,8096,32400,7878,8989,8182,8081,6789))) {
  789. $scheme = 'http';
  790. } else {
  791. $scheme = 'https';
  792. }
  793. } else {
  794. $scheme = $digest['scheme'];
  795. }
  796. // Host
  797. $host = (isset($digest['host'])?$digest['host']:'');
  798. // Port
  799. $port = (isset($digest['port'])?':'.$digest['port']:'');
  800. // Path
  801. $path = (isset($digest['path'])?$digest['path']:'');
  802. // Output
  803. return $scheme.'://'.$host.$port.$path;
  804. }
  805. // Function to be called at top of each to allow upgrading environment as the spec changes
  806. function upgradeCheck() {
  807. // Upgrade to 1.31
  808. if (file_exists('homepageSettings.ini.php')) {
  809. $databaseConfig = parse_ini_file('databaseLocation.ini.php', true);
  810. $homepageConfig = parse_ini_file('homepageSettings.ini.php', true);
  811. $databaseConfig = array_merge($databaseConfig, $homepageConfig);
  812. $databaseData = '; <?php die("Access denied"); ?>' . "\r\n";
  813. foreach($databaseConfig as $k => $v) {
  814. if(substr($v, -1) == "/") : $v = rtrim($v, "/"); endif;
  815. $databaseData .= $k . " = \"" . $v . "\"\r\n";
  816. }
  817. write_ini_file($databaseData, 'databaseLocation.ini.php');
  818. unlink('homepageSettings.ini.php');
  819. unset($databaseData);
  820. unset($homepageConfig);
  821. }
  822. // Upgrade to 1.32
  823. if (file_exists('databaseLocation.ini.php')) {
  824. // Load Existing
  825. $config = parse_ini_file('databaseLocation.ini.php', true);
  826. // Refactor
  827. $config['database_Location'] = str_replace('//','/',$config['databaseLocation'].'/');
  828. $config['user_home'] = $config['database_Location'].'users/';
  829. unset($config['databaseLocation']);
  830. // Turn Off Emby And Plex Recent
  831. $config["embyURL"] = $config["embyURL"].(!empty($config["embyPort"])?':'.$config["embyPort"]:'');
  832. unset($config["embyPort"]);
  833. $config["plexURL"] = $config["plexURL"].(!empty($config["plexPort"])?':'.$config["plexPort"]:'');
  834. unset($config["plexPort"]);
  835. $config["nzbgetURL"] = $config["nzbgetURL"].(!empty($config["nzbgetPort"])?':'.$config["nzbgetPort"]:'');
  836. unset($config["nzbgetPort"]);
  837. $config["sabnzbdURL"] = $config["sabnzbdURL"].(!empty($config["sabnzbdPort"])?':'.$config["sabnzbdPort"]:'');
  838. unset($config["sabnzbdPort"]);
  839. $config["headphonesURL"] = $config["headphonesURL"].(!empty($config["headphonesPort"])?':'.$config["headphonesPort"]:'');
  840. unset($config["headphonesPort"]);
  841. // Write config file
  842. $config['CONFIG_VERSION'] = '1.32';
  843. $createConfigSuccess = createConfig($config);
  844. // Create new config
  845. if ($createConfigSuccess) {
  846. if (file_exists('config/config.php')) {
  847. // Remove Old ini file
  848. unlink('databaseLocation.ini.php');
  849. } else {
  850. debug_out('Something is not right here!');
  851. }
  852. } else {
  853. debug_out('Couldn\'t create updated configuration.' ,1);
  854. }
  855. }
  856. // Upgrade to 1.33
  857. $config = loadConfig();
  858. if (isset($config['database_Location']) && (!isset($config['CONFIG_VERSION']) || $config['CONFIG_VERSION'] < '1.33')) {
  859. // Fix User Directory
  860. $config['user_home'] = $config['database_Location'].'users/';
  861. unset($config['USER_HOME']);
  862. // Backend auth merge
  863. if (isset($config['authBackendPort']) && !isset(parse_url($config['authBackendHost'])['port'])) {
  864. $config['authBackendHost'] .= ':'.$config['authBackendPort'];
  865. }
  866. unset($config['authBackendPort']);
  867. // If auth is being used move it to embyURL as that is now used in auth functions
  868. 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')))) {
  869. $config['embyURL'] = $config['authBackendHost'];
  870. }
  871. // Upgrade database to latest version
  872. updateSQLiteDB($config['database_Location']);
  873. // Update Version and Commit
  874. $config['CONFIG_VERSION'] = '1.33';
  875. $createConfigSuccess = createConfig($config);
  876. $effectiveVersion = $config['CONFIG_VERSION'];
  877. unset($config);
  878. }
  879. return true;
  880. }
  881. // Check if all software dependancies are met
  882. function dependCheck() {
  883. return true;
  884. }
  885. // Process file uploads
  886. function uploadFiles($path, $ext_mask = null) {
  887. if (isset($_FILES) && count($_FILES)) {
  888. require_once('class.uploader.php');
  889. $uploader = new Uploader();
  890. $data = $uploader->upload($_FILES['files'], array(
  891. 'limit' => 10,
  892. 'maxSize' => 10,
  893. 'extensions' => $ext_mask,
  894. 'required' => false,
  895. 'uploadDir' => str_replace('//','/',$path.'/'),
  896. 'title' => array('name'),
  897. 'removeFiles' => true,
  898. 'replace' => true,
  899. ));
  900. if($data['isComplete']){
  901. $files = $data['data'];
  902. echo json_encode($files['metas'][0]['name']);
  903. }
  904. if($data['hasErrors']){
  905. $errors = $data['errors'];
  906. echo json_encode($errors);
  907. }
  908. } else {
  909. echo json_encode('No files submitted!');
  910. }
  911. }
  912. // Remove file
  913. function removeFiles($path) {
  914. if(is_file($path)) {
  915. unlink($path);
  916. } else {
  917. echo json_encode('No file specified for removal!');
  918. }
  919. }
  920. // Lazy select options
  921. function resolveSelectOptions($array, $selected = '', $multi = false) {
  922. $output = array();
  923. $selectedArr = ($multi?explode('|', $selected):array());
  924. foreach ($array as $key => $value) {
  925. if (is_array($value)) {
  926. if (isset($value['optgroup'])) {
  927. $output[] = '<optgroup label="'.$key.'">';
  928. foreach($value['optgroup'] as $k => $v) {
  929. $output[] = '<option value="'.$v['value'].'"'.($selected===$v['value']||in_array($v['value'],$selectedArr)?' selected':'').(isset($v['disabled']) && $v['disabled']?' disabled':'').'>'.$k.'</option>';
  930. }
  931. } else {
  932. $output[] = '<option value="'.$value['value'].'"'.($selected===$value['value']||in_array($value['value'],$selectedArr)?' selected':'').(isset($value['disabled']) && $value['disabled']?' disabled':'').'>'.$key.'</option>';
  933. }
  934. } else {
  935. $output[] = '<option value="'.$value.'"'.($selected===$value||in_array($value,$selectedArr)?' selected':'').'>'.$key.'</option>';
  936. }
  937. }
  938. return implode('',$output);
  939. }
  940. // Check if user is allowed to continue
  941. function qualifyUser($type, $errOnFail = false) {
  942. if (!isset($GLOBALS['USER'])) {
  943. require_once("user.php");
  944. $GLOBALS['USER'] = new User('registration_callback');
  945. }
  946. if (is_bool($type)) {
  947. if ($type === true) {
  948. $authorized = ($GLOBALS['USER']->authenticated == true);
  949. } else {
  950. $authorized = true;
  951. }
  952. } elseif (is_string($type) || is_array($type)) {
  953. if ($type !== 'false') {
  954. if (!is_array($type)) {
  955. $type = explode('|',$type);
  956. }
  957. $authorized = ($GLOBALS['USER']->authenticated && in_array($GLOBALS['USER']->role,$type));
  958. } else {
  959. $authorized = true;
  960. }
  961. } else {
  962. debug_out('Invalid Syntax!',1);
  963. }
  964. if (!$authorized && $errOnFail) {
  965. if ($GLOBALS['USER']->authenticated) {
  966. header('Location: error.php?error=401');
  967. echo '<script>window.location.href = \''.dirname($_SERVER['SCRIPT_NAME']).'/error.php?error=401\'</script>';
  968. } else {
  969. header('Location: error.php?error=999');
  970. echo '<script>window.location.href = \''.dirname($_SERVER['SCRIPT_NAME']).'/error.php?error=999\'</script>';
  971. }
  972. debug_out('Not Authorized' ,1);
  973. } else {
  974. return $authorized;
  975. }
  976. }
  977. // Build an (optionally) tabbed settings page.
  978. function buildSettings($array) {
  979. /*
  980. array(
  981. 'title' => '',
  982. 'id' => '',
  983. 'fields' => array( See buildField() ),
  984. 'tabs' => array(
  985. array(
  986. 'title' => '',
  987. 'id' => '',
  988. 'image' => '',
  989. 'fields' => array( See buildField() ),
  990. ),
  991. ),
  992. );
  993. */
  994. $fieldFunc = function($fieldArr) {
  995. $fields = '<div class="row">';
  996. foreach($fieldArr as $key => $value) {
  997. $isSingle = isset($value['type']);
  998. if ($isSingle) { $value = array($value); }
  999. $tmpField = '';
  1000. $sizeLg = max(floor(12/count($value)),2);
  1001. $sizeMd = max(floor(($isSingle?12:6)/count($value)),3);
  1002. foreach($value as $k => $v) {
  1003. $tmpField .= buildField($v, 12, $sizeMd, $sizeLg);
  1004. }
  1005. $fields .= ($isSingle?$tmpField:'<div class="row col-sm-12 content-form">'.$tmpField.'</div>');
  1006. }
  1007. $fields .= '</div>';
  1008. return $fields;
  1009. };
  1010. $fields = (isset($array['fields'])?$fieldFunc($array['fields']):'');
  1011. $tabSelectors = array();
  1012. $tabContent = array();
  1013. if (isset($array['tabs'])) {
  1014. foreach($array['tabs'] as $key => $value) {
  1015. $id = (isset($value['id'])?$value['id']:randString(32));
  1016. $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>';
  1017. $tabContent[$key] = '<div class="tab-pane big-box fade'.($tabContent?'':' active in').'" id="tab-'.$id.'">'.$fieldFunc($value['fields']).'</div>';
  1018. }
  1019. }
  1020. $pageID = (isset($array['id'])?$array['id']:str_replace(array(' ','"',"'"),array('_'),strtolower($array['id'])));
  1021. return '
  1022. <div class="email-body">
  1023. <div class="email-header gray-bg">
  1024. <button type="button" class="btn btn-danger btn-sm waves close-button"><i class="fa fa-close"></i></button>
  1025. <h1>'.$array['title'].'</h1>
  1026. </div>
  1027. <div class="email-inner small-box">
  1028. <div class="email-inner-section">
  1029. <div class="small-box fade in" id="'.$pageID.'_frame">
  1030. <div class="col-lg-12">
  1031. '.(isset($array['customBeforeForm'])?$array['customBeforeForm']:'').'
  1032. <form class="content-form" name="'.$pageID.'" id="'.$pageID.'_form" onsubmit="return false;">
  1033. <button type="submit" class="btn waves btn-labeled btn-success btn btn-sm pull-right text-uppercase waves-effect waves-float">
  1034. <span class="btn-label"><i class="fa fa-floppy-o"></i></span>Save
  1035. </button>
  1036. '.$fields.($tabContent?'
  1037. <div class="tabbable tabs-with-bg" id="'.$pageID.'_tabs">
  1038. <ul class="nav nav-tabs apps">
  1039. '.implode('', $tabSelectors).'
  1040. </ul>
  1041. <div class="clearfix"></div>
  1042. <div class="tab-content">
  1043. '.implode('', $tabContent).'
  1044. </div>
  1045. </div>':'').'
  1046. </form>
  1047. '.(isset($array['customAfterForm'])?$array['customAfterForm']:'').'
  1048. </div>
  1049. </div>
  1050. </div>
  1051. </div>
  1052. </div>
  1053. <script>
  1054. $(document).ready(function() {
  1055. $(\'#'.$pageID.'_form\').find(\'input, select, textarea\').on(\'change\', function() { $(this).attr(\'data-changed\', \'true\'); });
  1056. var '.$pageID.'Validate = function() { if (this.value && !RegExp(\'^\'+this.pattern+\'$\').test(this.value)) { $(this).addClass(\'invalid\'); } else { $(this).removeClass(\'invalid\'); } };
  1057. $(\'#'.$pageID.'_form\').find(\'input[pattern]\').each('.$pageID.'Validate).on(\'keyup\', '.$pageID.'Validate);
  1058. $(\'#'.$pageID.'_form\').find(\'select[multiple]\').on(\'click\', function() { $(this).attr(\'data-changed\', \'true\'); });
  1059. $(\'#'.$pageID.'_form\').submit(function () {
  1060. var newVals = {};
  1061. var hasVals = false;
  1062. $(\'#'.$pageID.'_form\').find(\'[data-changed=true]\').each(function() {
  1063. hasVals = true;
  1064. if (this.type == \'checkbox\') {
  1065. newVals[this.name] = this.checked;
  1066. } else {
  1067. var fieldVal = $(this).val();
  1068. if (typeof fieldVal == \'object\') {
  1069. if (typeof fieldVal.join == \'function\') {
  1070. fieldVal = fieldVal.join(\'|\');
  1071. } else {
  1072. fieldVal = JSON.stringify(fieldVal);
  1073. }
  1074. }
  1075. newVals[this.name] = fieldVal;
  1076. }
  1077. });
  1078. if (hasVals) {
  1079. console.log(newVals);
  1080. ajax_request(\'POST\', \''.(isset($array['submitAction'])?$array['submitAction']:'update-config').'\', newVals, function(data, code) {
  1081. $(\'#'.$pageID.'_form\').find(\'[data-changed=true]\').removeAttr(\'data-changed\');
  1082. });
  1083. } else {
  1084. parent.notify(\'Nothing to update!\', \'bullhorn\', \'success\', 5000, \'bar\', \'slidetop\');
  1085. }
  1086. return false;
  1087. });
  1088. '.(isset($array['onready'])?$array['onready']:'').'
  1089. });
  1090. </script>
  1091. ';
  1092. }
  1093. // Build Settings Fields
  1094. function buildField($params, $sizeSm = 12, $sizeMd = 12, $sizeLg = 12) {
  1095. /*
  1096. array(
  1097. 'type' => '',
  1098. 'placeholder' => '',
  1099. 'label' => '',
  1100. 'labelTranslate' => '',
  1101. 'assist' => '',
  1102. 'name' => '',
  1103. 'pattern' => '',
  1104. 'options' => array( // For SELECT only
  1105. 'Display' => 'value',
  1106. ),
  1107. )
  1108. */
  1109. // Tags
  1110. $tags = array();
  1111. foreach(array('placeholder','style','disabled','readonly','pattern','min','max','required','onkeypress','onchange','onfocus','onleave','href') as $value) {
  1112. $tags[] = (isset($params[$value])?$value.'="'.$params[$value].'"':'');
  1113. }
  1114. $format = (isset($params['format']) && in_array($params['format'],array(false,'colour','color'))?$params['format']:false);
  1115. $name = (isset($params['name'])?$params['name']:(isset($params['id'])?$params['id']:''));
  1116. $id = (isset($params['id'])?$params['id']:(isset($params['name'])?$params['name'].'_id':randString(32)));
  1117. $val = (isset($params['value'])?$params['value']:'');
  1118. $class = (isset($params['class'])?' '.$params['class']:'');
  1119. $wrapClass = (isset($params['wrapClass'])?$params['wrapClass']:'form-content');
  1120. $assist = (isset($params['assist'])?' - i.e. '.$params['assist']:'');
  1121. $label = (isset($params['labelTranslate'])?translate($params['labelTranslate']):(isset($params['label'])?$params['label']:''));
  1122. $labelOut = '<p class="help-text">'.$label.$assist.'</p>';
  1123. // Field Design
  1124. switch ($params['type']) {
  1125. case 'text':
  1126. case 'number':
  1127. case 'password':
  1128. $field = '<input id="'.$id.'" name="'.$name.'" type="'.$params['type'].'" class="form-control material input-sm'.$class.'" '.implode(' ',$tags).' autocorrect="off" autocapitalize="off" value="'.$val.'">';
  1129. break;
  1130. case 'select':
  1131. case 'dropdown':
  1132. $field = '<select id="'.$id.'" name="'.$name.'" class="form-control material input-sm" '.implode(' ',$tags).'>'.resolveSelectOptions($params['options'], $val).'</select>';
  1133. break;
  1134. case 'select-multi':
  1135. case 'dropdown-multi':
  1136. $field = '<select id="'.$id.'" name="'.$name.'" class="form-control input-sm" '.implode(' ',$tags).' multiple="multiple">'.resolveSelectOptions($params['options'], $val, true).'</select>';
  1137. break;
  1138. case 'check':
  1139. case 'checkbox':
  1140. case 'toggle':
  1141. $checked = ((is_bool($val) && $val) || trim($val) === 'true'?' checked':'');
  1142. $labelOut = '<label for="'.$id.'"></label>'.$label;
  1143. $field = '<input id="'.$id.'" name="'.$name.'" type="checkbox" class="switcher switcher-success'.$class.'" '.implode(' ',$tags).' value="'.$val.'"'.$checked.'>';
  1144. break;
  1145. case 'date':
  1146. $field = 'Unsupported, planned.';
  1147. break;
  1148. case 'hidden':
  1149. $labelOut = '';
  1150. $field = '<input id="'.$id.'" name="'.$name.'" type="hidden" class="'.$class.'" '.implode(' ',$tags).' value="'.$val.'">';
  1151. break;
  1152. case 'header':
  1153. $labelOut = '';
  1154. $headType = (isset($params['value'])?$params['value']:3);
  1155. $field = '<h'.$headType.' class="'.$class.'" '.implode(' ',$tags).'>'.$label.'</h'.$headType.'>';
  1156. break;
  1157. case 'button':
  1158. $labelOut = '';
  1159. $icon = (isset($params['icon'])?$params['icon']:'flask');
  1160. $bType = (isset($params['buttonType'])?$params['buttonType']:'success');
  1161. $bDropdown = (isset($params['buttonDrop'])?$params['buttonDrop']:'');
  1162. $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>':'');
  1163. break;
  1164. case 'textarea':
  1165. $rows = (isset($params['rows'])?$params['rows']:5);
  1166. $field = '<textarea id="'.$id.'" name="'.$name.'" class="form-control'.$class.'" rows="'.$rows.'" '.implode(' ',$tags).'>'.$val.'</textarea>';
  1167. break;
  1168. case 'custom':
  1169. // Settings
  1170. $settings = array(
  1171. '$id' => $id,
  1172. '$name' => $name,
  1173. '$val' => $val,
  1174. '$label' => $label,
  1175. '$labelOut' => $labelOut,
  1176. );
  1177. // Get HTML
  1178. $html = (isset($params['html'])?$params['html']:'Nothing Specified!');
  1179. // If LabelOut is in html dont print it twice
  1180. $labelOut = (strpos($html,'$labelOut')!==false?'':$labelOut);
  1181. // Replace variables in settings
  1182. $html = preg_replace_callback('/\$\w+\b/', function ($match) use ($settings) { return (isset($settings[$match[0]])?$settings[$match[0]]:'{'.$match[0].' is undefined}'); }, $html);
  1183. // Build Field
  1184. $field = '<div id="'.$id.'_html" class="custom-field">'.$html.'</div>';
  1185. break;
  1186. case 'space':
  1187. $labelOut = '';
  1188. $field = str_repeat('<br>', (isset($params['value'])?$params['value']:1));
  1189. break;
  1190. default:
  1191. $field = 'Unsupported field type';
  1192. break;
  1193. }
  1194. // Field Formats
  1195. switch ($format) {
  1196. case 'colour': // Fuckin Eh, Canada!
  1197. case 'color':
  1198. $labelBef = '<center>'.$label.'</center>';
  1199. $wrapClass = 'gray-bg colour-field';
  1200. $labelAft = '';
  1201. $field = str_replace(' material input-sm','',$field);
  1202. break;
  1203. default:
  1204. $labelBef = '';
  1205. $labelAft = $labelOut;
  1206. }
  1207. return '<div class="'.$wrapClass.' col-sm-'.$sizeSm.' col-md-'.$sizeMd.' col-lg-'.$sizeLg.'">'.$labelBef.$field.$labelAft.'</div>';
  1208. }
  1209. // Timezone array
  1210. function timezoneOptions() {
  1211. $output = array();
  1212. $timezones = array();
  1213. $regions = array(
  1214. 'Africa' => DateTimeZone::AFRICA,
  1215. 'America' => DateTimeZone::AMERICA,
  1216. 'Antarctica' => DateTimeZone::ANTARCTICA,
  1217. 'Arctic' => DateTimeZone::ARCTIC,
  1218. 'Asia' => DateTimeZone::ASIA,
  1219. 'Atlantic' => DateTimeZone::ATLANTIC,
  1220. 'Australia' => DateTimeZone::AUSTRALIA,
  1221. 'Europe' => DateTimeZone::EUROPE,
  1222. 'Indian' => DateTimeZone::INDIAN,
  1223. 'Pacific' => DateTimeZone::PACIFIC
  1224. );
  1225. foreach ($regions as $name => $mask) {
  1226. $zones = DateTimeZone::listIdentifiers($mask);
  1227. foreach($zones as $timezone) {
  1228. $time = new DateTime(NULL, new DateTimeZone($timezone));
  1229. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  1230. $output[$name]['optgroup'][substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm]['value'] = $timezone;
  1231. }
  1232. }
  1233. return $output;
  1234. }
  1235. // Build Database
  1236. function createSQLiteDB($path = false) {
  1237. if ($path === false) {
  1238. if (defined('DATABASE_LOCATION')) {
  1239. $path = DATABASE_LOCATION;
  1240. } else {
  1241. debug_out('No Path Specified!');
  1242. }
  1243. }
  1244. if (!is_file($path.'users.db') || filesize($path.'users.db') <= 0) {
  1245. if (!isset($GLOBALS['file_db'])) {
  1246. $GLOBALS['file_db'] = new PDO('sqlite:'.$path.'users.db');
  1247. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1248. }
  1249. // Create Users
  1250. $users = $GLOBALS['file_db']->query('CREATE TABLE `users` (
  1251. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1252. `username` TEXT UNIQUE,
  1253. `password` TEXT,
  1254. `email` TEXT,
  1255. `token` TEXT,
  1256. `role` TEXT,
  1257. `active` TEXT,
  1258. `last` TEXT,
  1259. `auth_service` TEXT DEFAULT \'internal\'
  1260. );');
  1261. // Create Tabs
  1262. $tabs = $GLOBALS['file_db']->query('CREATE TABLE `tabs` (
  1263. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1264. `users_id` INTEGER,
  1265. `name` TEXT,
  1266. `url` TEXT,
  1267. `defaultz` TEXT,
  1268. `active` TEXT,
  1269. `user` TEXT,
  1270. `guest` TEXT,
  1271. `icon` TEXT,
  1272. `iconurl` TEXT,
  1273. `window` TEXT
  1274. );');
  1275. // Create Options
  1276. $options = $GLOBALS['file_db']->query('CREATE TABLE `options` (
  1277. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1278. `users_id` INTEGER UNIQUE,
  1279. `title` TEXT UNIQUE,
  1280. `topbar` TEXT,
  1281. `bottombar` TEXT,
  1282. `sidebar` TEXT,
  1283. `hoverbg` TEXT,
  1284. `topbartext` TEXT,
  1285. `activetabBG` TEXT,
  1286. `activetabicon` TEXT,
  1287. `activetabtext` TEXT,
  1288. `inactiveicon` TEXT,
  1289. `inactivetext` TEXT,
  1290. `loading` TEXT,
  1291. `hovertext` TEXT
  1292. );');
  1293. return $users && $tabs && $options;
  1294. } else {
  1295. return false;
  1296. }
  1297. }
  1298. // Upgrade Database
  1299. function updateSQLiteDB($db_path = false) {
  1300. if (!$db_path) {
  1301. if (defined('DATABASE_LOCATION')) {
  1302. $db_path = DATABASE_LOCATION;
  1303. } else {
  1304. debug_out('No Path Specified',1);
  1305. }
  1306. }
  1307. if (!isset($GLOBALS['file_db'])) {
  1308. $GLOBALS['file_db'] = new PDO('sqlite:'.$db_path.'users.db');
  1309. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1310. }
  1311. // Cache current DB
  1312. $cache = array();
  1313. foreach($GLOBALS['file_db']->query('SELECT name FROM sqlite_master WHERE type="table";') as $table) {
  1314. foreach($GLOBALS['file_db']->query('SELECT * FROM '.$table['name'].';') as $key => $row) {
  1315. foreach($row as $k => $v) {
  1316. if (is_string($k)) {
  1317. $cache[$table['name']][$key][$k] = $v;
  1318. }
  1319. }
  1320. }
  1321. }
  1322. // Remove Current Database
  1323. $GLOBALS['file_db'] = null;
  1324. $pathDigest = pathinfo($db_path.'users.db');
  1325. if (file_exists($db_path.'users.db')) {
  1326. rename($db_path.'users.db', $pathDigest['dirname'].'/'.$pathDigest['filename'].'.bak.db');
  1327. }
  1328. // Create New Database
  1329. $success = createSQLiteDB($db_path);
  1330. // Restore Items
  1331. if ($success) {
  1332. foreach($cache as $table => $tableData) {
  1333. if ($tableData) {
  1334. $queryBase = 'INSERT INTO '.$table.' (`'.implode('`,`',array_keys(current($tableData))).'`) values ';
  1335. $insertValues = array();
  1336. reset($tableData);
  1337. foreach($tableData as $key => $value) {
  1338. $insertValues[] = '('.implode(',',array_map(function($d) {
  1339. return (isset($d)?"'".addslashes($d)."'":'null');
  1340. }, $value)).')';
  1341. }
  1342. $GLOBALS['file_db']->query($queryBase.implode(',',$insertValues).';');
  1343. }
  1344. }
  1345. return true;
  1346. } else {
  1347. return false;
  1348. }
  1349. }
  1350. // Commit colours to database
  1351. function updateDBOptions($values) {
  1352. if (!isset($GLOBALS['file_db'])) {
  1353. $GLOBALS['file_db'] = new PDO('sqlite:'.DATABASE_LOCATION.'users.db');
  1354. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1355. }
  1356. // Commit new values to database
  1357. if ($GLOBALS['file_db']->query('UPDATE options SET '.implode(',',array_map(function($d, $k) {
  1358. return '`'.$k.'` = '.(isset($d)?"'".addslashes($d)."'":'null');
  1359. }, $values, array_keys($values))).';')->rowCount()) {
  1360. return true;
  1361. } else if ($GLOBALS['file_db']->query('INSERT OR IGNORE INTO options (`'.implode('`,`',array_keys($values)).'`) VALUES (\''.implode("','",$values).'\');')->rowCount()) {
  1362. return true;
  1363. } else {
  1364. return false;
  1365. }
  1366. }
  1367. // Send AJAX notification
  1368. function sendNotification($success, $message = false, $send = true) {
  1369. $notifyExplode = explode("-", NOTIFYEFFECT);
  1370. if ($success) {
  1371. $msg = array(
  1372. 'html' => ($message?'<br>'.$message:'<strong>'.translate("SETTINGS_SAVED").'</strong>'),
  1373. 'icon' => 'floppy-o',
  1374. 'type' => 'success',
  1375. 'length' => '5000',
  1376. 'layout' => $notifyExplode[0],
  1377. 'effect' => $notifyExplode[1],
  1378. );
  1379. } else {
  1380. $msg = array(
  1381. 'html' => ($message?'<br>'.$message:'<strong>'.translate("SETTINGS_NOT_SAVED").'</strong>'),
  1382. 'icon' => 'floppy-o',
  1383. 'type' => 'failed',
  1384. 'length' => '5000',
  1385. 'layout' => $notifyExplode[0],
  1386. 'effect' => $notifyExplode[1],
  1387. );
  1388. }
  1389. // Send and kill script?
  1390. if ($send) {
  1391. header('Content-Type: application/json');
  1392. echo json_encode(array('notify'=>$msg));
  1393. die();
  1394. }
  1395. return $msg;
  1396. }
  1397. // Load colours from the database
  1398. function loadAppearance() {
  1399. if (!isset($GLOBALS['file_db'])) {
  1400. $GLOBALS['file_db'] = new PDO('sqlite:'.DATABASE_LOCATION.'users.db');
  1401. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1402. }
  1403. // Defaults
  1404. $defaults = array(
  1405. 'title' => 'Organizr',
  1406. 'topbartext' => '#66D9EF',
  1407. 'topbar' => '#333333',
  1408. 'bottombar' => '#333333',
  1409. 'sidebar' => '#393939',
  1410. 'hoverbg' => '#AD80FD',
  1411. 'activetabBG' => '#F92671',
  1412. 'activetabicon' => '#FFFFFF',
  1413. 'activetabtext' => '#FFFFFF',
  1414. 'inactiveicon' => '#66D9EF',
  1415. 'inactivetext' => '#66D9EF',
  1416. 'loading' => '#66D9EF',
  1417. 'hovertext' => '#000000',
  1418. );
  1419. // Database Lookup
  1420. $options = $GLOBALS['file_db']->query('SELECT * FROM options');
  1421. // Replace defaults with filled options
  1422. foreach($options as $row) {
  1423. foreach($defaults as $key => $value) {
  1424. if (isset($row[$key]) && $row[$key]) {
  1425. $defaults[$key] = $row[$key];
  1426. }
  1427. }
  1428. }
  1429. // Return the Results
  1430. return $defaults;
  1431. }
  1432. // Delete Database
  1433. function deleteDatabase() {
  1434. unset($_COOKIE['Organizr']);
  1435. setcookie('Organizr', '', time() - 3600, '/');
  1436. unset($_COOKIE['OrganizrU']);
  1437. setcookie('OrganizrU', '', time() - 3600, '/');
  1438. $GLOBALS['file_db'] = null;
  1439. unlink(DATABASE_LOCATION.'users.db');
  1440. foreach(glob(substr_replace($userdirpath, "", -1).'/*') as $file) {
  1441. if(is_dir($file)) {
  1442. rmdir($file);
  1443. } elseif (!is_dir($file)) {
  1444. unlink($file);
  1445. }
  1446. }
  1447. rmdir($userdirpath);
  1448. return true;
  1449. }
  1450. // Upgrade the installation
  1451. function upgradeInstall() {
  1452. function downloadFile($url, $path){
  1453. $folderPath = "upgrade/";
  1454. if(!mkdir($folderPath)) : echo "can't make dir"; endif;
  1455. $newfname = $folderPath . $path;
  1456. $file = fopen ($url, 'rb');
  1457. if ($file) {
  1458. $newf = fopen ($newfname, 'wb');
  1459. if ($newf) {
  1460. while(!feof($file)) {
  1461. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  1462. }
  1463. }
  1464. }
  1465. if ($file) {
  1466. fclose($file);
  1467. }
  1468. if ($newf) {
  1469. fclose($newf);
  1470. }
  1471. }
  1472. function unzipFile($zipFile){
  1473. $zip = new ZipArchive;
  1474. $extractPath = "upgrade/";
  1475. if($zip->open($extractPath . $zipFile) != "true"){
  1476. echo "Error :- Unable to open the Zip File";
  1477. }
  1478. /* Extract Zip File */
  1479. $zip->extractTo($extractPath);
  1480. $zip->close();
  1481. }
  1482. // Function to remove folders and files
  1483. function rrmdir($dir) {
  1484. if (is_dir($dir)) {
  1485. $files = scandir($dir);
  1486. foreach ($files as $file)
  1487. if ($file != "." && $file != "..") rrmdir("$dir/$file");
  1488. rmdir($dir);
  1489. }
  1490. else if (file_exists($dir)) unlink($dir);
  1491. }
  1492. // Function to Copy folders and files
  1493. function rcopy($src, $dst) {
  1494. if (is_dir ( $src )) {
  1495. if (!file_exists($dst)) : mkdir ( $dst ); endif;
  1496. $files = scandir ( $src );
  1497. foreach ( $files as $file )
  1498. if ($file != "." && $file != "..")
  1499. rcopy ( "$src/$file", "$dst/$file" );
  1500. } else if (file_exists ( $src ))
  1501. copy ( $src, $dst );
  1502. }
  1503. $url = "https://github.com/causefx/Organizr/archive/master.zip";
  1504. $file = "upgrade.zip";
  1505. $source = __DIR__ . "/upgrade/Organizr-master/";
  1506. $cleanup = __DIR__ . "/upgrade/";
  1507. $destination = __DIR__ . "/";
  1508. downloadFile($url, $file);
  1509. unzipFile($file);
  1510. rcopy($source, $destination);
  1511. rrmdir($cleanup);
  1512. return true;
  1513. }
  1514. // NzbGET Items
  1515. function nzbgetConnect($list = 'listgroups') {
  1516. $url = qualifyURL(NZBGETURL);
  1517. $api = file_get_contents($url.'/'.NZBGETUSERNAME.':'.NZBGETPASSWORD.'/jsonrpc/'.$list);
  1518. $api = json_decode($api, true);
  1519. $gotNZB = array();
  1520. foreach ($api['result'] AS $child) {
  1521. $downloadName = htmlentities($child['NZBName'], ENT_QUOTES);
  1522. $downloadStatus = $child['Status'];
  1523. $downloadCategory = $child['Category'];
  1524. if($list == "history"){ $downloadPercent = "100"; $progressBar = ""; }
  1525. if($list == "listgroups"){ $downloadPercent = (($child['FileSizeMB'] - $child['RemainingSizeMB']) / $child['FileSizeMB']) * 100; $progressBar = "progress-bar-striped active"; }
  1526. if($child['Health'] <= "750"){
  1527. $downloadHealth = "danger";
  1528. }elseif($child['Health'] <= "900"){
  1529. $downloadHealth = "warning";
  1530. }elseif($child['Health'] <= "1000"){
  1531. $downloadHealth = "success";
  1532. }
  1533. $gotNZB[] = '<tr>
  1534. <td>'.$downloadName.'</td>
  1535. <td>'.$downloadStatus.'</td>
  1536. <td>'.$downloadCategory.'</td>
  1537. <td>
  1538. <div class="progress">
  1539. <div class="progress-bar progress-bar-'.$downloadHealth.' '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  1540. <p class="text-center">'.round($downloadPercent).'%</p>
  1541. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  1542. </div>
  1543. </div>
  1544. </td>
  1545. </tr>';
  1546. }
  1547. if ($gotNZB) {
  1548. return implode('',$gotNZB);
  1549. } else {
  1550. return '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>';
  1551. }
  1552. }
  1553. // Sabnzbd Items
  1554. function sabnzbdConnect($list = 'queue') {
  1555. $url = qualifyURL(SABNZBDURL);
  1556. $api = file_get_contents($url.'/api?mode='.$list.'&output=json&apikey='.SABNZBDKEY);
  1557. $api = json_decode($api, true);
  1558. $gotNZB = array();
  1559. foreach ($api[$list]['slots'] AS $child) {
  1560. if($list == "queue"){ $downloadName = $child['filename']; $downloadCategory = $child['cat']; $downloadPercent = (($child['mb'] - $child['mbleft']) / $child['mb']) * 100; $progressBar = "progress-bar-striped active"; }
  1561. if($list == "history"){ $downloadName = $child['name']; $downloadCategory = $child['category']; $downloadPercent = "100"; $progressBar = ""; }
  1562. $downloadStatus = $child['status'];
  1563. $gotNZB[] = '<tr>
  1564. <td>'.$downloadName.'</td>
  1565. <td>'.$downloadStatus.'</td>
  1566. <td>'.$downloadCategory.'</td>
  1567. <td>
  1568. <div class="progress">
  1569. <div class="progress-bar progress-bar-success '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  1570. <p class="text-center">'.round($downloadPercent).'%</p>
  1571. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  1572. </div>
  1573. </div>
  1574. </td>
  1575. </tr>';
  1576. }
  1577. if ($gotNZB) {
  1578. return implode('',$gotNZB);
  1579. } else {
  1580. return '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>';
  1581. }
  1582. }
  1583. // ==============
  1584. function clean($strin) {
  1585. $strout = null;
  1586. for ($i = 0; $i < strlen($strin); $i++) {
  1587. $ord = ord($strin[$i]);
  1588. if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
  1589. $strout .= "&amp;#{$ord};";
  1590. }
  1591. else {
  1592. switch ($strin[$i]) {
  1593. case '<':
  1594. $strout .= '&lt;';
  1595. break;
  1596. case '>':
  1597. $strout .= '&gt;';
  1598. break;
  1599. case '&':
  1600. $strout .= '&amp;';
  1601. break;
  1602. case '"':
  1603. $strout .= '&quot;';
  1604. break;
  1605. default:
  1606. $strout .= $strin[$i];
  1607. }
  1608. }
  1609. }
  1610. return $strout;
  1611. }
  1612. function registration_callback($username, $email, $userdir){
  1613. global $data;
  1614. $data = array($username, $email, $userdir);
  1615. }
  1616. function printArray($arrayName){
  1617. $messageCount = count($arrayName);
  1618. $i = 0;
  1619. foreach ( $arrayName as $item ) :
  1620. $i++;
  1621. if($i < $messageCount) :
  1622. echo "<small class='text-uppercase'>" . $item . "</small> & ";
  1623. elseif($i = $messageCount) :
  1624. echo "<small class='text-uppercase'>" . $item . "</small>";
  1625. endif;
  1626. endforeach;
  1627. }
  1628. function write_ini_file($content, $path) {
  1629. if (!$handle = fopen($path, 'w')) {
  1630. return false;
  1631. }
  1632. $success = fwrite($handle, trim($content));
  1633. fclose($handle);
  1634. return $success;
  1635. }
  1636. function gotTimezone(){
  1637. $regions = array(
  1638. 'Africa' => DateTimeZone::AFRICA,
  1639. 'America' => DateTimeZone::AMERICA,
  1640. 'Antarctica' => DateTimeZone::ANTARCTICA,
  1641. 'Arctic' => DateTimeZone::ARCTIC,
  1642. 'Asia' => DateTimeZone::ASIA,
  1643. 'Atlantic' => DateTimeZone::ATLANTIC,
  1644. 'Australia' => DateTimeZone::AUSTRALIA,
  1645. 'Europe' => DateTimeZone::EUROPE,
  1646. 'Indian' => DateTimeZone::INDIAN,
  1647. 'Pacific' => DateTimeZone::PACIFIC
  1648. );
  1649. $timezones = array();
  1650. foreach ($regions as $name => $mask) {
  1651. $zones = DateTimeZone::listIdentifiers($mask);
  1652. foreach($zones as $timezone) {
  1653. $time = new DateTime(NULL, new DateTimeZone($timezone));
  1654. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  1655. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  1656. }
  1657. }
  1658. print '<select name="timezone" id="timezone" class="form-control material input-sm" required>';
  1659. foreach($timezones as $region => $list) {
  1660. print '<optgroup label="' . $region . '">' . "\n";
  1661. foreach($list as $timezone => $name) {
  1662. if($timezone == TIMEZONE) : $selected = " selected"; else : $selected = ""; endif;
  1663. print '<option value="' . $timezone . '"' . $selected . '>' . $name . '</option>' . "\n";
  1664. }
  1665. print '</optgroup>' . "\n";
  1666. }
  1667. print '</select>';
  1668. }
  1669. function getTimezone(){
  1670. $regions = array(
  1671. 'Africa' => DateTimeZone::AFRICA,
  1672. 'America' => DateTimeZone::AMERICA,
  1673. 'Antarctica' => DateTimeZone::ANTARCTICA,
  1674. 'Arctic' => DateTimeZone::ARCTIC,
  1675. 'Asia' => DateTimeZone::ASIA,
  1676. 'Atlantic' => DateTimeZone::ATLANTIC,
  1677. 'Australia' => DateTimeZone::AUSTRALIA,
  1678. 'Europe' => DateTimeZone::EUROPE,
  1679. 'Indian' => DateTimeZone::INDIAN,
  1680. 'Pacific' => DateTimeZone::PACIFIC
  1681. );
  1682. $timezones = array();
  1683. foreach ($regions as $name => $mask) {
  1684. $zones = DateTimeZone::listIdentifiers($mask);
  1685. foreach($zones as $timezone) {
  1686. $time = new DateTime(NULL, new DateTimeZone($timezone));
  1687. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  1688. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  1689. }
  1690. }
  1691. print '<select name="timezone" id="timezone" class="form-control material" required>';
  1692. foreach($timezones as $region => $list) {
  1693. print '<optgroup label="' . $region . '">' . "\n";
  1694. foreach($list as $timezone => $name) {
  1695. print '<option value="' . $timezone . '">' . $name . '</option>' . "\n";
  1696. }
  1697. print '</optgroup>' . "\n";
  1698. }
  1699. print '</select>';
  1700. }
  1701. function explosion($string, $position){
  1702. $getWord = explode("|", $string);
  1703. return $getWord[$position];
  1704. }
  1705. function getServerPath() {
  1706. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  1707. $protocol = "https://";
  1708. } else {
  1709. $protocol = "http://";
  1710. }
  1711. return $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
  1712. }
  1713. function get_browser_name() {
  1714. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  1715. if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
  1716. elseif (strpos($user_agent, 'Edge')) return 'Edge';
  1717. elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
  1718. elseif (strpos($user_agent, 'Safari')) return 'Safari';
  1719. elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
  1720. elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
  1721. return 'Other';
  1722. }
  1723. function getSickrageCalendarWanted($array){
  1724. $array = json_decode($array, true);
  1725. $gotCalendar = "";
  1726. $i = 0;
  1727. foreach($array['data']['missed'] AS $child) {
  1728. $i++;
  1729. $seriesName = $child['show_name'];
  1730. $episodeID = $child['tvdbid'];
  1731. $episodeAirDate = $child['airdate'];
  1732. $episodeAirDateTime = explode(" ",$child['airs']);
  1733. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1734. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1735. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1736. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1737. $downloaded = "0";
  1738. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  1739. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1740. }
  1741. foreach($array['data']['today'] AS $child) {
  1742. $i++;
  1743. $seriesName = $child['show_name'];
  1744. $episodeID = $child['tvdbid'];
  1745. $episodeAirDate = $child['airdate'];
  1746. $episodeAirDateTime = explode(" ",$child['airs']);
  1747. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1748. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1749. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1750. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1751. $downloaded = "0";
  1752. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  1753. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1754. }
  1755. foreach($array['data']['soon'] AS $child) {
  1756. $i++;
  1757. $seriesName = $child['show_name'];
  1758. $episodeID = $child['tvdbid'];
  1759. $episodeAirDate = $child['airdate'];
  1760. $episodeAirDateTime = explode(" ",$child['airs']);
  1761. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1762. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1763. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1764. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1765. $downloaded = "0";
  1766. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  1767. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1768. }
  1769. foreach($array['data']['later'] AS $child) {
  1770. $i++;
  1771. $seriesName = $child['show_name'];
  1772. $episodeID = $child['tvdbid'];
  1773. $episodeAirDate = $child['airdate'];
  1774. $episodeAirDateTime = explode(" ",$child['airs']);
  1775. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1776. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1777. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1778. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1779. $downloaded = "0";
  1780. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  1781. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1782. }
  1783. if ($i != 0){ return $gotCalendar; }
  1784. }
  1785. function getSickrageCalendarHistory($array){
  1786. $array = json_decode($array, true);
  1787. $gotCalendar = "";
  1788. $i = 0;
  1789. foreach($array['data'] AS $child) {
  1790. $i++;
  1791. $seriesName = $child['show_name'];
  1792. $episodeID = $child['tvdbid'];
  1793. $episodeAirDate = $child['date'];
  1794. $downloaded = "green-bg";
  1795. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1796. }
  1797. if ($i != 0){ return $gotCalendar; }
  1798. }
  1799. function getSonarrCalendar($array){
  1800. $array = json_decode($array, true);
  1801. $gotCalendar = "";
  1802. $i = 0;
  1803. foreach($array AS $child) {
  1804. $i++;
  1805. $seriesName = $child['series']['title'];
  1806. $episodeID = $child['series']['tvdbId'];
  1807. if(!isset($episodeID)){ $episodeID = ""; }
  1808. $episodeName = htmlentities($child['title'], ENT_QUOTES);
  1809. if($child['episodeNumber'] == "1"){ $episodePremier = "true"; }else{ $episodePremier = "false"; }
  1810. $episodeAirDate = $child['airDateUtc'];
  1811. $episodeAirDate = strtotime($episodeAirDate);
  1812. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1813. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1814. $downloaded = $child['hasFile'];
  1815. 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"; }
  1816. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1817. }
  1818. if ($i != 0){ return $gotCalendar; }
  1819. }
  1820. function getRadarrCalendar($array){
  1821. $array = json_decode($array, true);
  1822. $gotCalendar = "";
  1823. $i = 0;
  1824. foreach($array AS $child) {
  1825. if(isset($child['inCinemas'])){
  1826. $i++;
  1827. $movieName = $child['title'];
  1828. $movieID = $child['tmdbId'];
  1829. if(!isset($movieID)){ $movieID = ""; }
  1830. if(isset($child['inCinemas']) && isset($child['physicalRelease'])){
  1831. $physicalRelease = $child['physicalRelease'];
  1832. $physicalRelease = strtotime($physicalRelease);
  1833. $physicalRelease = date("Y-m-d", $physicalRelease);
  1834. if (new DateTime() < new DateTime($physicalRelease)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  1835. $downloaded = $child['hasFile'];
  1836. if($downloaded == "0" && $notReleased == "true"){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg"; }else{ $downloaded = "red-bg"; }
  1837. }else{
  1838. $physicalRelease = $child['inCinemas'];
  1839. $downloaded = "light-blue-bg";
  1840. }
  1841. $gotCalendar .= "{ title: \"$movieName\", start: \"$physicalRelease\", className: \"$downloaded\", imagetype: \"film\", url: \"https://www.themoviedb.org/movie/$movieID\" }, \n";
  1842. }
  1843. }
  1844. if ($i != 0){ return $gotCalendar; }
  1845. }
  1846. function getHeadphonesCalendar($url, $key, $list){
  1847. $url = qualifyURL(HEADPHONESURL);
  1848. $api = file_get_contents($url."/api?apikey=".$key."&cmd=$list");
  1849. $api = json_decode($api, true);
  1850. $i = 0;
  1851. $gotCalendar = "";
  1852. foreach($api AS $child) {
  1853. if($child['Status'] == "Wanted"){
  1854. $i++;
  1855. $albumName = addslashes($child['AlbumTitle']);
  1856. $albumArtist = htmlentities($child['ArtistName'], ENT_QUOTES);
  1857. $albumDate = $child['ReleaseDate'];
  1858. $albumID = $child['AlbumID'];
  1859. $albumDate = strtotime($albumDate);
  1860. $albumDate = date("Y-m-d", $albumDate);
  1861. $albumStatus = $child['Status'];
  1862. if (new DateTime() < new DateTime($albumDate)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  1863. if($albumStatus == "Wanted" && $notReleased == "true"){ $albumStatusColor = "indigo-bg"; }elseif($albumStatus == "Downloaded"){ $albumStatusColor = "green-bg"; }else{ $albumStatusColor = "red-bg"; }
  1864. $gotCalendar .= "{ title: \"$albumArtist - $albumName\", start: \"$albumDate\", className: \"$albumStatusColor\", imagetype: \"music\", url: \"https://musicbrainz.org/release-group/$albumID\" }, \n";
  1865. }
  1866. }
  1867. if ($i != 0){ return $gotCalendar; }
  1868. }
  1869. ?>