functions.php 161 KB

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