functions.php 108 KB

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