functions.php 108 KB

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