functions.php 157 KB

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