functions.php 162 KB

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