functions.php 78 KB

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