functions.php 126 KB

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