functions.php 80 KB

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