functions.php 162 KB

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