functions.php 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139
  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. );
  2483. if (array_key_exists($platform, $allPlatforms)) {
  2484. return $allPlatforms[$platform];
  2485. }else{
  2486. return "pmp.png";
  2487. }
  2488. }
  2489. function getServer(){
  2490. $server = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : $_SERVER["SERVER_NAME"];
  2491. return $server;
  2492. }
  2493. function prettyPrint($a) {
  2494. echo "HEADERS: <pre>";
  2495. print_r($a);
  2496. echo "</pre>";
  2497. echo "<br/>";
  2498. }
  2499. function checkFrame($array, $url){
  2500. if(array_key_exists("x-frame-options", $array)){
  2501. if($array['x-frame-options'] == "deny"){
  2502. return false;
  2503. }elseif($array['x-frame-options'] == "sameorgin"){
  2504. $digest = parse_url($url);
  2505. $host = (isset($digest['host'])?$digest['host']:'');
  2506. if(getServer() == $host){
  2507. return true;
  2508. }else{
  2509. return false;
  2510. }
  2511. }
  2512. }else{
  2513. if(!$array){
  2514. return false;
  2515. }
  2516. return true;
  2517. }
  2518. }
  2519. function frameTest($url){
  2520. $array = array_change_key_case(get_headers(qualifyURL($url), 1));
  2521. $url = qualifyURL($url);
  2522. if(checkFrame($array, $url)){
  2523. return true;
  2524. }else{
  2525. return false;
  2526. }
  2527. }
  2528. function sendResult($result, $icon = "floppy-o", $message = false, $success = "WAS_SUCCESSFUL", $fail = "HAS_FAILED", $send = true) {
  2529. $notifyExplode = explode("-", NOTIFYEFFECT);
  2530. if ($result) {
  2531. $msg = array(
  2532. 'html' => ($message?''.$message.' <strong>'.translate($success).'</strong>':'<strong>'.translate($success).'</strong>'),
  2533. 'icon' => $icon,
  2534. 'type' => 'success',
  2535. 'length' => '5000',
  2536. 'layout' => $notifyExplode[0],
  2537. 'effect' => $notifyExplode[1],
  2538. );
  2539. } else {
  2540. $msg = array(
  2541. 'html' => ($message?''.$message.' <strong>'.translate($fail).'</strong>':'<strong>'.translate($fail).'</strong>'),
  2542. 'icon' => $icon,
  2543. 'type' => 'error',
  2544. 'length' => '5000',
  2545. 'layout' => $notifyExplode[0],
  2546. 'effect' => $notifyExplode[1],
  2547. );
  2548. }
  2549. // Send and kill script?
  2550. if ($send) {
  2551. header('Content-Type: application/json');
  2552. echo json_encode(array('notify'=>$msg));
  2553. die();
  2554. }
  2555. return $msg;
  2556. }
  2557. function buildHomepageNotice($layout, $type, $title, $message){
  2558. switch ($layout) {
  2559. case 'elegant':
  2560. return '
  2561. <div id="homepageNotice" class="row">
  2562. <div class="col-lg-12">
  2563. <div class="content-box big-box box-shadow panel-box panel-'.$type.'">
  2564. <div class="content-title i-block">
  2565. <h4 class="zero-m"><strong>'.$title.'</strong></h4>
  2566. <div class="content-tools i-block pull-right">
  2567. <a class="close-btn">
  2568. <i class="fa fa-times"></i>
  2569. </a>
  2570. </div>
  2571. </div>
  2572. '.$message.'
  2573. </div>
  2574. </div>
  2575. </div>
  2576. ';
  2577. break;
  2578. case 'basic':
  2579. return '
  2580. <div id="homepageNotice" class="row">
  2581. <div class="col-lg-12">
  2582. <div class="panel panel-'.$type.'">
  2583. <div class="panel-heading">
  2584. <h3 class="panel-title">'.$title.'</h3>
  2585. </div>
  2586. <div class="panel-body">
  2587. '.$message.'
  2588. </div>
  2589. </div>
  2590. </div>
  2591. </div>
  2592. ';
  2593. break;
  2594. case 'jumbotron';
  2595. return '
  2596. <div id="homepageNotice" class="row">
  2597. <div class="col-lg-12">
  2598. <div class="jumbotron">
  2599. <div class="container">
  2600. <h1>'.$title.'</h1>
  2601. <p>'.$message.'</p>
  2602. </div>
  2603. </div>
  2604. </div>
  2605. </div>
  2606. ';
  2607. }
  2608. }
  2609. function embyArray($array, $type) {
  2610. $key = ($type == "video" ? "Height" : "Channels");
  2611. if (array_key_exists($key, $array)) {
  2612. switch ($type) {
  2613. case "video":
  2614. $codec = $array["Codec"];
  2615. $height = $array["Height"];
  2616. $width = $array["Width"];
  2617. break;
  2618. default:
  2619. $codec = $array["Codec"];
  2620. $channels = $array["Channels"];
  2621. }
  2622. return ($type == "video" ? "(".$codec.") (".$width."x".$height.")" : "(".$codec.") (".$channels."ch)");
  2623. }
  2624. foreach ($array as $element) {
  2625. if (is_array($element)) {
  2626. if (embyArray($element, $type)) {
  2627. return embyArray($element, $type);
  2628. }
  2629. }
  2630. }
  2631. }
  2632. // Get Now Playing Streams From Plex
  2633. function searchPlex($query){
  2634. $address = qualifyURL(PLEXURL);
  2635. // Perform API requests
  2636. $api = @curl_get($address."/search?query=".rawurlencode($query)."&X-Plex-Token=".PLEXTOKEN);
  2637. $api = simplexml_load_string($api);
  2638. $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>";
  2639. $items = "";
  2640. $albums = $movies = $shows = 0;
  2641. $style = 'style="vertical-align: middle"';
  2642. foreach($api AS $child) {
  2643. if($child['type'] != "artist" && $child['type'] != "episode" && isset($child['librarySectionID'])){
  2644. $time = (string)$child['addedAt'];
  2645. $time = new DateTime("@$time");
  2646. $results = array(
  2647. "title" => (string)$child['title'],
  2648. "image" => (string)$child['thumb'],
  2649. "type" => (string)ucwords($child['type']),
  2650. "year" => (string)$child['year'],
  2651. "key" => (string)$child['ratingKey']."-search",
  2652. "genre" => (string)$child->Genre['tag'],
  2653. "added" => $time->format('Y-m-d'),
  2654. "extra" => "",
  2655. );
  2656. switch ($child['type']){
  2657. case "album":
  2658. $push = array(
  2659. "title" => (string)$child['parentTitle']." - ".(string)$child['title'],
  2660. );
  2661. $results = array_replace($results,$push);
  2662. $albums++;
  2663. break;
  2664. case "movie":
  2665. $push = array(
  2666. "extra" => "Content Rating: ".(string)$child['contentRating']."<br/>Movie Rating: ".(string)$child['rating'],
  2667. );
  2668. $results = array_replace($results,$push);
  2669. $movies++;
  2670. break;
  2671. case "show":
  2672. $push = array(
  2673. "extra" => "Seasons: ".(string)$child['childCount']."<br/>Episodes: ".(string)$child['leafCount'],
  2674. );
  2675. $results = array_replace($results,$push);
  2676. $shows++;
  2677. break;
  2678. }
  2679. if (file_exists('images/cache/'.$results['key'].'.jpg')){ $image_url = 'images/cache/'.$results['key'].'.jpg'; }
  2680. if (file_exists('images/cache/'.$results['key'].'.jpg') && (time() - 604800) > filemtime('images/cache/'.$results['key'].'.jpg') || !file_exists('images/cache/'.$results['key'].'.jpg')) {
  2681. $image_url = 'ajax.php?a=plex-image&img='.$results['image'].'&height=150&width=100&key='.$results['key'];
  2682. }
  2683. if(!$results['image']){ $image_url = "images/no-search.png"; $key = "no-search"; }
  2684. $items .= '<tr>
  2685. <th scope="row"><img src="'.$image_url.'"></th>
  2686. <td class="col-xs-2 nzbtable nzbtable-row"'.$style.'>'.$results['title'].'</td>
  2687. <td class="col-xs-3 nzbtable nzbtable-row"'.$style.'>'.$results['genre'].'</td>
  2688. <td class="col-xs-1 nzbtable nzbtable-row"'.$style.'>'.$results['year'].'</td>
  2689. <td class="col-xs-1 nzbtable nzbtable-row"'.$style.'>'.$results['type'].'</td>
  2690. <td class="col-xs-3 nzbtable nzbtable-row"'.$style.'>'.$results['added'].'</td>
  2691. <td class="col-xs-2 nzbtable nzbtable-row"'.$style.'>'.$results['extra'].'</td>
  2692. </tr>';
  2693. }
  2694. }
  2695. $totals = '<div style="margin: 10px;" class="sort-todo pull-right">
  2696. <span class="badge gray-bg"><i class="fa fa-film fa-2x white"></i><strong style="
  2697. font-size: 23px;
  2698. ">&nbsp;'.$movies.'</strong></span>
  2699. <span class="badge gray-bg"><i class="fa fa-tv fa-2x white"></i><strong style="
  2700. font-size: 23px;
  2701. ">&nbsp;'.$shows.'</strong></span>
  2702. <span class="badge gray-bg"><i class="fa fa-music fa-2x white"></i><strong style="
  2703. font-size: 23px;
  2704. ">&nbsp;'.$albums.'</strong></span>
  2705. </div>';
  2706. return (!empty($items) ? $totals.$pre.$items."</div></table>" : "<h2 class='text-center'>No Results for $query</h2>" );
  2707. }
  2708. function getBannedUsers($string){
  2709. if (strpos($string, ',') !== false) {
  2710. $banned = explode(",", $string);
  2711. }else{
  2712. $banned = array($string);
  2713. }
  2714. return $banned;
  2715. }
  2716. function getWhitelist($string){
  2717. if (strpos($string, ',') !== false) {
  2718. $whitelist = explode(",", $string);
  2719. }else{
  2720. $whitelist = array($string);
  2721. }
  2722. foreach($whitelist as &$ip){
  2723. $ip = is_numeric(substr($ip, 0, 1)) ? $ip : gethostbyname($ip);
  2724. }
  2725. return $whitelist;
  2726. }
  2727. function get_client_ip() {
  2728. $ipaddress = '';
  2729. if (isset($_SERVER['HTTP_CLIENT_IP']))
  2730. $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  2731. else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  2732. $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  2733. else if(isset($_SERVER['HTTP_X_FORWARDED']))
  2734. $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  2735. else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
  2736. $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  2737. else if(isset($_SERVER['HTTP_FORWARDED']))
  2738. $ipaddress = $_SERVER['HTTP_FORWARDED'];
  2739. else if(isset($_SERVER['REMOTE_ADDR']))
  2740. $ipaddress = $_SERVER['REMOTE_ADDR'];
  2741. else
  2742. $ipaddress = 'UNKNOWN';
  2743. return $ipaddress;
  2744. }
  2745. // Always run this
  2746. dependCheck();