functions.php 127 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495
  1. <?php
  2. // ===================================
  3. // Define Version
  4. define('INSTALLEDVERSION', '1.40');
  5. // ===================================
  6. // Debugging output functions
  7. function debug_out($variable, $die = false) {
  8. $trace = debug_backtrace()[0];
  9. echo '<pre style="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 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 = $item['ratingKey'] . "-np";
  686. $extraInfo = isset($item['extraType']) ? "Trailer" : (isset($item['live']) ? "Live TV" : ":)");
  687. $elapsed = $item['viewOffset'];
  688. $duration = $item['duration'];
  689. $watched = (!empty($elapsed) ? floor(($elapsed / $duration) * 100) : 0);
  690. $transcoded = floor($item->TranscodeSession['progress']- $watched);
  691. $stream = $item->Media->Part->Stream['decision'];
  692. $user = $role == "admin" ? $item->User['title'] : "";
  693. $id = str_replace('"', '', $item->Player['machineIdentifier']);
  694. $streamInfo = buildStream(array(
  695. 'platform' => (string) $item->Player['platform'],
  696. 'device' => (string) $item->Player['device'],
  697. 'stream' => "&nbsp;".streamType($item->Media->Part['decision']),
  698. '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'].")",
  699. 'audio' => "&nbsp;".streamType($item->Media->Part->Stream[1]['decision'])." (".$item->Media->Part->Stream[1]['codec'].") (".$item->Media->Part->Stream[1]['channels']."ch)",
  700. ));
  701. $state = (($item->Player['state'] == "paused") ? "pause" : "play");
  702. $topTitle = '<h5 class="text-center zero-m elip">'.$title.'</h5>';
  703. $bottomTitle = '<small class="zero-m">'.$extraInfo.'</small>';
  704. if($showNames == "true"){ $bottomTitle .= '<small class="zero-m pull-right">'.$user.'</small>'; }
  705. }
  706. break;
  707. case 'album':
  708. case 'track':
  709. $title = $item['parentTitle'];
  710. $summary = $item['title'];
  711. $image = 'slick-image-short';
  712. $style = 'left: 160px !important;';
  713. $item['ratingKey'] = $item['parentRatingKey'];
  714. if(!$nowPlaying){
  715. $width = 444;
  716. $thumb = $item['thumb'];
  717. $key = $item['ratingKey'] . "-list";
  718. }else {
  719. $height = 281;
  720. $width = 500;
  721. $thumb = $item['art'];
  722. $key = $item['ratingKey'] . "-np";
  723. $elapsed = $item['viewOffset'];
  724. $duration = $item['duration'];
  725. $watched = (!empty($elapsed) ? floor(($elapsed / $duration) * 100) : 0);
  726. $transcoded = floor($item->TranscodeSession['progress']- $watched);
  727. $stream = $item->Media->Part->Stream['decision'];
  728. $user = $role == "admin" ? $item->User['title'] : "";
  729. $id = str_replace('"', '', $item->Player['machineIdentifier']);
  730. $streamInfo = buildStream(array(
  731. 'platform' => (string) $item->Player['platform'],
  732. 'device' => (string) $item->Player['device'],
  733. 'stream' => "&nbsp;".streamType($item->Media->Part['decision']),
  734. 'audio' => "&nbsp;".streamType($item->Media->Part->Stream[0]['decision'])." (".$item->Media->Part->Stream[0]['codec'].") (".$item->Media->Part->Stream[0]['channels']."ch)",
  735. ));
  736. $state = (($item->Player['state'] == "paused") ? "pause" : "play");
  737. $topTitle = '<h5 class="text-center zero-m elip">'.$item['grandparentTitle'].' - '.$item['title'].'</h5>';
  738. $bottomTitle = '<small class="zero-m">'.$title.'</small>';
  739. if($showNames == "true"){ $bottomTitle .= '<small class="zero-m pull-right">'.$user.'</small>'; }
  740. }
  741. break;
  742. default:
  743. $title = $item['title'];
  744. $summary = $item['summary'];
  745. $image = 'slick-image-tall';
  746. $style = '';
  747. if(!$nowPlaying){
  748. $width = 300;
  749. $thumb = $item['thumb'];
  750. $key = $item['ratingKey'] . "-list";
  751. }else {
  752. $height = 281;
  753. $width = 500;
  754. $thumb = $item['art'];
  755. $key = $item['ratingKey'] . "-np";
  756. $elapsed = $item['viewOffset'];
  757. $duration = $item['duration'];
  758. $watched = (!empty($elapsed) ? floor(($elapsed / $duration) * 100) : 0);
  759. $transcoded = floor($item->TranscodeSession['progress']- $watched);
  760. $stream = $item->Media->Part->Stream['decision'];
  761. $user = $role == "admin" ? $item->User['title'] : "";
  762. $id = str_replace('"', '', $item->Player['machineIdentifier']);
  763. $streamInfo = buildStream(array(
  764. 'platform' => (string) $item->Player['platform'],
  765. 'device' => (string) $item->Player['device'],
  766. 'stream' => "&nbsp;".streamType($item->Media->Part['decision']),
  767. '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'].")",
  768. 'audio' => "&nbsp;".streamType($item->Media->Part->Stream[1]['decision'])." (".$item->Media->Part->Stream[1]['codec'].") (".$item->Media->Part->Stream[1]['channels']."ch)",
  769. ));
  770. $state = (($item->Player['state'] == "paused") ? "pause" : "play");
  771. $topTitle = '<h5 class="text-center zero-m elip">'.$title.'</h5>';
  772. $bottomTitle = '<small class="zero-m">'.$item['year'].'</small>';
  773. if($showNames == "true"){ $bottomTitle .= '<small class="zero-m pull-right">'.$user.'</small>'; }
  774. }
  775. }
  776. if (substr_count(PLEXURL, ':') == 2) {
  777. $address = "https://app.plex.tv/web/app#!/server/$server/details?key=/library/metadata/".$item['ratingKey'];
  778. }else{
  779. $address = PLEXURL."/web/index.html#!/server/$server/details?key=/library/metadata/".$item['ratingKey'];
  780. }
  781. // If No Overview
  782. if (!isset($itemDetails['Overview'])) { $itemDetails['Overview'] = ''; }
  783. if (file_exists('images/cache/'.$key.'.jpg')){ $image_url = 'images/cache/'.$key.'.jpg'; }
  784. if (file_exists('images/cache/'.$key.'.jpg') && (time() - 604800) > filemtime('images/cache/'.$key.'.jpg') || !file_exists('images/cache/'.$key.'.jpg')) {
  785. $image_url = 'ajax.php?a=plex-image&img='.$thumb.'&height='.$height.'&width='.$width.'&key='.$key.'';
  786. }
  787. if(!$thumb){ $image_url = "images/no-np.png"; $key = "no-np"; }
  788. $openTab = (PLEXTABNAME) ? "true" : "false";
  789. // Assemble Item And Cache Into Array
  790. if($nowPlaying){
  791. 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>';
  792. }else{
  793. 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>';
  794. }
  795. }
  796. //Recent Added
  797. function outputRecentAdded($header, $items, $script = false, $array) {
  798. $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">';
  799. if($array["movie"] == "true"){
  800. $hideMenu .= '<li><a class="js-filter-movie" href="javascript:void(0)">Hide Movies</a></li>';
  801. }
  802. if($array["season"] == "true"){
  803. $hideMenu .= '<li><a class="js-filter-season" href="javascript:void(0)">Hide Show</a></li>';
  804. }
  805. if($array["album"] == "true"){
  806. $hideMenu .= '<li><a class="js-filter-album" href="javascript:void(0)">Hide Music</a></li>';
  807. }
  808. $hideMenu .= '</ul></div></div>';
  809. // If None Populate Empty Item
  810. if (!count($items)) {
  811. return '<div id=recentMedia><h5 class="text-center">'.$header.'</h5><p class="text-center">No Media Found</p></div>';
  812. }else{
  813. 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>':'');
  814. }
  815. }
  816. // Create Carousel
  817. function outputNowPlaying($header, $size, $type, $items, $script = false) {
  818. // If None Populate Empty Item
  819. if (!count($items)) {
  820. return '<div id=streamz></div>'.($script?'<script>'.$script.'</script>':'');
  821. }else{
  822. return '<div id=streamz><h5 class="text-center">'.$header.'</h5>'.implode('',$items).'</div>'.($script?'<script>'.$script.'</script>':'');
  823. }
  824. }
  825. // Get Now Playing Streams From Emby
  826. function getEmbyStreams($size, $showNames, $role) {
  827. $address = qualifyURL(EMBYURL);
  828. $api = json_decode(@file_get_contents($address.'/Sessions?api_key='.EMBYTOKEN),true);
  829. if (!is_array($api)) { return 'Could not load!'; }
  830. $playingItems = array();
  831. foreach($api as $key => $value) {
  832. if (isset($value['NowPlayingItem'])) {
  833. $playingItems[] = resolveEmbyItem($address, EMBYTOKEN, $value['NowPlayingItem'], true, $showNames, $role, $value);
  834. }
  835. }
  836. return outputNowPlaying(translate('PLAYING_NOW_ON_EMBY'), $size, 'streams-emby', $playingItems, "
  837. setInterval(function() {
  838. $('<div></div>').load('ajax.php?a=emby-streams',function() {
  839. var element = $(this).find('[id]');
  840. var loadedID = element.attr('id');
  841. $('#'+loadedID).replaceWith(element);
  842. console.log('Loaded updated: '+loadedID);
  843. });
  844. }, 15000);
  845. ");
  846. }
  847. // Get Now Playing Streams From Plex
  848. function getPlexStreams($size, $showNames, $role){
  849. $address = qualifyURL(PLEXURL);
  850. // Perform API requests
  851. $api = @curl_get($address."/status/sessions?X-Plex-Token=".PLEXTOKEN);
  852. $api = simplexml_load_string($api);
  853. $getServer = simplexml_load_string(@curl_get($address."/?X-Plex-Token=".PLEXTOKEN));
  854. if (!$getServer) { return 'Could not load!'; }
  855. // Identify the local machine
  856. $gotServer = $getServer['machineIdentifier'];
  857. $items = array();
  858. foreach($api AS $child) {
  859. $items[] = resolvePlexItem($gotServer, PLEXTOKEN, $child, true, $showNames, $role);
  860. }
  861. return outputNowPlaying(translate('PLAYING_NOW_ON_PLEX'), $size, 'streams-plex', $items, "
  862. setInterval(function() {
  863. $('<div></div>').load('ajax.php?a=plex-streams',function() {
  864. var element = $(this).find('[id]');
  865. var loadedID = element.attr('id');
  866. $('#'+loadedID).replaceWith(element);
  867. console.log('Loaded updated: '+loadedID);
  868. });
  869. }, 15000);
  870. ");
  871. }
  872. // Get Recent Content From Emby
  873. function getEmbyRecent($array) {
  874. $address = qualifyURL(EMBYURL);
  875. $header = translate('RECENT_CONTENT');
  876. // Currently Logged In User
  877. $username = false;
  878. if (isset($GLOBALS['USER'])) {
  879. $username = strtolower($GLOBALS['USER']->username);
  880. }
  881. // Get A User
  882. $userIds = json_decode(@file_get_contents($address.'/Users?api_key='.EMBYTOKEN),true);
  883. if (!is_array($userIds)) { return 'Could not load!'; }
  884. $showPlayed = true;
  885. foreach ($userIds as $value) { // Scan for admin user
  886. if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
  887. $userId = $value['Id'];
  888. }
  889. if ($username && strtolower($value['Name']) == $username) {
  890. $userId = $value['Id'];
  891. $showPlayed = false;
  892. break;
  893. }
  894. }
  895. // Get the latest Items
  896. $latest = json_decode(file_get_contents($address.'/Users/'.$userId.'/Items/Latest?EnableImages=false&Limit='.EMBYRECENTITEMS.'&api_key='.EMBYTOKEN.($showPlayed?'':'&IsPlayed=false')),true);
  897. // For Each Item In Category
  898. $items = array();
  899. foreach ($latest as $k => $v) {
  900. $type = (string) $v['Type'];
  901. if(@$array[$type] == "true"){
  902. $items[] = resolveEmbyItem($address, EMBYTOKEN, $v, false, false, false);
  903. }
  904. }
  905. $array["movie"] = $array["Movie"];
  906. $array["season"] = $array["Episode"];
  907. $array["album"] = $array["MusicAlbum"];
  908. unset($array["Movie"]);
  909. unset($array["Episode"]);
  910. unset($array["MusicAlbum"]);
  911. unset($array["Series"]);
  912. return outputRecentAdded($header, $items, "", $array);
  913. }
  914. // Get Recent Content From Plex
  915. function getPlexRecent($array){
  916. $address = qualifyURL(PLEXURL);
  917. $header = translate('RECENT_CONTENT');
  918. // Perform Requests
  919. $api = @curl_get($address."/library/recentlyAdded?limit=".PLEXRECENTITEMS."&X-Plex-Token=".PLEXTOKEN);
  920. $api = simplexml_load_string($api);
  921. $getServer = simplexml_load_string(@curl_get($address."/?X-Plex-Token=".PLEXTOKEN));
  922. if (!$getServer) { return 'Could not load!'; }
  923. // Identify the local machine
  924. $gotServer = $getServer['machineIdentifier'];
  925. $items = array();
  926. foreach($api AS $child) {
  927. $type = (string) $child['type'];
  928. if($array[$type] == "true"){
  929. $items[] = resolvePlexItem($gotServer, PLEXTOKEN, $child, false, false, false);
  930. }
  931. }
  932. return outputRecentAdded($header, $items, "", $array);
  933. }
  934. // Get Image From Emby
  935. function getEmbyImage() {
  936. $embyAddress = qualifyURL(EMBYURL);
  937. if (!file_exists('images/cache')) {
  938. mkdir('images/cache', 0777, true);
  939. }
  940. $itemId = $_GET['img'];
  941. $key = $_GET['key'];
  942. $itemType = $_GET['type'];
  943. $imgParams = array();
  944. if (isset($_GET['height'])) { $imgParams['height'] = 'maxHeight='.$_GET['height']; }
  945. if (isset($_GET['width'])) { $imgParams['width'] = 'maxWidth='.$_GET['width']; }
  946. if(isset($itemId)) {
  947. $image_src = $embyAddress . '/Items/'.$itemId.'/Images/'.$itemType.'?'.implode('&', $imgParams);
  948. $cachefile = 'images/cache/'.$key.'.jpg';
  949. $cachetime = 604800;
  950. // Serve from the cache if it is younger than $cachetime
  951. if (file_exists($cachefile) && time() - $cachetime > filemtime($cachefile)) {
  952. header("Content-type: image/jpeg");
  953. @readfile($cachefile);
  954. exit;
  955. }
  956. ob_start(); // Start the output buffer
  957. header('Content-type: image/jpeg');
  958. @readfile($image_src);
  959. // Cache the output to a file
  960. $fp = fopen($cachefile, 'wb');
  961. fwrite($fp, ob_get_contents());
  962. fclose($fp);
  963. ob_end_flush(); // Send the output to the browser
  964. die();
  965. } else {
  966. debug_out('Invalid Request',1);
  967. }
  968. }
  969. // Get Image From Plex
  970. function getPlexImage() {
  971. $plexAddress = qualifyURL(PLEXURL);
  972. if (!file_exists('images/cache')) {
  973. mkdir('images/cache', 0777, true);
  974. }
  975. $image_url = $_GET['img'];
  976. $key = $_GET['key'];
  977. $image_height = $_GET['height'];
  978. $image_width = $_GET['width'];
  979. if(isset($image_url) && isset($image_height) && isset($image_width)) {
  980. $image_src = $plexAddress . '/photo/:/transcode?height='.$image_height.'&width='.$image_width.'&upscale=1&url=' . $image_url . '&X-Plex-Token=' . PLEXTOKEN;
  981. $cachefile = 'images/cache/'.$key.'.jpg';
  982. $cachetime = 604800;
  983. // Serve from the cache if it is younger than $cachetime
  984. if (file_exists($cachefile) && time() - $cachetime > filemtime($cachefile)) {
  985. header("Content-type: image/jpeg");
  986. @readfile($cachefile);
  987. exit;
  988. }
  989. ob_start(); // Start the output buffer
  990. header('Content-type: image/jpeg');
  991. @readfile($image_src);
  992. // Cache the output to a file
  993. $fp = fopen($cachefile, 'wb');
  994. fwrite($fp, ob_get_contents());
  995. fclose($fp);
  996. ob_end_flush(); // Send the output to the browser
  997. die();
  998. } else {
  999. echo "Invalid Plex Request";
  1000. }
  1001. }
  1002. // Simplier access to class
  1003. function translate($string) {
  1004. if (isset($GLOBALS['language'])) {
  1005. return $GLOBALS['language']->translate($string);
  1006. } else {
  1007. return '!Translations Not Loaded!';
  1008. }
  1009. }
  1010. // Generate Random string
  1011. function randString($length = 10, $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
  1012. $tmp = '';
  1013. for ($i = 0; $i < $length; $i++) {
  1014. $tmp .= substr(str_shuffle($chars), 0, 1);
  1015. }
  1016. return $tmp;
  1017. }
  1018. // Create config file in the return syntax
  1019. function createConfig($array, $path = 'config/config.php', $nest = 0) {
  1020. // Define Initial Value
  1021. $output = array();
  1022. // Sort Items
  1023. ksort($array);
  1024. // Update the current config version
  1025. if (!$nest) {
  1026. // Inject Current Version
  1027. $output[] = "\t'CONFIG_VERSION' => '".(isset($array['apply_CONFIG_VERSION'])?$array['apply_CONFIG_VERSION']:INSTALLEDVERSION)."'";
  1028. }
  1029. unset($array['CONFIG_VERSION']);
  1030. unset($array['apply_CONFIG_VERSION']);
  1031. // Process Settings
  1032. foreach ($array as $k => $v) {
  1033. $allowCommit = true;
  1034. switch (gettype($v)) {
  1035. case 'boolean':
  1036. $item = ($v?'true':'false');
  1037. break;
  1038. case 'integer':
  1039. case 'double':
  1040. case 'integer':
  1041. case 'NULL':
  1042. $item = $v;
  1043. break;
  1044. case 'string':
  1045. $item = "'".str_replace(array('\\',"'"),array('\\\\',"\'"),$v)."'";
  1046. break;
  1047. case 'array':
  1048. $item = createConfig($v, false, $nest+1);
  1049. break;
  1050. default:
  1051. $allowCommit = false;
  1052. }
  1053. if($allowCommit) {
  1054. $output[] = str_repeat("\t",$nest+1)."'$k' => $item";
  1055. }
  1056. }
  1057. // Build output
  1058. $output = (!$nest?"<?php\nreturn ":'')."array(\n".implode(",\n",$output)."\n".str_repeat("\t",$nest).')'.(!$nest?';':'');
  1059. if (!$nest && $path) {
  1060. $pathDigest = pathinfo($path);
  1061. @mkdir($pathDigest['dirname'], 0770, true);
  1062. if (file_exists($path)) {
  1063. rename($path, $pathDigest['dirname'].'/'.$pathDigest['filename'].'.bak.php');
  1064. }
  1065. $file = fopen($path, 'w');
  1066. fwrite($file, $output);
  1067. fclose($file);
  1068. if (file_exists($path)) {
  1069. return true;
  1070. }
  1071. writeLog("error", "config was unable to write");
  1072. return false;
  1073. } else {
  1074. writeLog("success", "config was updated with new values");
  1075. return $output;
  1076. }
  1077. }
  1078. // Load a config file written in the return syntax
  1079. function loadConfig($path = 'config/config.php') {
  1080. // Adapted from http://stackoverflow.com/a/14173339/6810513
  1081. if (!is_file($path)) {
  1082. return null;
  1083. } else {
  1084. return (array) call_user_func(function() use($path) {
  1085. return include($path);
  1086. });
  1087. }
  1088. }
  1089. // Commit new values to the configuration
  1090. function updateConfig($new, $current = false) {
  1091. // Get config if not supplied
  1092. if ($current === false) {
  1093. $current = loadConfig();
  1094. } else if (is_string($current) && is_file($current)) {
  1095. $current = loadConfig($current);
  1096. }
  1097. // Inject Parts
  1098. foreach ($new as $k => $v) {
  1099. $current[$k] = $v;
  1100. }
  1101. // Return Create
  1102. return createConfig($current);
  1103. }
  1104. // Inject Defaults As Needed
  1105. function fillDefaultConfig($array, $path = 'config/configDefaults.php') {
  1106. if (is_string($path)) {
  1107. $loadedDefaults = loadConfig($path);
  1108. } else {
  1109. $loadedDefaults = $path;
  1110. }
  1111. return (is_array($loadedDefaults) ? fillDefaultConfig_recurse($array, $loadedDefaults) : false);
  1112. }
  1113. // support function for fillDefaultConfig()
  1114. function fillDefaultConfig_recurse($current, $defaults) {
  1115. foreach($defaults as $k => $v) {
  1116. if (!isset($current[$k])) {
  1117. $current[$k] = $v;
  1118. } else if (is_array($current[$k]) && is_array($v)) {
  1119. $current[$k] = fillDefaultConfig_recurse($current[$k], $v);
  1120. }
  1121. }
  1122. return $current;
  1123. };
  1124. // Define Scalar Variables (nest non-secular with underscores)
  1125. function defineConfig($array, $anyCase = true, $nest_prefix = false) {
  1126. foreach($array as $k => $v) {
  1127. if (is_scalar($v) && !defined($nest_prefix.$k)) {
  1128. define($nest_prefix.$k, $v, $anyCase);
  1129. } else if (is_array($v)) {
  1130. defineConfig($v, $anyCase, $nest_prefix.$k.'_');
  1131. }
  1132. }
  1133. }
  1134. // This function exists only because I am lazy
  1135. function configLazy($path = 'config/config.php') {
  1136. // Load config or default
  1137. if (file_exists($path)) {
  1138. $config = fillDefaultConfig(loadConfig($path));
  1139. } else {
  1140. $config = loadConfig('config/configDefaults.php');
  1141. }
  1142. if (is_array($config)) {
  1143. defineConfig($config);
  1144. }
  1145. return $config;
  1146. }
  1147. // Qualify URL
  1148. function qualifyURL($url) {
  1149. //local address?
  1150. if(substr($url, 0,1) == "/"){
  1151. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  1152. $protocol = "https://";
  1153. } else {
  1154. $protocol = "http://";
  1155. }
  1156. $url = $protocol.getServer().$url;
  1157. }
  1158. // Get Digest
  1159. $digest = parse_url($url);
  1160. // http/https
  1161. if (!isset($digest['scheme'])) {
  1162. if (isset($digest['port']) && in_array($digest['port'], array(80,8080,8096,32400,7878,8989,8182,8081,6789))) {
  1163. $scheme = 'http';
  1164. } else {
  1165. $scheme = 'https';
  1166. }
  1167. } else {
  1168. $scheme = $digest['scheme'];
  1169. }
  1170. // Host
  1171. $host = (isset($digest['host'])?$digest['host']:'');
  1172. // Port
  1173. $port = (isset($digest['port'])?':'.$digest['port']:'');
  1174. // Path
  1175. $path = (isset($digest['path'])?$digest['path']:'');
  1176. // Output
  1177. return $scheme.'://'.$host.$port.$path;
  1178. }
  1179. // Function to be called at top of each to allow upgrading environment as the spec changes
  1180. function upgradeCheck() {
  1181. // Upgrade to 1.31
  1182. if (file_exists('homepageSettings.ini.php')) {
  1183. $databaseConfig = parse_ini_file('databaseLocation.ini.php', true);
  1184. $homepageConfig = parse_ini_file('homepageSettings.ini.php', true);
  1185. $databaseConfig = array_merge($databaseConfig, $homepageConfig);
  1186. $databaseData = '; <?php die("Access denied"); ?>' . "\r\n";
  1187. foreach($databaseConfig as $k => $v) {
  1188. if(substr($v, -1) == "/") : $v = rtrim($v, "/"); endif;
  1189. $databaseData .= $k . " = \"" . $v . "\"\r\n";
  1190. }
  1191. write_ini_file($databaseData, 'databaseLocation.ini.php');
  1192. unlink('homepageSettings.ini.php');
  1193. unset($databaseData);
  1194. unset($homepageConfig);
  1195. }
  1196. // Upgrade to 1.32
  1197. if (file_exists('databaseLocation.ini.php')) {
  1198. // Load Existing
  1199. $config = parse_ini_file('databaseLocation.ini.php', true);
  1200. // Refactor
  1201. $config['database_Location'] = preg_replace('/\/\/$/','/',$config['databaseLocation'].'/');
  1202. $config['user_home'] = $config['database_Location'].'users/';
  1203. unset($config['databaseLocation']);
  1204. // Turn Off Emby And Plex Recent
  1205. $config["embyURL"] = $config["embyURL"].(!empty($config["embyPort"])?':'.$config["embyPort"]:'');
  1206. unset($config["embyPort"]);
  1207. $config["plexURL"] = $config["plexURL"].(!empty($config["plexPort"])?':'.$config["plexPort"]:'');
  1208. unset($config["plexPort"]);
  1209. $config["nzbgetURL"] = $config["nzbgetURL"].(!empty($config["nzbgetPort"])?':'.$config["nzbgetPort"]:'');
  1210. unset($config["nzbgetPort"]);
  1211. $config["sabnzbdURL"] = $config["sabnzbdURL"].(!empty($config["sabnzbdPort"])?':'.$config["sabnzbdPort"]:'');
  1212. unset($config["sabnzbdPort"]);
  1213. $config["headphonesURL"] = $config["headphonesURL"].(!empty($config["headphonesPort"])?':'.$config["headphonesPort"]:'');
  1214. unset($config["headphonesPort"]);
  1215. // Write config file
  1216. $config['CONFIG_VERSION'] = '1.32';
  1217. copy('config/config.php', 'config/config['.date('Y-m-d_H-i-s').'][pre1.32].bak.php');
  1218. $createConfigSuccess = createConfig($config);
  1219. // Create new config
  1220. if ($createConfigSuccess) {
  1221. if (file_exists('config/config.php')) {
  1222. // Remove Old ini file
  1223. unlink('databaseLocation.ini.php');
  1224. } else {
  1225. debug_out('Something is not right here!');
  1226. }
  1227. } else {
  1228. debug_out('Couldn\'t create updated configuration.' ,1);
  1229. }
  1230. }
  1231. // Upgrade to 1.33
  1232. $config = loadConfig();
  1233. if (isset($config['database_Location']) && (!isset($config['CONFIG_VERSION']) || $config['CONFIG_VERSION'] < '1.33')) {
  1234. // Fix User Directory
  1235. $config['database_Location'] = preg_replace('/\/\/$/','/',$config['database_Location'].'/');
  1236. $config['user_home'] = $config['database_Location'].'users/';
  1237. unset($config['USER_HOME']);
  1238. // Backend auth merge
  1239. if (isset($config['authBackendPort']) && !isset(parse_url($config['authBackendHost'])['port'])) {
  1240. $config['authBackendHost'] .= ':'.$config['authBackendPort'];
  1241. }
  1242. unset($config['authBackendPort']);
  1243. // If auth is being used move it to embyURL as that is now used in auth functions
  1244. 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')))) {
  1245. $config['embyURL'] = $config['authBackendHost'];
  1246. }
  1247. // Upgrade database to latest version
  1248. updateSQLiteDB($config['database_Location'],'1.32');
  1249. // Update Version and Commit
  1250. $config['apply_CONFIG_VERSION'] = '1.33';
  1251. copy('config/config.php', 'config/config['.date('Y-m-d_H-i-s').'][1.32].bak.php');
  1252. $createConfigSuccess = createConfig($config);
  1253. unset($config);
  1254. }
  1255. // Upgrade to 1.34
  1256. $config = loadConfig();
  1257. if (isset($config['database_Location']) && (!isset($config['CONFIG_VERSION']) || $config['CONFIG_VERSION'] < '1.34')) {
  1258. // Upgrade database to latest version
  1259. updateSQLiteDB($config['database_Location'],'1.33');
  1260. // Update Version and Commit
  1261. $config['CONFIG_VERSION'] = '1.34';
  1262. copy('config/config.php', 'config/config['.date('Y-m-d_H-i-s').'][1.33].bak.php');
  1263. $createConfigSuccess = createConfig($config);
  1264. unset($config);
  1265. }
  1266. // Upgrade to 1.40
  1267. $config = loadConfig();
  1268. if (isset($config['database_Location']) && (!isset($config['CONFIG_VERSION']) || $config['CONFIG_VERSION'] < '1.40')) {
  1269. // Upgrade database to latest version
  1270. updateSQLiteDB($config['database_Location'],'1.38');
  1271. // Update Version and Commit
  1272. $config['CONFIG_VERSION'] = '1.40';
  1273. copy('config/config.php', 'config/config['.date('Y-m-d_H-i-s').'][1.38].bak.php');
  1274. $createConfigSuccess = createConfig($config);
  1275. unset($config);
  1276. }
  1277. return true;
  1278. }
  1279. // Check if all software dependancies are met
  1280. function dependCheck() {
  1281. $output = array();
  1282. if (!extension_loaded('pdo_sqlite')) { $output[] = 'PDO:SQLite not enabled, please add "extension = php_pdo_sqlite.dll" to php.ini'; }
  1283. //if (!extension_loaded('sqlite3')) { $output[] = 'SQLite3 not enabled, please add "extension = php_sqlite3.dll" to php.ini'; }
  1284. if ($output) {
  1285. debug_out($output,1);
  1286. }
  1287. return true;
  1288. }
  1289. // Process file uploads
  1290. function uploadFiles($path, $ext_mask = null) {
  1291. if (isset($_FILES) && count($_FILES)) {
  1292. require_once('class.uploader.php');
  1293. $uploader = new Uploader();
  1294. $data = $uploader->upload($_FILES['files'], array(
  1295. 'limit' => 10,
  1296. 'maxSize' => 10,
  1297. 'extensions' => $ext_mask,
  1298. 'required' => false,
  1299. 'uploadDir' => str_replace('//','/',$path.'/'),
  1300. 'title' => array('name'),
  1301. 'removeFiles' => true,
  1302. 'replace' => true,
  1303. ));
  1304. if($data['isComplete']){
  1305. $files = $data['data'];
  1306. writeLog("success", $files['metas'][0]['name']." was uploaded");
  1307. echo json_encode($files['metas'][0]['name']);
  1308. }
  1309. if($data['hasErrors']){
  1310. $errors = $data['errors'];
  1311. writeLog("error", $files['metas'][0]['name']." was not able to upload");
  1312. echo json_encode($errors);
  1313. }
  1314. } else {
  1315. writeLog("error", "image was not uploaded");
  1316. echo json_encode('No files submitted!');
  1317. }
  1318. }
  1319. // Remove file
  1320. function removeFiles($path) {
  1321. if(is_file($path)) {
  1322. writeLog("success", "image was removed");
  1323. unlink($path);
  1324. } else {
  1325. writeLog("error", "image was not removed");
  1326. echo json_encode('No file specified for removal!');
  1327. }
  1328. }
  1329. // Lazy select options
  1330. function resolveSelectOptions($array, $selected = '', $multi = false) {
  1331. $output = array();
  1332. $selectedArr = ($multi?explode('|', $selected):array());
  1333. foreach ($array as $key => $value) {
  1334. if (is_array($value)) {
  1335. if (isset($value['optgroup'])) {
  1336. $output[] = '<optgroup label="'.$key.'">';
  1337. foreach($value['optgroup'] as $k => $v) {
  1338. $output[] = '<option value="'.$v['value'].'"'.($selected===$v['value']||in_array($v['value'],$selectedArr)?' selected':'').(isset($v['disabled']) && $v['disabled']?' disabled':'').'>'.$k.'</option>';
  1339. }
  1340. } else {
  1341. $output[] = '<option value="'.$value['value'].'"'.($selected===$value['value']||in_array($value['value'],$selectedArr)?' selected':'').(isset($value['disabled']) && $value['disabled']?' disabled':'').'>'.$key.'</option>';
  1342. }
  1343. } else {
  1344. $output[] = '<option value="'.$value.'"'.($selected===$value||in_array($value,$selectedArr)?' selected':'').'>'.$key.'</option>';
  1345. }
  1346. }
  1347. return implode('',$output);
  1348. }
  1349. // Check if user is allowed to continue
  1350. function qualifyUser($type, $errOnFail = false) {
  1351. if (!isset($GLOBALS['USER'])) {
  1352. require_once("user.php");
  1353. $GLOBALS['USER'] = new User('registration_callback');
  1354. }
  1355. if (is_bool($type)) {
  1356. if ($type === true) {
  1357. $authorized = ($GLOBALS['USER']->authenticated == true);
  1358. } else {
  1359. $authorized = true;
  1360. }
  1361. } elseif (is_string($type) || is_array($type)) {
  1362. if ($type !== 'false') {
  1363. if (!is_array($type)) {
  1364. $type = explode('|',$type);
  1365. }
  1366. $authorized = ($GLOBALS['USER']->authenticated && in_array($GLOBALS['USER']->role,$type));
  1367. } else {
  1368. $authorized = true;
  1369. }
  1370. } else {
  1371. debug_out('Invalid Syntax!',1);
  1372. }
  1373. if (!$authorized && $errOnFail) {
  1374. if ($GLOBALS['USER']->authenticated) {
  1375. header('Location: error.php?error=401');
  1376. echo '<script>window.location.href = \''.dirname($_SERVER['SCRIPT_NAME']).'/error.php?error=401\'</script>';
  1377. } else {
  1378. header('Location: error.php?error=999');
  1379. echo '<script>window.location.href = \''.dirname($_SERVER['SCRIPT_NAME']).'/error.php?error=999\'</script>';
  1380. }
  1381. debug_out('Not Authorized' ,1);
  1382. } else {
  1383. return $authorized;
  1384. }
  1385. }
  1386. // Build an (optionally) tabbed settings page.
  1387. function buildSettings($array) {
  1388. /*
  1389. array(
  1390. 'title' => '',
  1391. 'id' => '',
  1392. 'fields' => array( See buildField() ),
  1393. 'tabs' => array(
  1394. array(
  1395. 'title' => '',
  1396. 'id' => '',
  1397. 'image' => '',
  1398. 'fields' => array( See buildField() ),
  1399. ),
  1400. ),
  1401. );
  1402. */
  1403. $notifyExplode = explode("-", NOTIFYEFFECT);
  1404. $fieldFunc = function($fieldArr) {
  1405. $fields = '<div class="row">';
  1406. foreach($fieldArr as $key => $value) {
  1407. $isSingle = isset($value['type']);
  1408. if ($isSingle) { $value = array($value); }
  1409. $tmpField = '';
  1410. $sizeLg = max(floor(12/count($value)),2);
  1411. $sizeMd = max(floor(($isSingle?12:6)/count($value)),3);
  1412. foreach($value as $k => $v) {
  1413. $tmpField .= buildField($v, 12, $sizeMd, $sizeLg);
  1414. }
  1415. $fields .= ($isSingle?$tmpField:'<div class="row col-sm-12 content-form">'.$tmpField.'</div>');
  1416. }
  1417. $fields .= '</div>';
  1418. return $fields;
  1419. };
  1420. $fields = (isset($array['fields'])?$fieldFunc($array['fields']):'');
  1421. $tabSelectors = array();
  1422. $tabContent = array();
  1423. if (isset($array['tabs'])) {
  1424. foreach($array['tabs'] as $key => $value) {
  1425. $id = (isset($value['id'])?$value['id']:randString(32));
  1426. $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>';
  1427. $tabContent[$key] = '<div class="tab-pane big-box fade'.($tabContent?'':' active in').'" id="tab-'.$id.'">'.$fieldFunc($value['fields']).'</div>';
  1428. }
  1429. }
  1430. $pageID = (isset($array['id'])?$array['id']:str_replace(array(' ','"',"'"),array('_'),strtolower($array['id'])));
  1431. return '
  1432. <div class="email-body">
  1433. <div class="email-header gray-bg">
  1434. <button type="button" class="btn btn-danger btn-sm waves close-button"><i class="fa fa-close"></i></button>
  1435. <h1>'.$array['title'].'</h1>
  1436. </div>
  1437. <div class="email-inner small-box">
  1438. <div class="email-inner-section">
  1439. <div class="small-box fade in" id="'.$pageID.'_frame">
  1440. <div class="col-lg-12">
  1441. '.(isset($array['customBeforeForm'])?$array['customBeforeForm']:'').'
  1442. <form class="content-form" name="'.$pageID.'" id="'.$pageID.'_form" onsubmit="return false;">
  1443. <button id="'.$pageID.'_form_submit" class="btn waves btn-labeled btn-success btn btn-sm pull-right text-uppercase waves-effect waves-float">
  1444. <span class="btn-label"><i class="fa fa-floppy-o"></i></span>Save
  1445. </button>
  1446. '.$fields.($tabContent?'
  1447. <div class="tabbable tabs-with-bg" id="'.$pageID.'_tabs">
  1448. <ul class="nav nav-tabs apps">
  1449. '.implode('', $tabSelectors).'
  1450. </ul>
  1451. <div class="clearfix"></div>
  1452. <div class="tab-content">
  1453. '.implode('', $tabContent).'
  1454. </div>
  1455. </div>':'').'
  1456. </form>
  1457. '.(isset($array['customAfterForm'])?$array['customAfterForm']:'').'
  1458. </div>
  1459. </div>
  1460. </div>
  1461. </div>
  1462. </div>
  1463. <script>
  1464. $(document).ready(function() {
  1465. $(\'#'.$pageID.'_form\').find(\'input, select, textarea\').on(\'change\', function() { $(this).attr(\'data-changed\', \'true\'); });
  1466. var '.$pageID.'Validate = function() { if (this.value && !RegExp(\'^\'+this.pattern+\'$\').test(this.value)) { $(this).addClass(\'invalid\'); } else { $(this).removeClass(\'invalid\'); } };
  1467. $(\'#'.$pageID.'_form\').find(\'input[pattern]\').each('.$pageID.'Validate).on(\'keyup\', '.$pageID.'Validate);
  1468. $(\'#'.$pageID.'_form\').find(\'select[multiple]\').on(\'change click\', function() { $(this).attr(\'data-changed\', \'true\'); });
  1469. $(\'#'.$pageID.'_form_submit\').on(\'click\', function () {
  1470. var newVals = {};
  1471. var hasVals = false;
  1472. var errorFields = [];
  1473. $(\'#'.$pageID.'_form\').find(\'[data-changed=true][name]\').each(function() {
  1474. hasVals = true;
  1475. if (this.type == \'checkbox\') {
  1476. newVals[this.name] = this.checked;
  1477. } else if ($(this).hasClass(\'summernote\')) {
  1478. newVals[$(this).attr(\'name\')] = $(this).siblings(\'.note-editor\').find(\'.panel-body\').html();
  1479. } else {
  1480. if (this.value && this.pattern && !RegExp(\'^\'+this.pattern+\'$\').test(this.value)) { errorFields.push(this.name); }
  1481. var fieldVal = $(this).val();
  1482. if (typeof fieldVal == \'object\') {
  1483. if (typeof fieldVal.join == \'function\') {
  1484. fieldVal = fieldVal.join(\'|\');
  1485. } else {
  1486. fieldVal = JSON.stringify(fieldVal);
  1487. }
  1488. }
  1489. newVals[this.name] = fieldVal;
  1490. }
  1491. });
  1492. if (errorFields.length) {
  1493. parent.notify(\'Fields have errors: \'+errorFields.join(\', \')+\'!\', \'bullhorn\', \'error\', 5000, \''.$notifyExplode[0].'\', \''.$notifyExplode[1].'\');
  1494. } else if (hasVals) {
  1495. console.log(newVals);
  1496. ajax_request(\'POST\', \''.(isset($array['submitAction'])?$array['submitAction']:'update-config').'\', newVals, function(data, code) {
  1497. $(\'#'.$pageID.'_form\').find(\'[data-changed=true][name]\').removeAttr(\'data-changed\');
  1498. });
  1499. } else {
  1500. parent.notify(\'Nothing to update!\', \'bullhorn\', \'error\', 5000, \''.$notifyExplode[0].'\', \''.$notifyExplode[1].'\');
  1501. }
  1502. return false;
  1503. });
  1504. '.(isset($array['onready'])?$array['onready']:'').'
  1505. });
  1506. </script>
  1507. ';
  1508. }
  1509. // Build Settings Fields
  1510. function buildField($params, $sizeSm = 12, $sizeMd = 12, $sizeLg = 12) {
  1511. /*
  1512. array(
  1513. 'type' => '',
  1514. 'placeholder' => '',
  1515. 'label' => '',
  1516. 'labelTranslate' => '',
  1517. 'assist' => '',
  1518. 'name' => '',
  1519. 'pattern' => '',
  1520. 'options' => array( // For SELECT only
  1521. 'Display' => 'value',
  1522. ),
  1523. )
  1524. */
  1525. // Tags
  1526. $tags = array();
  1527. foreach(array('placeholder','style','disabled','readonly','pattern','min','max','required','onkeypress','onchange','onfocus','onleave','href','onclick') as $value) {
  1528. if (isset($params[$value])) {
  1529. if (is_string($params[$value])) { $tags[] = $value.'="'.$params[$value].'"';
  1530. } else if ($params[$value] === true) { $tags[] = $value; }
  1531. }
  1532. }
  1533. $format = (isset($params['format']) && in_array($params['format'],array(false,'colour','color'))?$params['format']:false);
  1534. $name = (isset($params['name'])?$params['name']:(isset($params['id'])?$params['id']:''));
  1535. $id = (isset($params['id'])?$params['id']:(isset($params['name'])?$params['name'].'_id':randString(32)));
  1536. $val = (isset($params['value'])?$params['value']:'');
  1537. $class = (isset($params['class'])?' '.$params['class']:'');
  1538. $wrapClass = (isset($params['wrapClass'])?$params['wrapClass']:'form-content');
  1539. $assist = (isset($params['assist'])?' - i.e. '.$params['assist']:'');
  1540. $label = (isset($params['labelTranslate'])?translate($params['labelTranslate']):(isset($params['label'])?$params['label']:''));
  1541. $labelOut = '<p class="help-text">'.$label.$assist.'</p>';
  1542. // Field Design
  1543. switch ($params['type']) {
  1544. case 'text':
  1545. case 'number':
  1546. case 'password':
  1547. $field = '<input id="'.$id.'" name="'.$name.'" type="'.$params['type'].'" class="form-control material input-sm'.$class.'" '.implode(' ',$tags).' autocorrect="off" autocapitalize="off" value="'.$val.'">';
  1548. break;
  1549. case 'select':
  1550. case 'dropdown':
  1551. $field = '<select id="'.$id.'" name="'.$name.'" class="form-control material input-sm" '.implode(' ',$tags).'>'.resolveSelectOptions($params['options'], $val).'</select>';
  1552. break;
  1553. case 'select-multi':
  1554. case 'dropdown-multi':
  1555. $field = '<select id="'.$id.'" name="'.$name.'" class="form-control input-sm" '.implode(' ',$tags).' multiple="multiple">'.resolveSelectOptions($params['options'], $val, true).'</select>';
  1556. break;
  1557. case 'check':
  1558. case 'checkbox':
  1559. case 'toggle':
  1560. $checked = ((is_bool($val) && $val) || trim($val) === 'true'?' checked':'');
  1561. $colour = (isset($params['colour'])?$params['colour']:'success');
  1562. $labelOut = '<label for="'.$id.'"></label>'.$label;
  1563. $field = '<input id="'.$id.'" name="'.$name.'" type="checkbox" class="switcher switcher-'.$colour.' '.$class.'" '.implode(' ',$tags).' data-value="'.$val.'"'.$checked.'>';
  1564. break;
  1565. case 'radio':
  1566. $labelOut = '';
  1567. $checked = ((is_bool($val) && $val) || ($val && trim($val) !== 'false')?' checked':'');
  1568. $bType = (isset($params['buttonType'])?$params['buttonType']:'success');
  1569. $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>';
  1570. break;
  1571. case 'date':
  1572. $field = 'Unsupported, planned.';
  1573. break;
  1574. case 'hidden':
  1575. return '<input id="'.$id.'" name="'.$name.'" type="hidden" class="'.$class.'" '.implode(' ',$tags).' value="'.$val.'">';
  1576. break;
  1577. case 'header':
  1578. $labelOut = '';
  1579. $headType = (isset($params['value'])?$params['value']:3);
  1580. $field = '<h'.$headType.' class="'.$class.'" '.implode(' ',$tags).'>'.$label.'</h'.$headType.'>';
  1581. break;
  1582. case 'button':
  1583. $labelOut = '';
  1584. $icon = (isset($params['icon'])?$params['icon']:'flask');
  1585. $bType = (isset($params['buttonType'])?$params['buttonType']:'success');
  1586. $bDropdown = (isset($params['buttonDrop'])?$params['buttonDrop']:'');
  1587. $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>':'');
  1588. break;
  1589. case 'textarea':
  1590. $rows = (isset($params['rows'])?$params['rows']:5);
  1591. $field = '<textarea id="'.$id.'" name="'.$name.'" class="form-control'.$class.'" rows="'.$rows.'" '.implode(' ',$tags).'>'.$val.'</textarea>';
  1592. break;
  1593. case 'custom':
  1594. // Settings
  1595. $settings = array(
  1596. '$id' => $id,
  1597. '$name' => $name,
  1598. '$val' => $val,
  1599. '$label' => $label,
  1600. '$labelOut' => $labelOut,
  1601. );
  1602. // Get HTML
  1603. $html = (isset($params['html'])?$params['html']:'Nothing Specified!');
  1604. // If LabelOut is in html dont print it twice
  1605. $labelOut = (strpos($html,'$label')!==false?'':$labelOut);
  1606. // Replace variables in settings
  1607. $html = preg_replace_callback('/\$\w+\b/', function ($match) use ($settings) { return (isset($settings[$match[0]])?$settings[$match[0]]:'{'.$match[0].' is undefined}'); }, $html);
  1608. // Build Field
  1609. $field = '<div id="'.$id.'_html" class="custom-field">'.$html.'</div>';
  1610. break;
  1611. case 'space':
  1612. $labelOut = '';
  1613. $field = str_repeat('<br>', (isset($params['value'])?$params['value']:1));
  1614. break;
  1615. default:
  1616. $field = 'Unsupported field type';
  1617. break;
  1618. }
  1619. // Field Formats
  1620. switch ($format) {
  1621. case 'colour': // Fuckin Eh, Canada!
  1622. case 'color':
  1623. $labelBef = '<center>'.$label.'</center>';
  1624. $wrapClass = 'gray-bg colour-field';
  1625. $labelAft = '';
  1626. $field = str_replace(' material input-sm','',$field);
  1627. break;
  1628. default:
  1629. $labelBef = '';
  1630. $labelAft = $labelOut;
  1631. }
  1632. return '<div class="'.$wrapClass.' col-sm-'.$sizeSm.' col-md-'.$sizeMd.' col-lg-'.$sizeLg.'">'.$labelBef.$field.$labelAft.'</div>';
  1633. }
  1634. // Tab Settings Generation
  1635. function printTabRow($data) {
  1636. $hidden = false;
  1637. if ($data===false) {
  1638. $hidden = true;
  1639. $data = array( // New Tab Defaults
  1640. 'id' => 'new',
  1641. 'name' => '',
  1642. 'url' => '',
  1643. 'icon' => 'fa-diamond',
  1644. 'iconurl' => '',
  1645. 'active' => 'true',
  1646. 'user' => 'true',
  1647. 'guest' => 'true',
  1648. 'window' => 'false',
  1649. 'defaultz' => '',
  1650. );
  1651. }
  1652. $image = '<span style="font: normal normal normal 30px/1 FontAwesome;" class="fa fa-hand-paper-o"></span>';
  1653. $output = '
  1654. <li id="tab-'.$data['id'].'" class="list-group-item" style="position: relative; left: 0px; top: 0px; '.($hidden?' display: none;':'').'">
  1655. <tab class="content-form form-inline">
  1656. <div class="row">
  1657. '.buildField(array(
  1658. 'type' => 'custom',
  1659. '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>',
  1660. ),12,1,1).'
  1661. '.buildField(array(
  1662. 'type' => 'hidden',
  1663. 'id' => 'tab-'.$data['id'].'-id',
  1664. 'name' => 'id['.$data['id'].']',
  1665. 'value' => $data['id'],
  1666. ),12,2,1).'
  1667. '.buildField(array(
  1668. 'type' => 'text',
  1669. 'id' => 'tab-'.$data['id'].'-name',
  1670. 'name' => 'name['.$data['id'].']',
  1671. 'required' => true,
  1672. 'placeholder' => 'Organizr Homepage',
  1673. 'labelTranslate' => 'TAB_NAME',
  1674. 'value' => $data['name'],
  1675. ),12,2,1).'
  1676. '.buildField(array(
  1677. 'type' => 'text',
  1678. 'id' => 'tab-'.$data['id'].'-url',
  1679. 'name' => 'url['.$data['id'].']',
  1680. 'required' => true,
  1681. 'placeholder' => 'homepage.php',
  1682. 'labelTranslate' => 'TAB_URL',
  1683. 'value' => $data['url'],
  1684. ),12,2,1).'
  1685. '.buildField(array(
  1686. 'type' => 'text',
  1687. 'id' => 'tab-'.$data['id'].'-iconurl',
  1688. 'name' => 'iconurl['.$data['id'].']',
  1689. 'placeholder' => 'images/organizr.png',
  1690. 'labelTranslate' => 'ICON_URL',
  1691. 'value' => $data['iconurl'],
  1692. ),12,2,1).'
  1693. '.buildField(array(
  1694. 'type' => 'custom',
  1695. 'id' => 'tab-'.$data['id'].'-icon',
  1696. 'name' => 'icon['.$data['id'].']',
  1697. '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>',
  1698. 'value' => $data['icon'],
  1699. ),12,1,1).'
  1700. '.buildField(array(
  1701. 'type' => 'checkbox',
  1702. 'labelTranslate' => 'ACTIVE',
  1703. 'name' => 'active['.$data['id'].']',
  1704. 'value' => $data['active'],
  1705. ),12,1,1).'
  1706. '.buildField(array(
  1707. 'type' => 'checkbox',
  1708. 'labelTranslate' => 'USER',
  1709. 'colour' => 'primary',
  1710. 'name' => 'user['.$data['id'].']',
  1711. 'value' => $data['user'],
  1712. ),12,1,1).'
  1713. '.buildField(array(
  1714. 'type' => 'checkbox',
  1715. 'labelTranslate' => 'GUEST',
  1716. 'colour' => 'warning',
  1717. 'name' => 'guest['.$data['id'].']',
  1718. 'value' => $data['guest'],
  1719. ),12,1,1).'
  1720. '.buildField(array(
  1721. 'type' => 'checkbox',
  1722. 'labelTranslate' => 'NO_IFRAME',
  1723. 'colour' => 'danger',
  1724. 'name' => 'window['.$data['id'].']',
  1725. 'value' => $data['window'],
  1726. ),12,1,1).'
  1727. '.buildField(array(
  1728. 'type' => 'radio',
  1729. 'labelTranslate' => 'DEFAULT',
  1730. 'name' => 'defaultz['.$data['id'].']',
  1731. 'value' => $data['defaultz'],
  1732. 'onclick' => "$('[type=radio][id!=\''+this.id+'\']').each(function() { this.checked=false; });",
  1733. ),12,1,1).'
  1734. '.buildField(array(
  1735. 'type' => 'button',
  1736. 'icon' => 'trash',
  1737. 'buttonType' => 'danger',
  1738. 'labelTranslate' => 'REMOVE',
  1739. 'onclick' => "$(this).parents('li').remove();",
  1740. ),12,1,1).'
  1741. </div>
  1742. </tab>
  1743. </li>
  1744. ';
  1745. return $output;
  1746. }
  1747. // Timezone array
  1748. function timezoneOptions() {
  1749. $output = array();
  1750. $timezones = array();
  1751. $regions = array(
  1752. 'Africa' => DateTimeZone::AFRICA,
  1753. 'America' => DateTimeZone::AMERICA,
  1754. 'Antarctica' => DateTimeZone::ANTARCTICA,
  1755. 'Arctic' => DateTimeZone::ARCTIC,
  1756. 'Asia' => DateTimeZone::ASIA,
  1757. 'Atlantic' => DateTimeZone::ATLANTIC,
  1758. 'Australia' => DateTimeZone::AUSTRALIA,
  1759. 'Europe' => DateTimeZone::EUROPE,
  1760. 'Indian' => DateTimeZone::INDIAN,
  1761. 'Pacific' => DateTimeZone::PACIFIC
  1762. );
  1763. foreach ($regions as $name => $mask) {
  1764. $zones = DateTimeZone::listIdentifiers($mask);
  1765. foreach($zones as $timezone) {
  1766. $time = new DateTime(NULL, new DateTimeZone($timezone));
  1767. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  1768. $output[$name]['optgroup'][substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm]['value'] = $timezone;
  1769. }
  1770. }
  1771. return $output;
  1772. }
  1773. // Build Database
  1774. function createSQLiteDB($path = false) {
  1775. if ($path === false) {
  1776. if (defined('DATABASE_LOCATION')) {
  1777. $path = DATABASE_LOCATION;
  1778. } else {
  1779. debug_out('No Path Specified!');
  1780. }
  1781. }
  1782. if (!is_file($path.'users.db') || filesize($path.'users.db') <= 0) {
  1783. if (!isset($GLOBALS['file_db'])) {
  1784. $GLOBALS['file_db'] = new PDO('sqlite:'.$path.'users.db');
  1785. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1786. }
  1787. // Create Users
  1788. $users = $GLOBALS['file_db']->query('CREATE TABLE `users` (
  1789. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1790. `username` TEXT UNIQUE,
  1791. `password` TEXT,
  1792. `email` TEXT,
  1793. `token` TEXT,
  1794. `role` TEXT,
  1795. `active` TEXT,
  1796. `last` TEXT,
  1797. `auth_service` TEXT DEFAULT \'internal\'
  1798. );');
  1799. // Create Tabs
  1800. $tabs = $GLOBALS['file_db']->query('CREATE TABLE `tabs` (
  1801. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1802. `order` INTEGER,
  1803. `users_id` INTEGER,
  1804. `name` TEXT,
  1805. `url` TEXT,
  1806. `defaultz` TEXT,
  1807. `active` TEXT,
  1808. `user` TEXT,
  1809. `guest` TEXT,
  1810. `icon` TEXT,
  1811. `iconurl` TEXT,
  1812. `window` TEXT
  1813. );');
  1814. // Create Options
  1815. $options = $GLOBALS['file_db']->query('CREATE TABLE `options` (
  1816. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1817. `users_id` INTEGER UNIQUE,
  1818. `title` TEXT UNIQUE,
  1819. `topbar` TEXT,
  1820. `bottombar` TEXT,
  1821. `sidebar` TEXT,
  1822. `hoverbg` TEXT,
  1823. `topbartext` TEXT,
  1824. `activetabBG` TEXT,
  1825. `activetabicon` TEXT,
  1826. `activetabtext` TEXT,
  1827. `inactiveicon` TEXT,
  1828. `inactivetext` TEXT,
  1829. `loading` TEXT,
  1830. `hovertext` TEXT
  1831. );');
  1832. // Create Invites
  1833. $invites = $GLOBALS['file_db']->query('CREATE TABLE `invites` (
  1834. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1835. `code` TEXT UNIQUE,
  1836. `date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  1837. `email` TEXT,
  1838. `username` TEXT,
  1839. `dateused` TIMESTAMP,
  1840. `usedby` TEXT,
  1841. `ip` TEXT,
  1842. `valid` TEXT
  1843. );');
  1844. writeLog("success", "database created/saved");
  1845. return $users && $tabs && $options && $invites;
  1846. } else {
  1847. writeLog("error", "database was unable to be created/saved");
  1848. return false;
  1849. }
  1850. }
  1851. // Upgrade Database
  1852. function updateSQLiteDB($db_path = false, $oldVerNum = false) {
  1853. if (!$db_path) {
  1854. if (defined('DATABASE_LOCATION')) {
  1855. $db_path = DATABASE_LOCATION;
  1856. } else {
  1857. debug_out('No Path Specified',1);
  1858. }
  1859. }
  1860. if (!isset($GLOBALS['file_db'])) {
  1861. $GLOBALS['file_db'] = new PDO('sqlite:'.$db_path.'users.db');
  1862. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1863. }
  1864. // Cache current DB
  1865. $cache = array();
  1866. foreach($GLOBALS['file_db']->query('SELECT name FROM sqlite_master WHERE type="table";') as $table) {
  1867. foreach($GLOBALS['file_db']->query('SELECT * FROM '.$table['name'].';') as $key => $row) {
  1868. foreach($row as $k => $v) {
  1869. if (is_string($k)) {
  1870. $cache[$table['name']][$key][$k] = $v;
  1871. }
  1872. }
  1873. }
  1874. }
  1875. // Remove Current Database
  1876. $GLOBALS['file_db'] = null;
  1877. $pathDigest = pathinfo($db_path.'users.db');
  1878. if (file_exists($db_path.'users.db')) {
  1879. rename($db_path.'users.db', $pathDigest['dirname'].'/'.$pathDigest['filename'].'['.date('Y-m-d_H-i-s').']'.($oldVerNum?'['.$oldVerNum.']':'').'.bak.db');
  1880. }
  1881. // Create New Database
  1882. $success = createSQLiteDB($db_path);
  1883. // Restore Items
  1884. if ($success) {
  1885. foreach($cache as $table => $tableData) {
  1886. if ($tableData) {
  1887. $queryBase = 'INSERT INTO '.$table.' (`'.implode('`,`',array_keys(current($tableData))).'`) values ';
  1888. $insertValues = array();
  1889. reset($tableData);
  1890. foreach($tableData as $key => $value) {
  1891. $insertValues[] = '('.implode(',',array_map(function($d) {
  1892. return (isset($d)?$GLOBALS['file_db']->quote($d):'null');
  1893. }, $value)).')';
  1894. }
  1895. $GLOBALS['file_db']->query($queryBase.implode(',',$insertValues).';');
  1896. }
  1897. }
  1898. writeLog("success", "database values have been updated");
  1899. return true;
  1900. } else {
  1901. writeLog("error", "database values unable to be updated");
  1902. return false;
  1903. }
  1904. }
  1905. // Commit colours to database
  1906. function updateDBOptions($values) {
  1907. if (!isset($GLOBALS['file_db'])) {
  1908. $GLOBALS['file_db'] = new PDO('sqlite:'.DATABASE_LOCATION.'users.db');
  1909. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1910. }
  1911. // Commit new values to database
  1912. if ($GLOBALS['file_db']->query('UPDATE options SET '.implode(',',array_map(function($d, $k) {
  1913. return '`'.$k.'` = '.(isset($d)?"'".addslashes($d)."'":'null');
  1914. }, $values, array_keys($values))).';')->rowCount()) {
  1915. return true;
  1916. } else if ($GLOBALS['file_db']->query('INSERT OR IGNORE INTO options (`'.implode('`,`',array_keys($values)).'`) VALUES (\''.implode("','",$values).'\');')->rowCount()) {
  1917. writeLog("success", "database values for options table have been updated");
  1918. return true;
  1919. } else {
  1920. writeLog("error", "database values for options table unable to be updated");
  1921. return false;
  1922. }
  1923. }
  1924. // Send AJAX notification
  1925. function sendNotification($success, $message = false, $send = true) {
  1926. $notifyExplode = explode("-", NOTIFYEFFECT);
  1927. if ($success) {
  1928. $msg = array(
  1929. 'html' => ($message?''.$message:'<strong>'.translate("SETTINGS_SAVED").'</strong>'),
  1930. 'icon' => 'floppy-o',
  1931. 'type' => 'success',
  1932. 'length' => '5000',
  1933. 'layout' => $notifyExplode[0],
  1934. 'effect' => $notifyExplode[1],
  1935. );
  1936. } else {
  1937. $msg = array(
  1938. 'html' => ($message?''.$message:'<strong>'.translate("SETTINGS_NOT_SAVED").'</strong>'),
  1939. 'icon' => 'floppy-o',
  1940. 'type' => 'failed',
  1941. 'length' => '5000',
  1942. 'layout' => $notifyExplode[0],
  1943. 'effect' => $notifyExplode[1],
  1944. );
  1945. }
  1946. // Send and kill script?
  1947. if ($send) {
  1948. header('Content-Type: application/json');
  1949. echo json_encode(array('notify'=>$msg));
  1950. die();
  1951. }
  1952. return $msg;
  1953. }
  1954. // Load colours from the database
  1955. function loadAppearance() {
  1956. if (!isset($GLOBALS['file_db'])) {
  1957. $GLOBALS['file_db'] = new PDO('sqlite:'.DATABASE_LOCATION.'users.db');
  1958. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1959. }
  1960. // Defaults
  1961. $defaults = array(
  1962. 'title' => 'Organizr',
  1963. 'topbartext' => '#66D9EF',
  1964. 'topbar' => '#333333',
  1965. 'bottombar' => '#333333',
  1966. 'sidebar' => '#393939',
  1967. 'hoverbg' => '#AD80FD',
  1968. 'activetabBG' => '#F92671',
  1969. 'activetabicon' => '#FFFFFF',
  1970. 'activetabtext' => '#FFFFFF',
  1971. 'inactiveicon' => '#66D9EF',
  1972. 'inactivetext' => '#66D9EF',
  1973. 'loading' => '#66D9EF',
  1974. 'hovertext' => '#000000',
  1975. );
  1976. // Database Lookup
  1977. $options = $GLOBALS['file_db']->query('SELECT * FROM options');
  1978. // Replace defaults with filled options
  1979. foreach($options as $row) {
  1980. foreach($defaults as $key => $value) {
  1981. if (isset($row[$key]) && $row[$key]) {
  1982. $defaults[$key] = $row[$key];
  1983. }
  1984. }
  1985. }
  1986. // Return the Results
  1987. return $defaults;
  1988. }
  1989. // Delete Database
  1990. function deleteDatabase() {
  1991. unset($_COOKIE['Organizr']);
  1992. setcookie('Organizr', '', time() - 3600, '/');
  1993. unset($_COOKIE['OrganizrU']);
  1994. setcookie('OrganizrU', '', time() - 3600, '/');
  1995. $GLOBALS['file_db'] = null;
  1996. unlink(DATABASE_LOCATION.'users.db');
  1997. foreach(glob(substr_replace($userdirpath, "", -1).'/*') as $file) {
  1998. if(is_dir($file)) {
  1999. rmdir($file);
  2000. } elseif (!is_dir($file)) {
  2001. unlink($file);
  2002. }
  2003. }
  2004. rmdir($userdirpath);
  2005. writeLog("success", "database has been deleted");
  2006. return true;
  2007. }
  2008. // Upgrade the installation
  2009. function upgradeInstall($branch = 'master') {
  2010. function downloadFile($url, $path){
  2011. ini_set('max_execution_time',0);
  2012. $folderPath = "upgrade/";
  2013. if(!mkdir($folderPath)){
  2014. writeLog("error", "organizr could not create upgrade folder");
  2015. }
  2016. $newfname = $folderPath . $path;
  2017. $file = fopen ($url, 'rb');
  2018. if ($file) {
  2019. $newf = fopen ($newfname, 'wb');
  2020. if ($newf) {
  2021. while(!feof($file)) {
  2022. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  2023. }
  2024. }
  2025. }else{
  2026. writeLog("error", "organizr could not download $url");
  2027. }
  2028. if ($file) {
  2029. fclose($file);
  2030. writeLog("success", "organizr finished downloading the github zip file");
  2031. }else{
  2032. writeLog("error", "organizr could not download the github zip file");
  2033. }
  2034. if ($newf) {
  2035. fclose($newf);
  2036. writeLog("success", "organizr created upgrade zip file from github zip file");
  2037. }else{
  2038. writeLog("error", "organizr could not create upgrade zip file from github zip file");
  2039. }
  2040. }
  2041. function unzipFile($zipFile){
  2042. $zip = new ZipArchive;
  2043. $extractPath = "upgrade/";
  2044. if($zip->open($extractPath . $zipFile) != "true"){
  2045. writeLog("error", "organizr could not unzip upgrade.zip");
  2046. }else{
  2047. writeLog("success", "organizr unzipped upgrade.zip");
  2048. }
  2049. /* Extract Zip File */
  2050. $zip->extractTo($extractPath);
  2051. $zip->close();
  2052. }
  2053. // Function to remove folders and files
  2054. function rrmdir($dir) {
  2055. if (is_dir($dir)) {
  2056. $files = scandir($dir);
  2057. foreach ($files as $file)
  2058. if ($file != "." && $file != "..") rrmdir("$dir/$file");
  2059. rmdir($dir);
  2060. }
  2061. else if (file_exists($dir)) unlink($dir);
  2062. }
  2063. // Function to Copy folders and files
  2064. function rcopy($src, $dst) {
  2065. if (is_dir ( $src )) {
  2066. if (!file_exists($dst)) : mkdir ( $dst ); endif;
  2067. $files = scandir ( $src );
  2068. foreach ( $files as $file )
  2069. if ($file != "." && $file != "..")
  2070. rcopy ( "$src/$file", "$dst/$file" );
  2071. } else if (file_exists ( $src ))
  2072. copy ( $src, $dst );
  2073. }
  2074. $url = 'https://github.com/causefx/Organizr/archive/'.$branch.'.zip';
  2075. $file = "upgrade.zip";
  2076. $source = __DIR__ . '/upgrade/Organizr-'.$branch.'/';
  2077. $cleanup = __DIR__ . "/upgrade/";
  2078. $destination = __DIR__ . "/";
  2079. writeLog("success", "starting organizr upgrade process");
  2080. downloadFile($url, $file);
  2081. unzipFile($file);
  2082. rcopy($source, $destination);
  2083. writeLog("success", "new organizr files copied");
  2084. rrmdir($cleanup);
  2085. writeLog("success", "organizr upgrade folder removed");
  2086. writeLog("success", "organizr has been updated");
  2087. return true;
  2088. }
  2089. // NzbGET Items
  2090. function nzbgetConnect($list = 'listgroups') {
  2091. $url = qualifyURL(NZBGETURL);
  2092. $api = curl_get($url.'/'.NZBGETUSERNAME.':'.NZBGETPASSWORD.'/jsonrpc/'.$list);
  2093. $api = json_decode($api, true);
  2094. $gotNZB = array();
  2095. foreach ($api['result'] AS $child) {
  2096. $downloadName = htmlentities($child['NZBName'], ENT_QUOTES);
  2097. $downloadStatus = $child['Status'];
  2098. $downloadCategory = $child['Category'];
  2099. if($list == "history"){ $downloadPercent = "100"; $progressBar = ""; }
  2100. if($list == "listgroups"){ $downloadPercent = (($child['FileSizeMB'] - $child['RemainingSizeMB']) / $child['FileSizeMB']) * 100; $progressBar = "progress-bar-striped active"; }
  2101. if($child['Health'] <= "750"){
  2102. $downloadHealth = "danger";
  2103. }elseif($child['Health'] <= "900"){
  2104. $downloadHealth = "warning";
  2105. }elseif($child['Health'] <= "1000"){
  2106. $downloadHealth = "success";
  2107. }
  2108. $gotNZB[] = '<tr>
  2109. <td class="col-xs-7 nzbtable-file-row">'.$downloadName.'</td>
  2110. <td class="col-xs-2 nzbtable nzbtable-row">'.$downloadStatus.'</td>
  2111. <td class="col-xs-1 nzbtable nzbtable-row">'.$downloadCategory.'</td>
  2112. <td class="col-xs-2 nzbtable nzbtable-row">
  2113. <div class="progress">
  2114. <div class="progress-bar progress-bar-'.$downloadHealth.' '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  2115. <p class="text-center">'.round($downloadPercent).'%</p>
  2116. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  2117. </div>
  2118. </div>
  2119. </td>
  2120. </tr>';
  2121. }
  2122. if ($gotNZB) {
  2123. return implode('',$gotNZB);
  2124. } else {
  2125. return '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>';
  2126. }
  2127. }
  2128. // Sabnzbd Items
  2129. function sabnzbdConnect($list = 'queue') {
  2130. $url = qualifyURL(SABNZBDURL);
  2131. $api = file_get_contents($url.'/api?mode='.$list.'&output=json&apikey='.SABNZBDKEY);
  2132. $api = json_decode($api, true);
  2133. $gotNZB = array();
  2134. foreach ($api[$list]['slots'] AS $child) {
  2135. if($list == "queue"){ $downloadName = $child['filename']; $downloadCategory = $child['cat']; $downloadPercent = (($child['mb'] - $child['mbleft']) / $child['mb']) * 100; $progressBar = "progress-bar-striped active"; }
  2136. if($list == "history"){ $downloadName = $child['name']; $downloadCategory = $child['category']; $downloadPercent = "100"; $progressBar = ""; }
  2137. $downloadStatus = $child['status'];
  2138. $gotNZB[] = '<tr>
  2139. <td>'.$downloadName.'</td>
  2140. <td>'.$downloadStatus.'</td>
  2141. <td>'.$downloadCategory.'</td>
  2142. <td>
  2143. <div class="progress">
  2144. <div class="progress-bar progress-bar-success '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  2145. <p class="text-center">'.round($downloadPercent).'%</p>
  2146. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  2147. </div>
  2148. </div>
  2149. </td>
  2150. </tr>';
  2151. }
  2152. if ($gotNZB) {
  2153. return implode('',$gotNZB);
  2154. } else {
  2155. return '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>';
  2156. }
  2157. }
  2158. // Apply new tab settings
  2159. function updateTabs($tabs) {
  2160. if (!isset($GLOBALS['file_db'])) {
  2161. $GLOBALS['file_db'] = new PDO('sqlite:'.DATABASE_LOCATION.'users.db');
  2162. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  2163. }
  2164. // Validate
  2165. if (!isset($tabs['defaultz'])) { $tabs['defaultz'][current(array_keys($tabs['name']))] = 'true'; }
  2166. if (isset($tabs['name']) && isset($tabs['url']) && is_array($tabs['name'])) {
  2167. // Clear Existing Tabs
  2168. $GLOBALS['file_db']->query("DELETE FROM tabs");
  2169. // Process New Tabs
  2170. $totalValid = 0;
  2171. foreach ($tabs['name'] as $key => $value) {
  2172. // Qualify
  2173. if (!$value || !isset($tabs['url']) || !$tabs['url'][$key]) { continue; }
  2174. $totalValid++;
  2175. $fields = array();
  2176. foreach(array('id','name','url','icon','iconurl','order') as $v) {
  2177. if (isset($tabs[$v]) && isset($tabs[$v][$key])) { $fields[$v] = $tabs[$v][$key]; }
  2178. }
  2179. foreach(array('active','user','guest','defaultz','window') as $v) {
  2180. if (isset($tabs[$v]) && isset($tabs[$v][$key])) { $fields[$v] = ($tabs[$v][$key]!=='false'?'true':'false'); }
  2181. }
  2182. $GLOBALS['file_db']->query('INSERT INTO tabs (`'.implode('`,`',array_keys($fields)).'`) VALUES (\''.implode("','",$fields).'\');');
  2183. }
  2184. writeLog("success", "tabs successfully saved");
  2185. return $totalValid;
  2186. } else {
  2187. writeLog("error", "tabs could not save");
  2188. return false;
  2189. }
  2190. writeLog("error", "tabs could not save");
  2191. return false;
  2192. }
  2193. // ==============
  2194. function clean($strin) {
  2195. $strout = null;
  2196. for ($i = 0; $i < strlen($strin); $i++) {
  2197. $ord = ord($strin[$i]);
  2198. if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
  2199. $strout .= "&amp;#{$ord};";
  2200. }
  2201. else {
  2202. switch ($strin[$i]) {
  2203. case '<':
  2204. $strout .= '&lt;';
  2205. break;
  2206. case '>':
  2207. $strout .= '&gt;';
  2208. break;
  2209. case '&':
  2210. $strout .= '&amp;';
  2211. break;
  2212. case '"':
  2213. $strout .= '&quot;';
  2214. break;
  2215. default:
  2216. $strout .= $strin[$i];
  2217. }
  2218. }
  2219. }
  2220. return $strout;
  2221. }
  2222. function registration_callback($username, $email, $userdir){
  2223. global $data;
  2224. $data = array($username, $email, $userdir);
  2225. }
  2226. function printArray($arrayName){
  2227. $messageCount = count($arrayName);
  2228. $i = 0;
  2229. foreach ( $arrayName as $item ) :
  2230. $i++;
  2231. if($i < $messageCount) :
  2232. echo "<small class='text-uppercase'>" . $item . "</small> & ";
  2233. elseif($i = $messageCount) :
  2234. echo "<small class='text-uppercase'>" . $item . "</small>";
  2235. endif;
  2236. endforeach;
  2237. }
  2238. function write_ini_file($content, $path) {
  2239. if (!$handle = fopen($path, 'w')) {
  2240. return false;
  2241. }
  2242. $success = fwrite($handle, trim($content));
  2243. fclose($handle);
  2244. return $success;
  2245. }
  2246. function gotTimezone(){
  2247. $regions = array(
  2248. 'Africa' => DateTimeZone::AFRICA,
  2249. 'America' => DateTimeZone::AMERICA,
  2250. 'Antarctica' => DateTimeZone::ANTARCTICA,
  2251. 'Arctic' => DateTimeZone::ARCTIC,
  2252. 'Asia' => DateTimeZone::ASIA,
  2253. 'Atlantic' => DateTimeZone::ATLANTIC,
  2254. 'Australia' => DateTimeZone::AUSTRALIA,
  2255. 'Europe' => DateTimeZone::EUROPE,
  2256. 'Indian' => DateTimeZone::INDIAN,
  2257. 'Pacific' => DateTimeZone::PACIFIC
  2258. );
  2259. $timezones = array();
  2260. foreach ($regions as $name => $mask) {
  2261. $zones = DateTimeZone::listIdentifiers($mask);
  2262. foreach($zones as $timezone) {
  2263. $time = new DateTime(NULL, new DateTimeZone($timezone));
  2264. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  2265. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  2266. }
  2267. }
  2268. print '<select name="timezone" id="timezone" class="form-control material input-sm" required>';
  2269. foreach($timezones as $region => $list) {
  2270. print '<optgroup label="' . $region . '">' . "\n";
  2271. foreach($list as $timezone => $name) {
  2272. if($timezone == TIMEZONE) : $selected = " selected"; else : $selected = ""; endif;
  2273. print '<option value="' . $timezone . '"' . $selected . '>' . $name . '</option>' . "\n";
  2274. }
  2275. print '</optgroup>' . "\n";
  2276. }
  2277. print '</select>';
  2278. }
  2279. function getTimezone(){
  2280. $regions = array(
  2281. 'Africa' => DateTimeZone::AFRICA,
  2282. 'America' => DateTimeZone::AMERICA,
  2283. 'Antarctica' => DateTimeZone::ANTARCTICA,
  2284. 'Arctic' => DateTimeZone::ARCTIC,
  2285. 'Asia' => DateTimeZone::ASIA,
  2286. 'Atlantic' => DateTimeZone::ATLANTIC,
  2287. 'Australia' => DateTimeZone::AUSTRALIA,
  2288. 'Europe' => DateTimeZone::EUROPE,
  2289. 'Indian' => DateTimeZone::INDIAN,
  2290. 'Pacific' => DateTimeZone::PACIFIC
  2291. );
  2292. $timezones = array();
  2293. foreach ($regions as $name => $mask) {
  2294. $zones = DateTimeZone::listIdentifiers($mask);
  2295. foreach($zones as $timezone) {
  2296. $time = new DateTime(NULL, new DateTimeZone($timezone));
  2297. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  2298. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  2299. }
  2300. }
  2301. print '<select name="timezone" id="timezone" class="form-control material" required>';
  2302. foreach($timezones as $region => $list) {
  2303. print '<optgroup label="' . $region . '">' . "\n";
  2304. foreach($list as $timezone => $name) {
  2305. print '<option value="' . $timezone . '">' . $name . '</option>' . "\n";
  2306. }
  2307. print '</optgroup>' . "\n";
  2308. }
  2309. print '</select>';
  2310. }
  2311. function explosion($string, $position){
  2312. $getWord = explode("|", $string);
  2313. return $getWord[$position];
  2314. }
  2315. function getServerPath() {
  2316. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  2317. $protocol = "https://";
  2318. } else {
  2319. $protocol = "http://";
  2320. }
  2321. return $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
  2322. }
  2323. function get_browser_name() {
  2324. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  2325. if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
  2326. elseif (strpos($user_agent, 'Edge')) return 'Edge';
  2327. elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
  2328. elseif (strpos($user_agent, 'Safari')) return 'Safari';
  2329. elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
  2330. elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
  2331. return 'Other';
  2332. }
  2333. function getSickrageCalendarWanted($array){
  2334. $array = json_decode($array, true);
  2335. $gotCalendar = "";
  2336. $i = 0;
  2337. foreach($array['data']['missed'] AS $child) {
  2338. $i++;
  2339. $seriesName = $child['show_name'];
  2340. $episodeID = $child['tvdbid'];
  2341. $episodeAirDate = $child['airdate'];
  2342. $episodeAirDateTime = explode(" ",$child['airs']);
  2343. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  2344. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  2345. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2346. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  2347. $downloaded = "0";
  2348. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  2349. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  2350. }
  2351. foreach($array['data']['today'] AS $child) {
  2352. $i++;
  2353. $seriesName = $child['show_name'];
  2354. $episodeID = $child['tvdbid'];
  2355. $episodeAirDate = $child['airdate'];
  2356. $episodeAirDateTime = explode(" ",$child['airs']);
  2357. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  2358. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  2359. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2360. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  2361. $downloaded = "0";
  2362. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  2363. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  2364. }
  2365. foreach($array['data']['soon'] AS $child) {
  2366. $i++;
  2367. $seriesName = $child['show_name'];
  2368. $episodeID = $child['tvdbid'];
  2369. $episodeAirDate = $child['airdate'];
  2370. $episodeAirDateTime = explode(" ",$child['airs']);
  2371. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  2372. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  2373. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2374. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  2375. $downloaded = "0";
  2376. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  2377. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  2378. }
  2379. foreach($array['data']['later'] AS $child) {
  2380. $i++;
  2381. $seriesName = $child['show_name'];
  2382. $episodeID = $child['tvdbid'];
  2383. $episodeAirDate = $child['airdate'];
  2384. $episodeAirDateTime = explode(" ",$child['airs']);
  2385. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  2386. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  2387. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2388. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  2389. $downloaded = "0";
  2390. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  2391. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  2392. }
  2393. if ($i != 0){ return $gotCalendar; }
  2394. }
  2395. function getSickrageCalendarHistory($array){
  2396. $array = json_decode($array, true);
  2397. $gotCalendar = "";
  2398. $i = 0;
  2399. foreach($array['data'] AS $child) {
  2400. $i++;
  2401. $seriesName = $child['show_name'];
  2402. $episodeID = $child['tvdbid'];
  2403. $episodeAirDate = $child['date'];
  2404. $downloaded = "green-bg";
  2405. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  2406. }
  2407. if ($i != 0){ return $gotCalendar; }
  2408. }
  2409. function getSonarrCalendar($array){
  2410. $array = json_decode($array, true);
  2411. $gotCalendar = "";
  2412. $i = 0;
  2413. foreach($array AS $child) {
  2414. $i++;
  2415. $seriesName = $child['series']['title'];
  2416. $episodeID = $child['series']['tvdbId'];
  2417. if(!isset($episodeID)){ $episodeID = ""; }
  2418. $episodeName = htmlentities($child['title'], ENT_QUOTES);
  2419. if($child['episodeNumber'] == "1"){ $episodePremier = "true"; }else{ $episodePremier = "false"; }
  2420. $episodeAirDate = $child['airDateUtc'];
  2421. $episodeAirDate = strtotime($episodeAirDate);
  2422. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2423. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  2424. $downloaded = $child['hasFile'];
  2425. 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"; }
  2426. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  2427. }
  2428. if ($i != 0){ return $gotCalendar; }
  2429. }
  2430. function getRadarrCalendar($array){
  2431. $array = json_decode($array, true);
  2432. $gotCalendar = "";
  2433. $i = 0;
  2434. foreach($array AS $child) {
  2435. if(isset($child['inCinemas'])){
  2436. $i++;
  2437. $movieName = $child['title'];
  2438. $movieID = $child['tmdbId'];
  2439. if(!isset($movieID)){ $movieID = ""; }
  2440. if(isset($child['inCinemas']) && isset($child['physicalRelease'])){
  2441. $physicalRelease = $child['physicalRelease'];
  2442. $physicalRelease = strtotime($physicalRelease);
  2443. $physicalRelease = date("Y-m-d", $physicalRelease);
  2444. if (new DateTime() < new DateTime($physicalRelease)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  2445. $downloaded = $child['hasFile'];
  2446. if($downloaded == "0" && $notReleased == "true"){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg"; }else{ $downloaded = "red-bg"; }
  2447. }else{
  2448. $physicalRelease = $child['inCinemas'];
  2449. $downloaded = "light-blue-bg";
  2450. }
  2451. $gotCalendar .= "{ title: \"$movieName\", start: \"$physicalRelease\", className: \"$downloaded\", imagetype: \"film\", url: \"https://www.themoviedb.org/movie/$movieID\" }, \n";
  2452. }
  2453. }
  2454. if ($i != 0){ return $gotCalendar; }
  2455. }
  2456. function getHeadphonesCalendar($url, $key, $list){
  2457. $url = qualifyURL(HEADPHONESURL);
  2458. $api = curl_get($url."/api?apikey=".$key."&cmd=$list");
  2459. $api = json_decode($api, true);
  2460. $i = 0;
  2461. $gotCalendar = "";
  2462. foreach($api AS $child) {
  2463. if($child['Status'] == "Wanted"){
  2464. $i++;
  2465. $albumName = addslashes($child['AlbumTitle']);
  2466. $albumArtist = htmlentities($child['ArtistName'], ENT_QUOTES);
  2467. $albumDate = $child['ReleaseDate'];
  2468. $albumID = $child['AlbumID'];
  2469. $albumDate = strtotime($albumDate);
  2470. $albumDate = date("Y-m-d", $albumDate);
  2471. $albumStatus = $child['Status'];
  2472. if (new DateTime() < new DateTime($albumDate)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  2473. if($albumStatus == "Wanted" && $notReleased == "true"){ $albumStatusColor = "indigo-bg"; }elseif($albumStatus == "Downloaded"){ $albumStatusColor = "green-bg"; }else{ $albumStatusColor = "red-bg"; }
  2474. $gotCalendar .= "{ title: \"$albumArtist - $albumName\", start: \"$albumDate\", className: \"$albumStatusColor\", imagetype: \"music\", url: \"https://musicbrainz.org/release-group/$albumID\" }, \n";
  2475. }
  2476. }
  2477. if ($i != 0){ return $gotCalendar; }
  2478. }
  2479. function checkRootPath($string){
  2480. if($string == "\\" || $string == "/"){
  2481. return "/";
  2482. }else{
  2483. return str_replace("\\", "/", $string) . "/";
  2484. }
  2485. }
  2486. function writeLog($type, $message){
  2487. $message = date("Y-m-d H:i:s")."|".$type."|".$message."\n";
  2488. file_put_contents("org.log", $message, FILE_APPEND | LOCK_EX);
  2489. }
  2490. function readLog(){
  2491. $log = file("org.log");
  2492. $log = array_reverse($log);
  2493. foreach($log as $line){
  2494. $line = explode("|", $line);
  2495. $line[1] = ($line[1] == "error") ? '<span class="label label-danger">Error</span>' : '<span class="label label-primary">Success</span>';
  2496. echo "<tr><td>".$line[0]."</td><td>".$line[2]."</td><td>".$line[1]."</td></tr>";
  2497. }
  2498. }
  2499. function buildStream($array){
  2500. $result = "";
  2501. if (array_key_exists('platform', $array)) {
  2502. $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>';
  2503. }
  2504. if (array_key_exists('device', $array)) {
  2505. $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>';
  2506. }
  2507. if (array_key_exists('stream', $array)) {
  2508. $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>';
  2509. }
  2510. if (array_key_exists('video', $array)) {
  2511. $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>';
  2512. }
  2513. if (array_key_exists('audio', $array)) {
  2514. $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>';
  2515. }
  2516. return $result;
  2517. }
  2518. function streamType($value){
  2519. if($value == "transcode" || $value == "Transcode"){
  2520. return "Transcode";
  2521. }elseif($value == "copy" || $value == "DirectStream"){
  2522. return "Direct Stream";
  2523. }elseif($value == "directplay" || $value == "DirectPlay"){
  2524. return "Direct Play";
  2525. }else{
  2526. return "Direct Play";
  2527. }
  2528. }
  2529. function getPlatform($platform){
  2530. $allPlatforms = array(
  2531. "Chrome" => "chrome.png",
  2532. "tvOS" => "atv.png",
  2533. "iOS" => "ios.png",
  2534. "Xbox One" => "xbox.png",
  2535. "Mystery 4" => "playstation.png",
  2536. "Samsung" => "samsung.png",
  2537. "Roku" => "roku.png",
  2538. "Emby for iOS" => "ios.png",
  2539. "Emby Mobile" => "emby.png",
  2540. "Emby Theater" => "emby.png",
  2541. "Emby Classic" => "emby.png",
  2542. "Safari" => "safari.png",
  2543. "Android" => "android.png",
  2544. "Chromecast" => "chromecast.png",
  2545. "Dashboard" => "emby.png",
  2546. "Dlna" => "dlna.png",
  2547. "Windows Phone" => "wp.png",
  2548. "Windows RT" => "win8.png",
  2549. "Kodi" => "koid.png",
  2550. );
  2551. if (array_key_exists($platform, $allPlatforms)) {
  2552. return $allPlatforms[$platform];
  2553. }else{
  2554. return "pmp.png";
  2555. }
  2556. }
  2557. function getServer(){
  2558. $server = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : $_SERVER["SERVER_NAME"];
  2559. return $server;
  2560. }
  2561. function prettyPrint($array) {
  2562. echo "<pre>";
  2563. print_r($array);
  2564. echo "</pre>";
  2565. echo "<br/>";
  2566. }
  2567. function checkFrame($array, $url){
  2568. if(array_key_exists("x-frame-options", $array)){
  2569. if($array['x-frame-options'] == "deny"){
  2570. return false;
  2571. }elseif($array['x-frame-options'] == "sameorgin"){
  2572. $digest = parse_url($url);
  2573. $host = (isset($digest['host'])?$digest['host']:'');
  2574. if(getServer() == $host){
  2575. return true;
  2576. }else{
  2577. return false;
  2578. }
  2579. }
  2580. }else{
  2581. if(!$array){
  2582. return false;
  2583. }
  2584. return true;
  2585. }
  2586. }
  2587. function frameTest($url){
  2588. $array = array_change_key_case(get_headers(qualifyURL($url), 1));
  2589. $url = qualifyURL($url);
  2590. if(checkFrame($array, $url)){
  2591. return true;
  2592. }else{
  2593. return false;
  2594. }
  2595. }
  2596. function sendResult($result, $icon = "floppy-o", $message = false, $success = "WAS_SUCCESSFUL", $fail = "HAS_FAILED", $send = true) {
  2597. $notifyExplode = explode("-", NOTIFYEFFECT);
  2598. if ($result) {
  2599. $msg = array(
  2600. 'html' => ($message?''.$message.' <strong>'.translate($success).'</strong>':'<strong>'.translate($success).'</strong>'),
  2601. 'icon' => $icon,
  2602. 'type' => 'success',
  2603. 'length' => '5000',
  2604. 'layout' => $notifyExplode[0],
  2605. 'effect' => $notifyExplode[1],
  2606. );
  2607. } else {
  2608. $msg = array(
  2609. 'html' => ($message?''.$message.' <strong>'.translate($fail).'</strong>':'<strong>'.translate($fail).'</strong>'),
  2610. 'icon' => $icon,
  2611. 'type' => 'error',
  2612. 'length' => '5000',
  2613. 'layout' => $notifyExplode[0],
  2614. 'effect' => $notifyExplode[1],
  2615. );
  2616. }
  2617. // Send and kill script?
  2618. if ($send) {
  2619. header('Content-Type: application/json');
  2620. echo json_encode(array('notify'=>$msg));
  2621. die();
  2622. }
  2623. return $msg;
  2624. }
  2625. function buildHomepageNotice($layout, $type, $title, $message){
  2626. switch ($layout) {
  2627. case 'elegant':
  2628. return '
  2629. <div id="homepageNotice" class="row">
  2630. <div class="col-lg-12">
  2631. <div class="content-box big-box box-shadow panel-box panel-'.$type.'">
  2632. <div class="content-title i-block">
  2633. <h4 class="zero-m"><strong>'.$title.'</strong></h4>
  2634. <div class="content-tools i-block pull-right">
  2635. <a class="close-btn">
  2636. <i class="fa fa-times"></i>
  2637. </a>
  2638. </div>
  2639. </div>
  2640. '.$message.'
  2641. </div>
  2642. </div>
  2643. </div>
  2644. ';
  2645. break;
  2646. case 'basic':
  2647. return '
  2648. <div id="homepageNotice" class="row">
  2649. <div class="col-lg-12">
  2650. <div class="panel panel-'.$type.'">
  2651. <div class="panel-heading">
  2652. <h3 class="panel-title">'.$title.'</h3>
  2653. </div>
  2654. <div class="panel-body">
  2655. '.$message.'
  2656. </div>
  2657. </div>
  2658. </div>
  2659. </div>
  2660. ';
  2661. break;
  2662. case 'jumbotron';
  2663. return '
  2664. <div id="homepageNotice" class="row">
  2665. <div class="col-lg-12">
  2666. <div class="jumbotron">
  2667. <div class="container">
  2668. <h1>'.$title.'</h1>
  2669. <p>'.$message.'</p>
  2670. </div>
  2671. </div>
  2672. </div>
  2673. </div>
  2674. ';
  2675. }
  2676. }
  2677. function embyArray($array, $type) {
  2678. $key = ($type == "video" ? "Height" : "Channels");
  2679. if (array_key_exists($key, $array)) {
  2680. switch ($type) {
  2681. case "video":
  2682. $codec = $array["Codec"];
  2683. $height = $array["Height"];
  2684. $width = $array["Width"];
  2685. break;
  2686. default:
  2687. $codec = $array["Codec"];
  2688. $channels = $array["Channels"];
  2689. }
  2690. return ($type == "video" ? "(".$codec.") (".$width."x".$height.")" : "(".$codec.") (".$channels."ch)");
  2691. }
  2692. foreach ($array as $element) {
  2693. if (is_array($element)) {
  2694. if (embyArray($element, $type)) {
  2695. return embyArray($element, $type);
  2696. }
  2697. }
  2698. }
  2699. }
  2700. // Get Now Playing Streams From Plex
  2701. function searchPlex($query){
  2702. $address = qualifyURL(PLEXURL);
  2703. $openTab = (PLEXTABNAME) ? "true" : "false";
  2704. // Perform API requests
  2705. $api = @curl_get($address."/search?query=".rawurlencode($query)."&X-Plex-Token=".PLEXTOKEN);
  2706. $api = simplexml_load_string($api);
  2707. $getServer = simplexml_load_string(@curl_get($address."/?X-Plex-Token=".PLEXTOKEN));
  2708. if (!$getServer) { return 'Could not load!'; }
  2709. // Identify the local machine
  2710. $server = $getServer['machineIdentifier'];
  2711. $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>";
  2712. $items = "";
  2713. $albums = $movies = $shows = 0;
  2714. $style = 'style="vertical-align: middle"';
  2715. foreach($api AS $child) {
  2716. if($child['type'] != "artist" && $child['type'] != "episode" && isset($child['librarySectionID'])){
  2717. $time = (string)$child['addedAt'];
  2718. $time = new DateTime("@$time");
  2719. $results = array(
  2720. "title" => (string)$child['title'],
  2721. "image" => (string)$child['thumb'],
  2722. "type" => (string)ucwords($child['type']),
  2723. "year" => (string)$child['year'],
  2724. "key" => (string)$child['ratingKey']."-search",
  2725. "ratingkey" => (string)$child['ratingKey'],
  2726. "genre" => (string)$child->Genre['tag'],
  2727. "added" => $time->format('Y-m-d'),
  2728. "extra" => "",
  2729. );
  2730. switch ($child['type']){
  2731. case "album":
  2732. $push = array(
  2733. "title" => (string)$child['parentTitle']." - ".(string)$child['title'],
  2734. );
  2735. $results = array_replace($results,$push);
  2736. $albums++;
  2737. break;
  2738. case "movie":
  2739. $push = array(
  2740. "extra" => "Content Rating: ".(string)$child['contentRating']."<br/>Movie Rating: ".(string)$child['rating'],
  2741. );
  2742. $results = array_replace($results,$push);
  2743. $movies++;
  2744. break;
  2745. case "show":
  2746. $push = array(
  2747. "extra" => "Seasons: ".(string)$child['childCount']."<br/>Episodes: ".(string)$child['leafCount'],
  2748. );
  2749. $results = array_replace($results,$push);
  2750. $shows++;
  2751. break;
  2752. }
  2753. if (file_exists('images/cache/'.$results['key'].'.jpg')){ $image_url = 'images/cache/'.$results['key'].'.jpg'; }
  2754. if (file_exists('images/cache/'.$results['key'].'.jpg') && (time() - 604800) > filemtime('images/cache/'.$results['key'].'.jpg') || !file_exists('images/cache/'.$results['key'].'.jpg')) {
  2755. $image_url = 'ajax.php?a=plex-image&img='.$results['image'].'&height=150&width=100&key='.$results['key'];
  2756. }
  2757. if(!$results['image']){ $image_url = "images/no-search.png"; $key = "no-search"; }
  2758. if (substr_count(PLEXURL, ':') == 2) {
  2759. $link = "https://app.plex.tv/web/app#!/server/$server/details?key=/library/metadata/".$results['ratingkey'];
  2760. }else{
  2761. $link = PLEXURL."/web/index.html#!/server/$server/details?key=/library/metadata/".$results['ratingkey'];
  2762. }
  2763. $items .= '<tr style="cursor: pointer;" class="openTab" openTab="'.$openTab.'" href="'.$link.'">
  2764. <th scope="row"><img src="'.$image_url.'"></th>
  2765. <td class="col-xs-2 nzbtable nzbtable-row"'.$style.'>'.$results['title'].'</td>
  2766. <td class="col-xs-3 nzbtable nzbtable-row"'.$style.'>'.$results['genre'].'</td>
  2767. <td class="col-xs-1 nzbtable nzbtable-row"'.$style.'>'.$results['year'].'</td>
  2768. <td class="col-xs-1 nzbtable nzbtable-row"'.$style.'>'.$results['type'].'</td>
  2769. <td class="col-xs-3 nzbtable nzbtable-row"'.$style.'>'.$results['added'].'</td>
  2770. <td class="col-xs-2 nzbtable nzbtable-row"'.$style.'>'.$results['extra'].'</td>
  2771. </tr>';
  2772. }
  2773. }
  2774. $totals = '<div style="margin: 10px;" class="sort-todo pull-right">
  2775. <span class="badge gray-bg"><i class="fa fa-film fa-2x white"></i><strong style="
  2776. font-size: 23px;
  2777. ">&nbsp;'.$movies.'</strong></span>
  2778. <span class="badge gray-bg"><i class="fa fa-tv fa-2x white"></i><strong style="
  2779. font-size: 23px;
  2780. ">&nbsp;'.$shows.'</strong></span>
  2781. <span class="badge gray-bg"><i class="fa fa-music fa-2x white"></i><strong style="
  2782. font-size: 23px;
  2783. ">&nbsp;'.$albums.'</strong></span>
  2784. </div>';
  2785. return (!empty($items) ? $totals.$pre.$items."</div></table>" : "<h2 class='text-center'>No Results for $query</h2>" );
  2786. }
  2787. function getBannedUsers($string){
  2788. if (strpos($string, ',') !== false) {
  2789. $banned = explode(",", $string);
  2790. }else{
  2791. $banned = array($string);
  2792. }
  2793. return $banned;
  2794. }
  2795. function getWhitelist($string){
  2796. if (strpos($string, ',') !== false) {
  2797. $whitelist = explode(",", $string);
  2798. }else{
  2799. $whitelist = array($string);
  2800. }
  2801. foreach($whitelist as &$ip){
  2802. $ip = is_numeric(substr($ip, 0, 1)) ? $ip : gethostbyname($ip);
  2803. }
  2804. return $whitelist;
  2805. }
  2806. function get_client_ip() {
  2807. $ipaddress = '';
  2808. if (isset($_SERVER['HTTP_CLIENT_IP']))
  2809. $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  2810. else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  2811. $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  2812. else if(isset($_SERVER['HTTP_X_FORWARDED']))
  2813. $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  2814. else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
  2815. $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  2816. else if(isset($_SERVER['HTTP_FORWARDED']))
  2817. $ipaddress = $_SERVER['HTTP_FORWARDED'];
  2818. else if(isset($_SERVER['REMOTE_ADDR']))
  2819. $ipaddress = $_SERVER['REMOTE_ADDR'];
  2820. else
  2821. $ipaddress = 'UNKNOWN';
  2822. return $ipaddress;
  2823. }
  2824. //EMAIL SHIT
  2825. function sendEmail($email, $username = "Organizr User", $subject, $body, $cc = null){
  2826. $mail = new PHPMailer;
  2827. $mail->isSMTP();
  2828. $mail->Host = SMTPHOST;
  2829. $mail->SMTPAuth = SMTPHOSTAUTH;
  2830. $mail->Username = SMTPHOSTUSERNAME;
  2831. $mail->Password = SMTPHOSTPASSWORD;
  2832. $mail->SMTPSecure = SMTPHOSTTYPE;
  2833. $mail->Port = SMTPHOSTPORT;
  2834. $mail->setFrom(SMTPHOSTSENDEREMAIL, SMTPHOSTSENDERNAME);
  2835. $mail->addReplyTo(SMTPHOSTSENDEREMAIL, SMTPHOSTSENDERNAME);
  2836. $mail->isHTML(true);
  2837. $mail->addAddress($email, $username);
  2838. $mail->Subject = $subject;
  2839. $mail->Body = $body;
  2840. //$mail->send();
  2841. if(!$mail->send()) {
  2842. writeLog("error", "mail failed to send");
  2843. } else {
  2844. writeLog("success", "mail has been sent");
  2845. }
  2846. }
  2847. function libraryList(){
  2848. $address = qualifyURL(PLEXURL);
  2849. $headers = array(
  2850. "Accept" => "application/json",
  2851. "X-Plex-Token" => PLEXTOKEN
  2852. );
  2853. $getServer = simplexml_load_string(@curl_get($address."/?X-Plex-Token=".PLEXTOKEN));
  2854. if (!$getServer) { return 'Could not load!'; }else { $gotServer = $getServer['machineIdentifier']; }
  2855. $api = simplexml_load_string(@curl_get("https://plex.tv/api/servers/$gotServer/shared_servers", $headers));
  2856. $libraryList = array();
  2857. foreach($api->SharedServer->Section AS $child) {
  2858. $libraryList['libraries'][(string)$child['title']] = (string)$child['id'];
  2859. }
  2860. foreach($api->SharedServer AS $child) {
  2861. if(!empty($child['username'])){
  2862. $username = (string)strtolower($child['username']);
  2863. $libraryList['users'][$username] = (string)$child['id'];
  2864. }
  2865. }
  2866. return (!empty($libraryList) ? array_change_key_case($libraryList,CASE_LOWER) : null );
  2867. }
  2868. function plexUserShare($username){
  2869. $address = qualifyURL(PLEXURL);
  2870. $headers = array(
  2871. "Accept" => "application/json",
  2872. "Content-Type" => "application/json",
  2873. "X-Plex-Token" => PLEXTOKEN
  2874. );
  2875. $getServer = simplexml_load_string(@curl_get($address."/?X-Plex-Token=".PLEXTOKEN));
  2876. if (!$getServer) { return 'Could not load!'; }else { $gotServer = $getServer['machineIdentifier']; }
  2877. $json = array(
  2878. "server_id" => $gotServer,
  2879. "shared_server" => array(
  2880. //"library_section_ids" => "[26527637]",
  2881. "invited_email" => $username
  2882. )
  2883. );
  2884. $api = curl_post("https://plex.tv/api/servers/$gotServer/shared_servers/", $json, $headers);
  2885. switch ($api['http_code']['http_code']){
  2886. case 400:
  2887. writeLog("error", "PLEX INVITE: $username already has access to the shared libraries");
  2888. $result = "$username already has access to the shared libraries";
  2889. break;
  2890. case 401:
  2891. writeLog("error", "PLEX INVITE: Invalid Plex Token");
  2892. $result = "Invalid Plex Token";
  2893. break;
  2894. case 200:
  2895. writeLog("success", "PLEX INVITE: $username now has access to your Plex Library");
  2896. $result = "$username now has access to your Plex Library";
  2897. break;
  2898. default:
  2899. writeLog("error", "PLEX INVITE: unknown error");
  2900. $result = false;
  2901. }
  2902. return (!empty($result) ? $result : null );
  2903. }
  2904. function plexUserDelete($username){
  2905. $address = qualifyURL(PLEXURL);
  2906. $headers = array(
  2907. "Accept" => "application/json",
  2908. "Content-Type" => "application/json",
  2909. "X-Plex-Token" => PLEXTOKEN
  2910. );
  2911. $getServer = simplexml_load_string(@curl_get($address."/?X-Plex-Token=".PLEXTOKEN));
  2912. if (!$getServer) { return 'Could not load!'; }else { $gotServer = $getServer['machineIdentifier']; }
  2913. $id = convertPlexName($username, "id");
  2914. $api = curl_delete("https://plex.tv/api/servers/$gotServer/shared_servers/$id", $headers);
  2915. switch ($api['http_code']['http_code']){
  2916. case 401:
  2917. writeLog("error", "PLEX INVITE: Invalid Plex Token");
  2918. $result = "Invalid Plex Token";
  2919. break;
  2920. case 200:
  2921. writeLog("success", "PLEX INVITE: $username doesn't have access to your Plex Library anymore");
  2922. $result = "$username doesn't have access to your Plex Library anymore";
  2923. break;
  2924. default:
  2925. writeLog("error", "PLEX INVITE: unknown error");
  2926. $result = false;
  2927. }
  2928. return (!empty($result) ? $result : null );
  2929. }
  2930. function convertPlexName($user, $type){
  2931. $array = libraryList();
  2932. switch ($type){
  2933. case "username":
  2934. $plexUser = array_search ($user, $array['users']);
  2935. break;
  2936. case "id":
  2937. if (array_key_exists(strtolower($user), $array['users'])) {
  2938. $plexUser = $array['users'][strtolower($user)];
  2939. }
  2940. break;
  2941. default:
  2942. $plexUser = false;
  2943. }
  2944. return (!empty($plexUser) ? $plexUser : null );
  2945. }
  2946. function randomCode($length = 5, $type = null) {
  2947. switch ($type){
  2948. case "alpha":
  2949. $legend = array_merge(range('A', 'Z'));
  2950. break;
  2951. case "numeric":
  2952. $legend = array_merge(range(0,9));
  2953. break;
  2954. default:
  2955. $legend = array_merge(range(0,9),range('A', 'Z'));
  2956. }
  2957. $code = "";
  2958. for($i=0; $i < $length; $i++) {
  2959. $code .= $legend[mt_rand(0, count($legend) - 1)];
  2960. }
  2961. return $code;
  2962. }
  2963. function inviteCodes($action, $code = null, $usedBy = null) {
  2964. if (!isset($GLOBALS['file_db'])) {
  2965. $GLOBALS['file_db'] = new PDO('sqlite:'.DATABASE_LOCATION.'users.db');
  2966. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  2967. }
  2968. $now = date("Y-m-d H:i:s");
  2969. switch ($action) {
  2970. case "get":
  2971. // Start Array
  2972. $result = array();
  2973. // Database Lookup
  2974. $invites = $GLOBALS['file_db']->query('SELECT * FROM invites WHERE valid = "Yes"');
  2975. // Get Codes
  2976. foreach($invites as $row) {
  2977. array_push($result, $row['code']);
  2978. }
  2979. // Return the Results
  2980. return (!empty($result) ? $result : false );
  2981. break;
  2982. case "check":
  2983. // Start Array
  2984. $result = array();
  2985. // Database Lookup
  2986. $invites = $GLOBALS['file_db']->query('SELECT * FROM invites WHERE valid = "Yes" AND code = "'.$code.'"');
  2987. // Get Codes
  2988. foreach($invites as $row) {
  2989. $result = $row['code'];
  2990. }
  2991. // Return the Results
  2992. return (!empty($result) ? $result : false );
  2993. break;
  2994. case "use":
  2995. $currentIP = get_client_ip();
  2996. $invites = $GLOBALS['file_db']->query('UPDATE invites SET valid = "No", usedby = "'.$usedBy.'", dateused = "'.$now.'", ip = "'.$currentIP.'" WHERE code = "'.$code.'"');
  2997. return (!empty($invites) ? true : false );
  2998. break;
  2999. }
  3000. }
  3001. function plexJoin($username, $email, $password){
  3002. $connectURL = 'https://plex.tv/users.json';
  3003. $headers = array(
  3004. 'Accept'=> 'application/json',
  3005. 'Content-Type' => 'application/x-www-form-urlencoded',
  3006. 'X-Plex-Product' => 'Organizr',
  3007. 'X-Plex-Version' => '1.0',
  3008. 'X-Plex-Client-Identifier' => '01010101-10101010',
  3009. );
  3010. $body = array(
  3011. 'user[email]' => $email,
  3012. 'user[username]' => $username,
  3013. 'user[password]' => $password,
  3014. );
  3015. $api = curl_post($connectURL, $body, $headers);
  3016. $json = json_decode($api['content'], true);
  3017. $errors = (!empty($json['errors']) ? true : false);
  3018. $success = (!empty($json['user']) ? true : false);
  3019. //Use This for later
  3020. $usernameError = (!empty($json['errors']['username']) ? $json['errors']['username'][0] : false);
  3021. $emailError = (!empty($json['errors']['email']) ? $json['errors']['email'][0] : false);
  3022. $passwordError = (!empty($json['errors']['password']) ? $json['errors']['password'][0] : false);
  3023. switch ($api['http_code']['http_code']){
  3024. case 400:
  3025. writeLog("error", "PLEX JOIN: $username already has access to the shared libraries");
  3026. break;
  3027. case 401:
  3028. writeLog("error", "PLEX JOIN: invalid Plex Token");
  3029. break;
  3030. case 422:
  3031. writeLog("error", "PLEX JOIN: user info error");
  3032. break;
  3033. case 429:
  3034. writeLog("error", "PLEX JOIN: too many requests to plex.tv please try later");
  3035. break;
  3036. case 200:
  3037. case 201:
  3038. writeLog("success", "PLEX JOIN: $username now has access to your Plex Library");
  3039. break;
  3040. default:
  3041. writeLog("error", "PLEX JOIN: unknown error, Error: ".$api['http_code']['http_code']);
  3042. }
  3043. //prettyPrint($api);
  3044. //prettyPrint(json_decode($api['content'], true));
  3045. return (!empty($success) && empty($errors) ? true : false );
  3046. }
  3047. function getCert(){
  3048. $url = "http://curl.haxx.se/ca/cacert.pem";
  3049. $file = getcwd()."/config/cacert.pem";
  3050. $directory = getcwd()."/config/";
  3051. @mkdir($directory, 0770, true);
  3052. if(!file_exists($file)){
  3053. file_put_contents( $file, fopen($url, 'r'));
  3054. writeLog("success", "CERT PEM: pem file created");
  3055. }elseif (file_exists($file) && time() - 2592000 > filemtime($file)) {
  3056. writeLog("success", "CERT PEM: downloaded new pem file");
  3057. }
  3058. return $file;
  3059. }
  3060. function customCSS(){
  3061. if(CUSTOMCSS == "true") {
  3062. $template_file = "custom.css";
  3063. $file_handle = fopen($template_file, "rb");
  3064. echo "\n";
  3065. echo fread($file_handle, filesize($template_file));
  3066. fclose($file_handle);
  3067. echo "\n";
  3068. }
  3069. }
  3070. // Always run this
  3071. dependCheck();