functions.php 159 KB

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