functions.php 113 KB

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