functions.php 69 KB

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