functions.php 126 KB

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