functions.php 115 KB

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