functions.php 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413
  1. <?php
  2. // ===================================
  3. // Define Version
  4. define('INSTALLEDVERSION', '1.34');
  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 = (isset($itemDetails['SeriesName'])?$itemDetails['SeriesName'].': ':'').$itemDetails['Name'].(isset($itemDetails['ParentIndexNumber']) && isset($itemDetails['IndexNumber'])?' (Season '.$itemDetails['ParentIndexNumber'].': Episode '.$itemDetails['IndexNumber'].')':'');
  392. $imageId = (isset($itemDetails['SeriesId'])?$itemDetails['SeriesId']:$itemDetails['Id']);
  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 === false) {
  730. $current = loadConfig();
  731. } else if (is_string($current) && is_file($current)) {
  732. $current = loadConfig($current);
  733. }
  734. // Inject Parts
  735. foreach ($new as $k => $v) {
  736. $current[$k] = $v;
  737. }
  738. // Return Create
  739. return createConfig($current);
  740. }
  741. // Inject Defaults As Needed
  742. function fillDefaultConfig($array, $path = 'config/configDefaults.php') {
  743. if (is_string($path)) {
  744. $loadedDefaults = loadConfig($path);
  745. } else {
  746. $loadedDefaults = $path;
  747. }
  748. return (is_array($loadedDefaults) ? fillDefaultConfig_recurse($array, $loadedDefaults) : false);
  749. }
  750. // support function for fillDefaultConfig()
  751. function fillDefaultConfig_recurse($current, $defaults) {
  752. foreach($defaults as $k => $v) {
  753. if (!isset($current[$k])) {
  754. $current[$k] = $v;
  755. } else if (is_array($current[$k]) && is_array($v)) {
  756. $current[$k] = fillDefaultConfig_recurse($current[$k], $v);
  757. }
  758. }
  759. return $current;
  760. };
  761. // Define Scalar Variables (nest non-secular with underscores)
  762. function defineConfig($array, $anyCase = true, $nest_prefix = false) {
  763. foreach($array as $k => $v) {
  764. if (is_scalar($v) && !defined($nest_prefix.$k)) {
  765. define($nest_prefix.$k, $v, $anyCase);
  766. } else if (is_array($v)) {
  767. defineConfig($v, $anyCase, $nest_prefix.$k.'_');
  768. }
  769. }
  770. }
  771. // This function exists only because I am lazy
  772. function configLazy($path = 'config/config.php') {
  773. // Load config or default
  774. if (file_exists($path)) {
  775. $config = fillDefaultConfig(loadConfig($path));
  776. } else {
  777. $config = loadConfig('config/configDefaults.php');
  778. }
  779. if (is_array($config)) {
  780. defineConfig($config);
  781. }
  782. return $config;
  783. }
  784. // Qualify URL
  785. function qualifyURL($url) {
  786. // Get Digest
  787. $digest = parse_url($url);
  788. // http/https
  789. if (!isset($digest['scheme'])) {
  790. if (isset($digest['port']) && in_array($digest['port'], array(80,8080,8096,32400,7878,8989,8182,8081,6789))) {
  791. $scheme = 'http';
  792. } else {
  793. $scheme = 'https';
  794. }
  795. } else {
  796. $scheme = $digest['scheme'];
  797. }
  798. // Host
  799. $host = (isset($digest['host'])?$digest['host']:'');
  800. // Port
  801. $port = (isset($digest['port'])?':'.$digest['port']:'');
  802. // Path
  803. $path = (isset($digest['path'])?$digest['path']:'');
  804. // Output
  805. return $scheme.'://'.$host.$port.$path;
  806. }
  807. // Function to be called at top of each to allow upgrading environment as the spec changes
  808. function upgradeCheck() {
  809. // Upgrade to 1.31
  810. if (file_exists('homepageSettings.ini.php')) {
  811. $databaseConfig = parse_ini_file('databaseLocation.ini.php', true);
  812. $homepageConfig = parse_ini_file('homepageSettings.ini.php', true);
  813. $databaseConfig = array_merge($databaseConfig, $homepageConfig);
  814. $databaseData = '; <?php die("Access denied"); ?>' . "\r\n";
  815. foreach($databaseConfig as $k => $v) {
  816. if(substr($v, -1) == "/") : $v = rtrim($v, "/"); endif;
  817. $databaseData .= $k . " = \"" . $v . "\"\r\n";
  818. }
  819. write_ini_file($databaseData, 'databaseLocation.ini.php');
  820. unlink('homepageSettings.ini.php');
  821. unset($databaseData);
  822. unset($homepageConfig);
  823. }
  824. // Upgrade to 1.32
  825. if (file_exists('databaseLocation.ini.php')) {
  826. // Load Existing
  827. $config = parse_ini_file('databaseLocation.ini.php', true);
  828. // Refactor
  829. $config['database_Location'] = str_replace('//','/',$config['databaseLocation'].'/');
  830. $config['user_home'] = $config['database_Location'].'users/';
  831. unset($config['databaseLocation']);
  832. // Turn Off Emby And Plex Recent
  833. $config["embyURL"] = $config["embyURL"].(!empty($config["embyPort"])?':'.$config["embyPort"]:'');
  834. unset($config["embyPort"]);
  835. $config["plexURL"] = $config["plexURL"].(!empty($config["plexPort"])?':'.$config["plexPort"]:'');
  836. unset($config["plexPort"]);
  837. $config["nzbgetURL"] = $config["nzbgetURL"].(!empty($config["nzbgetPort"])?':'.$config["nzbgetPort"]:'');
  838. unset($config["nzbgetPort"]);
  839. $config["sabnzbdURL"] = $config["sabnzbdURL"].(!empty($config["sabnzbdPort"])?':'.$config["sabnzbdPort"]:'');
  840. unset($config["sabnzbdPort"]);
  841. $config["headphonesURL"] = $config["headphonesURL"].(!empty($config["headphonesPort"])?':'.$config["headphonesPort"]:'');
  842. unset($config["headphonesPort"]);
  843. // Write config file
  844. $config['CONFIG_VERSION'] = '1.32';
  845. copy('config/config.php', 'config/config['.date('Y-m-d_H-i-s').'][pre1.32].bak.php');
  846. $createConfigSuccess = createConfig($config);
  847. // Create new config
  848. if ($createConfigSuccess) {
  849. if (file_exists('config/config.php')) {
  850. // Remove Old ini file
  851. unlink('databaseLocation.ini.php');
  852. } else {
  853. debug_out('Something is not right here!');
  854. }
  855. } else {
  856. debug_out('Couldn\'t create updated configuration.' ,1);
  857. }
  858. }
  859. // Upgrade to 1.33
  860. $config = loadConfig();
  861. if (isset($config['database_Location']) && (!isset($config['CONFIG_VERSION']) || $config['CONFIG_VERSION'] < '1.33')) {
  862. // Fix User Directory
  863. $config['user_home'] = $config['database_Location'].'users/';
  864. unset($config['USER_HOME']);
  865. // Backend auth merge
  866. if (isset($config['authBackendPort']) && !isset(parse_url($config['authBackendHost'])['port'])) {
  867. $config['authBackendHost'] .= ':'.$config['authBackendPort'];
  868. }
  869. unset($config['authBackendPort']);
  870. // If auth is being used move it to embyURL as that is now used in auth functions
  871. 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')))) {
  872. $config['embyURL'] = $config['authBackendHost'];
  873. }
  874. // Upgrade database to latest version
  875. updateSQLiteDB($config['database_Location'],'1.32');
  876. // Update Version and Commit
  877. $config['CONFIG_VERSION'] = '1.33';
  878. copy('config/config.php', 'config/config['.date('Y-m-d_H-i-s').'][1.32].bak.php');
  879. $createConfigSuccess = createConfig($config);
  880. unset($config);
  881. }
  882. // Upgrade to 1.34
  883. $config = loadConfig();
  884. if (isset($config['database_Location']) && (!isset($config['CONFIG_VERSION']) || $config['CONFIG_VERSION'] < '1.34')) {
  885. // Upgrade database to latest version
  886. updateSQLiteDB($config['database_Location'],'1.33');
  887. // Update Version and Commit
  888. $config['CONFIG_VERSION'] = '1.34';
  889. copy('config/config.php', 'config/config['.date('Y-m-d_H-i-s').'][1.33].bak.php');
  890. $createConfigSuccess = createConfig($config);
  891. unset($config);
  892. }
  893. return true;
  894. }
  895. // Check if all software dependancies are met
  896. function dependCheck() {
  897. return true;
  898. }
  899. // Process file uploads
  900. function uploadFiles($path, $ext_mask = null) {
  901. if (isset($_FILES) && count($_FILES)) {
  902. require_once('class.uploader.php');
  903. $uploader = new Uploader();
  904. $data = $uploader->upload($_FILES['files'], array(
  905. 'limit' => 10,
  906. 'maxSize' => 10,
  907. 'extensions' => $ext_mask,
  908. 'required' => false,
  909. 'uploadDir' => str_replace('//','/',$path.'/'),
  910. 'title' => array('name'),
  911. 'removeFiles' => true,
  912. 'replace' => true,
  913. ));
  914. if($data['isComplete']){
  915. $files = $data['data'];
  916. echo json_encode($files['metas'][0]['name']);
  917. }
  918. if($data['hasErrors']){
  919. $errors = $data['errors'];
  920. echo json_encode($errors);
  921. }
  922. } else {
  923. echo json_encode('No files submitted!');
  924. }
  925. }
  926. // Remove file
  927. function removeFiles($path) {
  928. if(is_file($path)) {
  929. unlink($path);
  930. } else {
  931. echo json_encode('No file specified for removal!');
  932. }
  933. }
  934. // Lazy select options
  935. function resolveSelectOptions($array, $selected = '', $multi = false) {
  936. $output = array();
  937. $selectedArr = ($multi?explode('|', $selected):array());
  938. foreach ($array as $key => $value) {
  939. if (is_array($value)) {
  940. if (isset($value['optgroup'])) {
  941. $output[] = '<optgroup label="'.$key.'">';
  942. foreach($value['optgroup'] as $k => $v) {
  943. $output[] = '<option value="'.$v['value'].'"'.($selected===$v['value']||in_array($v['value'],$selectedArr)?' selected':'').(isset($v['disabled']) && $v['disabled']?' disabled':'').'>'.$k.'</option>';
  944. }
  945. } else {
  946. $output[] = '<option value="'.$value['value'].'"'.($selected===$value['value']||in_array($value['value'],$selectedArr)?' selected':'').(isset($value['disabled']) && $value['disabled']?' disabled':'').'>'.$key.'</option>';
  947. }
  948. } else {
  949. $output[] = '<option value="'.$value.'"'.($selected===$value||in_array($value,$selectedArr)?' selected':'').'>'.$key.'</option>';
  950. }
  951. }
  952. return implode('',$output);
  953. }
  954. // Check if user is allowed to continue
  955. function qualifyUser($type, $errOnFail = false) {
  956. if (!isset($GLOBALS['USER'])) {
  957. require_once("user.php");
  958. $GLOBALS['USER'] = new User('registration_callback');
  959. }
  960. if (is_bool($type)) {
  961. if ($type === true) {
  962. $authorized = ($GLOBALS['USER']->authenticated == true);
  963. } else {
  964. $authorized = true;
  965. }
  966. } elseif (is_string($type) || is_array($type)) {
  967. if ($type !== 'false') {
  968. if (!is_array($type)) {
  969. $type = explode('|',$type);
  970. }
  971. $authorized = ($GLOBALS['USER']->authenticated && in_array($GLOBALS['USER']->role,$type));
  972. } else {
  973. $authorized = true;
  974. }
  975. } else {
  976. debug_out('Invalid Syntax!',1);
  977. }
  978. if (!$authorized && $errOnFail) {
  979. if ($GLOBALS['USER']->authenticated) {
  980. header('Location: error.php?error=401');
  981. echo '<script>window.location.href = \''.dirname($_SERVER['SCRIPT_NAME']).'/error.php?error=401\'</script>';
  982. } else {
  983. header('Location: error.php?error=999');
  984. echo '<script>window.location.href = \''.dirname($_SERVER['SCRIPT_NAME']).'/error.php?error=999\'</script>';
  985. }
  986. debug_out('Not Authorized' ,1);
  987. } else {
  988. return $authorized;
  989. }
  990. }
  991. // Build an (optionally) tabbed settings page.
  992. function buildSettings($array) {
  993. /*
  994. array(
  995. 'title' => '',
  996. 'id' => '',
  997. 'fields' => array( See buildField() ),
  998. 'tabs' => array(
  999. array(
  1000. 'title' => '',
  1001. 'id' => '',
  1002. 'image' => '',
  1003. 'fields' => array( See buildField() ),
  1004. ),
  1005. ),
  1006. );
  1007. */
  1008. $fieldFunc = function($fieldArr) {
  1009. $fields = '<div class="row">';
  1010. foreach($fieldArr as $key => $value) {
  1011. $isSingle = isset($value['type']);
  1012. if ($isSingle) { $value = array($value); }
  1013. $tmpField = '';
  1014. $sizeLg = max(floor(12/count($value)),2);
  1015. $sizeMd = max(floor(($isSingle?12:6)/count($value)),3);
  1016. foreach($value as $k => $v) {
  1017. $tmpField .= buildField($v, 12, $sizeMd, $sizeLg);
  1018. }
  1019. $fields .= ($isSingle?$tmpField:'<div class="row col-sm-12 content-form">'.$tmpField.'</div>');
  1020. }
  1021. $fields .= '</div>';
  1022. return $fields;
  1023. };
  1024. $fields = (isset($array['fields'])?$fieldFunc($array['fields']):'');
  1025. $tabSelectors = array();
  1026. $tabContent = array();
  1027. if (isset($array['tabs'])) {
  1028. foreach($array['tabs'] as $key => $value) {
  1029. $id = (isset($value['id'])?$value['id']:randString(32));
  1030. $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>';
  1031. $tabContent[$key] = '<div class="tab-pane big-box fade'.($tabContent?'':' active in').'" id="tab-'.$id.'">'.$fieldFunc($value['fields']).'</div>';
  1032. }
  1033. }
  1034. $pageID = (isset($array['id'])?$array['id']:str_replace(array(' ','"',"'"),array('_'),strtolower($array['id'])));
  1035. return '
  1036. <div class="email-body">
  1037. <div class="email-header gray-bg">
  1038. <button type="button" class="btn btn-danger btn-sm waves close-button"><i class="fa fa-close"></i></button>
  1039. <h1>'.$array['title'].'</h1>
  1040. </div>
  1041. <div class="email-inner small-box">
  1042. <div class="email-inner-section">
  1043. <div class="small-box fade in" id="'.$pageID.'_frame">
  1044. <div class="col-lg-12">
  1045. '.(isset($array['customBeforeForm'])?$array['customBeforeForm']:'').'
  1046. <form class="content-form" name="'.$pageID.'" id="'.$pageID.'_form" onsubmit="return false;">
  1047. <button type="submit" class="btn waves btn-labeled btn-success btn btn-sm pull-right text-uppercase waves-effect waves-float">
  1048. <span class="btn-label"><i class="fa fa-floppy-o"></i></span>Save
  1049. </button>
  1050. '.$fields.($tabContent?'
  1051. <div class="tabbable tabs-with-bg" id="'.$pageID.'_tabs">
  1052. <ul class="nav nav-tabs apps">
  1053. '.implode('', $tabSelectors).'
  1054. </ul>
  1055. <div class="clearfix"></div>
  1056. <div class="tab-content">
  1057. '.implode('', $tabContent).'
  1058. </div>
  1059. </div>':'').'
  1060. </form>
  1061. '.(isset($array['customAfterForm'])?$array['customAfterForm']:'').'
  1062. </div>
  1063. </div>
  1064. </div>
  1065. </div>
  1066. </div>
  1067. <script>
  1068. $(document).ready(function() {
  1069. $(\'#'.$pageID.'_form\').find(\'input, select, textarea\').on(\'change\', function() { $(this).attr(\'data-changed\', \'true\'); });
  1070. var '.$pageID.'Validate = function() { if (this.value && !RegExp(\'^\'+this.pattern+\'$\').test(this.value)) { $(this).addClass(\'invalid\'); } else { $(this).removeClass(\'invalid\'); } };
  1071. $(\'#'.$pageID.'_form\').find(\'input[pattern]\').each('.$pageID.'Validate).on(\'keyup\', '.$pageID.'Validate);
  1072. $(\'#'.$pageID.'_form\').find(\'select[multiple]\').on(\'click\', function() { $(this).attr(\'data-changed\', \'true\'); });
  1073. $(\'#'.$pageID.'_form\').submit(function () {
  1074. var newVals = {};
  1075. var hasVals = false;
  1076. $(\'#'.$pageID.'_form\').find(\'[data-changed=true]\').each(function() {
  1077. hasVals = true;
  1078. if (this.type == \'checkbox\') {
  1079. newVals[this.name] = this.checked;
  1080. } else {
  1081. var fieldVal = $(this).val();
  1082. if (typeof fieldVal == \'object\') {
  1083. if (typeof fieldVal.join == \'function\') {
  1084. fieldVal = fieldVal.join(\'|\');
  1085. } else {
  1086. fieldVal = JSON.stringify(fieldVal);
  1087. }
  1088. }
  1089. newVals[this.name] = fieldVal;
  1090. }
  1091. });
  1092. if (hasVals) {
  1093. console.log(newVals);
  1094. ajax_request(\'POST\', \''.(isset($array['submitAction'])?$array['submitAction']:'update-config').'\', newVals, function(data, code) {
  1095. $(\'#'.$pageID.'_form\').find(\'[data-changed=true]\').removeAttr(\'data-changed\');
  1096. });
  1097. } else {
  1098. parent.notify(\'Nothing to update!\', \'bullhorn\', \'success\', 5000, \'bar\', \'slidetop\');
  1099. }
  1100. return false;
  1101. });
  1102. '.(isset($array['onready'])?$array['onready']:'').'
  1103. });
  1104. </script>
  1105. ';
  1106. }
  1107. // Build Settings Fields
  1108. function buildField($params, $sizeSm = 12, $sizeMd = 12, $sizeLg = 12) {
  1109. /*
  1110. array(
  1111. 'type' => '',
  1112. 'placeholder' => '',
  1113. 'label' => '',
  1114. 'labelTranslate' => '',
  1115. 'assist' => '',
  1116. 'name' => '',
  1117. 'pattern' => '',
  1118. 'options' => array( // For SELECT only
  1119. 'Display' => 'value',
  1120. ),
  1121. )
  1122. */
  1123. // Tags
  1124. $tags = array();
  1125. foreach(array('placeholder','style','disabled','readonly','pattern','min','max','required','onkeypress','onchange','onfocus','onleave','href','onclick') as $value) {
  1126. if (isset($params[$value])) {
  1127. if (is_string($params[$value])) { $tags[] = $value.'="'.$params[$value].'"';
  1128. } else if ($params[$value] === true) { $tags[] = $value; }
  1129. }
  1130. }
  1131. $format = (isset($params['format']) && in_array($params['format'],array(false,'colour','color'))?$params['format']:false);
  1132. $name = (isset($params['name'])?$params['name']:(isset($params['id'])?$params['id']:''));
  1133. $id = (isset($params['id'])?$params['id']:(isset($params['name'])?$params['name'].'_id':randString(32)));
  1134. $val = (isset($params['value'])?$params['value']:'');
  1135. $class = (isset($params['class'])?' '.$params['class']:'');
  1136. $wrapClass = (isset($params['wrapClass'])?$params['wrapClass']:'form-content');
  1137. $assist = (isset($params['assist'])?' - i.e. '.$params['assist']:'');
  1138. $label = (isset($params['labelTranslate'])?translate($params['labelTranslate']):(isset($params['label'])?$params['label']:''));
  1139. $labelOut = '<p class="help-text">'.$label.$assist.'</p>';
  1140. // Field Design
  1141. switch ($params['type']) {
  1142. case 'text':
  1143. case 'number':
  1144. case 'password':
  1145. $field = '<input id="'.$id.'" name="'.$name.'" type="'.$params['type'].'" class="form-control material input-sm'.$class.'" '.implode(' ',$tags).' autocorrect="off" autocapitalize="off" value="'.$val.'">';
  1146. break;
  1147. case 'select':
  1148. case 'dropdown':
  1149. $field = '<select id="'.$id.'" name="'.$name.'" class="form-control material input-sm" '.implode(' ',$tags).'>'.resolveSelectOptions($params['options'], $val).'</select>';
  1150. break;
  1151. case 'select-multi':
  1152. case 'dropdown-multi':
  1153. $field = '<select id="'.$id.'" name="'.$name.'" class="form-control input-sm" '.implode(' ',$tags).' multiple="multiple">'.resolveSelectOptions($params['options'], $val, true).'</select>';
  1154. break;
  1155. case 'check':
  1156. case 'checkbox':
  1157. case 'toggle':
  1158. $checked = ((is_bool($val) && $val) || trim($val) === 'true'?' checked':'');
  1159. $colour = (isset($params['colour'])?$params['colour']:'success');
  1160. $labelOut = '<label for="'.$id.'"></label>'.$label;
  1161. $field = '<input id="'.$id.'" name="'.$name.'" type="checkbox" class="switcher switcher-'.$colour.' '.$class.'" '.implode(' ',$tags).' data-value="'.$val.'"'.$checked.'>';
  1162. break;
  1163. case 'radio':
  1164. $labelOut = '';
  1165. $checked = ((is_bool($val) && $val) || ($val && trim($val) !== 'false')?' checked':'');
  1166. $bType = (isset($params['buttonType'])?$params['buttonType']:'success');
  1167. $field = '<div class="radio radio-'.$bType.'"><input id="'.$id.'" name="'.$name.'" type="radio" class="'.$class.'" '.implode(' ',$tags).' value="'.$val.'"'.$checked.'><label for="'.$id.'">'.$label.'</label></div>';
  1168. break;
  1169. case 'date':
  1170. $field = 'Unsupported, planned.';
  1171. break;
  1172. case 'hidden':
  1173. return '<input id="'.$id.'" name="'.$name.'" type="hidden" class="'.$class.'" '.implode(' ',$tags).' value="'.$val.'">';
  1174. break;
  1175. case 'header':
  1176. $labelOut = '';
  1177. $headType = (isset($params['value'])?$params['value']:3);
  1178. $field = '<h'.$headType.' class="'.$class.'" '.implode(' ',$tags).'>'.$label.'</h'.$headType.'>';
  1179. break;
  1180. case 'button':
  1181. $labelOut = '';
  1182. $icon = (isset($params['icon'])?$params['icon']:'flask');
  1183. $bType = (isset($params['buttonType'])?$params['buttonType']:'success');
  1184. $bDropdown = (isset($params['buttonDrop'])?$params['buttonDrop']:'');
  1185. $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>':'');
  1186. break;
  1187. case 'textarea':
  1188. $rows = (isset($params['rows'])?$params['rows']:5);
  1189. $field = '<textarea id="'.$id.'" name="'.$name.'" class="form-control'.$class.'" rows="'.$rows.'" '.implode(' ',$tags).'>'.$val.'</textarea>';
  1190. break;
  1191. case 'custom':
  1192. // Settings
  1193. $settings = array(
  1194. '$id' => $id,
  1195. '$name' => $name,
  1196. '$val' => $val,
  1197. '$label' => $label,
  1198. '$labelOut' => $labelOut,
  1199. );
  1200. // Get HTML
  1201. $html = (isset($params['html'])?$params['html']:'Nothing Specified!');
  1202. // If LabelOut is in html dont print it twice
  1203. $labelOut = (strpos($html,'$label')!==false?'':$labelOut);
  1204. // Replace variables in settings
  1205. $html = preg_replace_callback('/\$\w+\b/', function ($match) use ($settings) { return (isset($settings[$match[0]])?$settings[$match[0]]:'{'.$match[0].' is undefined}'); }, $html);
  1206. // Build Field
  1207. $field = '<div id="'.$id.'_html" class="custom-field">'.$html.'</div>';
  1208. break;
  1209. case 'space':
  1210. $labelOut = '';
  1211. $field = str_repeat('<br>', (isset($params['value'])?$params['value']:1));
  1212. break;
  1213. default:
  1214. $field = 'Unsupported field type';
  1215. break;
  1216. }
  1217. // Field Formats
  1218. switch ($format) {
  1219. case 'colour': // Fuckin Eh, Canada!
  1220. case 'color':
  1221. $labelBef = '<center>'.$label.'</center>';
  1222. $wrapClass = 'gray-bg colour-field';
  1223. $labelAft = '';
  1224. $field = str_replace(' material input-sm','',$field);
  1225. break;
  1226. default:
  1227. $labelBef = '';
  1228. $labelAft = $labelOut;
  1229. }
  1230. return '<div class="'.$wrapClass.' col-sm-'.$sizeSm.' col-md-'.$sizeMd.' col-lg-'.$sizeLg.'">'.$labelBef.$field.$labelAft.'</div>';
  1231. }
  1232. // Tab Settings Generation
  1233. function printTabRow($data) {
  1234. $hidden = false;
  1235. if ($data===false) {
  1236. $hidden = true;
  1237. $data = array( // New Tab Defaults
  1238. 'id' => 'new',
  1239. 'name' => '',
  1240. 'url' => '',
  1241. 'icon' => 'fa-diamond',
  1242. 'iconurl' => '',
  1243. 'active' => 'true',
  1244. 'user' => 'true',
  1245. 'guest' => 'true',
  1246. 'window' => 'false',
  1247. 'defaultz' => '',
  1248. );
  1249. }
  1250. $image = '<span style="font: normal normal normal 30px/1 FontAwesome;" class="fa fa-hand-paper-o"></span>';
  1251. $output = '
  1252. <li id="tab-'.$data['id'].'" class="list-group-item" style="position: relative; left: 0px; top: 0px; '.($hidden?' display: none;':'').'">
  1253. <tab class="content-form form-inline">
  1254. <div class="row">
  1255. '.buildField(array(
  1256. 'type' => 'custom',
  1257. 'html' => '<div class="action-btns tabIconView"><a style="margin-left: 0px">'.($data['iconurl']?'<img src="'.$data['iconurl'].'" height="30" width="30">':'<span style="font: normal normal normal 30px/1 FontAwesome;" class="fa '.($data['icon']?$data['icon']:'hand-paper-o').'"></span>').'</a></div>',
  1258. ),12,1,1).'
  1259. '.buildField(array(
  1260. 'type' => 'hidden',
  1261. 'id' => 'tab-'.$data['id'].'-id',
  1262. 'name' => 'id['.$data['id'].']',
  1263. 'value' => $data['id'],
  1264. ),12,2,1).'
  1265. '.buildField(array(
  1266. 'type' => 'text',
  1267. 'id' => 'tab-'.$data['id'].'-name',
  1268. 'name' => 'name['.$data['id'].']',
  1269. 'required' => true,
  1270. 'placeholder' => 'Organizr Homepage',
  1271. 'labelTranslate' => 'TAB_NAME',
  1272. 'value' => $data['name'],
  1273. ),12,2,1).'
  1274. '.buildField(array(
  1275. 'type' => 'text',
  1276. 'id' => 'tab-'.$data['id'].'-url',
  1277. 'name' => 'url['.$data['id'].']',
  1278. 'required' => true,
  1279. 'placeholder' => 'homepage.php',
  1280. 'labelTranslate' => 'TAB_URL',
  1281. 'value' => $data['url'],
  1282. ),12,2,1).'
  1283. '.buildField(array(
  1284. 'type' => 'text',
  1285. 'id' => 'tab-'.$data['id'].'-iconurl',
  1286. 'name' => 'iconurl['.$data['id'].']',
  1287. 'placeholder' => 'images/organizr.png',
  1288. 'labelTranslate' => 'ICON_URL',
  1289. 'value' => $data['iconurl'],
  1290. ),12,2,1).'
  1291. '.buildField(array(
  1292. 'type' => 'custom',
  1293. 'id' => 'tab-'.$data['id'].'-icon',
  1294. 'name' => 'icon['.$data['id'].']',
  1295. 'html' => '- '.translate('OR').' - <div class="input-group"><input data-placement="bottomRight" class="form-control material icp-auto'.($hidden?'-pend':'').'" id="$id" name="$name" value="$val" type="text" /><span class="input-group-addon"></span></div>',
  1296. 'value' => $data['icon'],
  1297. ),12,1,1).'
  1298. '.buildField(array(
  1299. 'type' => 'checkbox',
  1300. 'labelTranslate' => 'ACTIVE',
  1301. 'name' => 'active['.$data['id'].']',
  1302. 'value' => $data['active'],
  1303. ),12,1,1).'
  1304. '.buildField(array(
  1305. 'type' => 'checkbox',
  1306. 'labelTranslate' => 'USER',
  1307. 'colour' => 'primary',
  1308. 'name' => 'user['.$data['id'].']',
  1309. 'value' => $data['user'],
  1310. ),12,1,1).'
  1311. '.buildField(array(
  1312. 'type' => 'checkbox',
  1313. 'labelTranslate' => 'GUEST',
  1314. 'colour' => 'warning',
  1315. 'name' => 'guest['.$data['id'].']',
  1316. 'value' => $data['guest'],
  1317. ),12,1,1).'
  1318. '.buildField(array(
  1319. 'type' => 'checkbox',
  1320. 'labelTranslate' => 'NO_IFRAME',
  1321. 'colour' => 'danger',
  1322. 'name' => 'window['.$data['id'].']',
  1323. 'value' => $data['window'],
  1324. ),12,1,1).'
  1325. '.buildField(array(
  1326. 'type' => 'radio',
  1327. 'labelTranslate' => 'DEFAULT',
  1328. 'name' => 'defaultz['.$data['id'].']',
  1329. 'value' => $data['defaultz'],
  1330. 'onclick' => "$('[type=radio][id!=\''+this.id+'\']').each(function() { this.checked=false; });",
  1331. ),12,1,1).'
  1332. '.buildField(array(
  1333. 'type' => 'button',
  1334. 'icon' => 'trash',
  1335. 'labelTranslate' => 'REMOVE',
  1336. 'onclick' => "$(this).parents('li').remove();",
  1337. ),12,1,1).'
  1338. </div>
  1339. </tab>
  1340. </li>
  1341. ';
  1342. return $output;
  1343. }
  1344. // Timezone array
  1345. function timezoneOptions() {
  1346. $output = array();
  1347. $timezones = array();
  1348. $regions = array(
  1349. 'Africa' => DateTimeZone::AFRICA,
  1350. 'America' => DateTimeZone::AMERICA,
  1351. 'Antarctica' => DateTimeZone::ANTARCTICA,
  1352. 'Arctic' => DateTimeZone::ARCTIC,
  1353. 'Asia' => DateTimeZone::ASIA,
  1354. 'Atlantic' => DateTimeZone::ATLANTIC,
  1355. 'Australia' => DateTimeZone::AUSTRALIA,
  1356. 'Europe' => DateTimeZone::EUROPE,
  1357. 'Indian' => DateTimeZone::INDIAN,
  1358. 'Pacific' => DateTimeZone::PACIFIC
  1359. );
  1360. foreach ($regions as $name => $mask) {
  1361. $zones = DateTimeZone::listIdentifiers($mask);
  1362. foreach($zones as $timezone) {
  1363. $time = new DateTime(NULL, new DateTimeZone($timezone));
  1364. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  1365. $output[$name]['optgroup'][substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm]['value'] = $timezone;
  1366. }
  1367. }
  1368. return $output;
  1369. }
  1370. // Build Database
  1371. function createSQLiteDB($path = false) {
  1372. if ($path === false) {
  1373. if (defined('DATABASE_LOCATION')) {
  1374. $path = DATABASE_LOCATION;
  1375. } else {
  1376. debug_out('No Path Specified!');
  1377. }
  1378. }
  1379. if (!is_file($path.'users.db') || filesize($path.'users.db') <= 0) {
  1380. if (!isset($GLOBALS['file_db'])) {
  1381. $GLOBALS['file_db'] = new PDO('sqlite:'.$path.'users.db');
  1382. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1383. }
  1384. // Create Users
  1385. $users = $GLOBALS['file_db']->query('CREATE TABLE `users` (
  1386. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1387. `username` TEXT UNIQUE,
  1388. `password` TEXT,
  1389. `email` TEXT,
  1390. `token` TEXT,
  1391. `role` TEXT,
  1392. `active` TEXT,
  1393. `last` TEXT,
  1394. `auth_service` TEXT DEFAULT \'internal\'
  1395. );');
  1396. // Create Tabs
  1397. $tabs = $GLOBALS['file_db']->query('CREATE TABLE `tabs` (
  1398. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1399. `order` INTEGER,
  1400. `users_id` INTEGER,
  1401. `name` TEXT,
  1402. `url` TEXT,
  1403. `defaultz` TEXT,
  1404. `active` TEXT,
  1405. `user` TEXT,
  1406. `guest` TEXT,
  1407. `icon` TEXT,
  1408. `iconurl` TEXT,
  1409. `window` TEXT
  1410. );');
  1411. // Create Options
  1412. $options = $GLOBALS['file_db']->query('CREATE TABLE `options` (
  1413. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1414. `users_id` INTEGER UNIQUE,
  1415. `title` TEXT UNIQUE,
  1416. `topbar` TEXT,
  1417. `bottombar` TEXT,
  1418. `sidebar` TEXT,
  1419. `hoverbg` TEXT,
  1420. `topbartext` TEXT,
  1421. `activetabBG` TEXT,
  1422. `activetabicon` TEXT,
  1423. `activetabtext` TEXT,
  1424. `inactiveicon` TEXT,
  1425. `inactivetext` TEXT,
  1426. `loading` TEXT,
  1427. `hovertext` TEXT
  1428. );');
  1429. return $users && $tabs && $options;
  1430. } else {
  1431. return false;
  1432. }
  1433. }
  1434. // Upgrade Database
  1435. function updateSQLiteDB($db_path = false, $oldVerNum = false) {
  1436. if (!$db_path) {
  1437. if (defined('DATABASE_LOCATION')) {
  1438. $db_path = DATABASE_LOCATION;
  1439. } else {
  1440. debug_out('No Path Specified',1);
  1441. }
  1442. }
  1443. if (!isset($GLOBALS['file_db'])) {
  1444. $GLOBALS['file_db'] = new PDO('sqlite:'.$db_path.'users.db');
  1445. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1446. }
  1447. // Cache current DB
  1448. $cache = array();
  1449. foreach($GLOBALS['file_db']->query('SELECT name FROM sqlite_master WHERE type="table";') as $table) {
  1450. foreach($GLOBALS['file_db']->query('SELECT * FROM '.$table['name'].';') as $key => $row) {
  1451. foreach($row as $k => $v) {
  1452. if (is_string($k)) {
  1453. $cache[$table['name']][$key][$k] = $v;
  1454. }
  1455. }
  1456. }
  1457. }
  1458. // Remove Current Database
  1459. $GLOBALS['file_db'] = null;
  1460. $pathDigest = pathinfo($db_path.'users.db');
  1461. if (file_exists($db_path.'users.db')) {
  1462. rename($db_path.'users.db', $pathDigest['dirname'].'/'.$pathDigest['filename'].'['.date('Y-m-d_H-i-s').']'.($oldVerNum?'['.$oldVerNum.']':'').'.bak.db');
  1463. }
  1464. // Create New Database
  1465. $success = createSQLiteDB($db_path);
  1466. // Restore Items
  1467. if ($success) {
  1468. foreach($cache as $table => $tableData) {
  1469. if ($tableData) {
  1470. $queryBase = 'INSERT INTO '.$table.' (`'.implode('`,`',array_keys(current($tableData))).'`) values ';
  1471. $insertValues = array();
  1472. reset($tableData);
  1473. foreach($tableData as $key => $value) {
  1474. $insertValues[] = '('.implode(',',array_map(function($d) {
  1475. return (isset($d)?"'".SQLite3::escapeString($d)."'":'null');
  1476. }, $value)).')';
  1477. }
  1478. $GLOBALS['file_db']->query($queryBase.implode(',',$insertValues).';');
  1479. }
  1480. }
  1481. return true;
  1482. } else {
  1483. return false;
  1484. }
  1485. }
  1486. // Commit colours to database
  1487. function updateDBOptions($values) {
  1488. if (!isset($GLOBALS['file_db'])) {
  1489. $GLOBALS['file_db'] = new PDO('sqlite:'.DATABASE_LOCATION.'users.db');
  1490. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1491. }
  1492. // Commit new values to database
  1493. if ($GLOBALS['file_db']->query('UPDATE options SET '.implode(',',array_map(function($d, $k) {
  1494. return '`'.$k.'` = '.(isset($d)?"'".addslashes($d)."'":'null');
  1495. }, $values, array_keys($values))).';')->rowCount()) {
  1496. return true;
  1497. } else if ($GLOBALS['file_db']->query('INSERT OR IGNORE INTO options (`'.implode('`,`',array_keys($values)).'`) VALUES (\''.implode("','",$values).'\');')->rowCount()) {
  1498. return true;
  1499. } else {
  1500. return false;
  1501. }
  1502. }
  1503. // Send AJAX notification
  1504. function sendNotification($success, $message = false, $send = true) {
  1505. $notifyExplode = explode("-", NOTIFYEFFECT);
  1506. if ($success) {
  1507. $msg = array(
  1508. 'html' => ($message?'<br>'.$message:'<strong>'.translate("SETTINGS_SAVED").'</strong>'),
  1509. 'icon' => 'floppy-o',
  1510. 'type' => 'success',
  1511. 'length' => '5000',
  1512. 'layout' => $notifyExplode[0],
  1513. 'effect' => $notifyExplode[1],
  1514. );
  1515. } else {
  1516. $msg = array(
  1517. 'html' => ($message?'<br>'.$message:'<strong>'.translate("SETTINGS_NOT_SAVED").'</strong>'),
  1518. 'icon' => 'floppy-o',
  1519. 'type' => 'failed',
  1520. 'length' => '5000',
  1521. 'layout' => $notifyExplode[0],
  1522. 'effect' => $notifyExplode[1],
  1523. );
  1524. }
  1525. // Send and kill script?
  1526. if ($send) {
  1527. header('Content-Type: application/json');
  1528. echo json_encode(array('notify'=>$msg));
  1529. die();
  1530. }
  1531. return $msg;
  1532. }
  1533. // Load colours from the database
  1534. function loadAppearance() {
  1535. if (!isset($GLOBALS['file_db'])) {
  1536. $GLOBALS['file_db'] = new PDO('sqlite:'.DATABASE_LOCATION.'users.db');
  1537. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1538. }
  1539. // Defaults
  1540. $defaults = array(
  1541. 'title' => 'Organizr',
  1542. 'topbartext' => '#66D9EF',
  1543. 'topbar' => '#333333',
  1544. 'bottombar' => '#333333',
  1545. 'sidebar' => '#393939',
  1546. 'hoverbg' => '#AD80FD',
  1547. 'activetabBG' => '#F92671',
  1548. 'activetabicon' => '#FFFFFF',
  1549. 'activetabtext' => '#FFFFFF',
  1550. 'inactiveicon' => '#66D9EF',
  1551. 'inactivetext' => '#66D9EF',
  1552. 'loading' => '#66D9EF',
  1553. 'hovertext' => '#000000',
  1554. );
  1555. // Database Lookup
  1556. $options = $GLOBALS['file_db']->query('SELECT * FROM options');
  1557. // Replace defaults with filled options
  1558. foreach($options as $row) {
  1559. foreach($defaults as $key => $value) {
  1560. if (isset($row[$key]) && $row[$key]) {
  1561. $defaults[$key] = $row[$key];
  1562. }
  1563. }
  1564. }
  1565. // Return the Results
  1566. return $defaults;
  1567. }
  1568. // Delete Database
  1569. function deleteDatabase() {
  1570. unset($_COOKIE['Organizr']);
  1571. setcookie('Organizr', '', time() - 3600, '/');
  1572. unset($_COOKIE['OrganizrU']);
  1573. setcookie('OrganizrU', '', time() - 3600, '/');
  1574. $GLOBALS['file_db'] = null;
  1575. unlink(DATABASE_LOCATION.'users.db');
  1576. foreach(glob(substr_replace($userdirpath, "", -1).'/*') as $file) {
  1577. if(is_dir($file)) {
  1578. rmdir($file);
  1579. } elseif (!is_dir($file)) {
  1580. unlink($file);
  1581. }
  1582. }
  1583. rmdir($userdirpath);
  1584. return true;
  1585. }
  1586. // Upgrade the installation
  1587. function upgradeInstall($branch = 'master') {
  1588. function downloadFile($url, $path){
  1589. $folderPath = "upgrade/";
  1590. if(!mkdir($folderPath)) : echo "can't make dir"; endif;
  1591. $newfname = $folderPath . $path;
  1592. $file = fopen ($url, 'rb');
  1593. if ($file) {
  1594. $newf = fopen ($newfname, 'wb');
  1595. if ($newf) {
  1596. while(!feof($file)) {
  1597. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  1598. }
  1599. }
  1600. }
  1601. if ($file) {
  1602. fclose($file);
  1603. }
  1604. if ($newf) {
  1605. fclose($newf);
  1606. }
  1607. }
  1608. function unzipFile($zipFile){
  1609. $zip = new ZipArchive;
  1610. $extractPath = "upgrade/";
  1611. if($zip->open($extractPath . $zipFile) != "true"){
  1612. echo "Error :- Unable to open the Zip File";
  1613. }
  1614. /* Extract Zip File */
  1615. $zip->extractTo($extractPath);
  1616. $zip->close();
  1617. }
  1618. // Function to remove folders and files
  1619. function rrmdir($dir) {
  1620. if (is_dir($dir)) {
  1621. $files = scandir($dir);
  1622. foreach ($files as $file)
  1623. if ($file != "." && $file != "..") rrmdir("$dir/$file");
  1624. rmdir($dir);
  1625. }
  1626. else if (file_exists($dir)) unlink($dir);
  1627. }
  1628. // Function to Copy folders and files
  1629. function rcopy($src, $dst) {
  1630. if (is_dir ( $src )) {
  1631. if (!file_exists($dst)) : mkdir ( $dst ); endif;
  1632. $files = scandir ( $src );
  1633. foreach ( $files as $file )
  1634. if ($file != "." && $file != "..")
  1635. rcopy ( "$src/$file", "$dst/$file" );
  1636. } else if (file_exists ( $src ))
  1637. copy ( $src, $dst );
  1638. }
  1639. $url = 'https://github.com/causefx/Organizr/archive/'.$branch.'.zip';
  1640. $file = "upgrade.zip";
  1641. $source = __DIR__ . '/upgrade/Organizr-'.$branch.'/';
  1642. $cleanup = __DIR__ . "/upgrade/";
  1643. $destination = __DIR__ . "/";
  1644. downloadFile($url, $file);
  1645. unzipFile($file);
  1646. rcopy($source, $destination);
  1647. rrmdir($cleanup);
  1648. return true;
  1649. }
  1650. // NzbGET Items
  1651. function nzbgetConnect($list = 'listgroups') {
  1652. $url = qualifyURL(NZBGETURL);
  1653. $api = file_get_contents($url.'/'.NZBGETUSERNAME.':'.NZBGETPASSWORD.'/jsonrpc/'.$list);
  1654. $api = json_decode($api, true);
  1655. $gotNZB = array();
  1656. foreach ($api['result'] AS $child) {
  1657. $downloadName = htmlentities($child['NZBName'], ENT_QUOTES);
  1658. $downloadStatus = $child['Status'];
  1659. $downloadCategory = $child['Category'];
  1660. if($list == "history"){ $downloadPercent = "100"; $progressBar = ""; }
  1661. if($list == "listgroups"){ $downloadPercent = (($child['FileSizeMB'] - $child['RemainingSizeMB']) / $child['FileSizeMB']) * 100; $progressBar = "progress-bar-striped active"; }
  1662. if($child['Health'] <= "750"){
  1663. $downloadHealth = "danger";
  1664. }elseif($child['Health'] <= "900"){
  1665. $downloadHealth = "warning";
  1666. }elseif($child['Health'] <= "1000"){
  1667. $downloadHealth = "success";
  1668. }
  1669. $gotNZB[] = '<tr>
  1670. <td>'.$downloadName.'</td>
  1671. <td>'.$downloadStatus.'</td>
  1672. <td>'.$downloadCategory.'</td>
  1673. <td>
  1674. <div class="progress">
  1675. <div class="progress-bar progress-bar-'.$downloadHealth.' '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  1676. <p class="text-center">'.round($downloadPercent).'%</p>
  1677. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  1678. </div>
  1679. </div>
  1680. </td>
  1681. </tr>';
  1682. }
  1683. if ($gotNZB) {
  1684. return implode('',$gotNZB);
  1685. } else {
  1686. return '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>';
  1687. }
  1688. }
  1689. // Sabnzbd Items
  1690. function sabnzbdConnect($list = 'queue') {
  1691. $url = qualifyURL(SABNZBDURL);
  1692. $api = file_get_contents($url.'/api?mode='.$list.'&output=json&apikey='.SABNZBDKEY);
  1693. $api = json_decode($api, true);
  1694. $gotNZB = array();
  1695. foreach ($api[$list]['slots'] AS $child) {
  1696. if($list == "queue"){ $downloadName = $child['filename']; $downloadCategory = $child['cat']; $downloadPercent = (($child['mb'] - $child['mbleft']) / $child['mb']) * 100; $progressBar = "progress-bar-striped active"; }
  1697. if($list == "history"){ $downloadName = $child['name']; $downloadCategory = $child['category']; $downloadPercent = "100"; $progressBar = ""; }
  1698. $downloadStatus = $child['status'];
  1699. $gotNZB[] = '<tr>
  1700. <td>'.$downloadName.'</td>
  1701. <td>'.$downloadStatus.'</td>
  1702. <td>'.$downloadCategory.'</td>
  1703. <td>
  1704. <div class="progress">
  1705. <div class="progress-bar progress-bar-success '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  1706. <p class="text-center">'.round($downloadPercent).'%</p>
  1707. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  1708. </div>
  1709. </div>
  1710. </td>
  1711. </tr>';
  1712. }
  1713. if ($gotNZB) {
  1714. return implode('',$gotNZB);
  1715. } else {
  1716. return '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>';
  1717. }
  1718. }
  1719. // Apply new tab settings
  1720. function updateTabs($tabs) {
  1721. if (!isset($GLOBALS['file_db'])) {
  1722. $GLOBALS['file_db'] = new PDO('sqlite:'.DATABASE_LOCATION.'users.db');
  1723. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1724. }
  1725. // Validate
  1726. if (!isset($tabs['defaultz'])) { $tabs['defaultz'][current(array_keys($tabs['name']))] = 'true'; }
  1727. if (isset($tabs['name']) && isset($tabs['url']) && is_array($tabs['name'])) {
  1728. // Clear Existing Tabs
  1729. $GLOBALS['file_db']->query("DELETE FROM tabs");
  1730. // Process New Tabs
  1731. $totalValid = 0;
  1732. foreach ($tabs['name'] as $key => $value) {
  1733. // Qualify
  1734. if (!$value || !isset($tabs['url']) || !$tabs['url'][$key]) { continue; }
  1735. $totalValid++;
  1736. $fields = array();
  1737. foreach(array('id','name','url','icon','iconurl','order') as $v) {
  1738. if (isset($tabs[$v]) && isset($tabs[$v][$key])) { $fields[$v] = $tabs[$v][$key]; }
  1739. }
  1740. foreach(array('active','user','guest','defaultz','window') as $v) {
  1741. if (isset($tabs[$v]) && isset($tabs[$v][$key])) { $fields[$v] = ($tabs[$v][$key]!=='false'?'true':'false'); }
  1742. }
  1743. $GLOBALS['file_db']->query('INSERT INTO tabs (`'.implode('`,`',array_keys($fields)).'`) VALUES (\''.implode("','",$fields).'\');');
  1744. }
  1745. return $totalValid;
  1746. } else {
  1747. return false;
  1748. }
  1749. return false;
  1750. }
  1751. // ==============
  1752. function clean($strin) {
  1753. $strout = null;
  1754. for ($i = 0; $i < strlen($strin); $i++) {
  1755. $ord = ord($strin[$i]);
  1756. if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
  1757. $strout .= "&amp;#{$ord};";
  1758. }
  1759. else {
  1760. switch ($strin[$i]) {
  1761. case '<':
  1762. $strout .= '&lt;';
  1763. break;
  1764. case '>':
  1765. $strout .= '&gt;';
  1766. break;
  1767. case '&':
  1768. $strout .= '&amp;';
  1769. break;
  1770. case '"':
  1771. $strout .= '&quot;';
  1772. break;
  1773. default:
  1774. $strout .= $strin[$i];
  1775. }
  1776. }
  1777. }
  1778. return $strout;
  1779. }
  1780. function registration_callback($username, $email, $userdir){
  1781. global $data;
  1782. $data = array($username, $email, $userdir);
  1783. }
  1784. function printArray($arrayName){
  1785. $messageCount = count($arrayName);
  1786. $i = 0;
  1787. foreach ( $arrayName as $item ) :
  1788. $i++;
  1789. if($i < $messageCount) :
  1790. echo "<small class='text-uppercase'>" . $item . "</small> & ";
  1791. elseif($i = $messageCount) :
  1792. echo "<small class='text-uppercase'>" . $item . "</small>";
  1793. endif;
  1794. endforeach;
  1795. }
  1796. function write_ini_file($content, $path) {
  1797. if (!$handle = fopen($path, 'w')) {
  1798. return false;
  1799. }
  1800. $success = fwrite($handle, trim($content));
  1801. fclose($handle);
  1802. return $success;
  1803. }
  1804. function gotTimezone(){
  1805. $regions = array(
  1806. 'Africa' => DateTimeZone::AFRICA,
  1807. 'America' => DateTimeZone::AMERICA,
  1808. 'Antarctica' => DateTimeZone::ANTARCTICA,
  1809. 'Arctic' => DateTimeZone::ARCTIC,
  1810. 'Asia' => DateTimeZone::ASIA,
  1811. 'Atlantic' => DateTimeZone::ATLANTIC,
  1812. 'Australia' => DateTimeZone::AUSTRALIA,
  1813. 'Europe' => DateTimeZone::EUROPE,
  1814. 'Indian' => DateTimeZone::INDIAN,
  1815. 'Pacific' => DateTimeZone::PACIFIC
  1816. );
  1817. $timezones = array();
  1818. foreach ($regions as $name => $mask) {
  1819. $zones = DateTimeZone::listIdentifiers($mask);
  1820. foreach($zones as $timezone) {
  1821. $time = new DateTime(NULL, new DateTimeZone($timezone));
  1822. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  1823. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  1824. }
  1825. }
  1826. print '<select name="timezone" id="timezone" class="form-control material input-sm" required>';
  1827. foreach($timezones as $region => $list) {
  1828. print '<optgroup label="' . $region . '">' . "\n";
  1829. foreach($list as $timezone => $name) {
  1830. if($timezone == TIMEZONE) : $selected = " selected"; else : $selected = ""; endif;
  1831. print '<option value="' . $timezone . '"' . $selected . '>' . $name . '</option>' . "\n";
  1832. }
  1833. print '</optgroup>' . "\n";
  1834. }
  1835. print '</select>';
  1836. }
  1837. function getTimezone(){
  1838. $regions = array(
  1839. 'Africa' => DateTimeZone::AFRICA,
  1840. 'America' => DateTimeZone::AMERICA,
  1841. 'Antarctica' => DateTimeZone::ANTARCTICA,
  1842. 'Arctic' => DateTimeZone::ARCTIC,
  1843. 'Asia' => DateTimeZone::ASIA,
  1844. 'Atlantic' => DateTimeZone::ATLANTIC,
  1845. 'Australia' => DateTimeZone::AUSTRALIA,
  1846. 'Europe' => DateTimeZone::EUROPE,
  1847. 'Indian' => DateTimeZone::INDIAN,
  1848. 'Pacific' => DateTimeZone::PACIFIC
  1849. );
  1850. $timezones = array();
  1851. foreach ($regions as $name => $mask) {
  1852. $zones = DateTimeZone::listIdentifiers($mask);
  1853. foreach($zones as $timezone) {
  1854. $time = new DateTime(NULL, new DateTimeZone($timezone));
  1855. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  1856. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  1857. }
  1858. }
  1859. print '<select name="timezone" id="timezone" class="form-control material" required>';
  1860. foreach($timezones as $region => $list) {
  1861. print '<optgroup label="' . $region . '">' . "\n";
  1862. foreach($list as $timezone => $name) {
  1863. print '<option value="' . $timezone . '">' . $name . '</option>' . "\n";
  1864. }
  1865. print '</optgroup>' . "\n";
  1866. }
  1867. print '</select>';
  1868. }
  1869. function explosion($string, $position){
  1870. $getWord = explode("|", $string);
  1871. return $getWord[$position];
  1872. }
  1873. function getServerPath() {
  1874. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  1875. $protocol = "https://";
  1876. } else {
  1877. $protocol = "http://";
  1878. }
  1879. return $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
  1880. }
  1881. function get_browser_name() {
  1882. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  1883. if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
  1884. elseif (strpos($user_agent, 'Edge')) return 'Edge';
  1885. elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
  1886. elseif (strpos($user_agent, 'Safari')) return 'Safari';
  1887. elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
  1888. elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
  1889. return 'Other';
  1890. }
  1891. function getSickrageCalendarWanted($array){
  1892. $array = json_decode($array, true);
  1893. $gotCalendar = "";
  1894. $i = 0;
  1895. foreach($array['data']['missed'] AS $child) {
  1896. $i++;
  1897. $seriesName = $child['show_name'];
  1898. $episodeID = $child['tvdbid'];
  1899. $episodeAirDate = $child['airdate'];
  1900. $episodeAirDateTime = explode(" ",$child['airs']);
  1901. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1902. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1903. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1904. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1905. $downloaded = "0";
  1906. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  1907. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1908. }
  1909. foreach($array['data']['today'] AS $child) {
  1910. $i++;
  1911. $seriesName = $child['show_name'];
  1912. $episodeID = $child['tvdbid'];
  1913. $episodeAirDate = $child['airdate'];
  1914. $episodeAirDateTime = explode(" ",$child['airs']);
  1915. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1916. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1917. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1918. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1919. $downloaded = "0";
  1920. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  1921. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1922. }
  1923. foreach($array['data']['soon'] AS $child) {
  1924. $i++;
  1925. $seriesName = $child['show_name'];
  1926. $episodeID = $child['tvdbid'];
  1927. $episodeAirDate = $child['airdate'];
  1928. $episodeAirDateTime = explode(" ",$child['airs']);
  1929. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1930. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1931. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1932. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1933. $downloaded = "0";
  1934. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  1935. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1936. }
  1937. foreach($array['data']['later'] AS $child) {
  1938. $i++;
  1939. $seriesName = $child['show_name'];
  1940. $episodeID = $child['tvdbid'];
  1941. $episodeAirDate = $child['airdate'];
  1942. $episodeAirDateTime = explode(" ",$child['airs']);
  1943. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  1944. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  1945. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1946. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1947. $downloaded = "0";
  1948. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  1949. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1950. }
  1951. if ($i != 0){ return $gotCalendar; }
  1952. }
  1953. function getSickrageCalendarHistory($array){
  1954. $array = json_decode($array, true);
  1955. $gotCalendar = "";
  1956. $i = 0;
  1957. foreach($array['data'] AS $child) {
  1958. $i++;
  1959. $seriesName = $child['show_name'];
  1960. $episodeID = $child['tvdbid'];
  1961. $episodeAirDate = $child['date'];
  1962. $downloaded = "green-bg";
  1963. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1964. }
  1965. if ($i != 0){ return $gotCalendar; }
  1966. }
  1967. function getSonarrCalendar($array){
  1968. $array = json_decode($array, true);
  1969. $gotCalendar = "";
  1970. $i = 0;
  1971. foreach($array AS $child) {
  1972. $i++;
  1973. $seriesName = $child['series']['title'];
  1974. $episodeID = $child['series']['tvdbId'];
  1975. if(!isset($episodeID)){ $episodeID = ""; }
  1976. $episodeName = htmlentities($child['title'], ENT_QUOTES);
  1977. if($child['episodeNumber'] == "1"){ $episodePremier = "true"; }else{ $episodePremier = "false"; }
  1978. $episodeAirDate = $child['airDateUtc'];
  1979. $episodeAirDate = strtotime($episodeAirDate);
  1980. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  1981. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  1982. $downloaded = $child['hasFile'];
  1983. 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"; }
  1984. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  1985. }
  1986. if ($i != 0){ return $gotCalendar; }
  1987. }
  1988. function getRadarrCalendar($array){
  1989. $array = json_decode($array, true);
  1990. $gotCalendar = "";
  1991. $i = 0;
  1992. foreach($array AS $child) {
  1993. if(isset($child['inCinemas'])){
  1994. $i++;
  1995. $movieName = $child['title'];
  1996. $movieID = $child['tmdbId'];
  1997. if(!isset($movieID)){ $movieID = ""; }
  1998. if(isset($child['inCinemas']) && isset($child['physicalRelease'])){
  1999. $physicalRelease = $child['physicalRelease'];
  2000. $physicalRelease = strtotime($physicalRelease);
  2001. $physicalRelease = date("Y-m-d", $physicalRelease);
  2002. if (new DateTime() < new DateTime($physicalRelease)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  2003. $downloaded = $child['hasFile'];
  2004. if($downloaded == "0" && $notReleased == "true"){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg"; }else{ $downloaded = "red-bg"; }
  2005. }else{
  2006. $physicalRelease = $child['inCinemas'];
  2007. $downloaded = "light-blue-bg";
  2008. }
  2009. $gotCalendar .= "{ title: \"$movieName\", start: \"$physicalRelease\", className: \"$downloaded\", imagetype: \"film\", url: \"https://www.themoviedb.org/movie/$movieID\" }, \n";
  2010. }
  2011. }
  2012. if ($i != 0){ return $gotCalendar; }
  2013. }
  2014. function getHeadphonesCalendar($url, $key, $list){
  2015. $url = qualifyURL(HEADPHONESURL);
  2016. $api = file_get_contents($url."/api?apikey=".$key."&cmd=$list");
  2017. $api = json_decode($api, true);
  2018. $i = 0;
  2019. $gotCalendar = "";
  2020. foreach($api AS $child) {
  2021. if($child['Status'] == "Wanted"){
  2022. $i++;
  2023. $albumName = addslashes($child['AlbumTitle']);
  2024. $albumArtist = htmlentities($child['ArtistName'], ENT_QUOTES);
  2025. $albumDate = $child['ReleaseDate'];
  2026. $albumID = $child['AlbumID'];
  2027. $albumDate = strtotime($albumDate);
  2028. $albumDate = date("Y-m-d", $albumDate);
  2029. $albumStatus = $child['Status'];
  2030. if (new DateTime() < new DateTime($albumDate)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  2031. if($albumStatus == "Wanted" && $notReleased == "true"){ $albumStatusColor = "indigo-bg"; }elseif($albumStatus == "Downloaded"){ $albumStatusColor = "green-bg"; }else{ $albumStatusColor = "red-bg"; }
  2032. $gotCalendar .= "{ title: \"$albumArtist - $albumName\", start: \"$albumDate\", className: \"$albumStatusColor\", imagetype: \"music\", url: \"https://musicbrainz.org/release-group/$albumID\" }, \n";
  2033. }
  2034. }
  2035. if ($i != 0){ return $gotCalendar; }
  2036. }
  2037. ?>