functions.php 130 KB

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