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