functions.php 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093
  1. <?php
  2. // ===================================
  3. // Define Version
  4. define('INSTALLEDVERSION', '1.39');
  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. // Format Data
  283. switch (isset($headers['Content-Type'])?$headers['Content-Type']:'') {
  284. case 'application/json':
  285. curl_setopt($curlReq, CURLOPT_POSTFIELDS, json_encode($data));
  286. break;
  287. case 'application/x-www-form-urlencoded';
  288. curl_setopt($curlReq, CURLOPT_POSTFIELDS, http_build_query($data));
  289. break;
  290. default:
  291. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  292. curl_setopt($curlReq, CURLOPT_POSTFIELDS, http_build_query($data));
  293. }
  294. // Format Headers
  295. $cHeaders = array();
  296. foreach ($headers as $k => $v) {
  297. $cHeaders[] = $k.': '.$v;
  298. }
  299. if (count($cHeaders)) {
  300. curl_setopt($curlReq, CURLOPT_HTTPHEADER, $cHeaders);
  301. }
  302. // Execute
  303. $result = curl_exec($curlReq);
  304. // Close
  305. curl_close($curlReq);
  306. // Return
  307. return array('content'=>$result);
  308. }
  309. //Curl Get Function
  310. function curl_get($url, $headers = array()) {
  311. // Initiate cURL
  312. $curlReq = curl_init($url);
  313. // As post request
  314. curl_setopt($curlReq, CURLOPT_CUSTOMREQUEST, "GET");
  315. curl_setopt($curlReq, CURLOPT_RETURNTRANSFER, true);
  316. curl_setopt($curlReq, CURLOPT_CONNECTTIMEOUT, 5);
  317. // Format Headers
  318. $cHeaders = array();
  319. foreach ($headers as $k => $v) {
  320. $cHeaders[] = $k.': '.$v;
  321. }
  322. if (count($cHeaders)) {
  323. curl_setopt($curlReq, CURLOPT_HTTPHEADER, $cHeaders);
  324. }
  325. // Execute
  326. $result = curl_exec($curlReq);
  327. // Close
  328. curl_close($curlReq);
  329. // Return
  330. return $result;
  331. }
  332. endif;
  333. //Case-Insensitive Function
  334. function in_arrayi($needle, $haystack) {
  335. return in_array(strtolower($needle), array_map('strtolower', $haystack));
  336. }
  337. // HTTP post request (Removes need for curl, probably useless)
  338. function post_request($url, $data, $headers = array(), $referer='') {
  339. // Adapted from http://stackoverflow.com/a/28387011/6810513
  340. // Convert the data array into URL Parameters like a=b&foo=bar etc.
  341. if (isset($headers['Content-Type'])) {
  342. switch ($headers['Content-Type']) {
  343. case 'application/json':
  344. $data = json_encode($data);
  345. break;
  346. case 'application/x-www-form-urlencoded':
  347. $data = http_build_query($data);
  348. break;
  349. }
  350. } else {
  351. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  352. $data = http_build_query($data);
  353. }
  354. // parse the given URL
  355. $urlDigest = parse_url($url);
  356. // extract host and path:
  357. $host = $urlDigest['host'];
  358. $path = $urlDigest['path'];
  359. if ($urlDigest['scheme'] != 'http') {
  360. die('Error: Only HTTP request are supported, please use cURL to add HTTPS support! ('.$urlDigest['scheme'].'://'.$host.')');
  361. }
  362. // open a socket connection on port 80 - timeout: 30 sec
  363. $fp = fsockopen($host, (isset($urlDigest['port'])?':'.$urlDigest['port']:80), $errno, $errstr, 30);
  364. if ($fp){
  365. // send the request headers:
  366. fputs($fp, "POST $path HTTP/1.1\r\n");
  367. fputs($fp, "Host: $host\r\n");
  368. if ($referer != '')
  369. fputs($fp, "Referer: $referer\r\n");
  370. fputs($fp, "Content-length: ". strlen($data) ."\r\n");
  371. foreach($headers as $k => $v) {
  372. fputs($fp, $k.": ".$v."\r\n");
  373. }
  374. fputs($fp, "Connection: close\r\n\r\n");
  375. fputs($fp, $data);
  376. $result = '';
  377. while(!feof($fp)) {
  378. // receive the results of the request
  379. $result .= fgets($fp, 128);
  380. }
  381. }
  382. else {
  383. return array(
  384. 'status' => 'err',
  385. 'error' => "$errstr ($errno)"
  386. );
  387. }
  388. // close the socket connection:
  389. fclose($fp);
  390. // split the result header from the content
  391. $result = explode("\r\n\r\n", $result, 2);
  392. $header = isset($result[0]) ? $result[0] : '';
  393. $content = isset($result[1]) ? $result[1] : '';
  394. // return as structured array:
  395. return array(
  396. 'status' => 'ok',
  397. 'header' => $header,
  398. 'content' => $content,
  399. );
  400. }
  401. // Format item from Emby for Carousel
  402. function resolveEmbyItem($address, $token, $item, $nowPlaying = false, $showNames = false, $role = false, $moreInfo = false) {
  403. // Static Height
  404. $height = 444;
  405. // Get Item Details
  406. $itemDetails = json_decode(file_get_contents($address.'/Items?Ids='.$item['Id'].'&api_key='.$token),true)['Items'][0];
  407. $URL = "http://app.emby.media/itemdetails.html?id=".$itemDetails['Id'];
  408. switch ($itemDetails['Type']) {
  409. case 'Episode':
  410. $title = (isset($itemDetails['SeriesName'])?$itemDetails['SeriesName']:"");
  411. $imageId = (isset($itemDetails['SeriesId'])?$itemDetails['SeriesId']:$itemDetails['Id']);
  412. $width = 300;
  413. $style = '';
  414. $image = 'slick-image-tall';
  415. if(!$nowPlaying){
  416. $imageType = (isset($itemDetails['ImageTags']['Primary']) ? "Primary" : false);
  417. $key = $itemDetails['Id'] . "-list";
  418. }else{
  419. $height = 281;
  420. $width = 500;
  421. $imageId = isset($itemDetails['ParentThumbItemId']) ? $itemDetails['ParentThumbItemId'] : (isset($itemDetails['ParentBackdropItemId']) ? $itemDetails['ParentBackdropItemId'] : false);
  422. $imageType = isset($itemDetails['ParentThumbItemId']) ? "Thumb" : (isset($itemDetails['ParentBackdropItemId']) ? "Backdrop" : false);
  423. $key = (isset($itemDetails['ParentThumbItemId']) ? $itemDetails['ParentThumbItemId']."-np" : "none-np");
  424. $elapsed = $moreInfo['PlayState']['PositionTicks'];
  425. $duration = $moreInfo['NowPlayingItem']['RunTimeTicks'];
  426. $watched = floor(($elapsed / $duration) * 100);
  427. //$transcoded = floor($item->TranscodeSession['progress']- $watched);
  428. $stream = $moreInfo['PlayState']['PlayMethod'];
  429. $user = $role == "admin" ? $moreInfo['UserName'] : "";
  430. $id = $moreInfo['DeviceId'];
  431. $streamInfo = buildStream(array(
  432. 'platform' => (string) $moreInfo['Client'],
  433. 'device' => (string) $moreInfo['DeviceName'],
  434. 'stream' => "&nbsp;".streamType($stream),
  435. 'video' => streamType($stream)." ".embyArray($moreInfo['NowPlayingItem']['MediaStreams'], "video"),
  436. 'audio' => "&nbsp;".streamType($stream)." ".embyArray($moreInfo['NowPlayingItem']['MediaStreams'], "audio"),
  437. ));
  438. $state = (($moreInfo['PlayState']['IsPaused'] == "1") ? "pause" : "play");
  439. $topTitle = '<h5 class="text-center zero-m elip">'.$title.' - '.$itemDetails['Name'].'</h5>';
  440. $bottomTitle = '<small class="zero-m">S'.$itemDetails['ParentIndexNumber'].' · E'.$itemDetails['IndexNumber'].'</small>';
  441. if($showNames == "true"){ $bottomTitle .= '</small><small class="zero-m pull-right">'.$user.'</small>'; }
  442. }
  443. break;
  444. case 'MusicAlbum':
  445. case 'Audio':
  446. $title = $itemDetails['Name'];
  447. $imageId = $itemDetails['Id'];
  448. $width = 444;
  449. $style = '';
  450. $image = 'slick-image-short';
  451. if(!$nowPlaying){
  452. $imageType = (isset($itemDetails['ImageTags']['Primary']) ? "Primary" : false);
  453. $key = $itemDetails['Id'] . "-list";
  454. }else{
  455. $height = 281;
  456. $width = 500;
  457. $imageId = (isset($itemDetails['ParentBackdropItemId']) ? $itemDetails['ParentBackdropItemId'] : false);
  458. $imageType = (isset($itemDetails['ParentBackdropItemId']) ? "Backdrop" : false);
  459. $key = (isset($itemDetails['ParentBackdropItemId']) ? $itemDetails['ParentBackdropItemId'] : "no-np") . "-np";
  460. $elapsed = $moreInfo['PlayState']['PositionTicks'];
  461. $duration = $moreInfo['NowPlayingItem']['RunTimeTicks'];
  462. $watched = floor(($elapsed / $duration) * 100);
  463. //$transcoded = floor($item->TranscodeSession['progress']- $watched);
  464. $stream = $moreInfo['PlayState']['PlayMethod'];
  465. $user = $role == "admin" ? $moreInfo['UserName'] : "";
  466. $id = $moreInfo['DeviceId'];
  467. $streamInfo = buildStream(array(
  468. 'platform' => (string) $moreInfo['Client'],
  469. 'device' => (string) $moreInfo['DeviceName'],
  470. 'stream' => "&nbsp;".streamType($stream),
  471. 'audio' => "&nbsp;".streamType($stream)." ".embyArray($moreInfo['NowPlayingItem']['MediaStreams'], "audio"),
  472. ));
  473. $state = (($moreInfo['PlayState']['IsPaused'] == "1") ? "pause" : "play");
  474. $topTitle = '<h5 class="text-center zero-m elip">'.$itemDetails['AlbumArtist'].' - '.$itemDetails['Album'].'</h5>';
  475. $bottomTitle = '<small class="zero-m">'.$title.'</small>';
  476. if($showNames == "true"){ $bottomTitle .= '</small><small class="zero-m pull-right">'.$user.'</small>'; }
  477. }
  478. break;
  479. case 'TvChannel':
  480. $title = $itemDetails['CurrentProgram']['Name'];
  481. $imageId = $itemDetails['Id'];
  482. $width = 300;
  483. $style = '';
  484. $image = 'slick-image-tall';
  485. if(!$nowPlaying){
  486. $imageType = "Primary";
  487. $key = $itemDetails['Id'] . "-list";
  488. }else{
  489. $height = 281;
  490. $width = 500;
  491. $imageType = "Thumb";
  492. $key = $itemDetails['Id'] . "-np";
  493. $useImage = "images/livetv.png";
  494. $watched = "0";
  495. $stream = $moreInfo['PlayState']['PlayMethod'];
  496. $user = $role == "admin" ? $moreInfo['UserName'] : "";
  497. $id = $moreInfo['DeviceId'];
  498. $streamInfo = buildStream(array(
  499. 'platform' => (string) $moreInfo['Client'],
  500. 'device' => (string) $moreInfo['DeviceName'],
  501. 'stream' => "&nbsp;".streamType($stream),
  502. 'video' => streamType($stream)." ".embyArray($moreInfo['NowPlayingItem']['MediaStreams'], "video"),
  503. 'audio' => "&nbsp;".streamType($stream)." ".embyArray($moreInfo['NowPlayingItem']['MediaStreams'], "audio"),
  504. ));
  505. $state = (($moreInfo['PlayState']['IsPaused'] == "1") ? "pause" : "play");
  506. $topTitle = '<h5 class="text-center zero-m elip">'.$title.'</h5>';
  507. $bottomTitle = '<small class="zero-m">'.$itemDetails['Name'].' - '.$itemDetails['ChannelNumber'].'</small>';
  508. if($showNames == "true"){ $bottomTitle .= '</small><small class="zero-m pull-right">'.$user.'</small>'; }
  509. }
  510. break;
  511. default:
  512. $title = $itemDetails['Name'];
  513. $imageId = $itemDetails['Id'];
  514. $width = 300;
  515. $style = '';
  516. $image = 'slick-image-tall';
  517. if(!$nowPlaying){
  518. $imageType = (isset($itemDetails['ImageTags']['Primary']) ? "Primary" : false);
  519. $key = $itemDetails['Id'] . "-list";
  520. }else{
  521. $height = 281;
  522. $width = 500;
  523. $imageType = isset($itemDetails['ImageTags']['Thumb']) ? "Thumb" : (isset($itemDetails['BackdropImageTags']) ? "Backdrop" : false);
  524. $key = $itemDetails['Id'] . "-np";
  525. $elapsed = $moreInfo['PlayState']['PositionTicks'];
  526. $duration = $moreInfo['NowPlayingItem']['RunTimeTicks'];
  527. $watched = floor(($elapsed / $duration) * 100);
  528. //$transcoded = floor($item->TranscodeSession['progress']- $watched);
  529. $stream = $moreInfo['PlayState']['PlayMethod'];
  530. $user = $role == "admin" ? $moreInfo['UserName'] : "";
  531. $id = $moreInfo['DeviceId'];
  532. $streamInfo = buildStream(array(
  533. 'platform' => (string) $moreInfo['Client'],
  534. 'device' => (string) $moreInfo['DeviceName'],
  535. 'stream' => "&nbsp;".streamType($stream),
  536. 'video' => streamType($stream)." ".embyArray($moreInfo['NowPlayingItem']['MediaStreams'], "video"),
  537. 'audio' => "&nbsp;".streamType($stream)." ".embyArray($moreInfo['NowPlayingItem']['MediaStreams'], "audio"),
  538. ));
  539. $state = (($moreInfo['PlayState']['IsPaused'] == "1") ? "pause" : "play");
  540. $topTitle = '<h5 class="text-center zero-m elip">'.$title.'</h5>';
  541. $bottomTitle = '<small class="zero-m">'.$moreInfo['NowPlayingItem']['ProductionYear'].'</small>';
  542. if($showNames == "true"){ $bottomTitle .= '</small><small class="zero-m pull-right">'.$user.'</small>'; }
  543. }
  544. }
  545. // If No Overview
  546. if (!isset($itemDetails['Overview'])) {
  547. $itemDetails['Overview'] = '';
  548. }
  549. if (file_exists('images/cache/'.$key.'.jpg')){ $image_url = 'images/cache/'.$key.'.jpg'; }
  550. if (file_exists('images/cache/'.$key.'.jpg') && (time() - 604800) > filemtime('images/cache/'.$key.'.jpg') || !file_exists('images/cache/'.$key.'.jpg')) {
  551. $image_url = 'ajax.php?a=emby-image&type='.$imageType.'&img='.$imageId.'&height='.$height.'&width='.$width.'&key='.$key.'';
  552. }
  553. if($nowPlaying){
  554. if(!$imageType){ $image_url = "images/no-np.png"; $key = "no-np"; }
  555. if(!$imageId){ $image_url = "images/no-np.png"; $key = "no-np"; }
  556. }else{
  557. if(!$imageType){ $image_url = "images/no-list.png"; $key = "no-list"; }
  558. if(!$imageId){ $image_url = "images/no-list.png"; $key = "no-list"; }
  559. }
  560. if(isset($useImage)){ $image_url = $useImage; }
  561. // Assemble Item And Cache Into Array
  562. if($nowPlaying){
  563. //prettyPrint($itemDetails);
  564. 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>';
  565. }else{
  566. 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>';
  567. }
  568. }
  569. // Format item from Plex for Carousel
  570. function resolvePlexItem($server, $token, $item, $nowPlaying = false, $showNames = false, $role = false) {
  571. // Static Height
  572. $height = 444;
  573. $address = "https://app.plex.tv/web/app#!/server/$server/details?key=/library/metadata/".$item['ratingKey'];
  574. switch ($item['type']) {
  575. case 'season':
  576. $title = $item['parentTitle'];
  577. $summary = $item['parentSummary'];
  578. $width = 300;
  579. $image = 'slick-image-tall';
  580. $style = '';
  581. if(!$nowPlaying){
  582. $thumb = $item['thumb'];
  583. $key = $item['ratingKey'] . "-list";
  584. }else {
  585. $height = 281;
  586. $width = 500;
  587. $thumb = $item['art'];
  588. $key = $item['ratingKey'] . "-np";
  589. $elapsed = $item['viewOffset'];
  590. $duration = $item['duration'];
  591. $watched = floor(($elapsed / $duration) * 100);
  592. $transcoded = floor($item->TranscodeSession['progress']- $watched);
  593. $stream = $item->Media->Part->Stream['decision'];
  594. $user = $role == "admin" ? $item->User['title'] : "";
  595. $id = $item->Session['id'];
  596. $streamInfo = buildStream(array(
  597. 'platform' => (string) $item->Player['platform'],
  598. 'device' => (string) $item->Player['device'],
  599. 'stream' => "&nbsp;".streamType($item->Media->Part['decision']),
  600. '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'].")",
  601. 'audio' => "&nbsp;".streamType($item->Media->Part->Stream[1]['decision'])." (".$item->Media->Part->Stream[1]['codec'].") (".$item->Media->Part->Stream[1]['channels']."ch)",
  602. ));
  603. $state = (($item->Player['state'] == "paused") ? "pause" : "play");
  604. }
  605. break;
  606. case 'episode':
  607. $title = $item['grandparentTitle'];
  608. $summary = $item['title'];
  609. $width = 300;
  610. $image = 'slick-image-tall';
  611. $style = '';
  612. if(!$nowPlaying){
  613. $thumb = $item['parentThumb'];
  614. $key = $item['ratingKey'] . "-list";
  615. }else {
  616. $height = 281;
  617. $width = 500;
  618. $thumb = $item['art'];
  619. $key = $item['ratingKey'] . "-np";
  620. $elapsed = $item['viewOffset'];
  621. $duration = $item['duration'];
  622. $watched = floor(($elapsed / $duration) * 100);
  623. $transcoded = floor($item->TranscodeSession['progress']- $watched);
  624. $stream = $item->Media->Part->Stream['decision'];
  625. $user = $role == "admin" ? $item->User['title'] : "";
  626. $id = $item->Session['id'];
  627. $streamInfo = buildStream(array(
  628. 'platform' => (string) $item->Player['platform'],
  629. 'device' => (string) $item->Player['device'],
  630. 'stream' => "&nbsp;".streamType($item->Media->Part['decision']),
  631. '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'].")",
  632. 'audio' => "&nbsp;".streamType($item->Media->Part->Stream[1]['decision'])." (".$item->Media->Part->Stream[1]['codec'].") (".$item->Media->Part->Stream[1]['channels']."ch)",
  633. ));
  634. $state = (($item->Player['state'] == "paused") ? "pause" : "play");
  635. $topTitle = '<h5 class="text-center zero-m elip">'.$title.' - '.$item['title'].'</h5>';
  636. $bottomTitle = '<small class="zero-m">S'.$item['parentIndex'].' · E'.$item['index'].'</small>';
  637. if($showNames == "true"){ $bottomTitle .= '</small><small class="zero-m pull-right">'.$user.'</small>'; }
  638. }
  639. break;
  640. case 'clip':
  641. $title = $item['title'];
  642. $summary = $item['summary'];
  643. $width = 300;
  644. $image = 'slick-image-tall';
  645. $style = '';
  646. if(!$nowPlaying){
  647. $thumb = $item['thumb'];
  648. $key = $item['ratingKey'] . "-list";
  649. }else {
  650. $height = 281;
  651. $width = 500;
  652. $thumb = $item['art'];
  653. $key = $item['ratingKey'] . "-np";
  654. $elapsed = $item['viewOffset'];
  655. $duration = $item['duration'];
  656. $watched = floor(($elapsed / $duration) * 100);
  657. $transcoded = floor($item->TranscodeSession['progress']- $watched);
  658. $stream = $item->Media->Part->Stream['decision'];
  659. $user = $role == "admin" ? $item->User['title'] : "";
  660. $id = $item->Session['id'];
  661. $streamInfo = buildStream(array(
  662. 'platform' => (string) $item->Player['platform'],
  663. 'device' => (string) $item->Player['device'],
  664. 'stream' => "&nbsp;".streamType($item->Media->Part['decision']),
  665. 'video' => streamType($item->Media->Part->Stream[0]['decision'])." (".$item->Media->Part->Stream[0]['codec'].") (".$item->Media->Part->Stream[0]['width']."x".$item->Media->Part->Stream[0]['height'].")",
  666. 'audio' => "&nbsp;".streamType($item->Media->Part->Stream[1]['decision'])." (".$item->Media->Part->Stream[1]['codec'].") (".$item->Media->Part->Stream[1]['channels']."ch)",
  667. ));
  668. $state = (($item->Player['state'] == "paused") ? "pause" : "play");
  669. $topTitle = '<h5 class="text-center zero-m elip">'.$title.' [Trailer/Clip]</h5>';
  670. $bottomTitle = '<small class="zero-m">'.$item['year'].'</small>';
  671. if($showNames == "true"){ $bottomTitle .= '<small class="zero-m pull-right">'.$user.'</small>'; }
  672. }
  673. break;
  674. case 'album':
  675. case 'track':
  676. $title = $item['parentTitle'];
  677. $summary = $item['title'];
  678. $image = 'slick-image-short';
  679. $style = 'left: 160px !important;';
  680. if(!$nowPlaying){
  681. $width = 444;
  682. $thumb = $item['thumb'];
  683. $key = $item['ratingKey'] . "-list";
  684. }else {
  685. $height = 281;
  686. $width = 500;
  687. $thumb = $item['art'];
  688. $key = $item['ratingKey'] . "-np";
  689. $elapsed = $item['viewOffset'];
  690. $duration = $item['duration'];
  691. $watched = floor(($elapsed / $duration) * 100);
  692. $transcoded = floor($item->TranscodeSession['progress']- $watched);
  693. $stream = $item->Media->Part->Stream['decision'];
  694. $user = $role == "admin" ? $item->User['title'] : "";
  695. $id = $item->Session['id'];
  696. $streamInfo = buildStream(array(
  697. 'platform' => (string) $item->Player['platform'],
  698. 'device' => (string) $item->Player['device'],
  699. 'stream' => "&nbsp;".streamType($item->Media->Part['decision']),
  700. 'audio' => "&nbsp;".streamType($item->Media->Part->Stream[0]['decision'])." (".$item->Media->Part->Stream[0]['codec'].") (".$item->Media->Part->Stream[0]['channels']."ch)",
  701. ));
  702. $state = (($item->Player['state'] == "paused") ? "pause" : "play");
  703. $topTitle = '<h5 class="text-center zero-m elip">'.$item['grandparentTitle'].' - '.$item['title'].'</h5>';
  704. $bottomTitle = '<small class="zero-m">'.$title.'</small>';
  705. if($showNames == "true"){ $bottomTitle .= '<small class="zero-m pull-right">'.$user.'</small>'; }
  706. }
  707. break;
  708. default:
  709. $title = $item['title'];
  710. $summary = $item['summary'];
  711. $image = 'slick-image-tall';
  712. $style = '';
  713. if(!$nowPlaying){
  714. $width = 300;
  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 = $item->Session['id'];
  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. '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'].")",
  734. 'audio' => "&nbsp;".streamType($item->Media->Part->Stream[1]['decision'])." (".$item->Media->Part->Stream[1]['codec'].") (".$item->Media->Part->Stream[1]['channels']."ch)",
  735. ));
  736. $state = (($item->Player['state'] == "paused") ? "pause" : "play");
  737. $topTitle = '<h5 class="text-center zero-m elip">'.$title.'</h5>';
  738. $bottomTitle = '<small class="zero-m">'.$item['year'].'</small>';
  739. if($showNames == "true"){ $bottomTitle .= '<small class="zero-m pull-right">'.$user.'</small>'; }
  740. }
  741. }
  742. // If No Overview
  743. if (!isset($itemDetails['Overview'])) { $itemDetails['Overview'] = ''; }
  744. if (file_exists('images/cache/'.$key.'.jpg')){ $image_url = 'images/cache/'.$key.'.jpg'; }
  745. if (file_exists('images/cache/'.$key.'.jpg') && (time() - 604800) > filemtime('images/cache/'.$key.'.jpg') || !file_exists('images/cache/'.$key.'.jpg')) {
  746. $image_url = 'ajax.php?a=plex-image&img='.$thumb.'&height='.$height.'&width='.$width.'&key='.$key.'';
  747. }
  748. if(!$thumb){ $image_url = "images/no-np.png"; $key = "no-np"; }
  749. // Assemble Item And Cache Into Array
  750. if($nowPlaying){
  751. 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="'.$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>';
  752. }else{
  753. return '<div class="item-'.$item['type'].'"><a 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>';
  754. }
  755. }
  756. //Recent Added
  757. function outputRecentAdded($header, $items, $script = false, $array) {
  758. $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">';
  759. if($array["movie"] == "true"){
  760. $hideMenu .= '<li><a class="js-filter-movie" href="javascript:void(0)">Hide Movies</a></li>';
  761. }
  762. if($array["season"] == "true"){
  763. $hideMenu .= '<li><a class="js-filter-season" href="javascript:void(0)">Hide Show</a></li>';
  764. }
  765. if($array["album"] == "true"){
  766. $hideMenu .= '<li><a class="js-filter-album" href="javascript:void(0)">Hide Music</a></li>';
  767. }
  768. $hideMenu .= '</ul></div></div>';
  769. // If None Populate Empty Item
  770. if (!count($items)) {
  771. return '<div id=recentMedia><h5 class="text-center">'.$header.'</h5><p class="text-center">No Media Found</p></div>';
  772. }else{
  773. 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>':'');
  774. }
  775. }
  776. // Create Carousel
  777. function outputNowPlaying($header, $size, $type, $items, $script = false) {
  778. // If None Populate Empty Item
  779. if (!count($items)) {
  780. return '<div id=streamz></div>'.($script?'<script>'.$script.'</script>':'');
  781. }else{
  782. return '<div id=streamz><h5 class="text-center">'.$header.'</h5>'.implode('',$items).'</div>'.($script?'<script>'.$script.'</script>':'');
  783. }
  784. }
  785. // Get Now Playing Streams From Emby
  786. function getEmbyStreams($size, $showNames, $role) {
  787. $address = qualifyURL(EMBYURL);
  788. $api = json_decode(@file_get_contents($address.'/Sessions?api_key='.EMBYTOKEN),true);
  789. if (!is_array($api)) { return 'Could not load!'; }
  790. $playingItems = array();
  791. foreach($api as $key => $value) {
  792. if (isset($value['NowPlayingItem'])) {
  793. $playingItems[] = resolveEmbyItem($address, EMBYTOKEN, $value['NowPlayingItem'], true, $showNames, $role, $value);
  794. }
  795. }
  796. return outputNowPlaying(translate('PLAYING_NOW_ON_EMBY'), $size, 'streams-emby', $playingItems, "
  797. setInterval(function() {
  798. $('<div></div>').load('ajax.php?a=emby-streams',function() {
  799. var element = $(this).find('[id]');
  800. var loadedID = element.attr('id');
  801. $('#'+loadedID).replaceWith(element);
  802. console.log('Loaded updated: '+loadedID);
  803. });
  804. }, 15000);
  805. ");
  806. }
  807. // Get Now Playing Streams From Plex
  808. function getPlexStreams($size, $showNames, $role){
  809. $address = qualifyURL(PLEXURL);
  810. // Perform API requests
  811. $api = @curl_get($address."/status/sessions?X-Plex-Token=".PLEXTOKEN);
  812. $api = simplexml_load_string($api);
  813. $getServer = simplexml_load_string(@curl_get($address."/?X-Plex-Token=".PLEXTOKEN));
  814. if (!$getServer) { return 'Could not load!'; }
  815. // Identify the local machine
  816. $gotServer = $getServer['machineIdentifier'];
  817. $items = array();
  818. foreach($api AS $child) {
  819. $items[] = resolvePlexItem($gotServer, PLEXTOKEN, $child, true, $showNames, $role);
  820. }
  821. return outputNowPlaying(translate('PLAYING_NOW_ON_PLEX'), $size, 'streams-plex', $items, "
  822. setInterval(function() {
  823. $('<div></div>').load('ajax.php?a=plex-streams',function() {
  824. var element = $(this).find('[id]');
  825. var loadedID = element.attr('id');
  826. $('#'+loadedID).replaceWith(element);
  827. console.log('Loaded updated: '+loadedID);
  828. });
  829. }, 15000);
  830. ");
  831. }
  832. // Get Recent Content From Emby
  833. function getEmbyRecent($array) {
  834. $address = qualifyURL(EMBYURL);
  835. $header = translate('RECENT_CONTENT');
  836. // Currently Logged In User
  837. $username = false;
  838. if (isset($GLOBALS['USER'])) {
  839. $username = strtolower($GLOBALS['USER']->username);
  840. }
  841. // Get A User
  842. $userIds = json_decode(@file_get_contents($address.'/Users?api_key='.EMBYTOKEN),true);
  843. if (!is_array($userIds)) { return 'Could not load!'; }
  844. $showPlayed = true;
  845. foreach ($userIds as $value) { // Scan for admin user
  846. if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
  847. $userId = $value['Id'];
  848. }
  849. if ($username && strtolower($value['Name']) == $username) {
  850. $userId = $value['Id'];
  851. $showPlayed = false;
  852. break;
  853. }
  854. }
  855. // Get the latest Items
  856. $latest = json_decode(file_get_contents($address.'/Users/'.$userId.'/Items/Latest?EnableImages=false&Limit='.EMBYRECENTITEMS.'&api_key='.EMBYTOKEN.($showPlayed?'':'&IsPlayed=false')),true);
  857. // For Each Item In Category
  858. $items = array();
  859. foreach ($latest as $k => $v) {
  860. $type = (string) $v['Type'];
  861. if(@$array[$type] == "true"){
  862. $items[] = resolveEmbyItem($address, EMBYTOKEN, $v, false, false, false);
  863. }
  864. }
  865. $array["movie"] = $array["Movie"];
  866. $array["season"] = $array["Episode"];
  867. $array["album"] = $array["MusicAlbum"];
  868. unset($array["Movie"]);
  869. unset($array["Episode"]);
  870. unset($array["MusicAlbum"]);
  871. unset($array["Series"]);
  872. return outputRecentAdded($header, $items, "", $array);
  873. }
  874. // Get Recent Content From Plex
  875. function getPlexRecent($array){
  876. $address = qualifyURL(PLEXURL);
  877. $header = translate('RECENT_CONTENT');
  878. // Perform Requests
  879. $api = @curl_get($address."/library/recentlyAdded?limit=".PLEXRECENTITEMS."&X-Plex-Token=".PLEXTOKEN);
  880. $api = simplexml_load_string($api);
  881. $getServer = simplexml_load_string(@curl_get($address."/?X-Plex-Token=".PLEXTOKEN));
  882. if (!$getServer) { return 'Could not load!'; }
  883. // Identify the local machine
  884. $gotServer = $getServer['machineIdentifier'];
  885. $items = array();
  886. foreach($api AS $child) {
  887. $type = (string) $child['type'];
  888. if($array[$type] == "true"){
  889. $items[] = resolvePlexItem($gotServer, PLEXTOKEN, $child, false, false, false);
  890. }
  891. }
  892. return outputRecentAdded($header, $items, "", $array);
  893. }
  894. // Get Image From Emby
  895. function getEmbyImage() {
  896. $embyAddress = qualifyURL(EMBYURL);
  897. if (!file_exists('images/cache')) {
  898. mkdir('images/cache', 0777, true);
  899. }
  900. $itemId = $_GET['img'];
  901. $key = $_GET['key'];
  902. $itemType = $_GET['type'];
  903. $imgParams = array();
  904. if (isset($_GET['height'])) { $imgParams['height'] = 'maxHeight='.$_GET['height']; }
  905. if (isset($_GET['width'])) { $imgParams['width'] = 'maxWidth='.$_GET['width']; }
  906. if(isset($itemId)) {
  907. $image_src = $embyAddress . '/Items/'.$itemId.'/Images/'.$itemType.'?'.implode('&', $imgParams);
  908. $cachefile = 'images/cache/'.$key.'.jpg';
  909. $cachetime = 604800;
  910. // Serve from the cache if it is younger than $cachetime
  911. if (file_exists($cachefile) && time() - $cachetime > filemtime($cachefile)) {
  912. header("Content-type: image/jpeg");
  913. @readfile($cachefile);
  914. exit;
  915. }
  916. ob_start(); // Start the output buffer
  917. header('Content-type: image/jpeg');
  918. @readfile($image_src);
  919. // Cache the output to a file
  920. $fp = fopen($cachefile, 'wb');
  921. fwrite($fp, ob_get_contents());
  922. fclose($fp);
  923. ob_end_flush(); // Send the output to the browser
  924. die();
  925. } else {
  926. debug_out('Invalid Request',1);
  927. }
  928. }
  929. // Get Image From Plex
  930. function getPlexImage() {
  931. $plexAddress = qualifyURL(PLEXURL);
  932. if (!file_exists('images/cache')) {
  933. mkdir('images/cache', 0777, true);
  934. }
  935. $image_url = $_GET['img'];
  936. $key = $_GET['key'];
  937. $image_height = $_GET['height'];
  938. $image_width = $_GET['width'];
  939. if(isset($image_url) && isset($image_height) && isset($image_width)) {
  940. $image_src = $plexAddress . '/photo/:/transcode?height='.$image_height.'&width='.$image_width.'&upscale=1&url=' . $image_url . '&X-Plex-Token=' . PLEXTOKEN;
  941. $cachefile = 'images/cache/'.$key.'.jpg';
  942. $cachetime = 604800;
  943. // Serve from the cache if it is younger than $cachetime
  944. if (file_exists($cachefile) && time() - $cachetime > filemtime($cachefile)) {
  945. header("Content-type: image/jpeg");
  946. @readfile($cachefile);
  947. exit;
  948. }
  949. ob_start(); // Start the output buffer
  950. header('Content-type: image/jpeg');
  951. @readfile($image_src);
  952. // Cache the output to a file
  953. $fp = fopen($cachefile, 'wb');
  954. fwrite($fp, ob_get_contents());
  955. fclose($fp);
  956. ob_end_flush(); // Send the output to the browser
  957. die();
  958. } else {
  959. echo "Invalid Plex Request";
  960. }
  961. }
  962. // Simplier access to class
  963. function translate($string) {
  964. if (isset($GLOBALS['language'])) {
  965. return $GLOBALS['language']->translate($string);
  966. } else {
  967. return '!Translations Not Loaded!';
  968. }
  969. }
  970. // Generate Random string
  971. function randString($length = 10, $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
  972. $tmp = '';
  973. for ($i = 0; $i < $length; $i++) {
  974. $tmp .= substr(str_shuffle($chars), 0, 1);
  975. }
  976. return $tmp;
  977. }
  978. // Create config file in the return syntax
  979. function createConfig($array, $path = 'config/config.php', $nest = 0) {
  980. // Define Initial Value
  981. $output = array();
  982. // Sort Items
  983. ksort($array);
  984. // Update the current config version
  985. if (!$nest) {
  986. // Inject Current Version
  987. $output[] = "\t'CONFIG_VERSION' => '".(isset($array['apply_CONFIG_VERSION'])?$array['apply_CONFIG_VERSION']:INSTALLEDVERSION)."'";
  988. }
  989. unset($array['CONFIG_VERSION']);
  990. unset($array['apply_CONFIG_VERSION']);
  991. // Process Settings
  992. foreach ($array as $k => $v) {
  993. $allowCommit = true;
  994. switch (gettype($v)) {
  995. case 'boolean':
  996. $item = ($v?'true':'false');
  997. break;
  998. case 'integer':
  999. case 'double':
  1000. case 'integer':
  1001. case 'NULL':
  1002. $item = $v;
  1003. break;
  1004. case 'string':
  1005. $item = "'".str_replace(array('\\',"'"),array('\\\\',"\'"),$v)."'";
  1006. break;
  1007. case 'array':
  1008. $item = createConfig($v, false, $nest+1);
  1009. break;
  1010. default:
  1011. $allowCommit = false;
  1012. }
  1013. if($allowCommit) {
  1014. $output[] = str_repeat("\t",$nest+1)."'$k' => $item";
  1015. }
  1016. }
  1017. // Build output
  1018. $output = (!$nest?"<?php\nreturn ":'')."array(\n".implode(",\n",$output)."\n".str_repeat("\t",$nest).')'.(!$nest?';':'');
  1019. if (!$nest && $path) {
  1020. $pathDigest = pathinfo($path);
  1021. @mkdir($pathDigest['dirname'], 0770, true);
  1022. if (file_exists($path)) {
  1023. rename($path, $pathDigest['dirname'].'/'.$pathDigest['filename'].'.bak.php');
  1024. }
  1025. $file = fopen($path, 'w');
  1026. fwrite($file, $output);
  1027. fclose($file);
  1028. if (file_exists($path)) {
  1029. return true;
  1030. }
  1031. writeLog("error", "config was unable to write");
  1032. return false;
  1033. } else {
  1034. writeLog("success", "config was updated with new values");
  1035. return $output;
  1036. }
  1037. }
  1038. // Load a config file written in the return syntax
  1039. function loadConfig($path = 'config/config.php') {
  1040. // Adapted from http://stackoverflow.com/a/14173339/6810513
  1041. if (!is_file($path)) {
  1042. return null;
  1043. } else {
  1044. return (array) call_user_func(function() use($path) {
  1045. return include($path);
  1046. });
  1047. }
  1048. }
  1049. // Commit new values to the configuration
  1050. function updateConfig($new, $current = false) {
  1051. // Get config if not supplied
  1052. if ($current === false) {
  1053. $current = loadConfig();
  1054. } else if (is_string($current) && is_file($current)) {
  1055. $current = loadConfig($current);
  1056. }
  1057. // Inject Parts
  1058. foreach ($new as $k => $v) {
  1059. $current[$k] = $v;
  1060. }
  1061. // Return Create
  1062. return createConfig($current);
  1063. }
  1064. // Inject Defaults As Needed
  1065. function fillDefaultConfig($array, $path = 'config/configDefaults.php') {
  1066. if (is_string($path)) {
  1067. $loadedDefaults = loadConfig($path);
  1068. } else {
  1069. $loadedDefaults = $path;
  1070. }
  1071. return (is_array($loadedDefaults) ? fillDefaultConfig_recurse($array, $loadedDefaults) : false);
  1072. }
  1073. // support function for fillDefaultConfig()
  1074. function fillDefaultConfig_recurse($current, $defaults) {
  1075. foreach($defaults as $k => $v) {
  1076. if (!isset($current[$k])) {
  1077. $current[$k] = $v;
  1078. } else if (is_array($current[$k]) && is_array($v)) {
  1079. $current[$k] = fillDefaultConfig_recurse($current[$k], $v);
  1080. }
  1081. }
  1082. return $current;
  1083. };
  1084. // Define Scalar Variables (nest non-secular with underscores)
  1085. function defineConfig($array, $anyCase = true, $nest_prefix = false) {
  1086. foreach($array as $k => $v) {
  1087. if (is_scalar($v) && !defined($nest_prefix.$k)) {
  1088. define($nest_prefix.$k, $v, $anyCase);
  1089. } else if (is_array($v)) {
  1090. defineConfig($v, $anyCase, $nest_prefix.$k.'_');
  1091. }
  1092. }
  1093. }
  1094. // This function exists only because I am lazy
  1095. function configLazy($path = 'config/config.php') {
  1096. // Load config or default
  1097. if (file_exists($path)) {
  1098. $config = fillDefaultConfig(loadConfig($path));
  1099. } else {
  1100. $config = loadConfig('config/configDefaults.php');
  1101. }
  1102. if (is_array($config)) {
  1103. defineConfig($config);
  1104. }
  1105. return $config;
  1106. }
  1107. // Qualify URL
  1108. function qualifyURL($url) {
  1109. //local address?
  1110. if(substr($url, 0,1) == "/"){
  1111. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  1112. $protocol = "https://";
  1113. } else {
  1114. $protocol = "http://";
  1115. }
  1116. $url = $protocol.getServer().$url;
  1117. }
  1118. // Get Digest
  1119. $digest = parse_url($url);
  1120. // http/https
  1121. if (!isset($digest['scheme'])) {
  1122. if (isset($digest['port']) && in_array($digest['port'], array(80,8080,8096,32400,7878,8989,8182,8081,6789))) {
  1123. $scheme = 'http';
  1124. } else {
  1125. $scheme = 'https';
  1126. }
  1127. } else {
  1128. $scheme = $digest['scheme'];
  1129. }
  1130. // Host
  1131. $host = (isset($digest['host'])?$digest['host']:'');
  1132. // Port
  1133. $port = (isset($digest['port'])?':'.$digest['port']:'');
  1134. // Path
  1135. $path = (isset($digest['path'])?$digest['path']:'');
  1136. // Output
  1137. return $scheme.'://'.$host.$port.$path;
  1138. }
  1139. // Function to be called at top of each to allow upgrading environment as the spec changes
  1140. function upgradeCheck() {
  1141. // Upgrade to 1.31
  1142. if (file_exists('homepageSettings.ini.php')) {
  1143. $databaseConfig = parse_ini_file('databaseLocation.ini.php', true);
  1144. $homepageConfig = parse_ini_file('homepageSettings.ini.php', true);
  1145. $databaseConfig = array_merge($databaseConfig, $homepageConfig);
  1146. $databaseData = '; <?php die("Access denied"); ?>' . "\r\n";
  1147. foreach($databaseConfig as $k => $v) {
  1148. if(substr($v, -1) == "/") : $v = rtrim($v, "/"); endif;
  1149. $databaseData .= $k . " = \"" . $v . "\"\r\n";
  1150. }
  1151. write_ini_file($databaseData, 'databaseLocation.ini.php');
  1152. unlink('homepageSettings.ini.php');
  1153. unset($databaseData);
  1154. unset($homepageConfig);
  1155. }
  1156. // Upgrade to 1.32
  1157. if (file_exists('databaseLocation.ini.php')) {
  1158. // Load Existing
  1159. $config = parse_ini_file('databaseLocation.ini.php', true);
  1160. // Refactor
  1161. $config['database_Location'] = preg_replace('/\/\/$/','/',$config['databaseLocation'].'/');
  1162. $config['user_home'] = $config['database_Location'].'users/';
  1163. unset($config['databaseLocation']);
  1164. // Turn Off Emby And Plex Recent
  1165. $config["embyURL"] = $config["embyURL"].(!empty($config["embyPort"])?':'.$config["embyPort"]:'');
  1166. unset($config["embyPort"]);
  1167. $config["plexURL"] = $config["plexURL"].(!empty($config["plexPort"])?':'.$config["plexPort"]:'');
  1168. unset($config["plexPort"]);
  1169. $config["nzbgetURL"] = $config["nzbgetURL"].(!empty($config["nzbgetPort"])?':'.$config["nzbgetPort"]:'');
  1170. unset($config["nzbgetPort"]);
  1171. $config["sabnzbdURL"] = $config["sabnzbdURL"].(!empty($config["sabnzbdPort"])?':'.$config["sabnzbdPort"]:'');
  1172. unset($config["sabnzbdPort"]);
  1173. $config["headphonesURL"] = $config["headphonesURL"].(!empty($config["headphonesPort"])?':'.$config["headphonesPort"]:'');
  1174. unset($config["headphonesPort"]);
  1175. // Write config file
  1176. $config['CONFIG_VERSION'] = '1.32';
  1177. copy('config/config.php', 'config/config['.date('Y-m-d_H-i-s').'][pre1.32].bak.php');
  1178. $createConfigSuccess = createConfig($config);
  1179. // Create new config
  1180. if ($createConfigSuccess) {
  1181. if (file_exists('config/config.php')) {
  1182. // Remove Old ini file
  1183. unlink('databaseLocation.ini.php');
  1184. } else {
  1185. debug_out('Something is not right here!');
  1186. }
  1187. } else {
  1188. debug_out('Couldn\'t create updated configuration.' ,1);
  1189. }
  1190. }
  1191. // Upgrade to 1.33
  1192. $config = loadConfig();
  1193. if (isset($config['database_Location']) && (!isset($config['CONFIG_VERSION']) || $config['CONFIG_VERSION'] < '1.33')) {
  1194. // Fix User Directory
  1195. $config['database_Location'] = preg_replace('/\/\/$/','/',$config['database_Location'].'/');
  1196. $config['user_home'] = $config['database_Location'].'users/';
  1197. unset($config['USER_HOME']);
  1198. // Backend auth merge
  1199. if (isset($config['authBackendPort']) && !isset(parse_url($config['authBackendHost'])['port'])) {
  1200. $config['authBackendHost'] .= ':'.$config['authBackendPort'];
  1201. }
  1202. unset($config['authBackendPort']);
  1203. // If auth is being used move it to embyURL as that is now used in auth functions
  1204. 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')))) {
  1205. $config['embyURL'] = $config['authBackendHost'];
  1206. }
  1207. // Upgrade database to latest version
  1208. updateSQLiteDB($config['database_Location'],'1.32');
  1209. // Update Version and Commit
  1210. $config['apply_CONFIG_VERSION'] = '1.33';
  1211. copy('config/config.php', 'config/config['.date('Y-m-d_H-i-s').'][1.32].bak.php');
  1212. $createConfigSuccess = createConfig($config);
  1213. unset($config);
  1214. }
  1215. // Upgrade to 1.34
  1216. $config = loadConfig();
  1217. if (isset($config['database_Location']) && (!isset($config['CONFIG_VERSION']) || $config['CONFIG_VERSION'] < '1.34')) {
  1218. // Upgrade database to latest version
  1219. updateSQLiteDB($config['database_Location'],'1.33');
  1220. // Update Version and Commit
  1221. $config['CONFIG_VERSION'] = '1.34';
  1222. copy('config/config.php', 'config/config['.date('Y-m-d_H-i-s').'][1.33].bak.php');
  1223. $createConfigSuccess = createConfig($config);
  1224. unset($config);
  1225. }
  1226. return true;
  1227. }
  1228. // Check if all software dependancies are met
  1229. function dependCheck() {
  1230. $output = array();
  1231. if (!extension_loaded('pdo_sqlite')) { $output[] = 'PDO:SQLite not enabled, please add "extension = php_pdo_sqlite.dll" to php.ini'; }
  1232. //if (!extension_loaded('sqlite3')) { $output[] = 'SQLite3 not enabled, please add "extension = php_sqlite3.dll" to php.ini'; }
  1233. if ($output) {
  1234. debug_out($output,1);
  1235. }
  1236. return true;
  1237. }
  1238. // Process file uploads
  1239. function uploadFiles($path, $ext_mask = null) {
  1240. if (isset($_FILES) && count($_FILES)) {
  1241. require_once('class.uploader.php');
  1242. $uploader = new Uploader();
  1243. $data = $uploader->upload($_FILES['files'], array(
  1244. 'limit' => 10,
  1245. 'maxSize' => 10,
  1246. 'extensions' => $ext_mask,
  1247. 'required' => false,
  1248. 'uploadDir' => str_replace('//','/',$path.'/'),
  1249. 'title' => array('name'),
  1250. 'removeFiles' => true,
  1251. 'replace' => true,
  1252. ));
  1253. if($data['isComplete']){
  1254. $files = $data['data'];
  1255. writeLog("success", $files['metas'][0]['name']." was uploaded");
  1256. echo json_encode($files['metas'][0]['name']);
  1257. }
  1258. if($data['hasErrors']){
  1259. $errors = $data['errors'];
  1260. writeLog("error", $files['metas'][0]['name']." was not able to upload");
  1261. echo json_encode($errors);
  1262. }
  1263. } else {
  1264. writeLog("error", "image was not uploaded");
  1265. echo json_encode('No files submitted!');
  1266. }
  1267. }
  1268. // Remove file
  1269. function removeFiles($path) {
  1270. if(is_file($path)) {
  1271. writeLog("success", "image was removed");
  1272. unlink($path);
  1273. } else {
  1274. writeLog("error", "image was not removed");
  1275. echo json_encode('No file specified for removal!');
  1276. }
  1277. }
  1278. // Lazy select options
  1279. function resolveSelectOptions($array, $selected = '', $multi = false) {
  1280. $output = array();
  1281. $selectedArr = ($multi?explode('|', $selected):array());
  1282. foreach ($array as $key => $value) {
  1283. if (is_array($value)) {
  1284. if (isset($value['optgroup'])) {
  1285. $output[] = '<optgroup label="'.$key.'">';
  1286. foreach($value['optgroup'] as $k => $v) {
  1287. $output[] = '<option value="'.$v['value'].'"'.($selected===$v['value']||in_array($v['value'],$selectedArr)?' selected':'').(isset($v['disabled']) && $v['disabled']?' disabled':'').'>'.$k.'</option>';
  1288. }
  1289. } else {
  1290. $output[] = '<option value="'.$value['value'].'"'.($selected===$value['value']||in_array($value['value'],$selectedArr)?' selected':'').(isset($value['disabled']) && $value['disabled']?' disabled':'').'>'.$key.'</option>';
  1291. }
  1292. } else {
  1293. $output[] = '<option value="'.$value.'"'.($selected===$value||in_array($value,$selectedArr)?' selected':'').'>'.$key.'</option>';
  1294. }
  1295. }
  1296. return implode('',$output);
  1297. }
  1298. // Check if user is allowed to continue
  1299. function qualifyUser($type, $errOnFail = false) {
  1300. if (!isset($GLOBALS['USER'])) {
  1301. require_once("user.php");
  1302. $GLOBALS['USER'] = new User('registration_callback');
  1303. }
  1304. if (is_bool($type)) {
  1305. if ($type === true) {
  1306. $authorized = ($GLOBALS['USER']->authenticated == true);
  1307. } else {
  1308. $authorized = true;
  1309. }
  1310. } elseif (is_string($type) || is_array($type)) {
  1311. if ($type !== 'false') {
  1312. if (!is_array($type)) {
  1313. $type = explode('|',$type);
  1314. }
  1315. $authorized = ($GLOBALS['USER']->authenticated && in_array($GLOBALS['USER']->role,$type));
  1316. } else {
  1317. $authorized = true;
  1318. }
  1319. } else {
  1320. debug_out('Invalid Syntax!',1);
  1321. }
  1322. if (!$authorized && $errOnFail) {
  1323. if ($GLOBALS['USER']->authenticated) {
  1324. header('Location: error.php?error=401');
  1325. echo '<script>window.location.href = \''.dirname($_SERVER['SCRIPT_NAME']).'/error.php?error=401\'</script>';
  1326. } else {
  1327. header('Location: error.php?error=999');
  1328. echo '<script>window.location.href = \''.dirname($_SERVER['SCRIPT_NAME']).'/error.php?error=999\'</script>';
  1329. }
  1330. debug_out('Not Authorized' ,1);
  1331. } else {
  1332. return $authorized;
  1333. }
  1334. }
  1335. // Build an (optionally) tabbed settings page.
  1336. function buildSettings($array) {
  1337. /*
  1338. array(
  1339. 'title' => '',
  1340. 'id' => '',
  1341. 'fields' => array( See buildField() ),
  1342. 'tabs' => array(
  1343. array(
  1344. 'title' => '',
  1345. 'id' => '',
  1346. 'image' => '',
  1347. 'fields' => array( See buildField() ),
  1348. ),
  1349. ),
  1350. );
  1351. */
  1352. $fieldFunc = function($fieldArr) {
  1353. $fields = '<div class="row">';
  1354. foreach($fieldArr as $key => $value) {
  1355. $isSingle = isset($value['type']);
  1356. if ($isSingle) { $value = array($value); }
  1357. $tmpField = '';
  1358. $sizeLg = max(floor(12/count($value)),2);
  1359. $sizeMd = max(floor(($isSingle?12:6)/count($value)),3);
  1360. foreach($value as $k => $v) {
  1361. $tmpField .= buildField($v, 12, $sizeMd, $sizeLg);
  1362. }
  1363. $fields .= ($isSingle?$tmpField:'<div class="row col-sm-12 content-form">'.$tmpField.'</div>');
  1364. }
  1365. $fields .= '</div>';
  1366. return $fields;
  1367. };
  1368. $fields = (isset($array['fields'])?$fieldFunc($array['fields']):'');
  1369. $tabSelectors = array();
  1370. $tabContent = array();
  1371. if (isset($array['tabs'])) {
  1372. foreach($array['tabs'] as $key => $value) {
  1373. $id = (isset($value['id'])?$value['id']:randString(32));
  1374. $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>';
  1375. $tabContent[$key] = '<div class="tab-pane big-box fade'.($tabContent?'':' active in').'" id="tab-'.$id.'">'.$fieldFunc($value['fields']).'</div>';
  1376. }
  1377. }
  1378. $pageID = (isset($array['id'])?$array['id']:str_replace(array(' ','"',"'"),array('_'),strtolower($array['id'])));
  1379. return '
  1380. <div class="email-body">
  1381. <div class="email-header gray-bg">
  1382. <button type="button" class="btn btn-danger btn-sm waves close-button"><i class="fa fa-close"></i></button>
  1383. <h1>'.$array['title'].'</h1>
  1384. </div>
  1385. <div class="email-inner small-box">
  1386. <div class="email-inner-section">
  1387. <div class="small-box fade in" id="'.$pageID.'_frame">
  1388. <div class="col-lg-12">
  1389. '.(isset($array['customBeforeForm'])?$array['customBeforeForm']:'').'
  1390. <form class="content-form" name="'.$pageID.'" id="'.$pageID.'_form" onsubmit="return false;">
  1391. <button id="'.$pageID.'_form_submit" class="btn waves btn-labeled btn-success btn btn-sm pull-right text-uppercase waves-effect waves-float">
  1392. <span class="btn-label"><i class="fa fa-floppy-o"></i></span>Save
  1393. </button>
  1394. '.$fields.($tabContent?'
  1395. <div class="tabbable tabs-with-bg" id="'.$pageID.'_tabs">
  1396. <ul class="nav nav-tabs apps">
  1397. '.implode('', $tabSelectors).'
  1398. </ul>
  1399. <div class="clearfix"></div>
  1400. <div class="tab-content">
  1401. '.implode('', $tabContent).'
  1402. </div>
  1403. </div>':'').'
  1404. </form>
  1405. '.(isset($array['customAfterForm'])?$array['customAfterForm']:'').'
  1406. </div>
  1407. </div>
  1408. </div>
  1409. </div>
  1410. </div>
  1411. <script>
  1412. $(document).ready(function() {
  1413. $(\'#'.$pageID.'_form\').find(\'input, select, textarea\').on(\'change\', function() { $(this).attr(\'data-changed\', \'true\'); });
  1414. var '.$pageID.'Validate = function() { if (this.value && !RegExp(\'^\'+this.pattern+\'$\').test(this.value)) { $(this).addClass(\'invalid\'); } else { $(this).removeClass(\'invalid\'); } };
  1415. $(\'#'.$pageID.'_form\').find(\'input[pattern]\').each('.$pageID.'Validate).on(\'keyup\', '.$pageID.'Validate);
  1416. $(\'#'.$pageID.'_form\').find(\'select[multiple]\').on(\'change click\', function() { $(this).attr(\'data-changed\', \'true\'); });
  1417. $(\'#'.$pageID.'_form_submit\').on(\'click\', function () {
  1418. var newVals = {};
  1419. var hasVals = false;
  1420. var errorFields = [];
  1421. $(\'#'.$pageID.'_form\').find(\'[data-changed=true][name]\').each(function() {
  1422. hasVals = true;
  1423. if (this.type == \'checkbox\') {
  1424. newVals[this.name] = this.checked;
  1425. } else if ($(this).hasClass(\'summernote\')) {
  1426. newVals[$(this).attr(\'name\')] = $(this).siblings(\'.note-editor\').find(\'.panel-body\').html();
  1427. } else {
  1428. if (this.value && this.pattern && !RegExp(\'^\'+this.pattern+\'$\').test(this.value)) { errorFields.push(this.name); }
  1429. var fieldVal = $(this).val();
  1430. if (typeof fieldVal == \'object\') {
  1431. if (typeof fieldVal.join == \'function\') {
  1432. fieldVal = fieldVal.join(\'|\');
  1433. } else {
  1434. fieldVal = JSON.stringify(fieldVal);
  1435. }
  1436. }
  1437. newVals[this.name] = fieldVal;
  1438. }
  1439. });
  1440. if (errorFields.length) {
  1441. parent.notify(\'Fields have errors: \'+errorFields.join(\', \')+\'!\', \'bullhorn\', \'success\', 5000, \'bar\', \'slidetop\');
  1442. } else if (hasVals) {
  1443. console.log(newVals);
  1444. ajax_request(\'POST\', \''.(isset($array['submitAction'])?$array['submitAction']:'update-config').'\', newVals, function(data, code) {
  1445. $(\'#'.$pageID.'_form\').find(\'[data-changed=true][name]\').removeAttr(\'data-changed\');
  1446. });
  1447. } else {
  1448. parent.notify(\'Nothing to update!\', \'bullhorn\', \'success\', 5000, \'bar\', \'slidetop\');
  1449. }
  1450. return false;
  1451. });
  1452. '.(isset($array['onready'])?$array['onready']:'').'
  1453. });
  1454. </script>
  1455. ';
  1456. }
  1457. // Build Settings Fields
  1458. function buildField($params, $sizeSm = 12, $sizeMd = 12, $sizeLg = 12) {
  1459. /*
  1460. array(
  1461. 'type' => '',
  1462. 'placeholder' => '',
  1463. 'label' => '',
  1464. 'labelTranslate' => '',
  1465. 'assist' => '',
  1466. 'name' => '',
  1467. 'pattern' => '',
  1468. 'options' => array( // For SELECT only
  1469. 'Display' => 'value',
  1470. ),
  1471. )
  1472. */
  1473. // Tags
  1474. $tags = array();
  1475. foreach(array('placeholder','style','disabled','readonly','pattern','min','max','required','onkeypress','onchange','onfocus','onleave','href','onclick') as $value) {
  1476. if (isset($params[$value])) {
  1477. if (is_string($params[$value])) { $tags[] = $value.'="'.$params[$value].'"';
  1478. } else if ($params[$value] === true) { $tags[] = $value; }
  1479. }
  1480. }
  1481. $format = (isset($params['format']) && in_array($params['format'],array(false,'colour','color'))?$params['format']:false);
  1482. $name = (isset($params['name'])?$params['name']:(isset($params['id'])?$params['id']:''));
  1483. $id = (isset($params['id'])?$params['id']:(isset($params['name'])?$params['name'].'_id':randString(32)));
  1484. $val = (isset($params['value'])?$params['value']:'');
  1485. $class = (isset($params['class'])?' '.$params['class']:'');
  1486. $wrapClass = (isset($params['wrapClass'])?$params['wrapClass']:'form-content');
  1487. $assist = (isset($params['assist'])?' - i.e. '.$params['assist']:'');
  1488. $label = (isset($params['labelTranslate'])?translate($params['labelTranslate']):(isset($params['label'])?$params['label']:''));
  1489. $labelOut = '<p class="help-text">'.$label.$assist.'</p>';
  1490. // Field Design
  1491. switch ($params['type']) {
  1492. case 'text':
  1493. case 'number':
  1494. case 'password':
  1495. $field = '<input id="'.$id.'" name="'.$name.'" type="'.$params['type'].'" class="form-control material input-sm'.$class.'" '.implode(' ',$tags).' autocorrect="off" autocapitalize="off" value="'.$val.'">';
  1496. break;
  1497. case 'select':
  1498. case 'dropdown':
  1499. $field = '<select id="'.$id.'" name="'.$name.'" class="form-control material input-sm" '.implode(' ',$tags).'>'.resolveSelectOptions($params['options'], $val).'</select>';
  1500. break;
  1501. case 'select-multi':
  1502. case 'dropdown-multi':
  1503. $field = '<select id="'.$id.'" name="'.$name.'" class="form-control input-sm" '.implode(' ',$tags).' multiple="multiple">'.resolveSelectOptions($params['options'], $val, true).'</select>';
  1504. break;
  1505. case 'check':
  1506. case 'checkbox':
  1507. case 'toggle':
  1508. $checked = ((is_bool($val) && $val) || trim($val) === 'true'?' checked':'');
  1509. $colour = (isset($params['colour'])?$params['colour']:'success');
  1510. $labelOut = '<label for="'.$id.'"></label>'.$label;
  1511. $field = '<input id="'.$id.'" name="'.$name.'" type="checkbox" class="switcher switcher-'.$colour.' '.$class.'" '.implode(' ',$tags).' data-value="'.$val.'"'.$checked.'>';
  1512. break;
  1513. case 'radio':
  1514. $labelOut = '';
  1515. $checked = ((is_bool($val) && $val) || ($val && trim($val) !== 'false')?' checked':'');
  1516. $bType = (isset($params['buttonType'])?$params['buttonType']:'success');
  1517. $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>';
  1518. break;
  1519. case 'date':
  1520. $field = 'Unsupported, planned.';
  1521. break;
  1522. case 'hidden':
  1523. return '<input id="'.$id.'" name="'.$name.'" type="hidden" class="'.$class.'" '.implode(' ',$tags).' value="'.$val.'">';
  1524. break;
  1525. case 'header':
  1526. $labelOut = '';
  1527. $headType = (isset($params['value'])?$params['value']:3);
  1528. $field = '<h'.$headType.' class="'.$class.'" '.implode(' ',$tags).'>'.$label.'</h'.$headType.'>';
  1529. break;
  1530. case 'button':
  1531. $labelOut = '';
  1532. $icon = (isset($params['icon'])?$params['icon']:'flask');
  1533. $bType = (isset($params['buttonType'])?$params['buttonType']:'success');
  1534. $bDropdown = (isset($params['buttonDrop'])?$params['buttonDrop']:'');
  1535. $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>':'');
  1536. break;
  1537. case 'textarea':
  1538. $rows = (isset($params['rows'])?$params['rows']:5);
  1539. $field = '<textarea id="'.$id.'" name="'.$name.'" class="form-control'.$class.'" rows="'.$rows.'" '.implode(' ',$tags).'>'.$val.'</textarea>';
  1540. break;
  1541. case 'custom':
  1542. // Settings
  1543. $settings = array(
  1544. '$id' => $id,
  1545. '$name' => $name,
  1546. '$val' => $val,
  1547. '$label' => $label,
  1548. '$labelOut' => $labelOut,
  1549. );
  1550. // Get HTML
  1551. $html = (isset($params['html'])?$params['html']:'Nothing Specified!');
  1552. // If LabelOut is in html dont print it twice
  1553. $labelOut = (strpos($html,'$label')!==false?'':$labelOut);
  1554. // Replace variables in settings
  1555. $html = preg_replace_callback('/\$\w+\b/', function ($match) use ($settings) { return (isset($settings[$match[0]])?$settings[$match[0]]:'{'.$match[0].' is undefined}'); }, $html);
  1556. // Build Field
  1557. $field = '<div id="'.$id.'_html" class="custom-field">'.$html.'</div>';
  1558. break;
  1559. case 'space':
  1560. $labelOut = '';
  1561. $field = str_repeat('<br>', (isset($params['value'])?$params['value']:1));
  1562. break;
  1563. default:
  1564. $field = 'Unsupported field type';
  1565. break;
  1566. }
  1567. // Field Formats
  1568. switch ($format) {
  1569. case 'colour': // Fuckin Eh, Canada!
  1570. case 'color':
  1571. $labelBef = '<center>'.$label.'</center>';
  1572. $wrapClass = 'gray-bg colour-field';
  1573. $labelAft = '';
  1574. $field = str_replace(' material input-sm','',$field);
  1575. break;
  1576. default:
  1577. $labelBef = '';
  1578. $labelAft = $labelOut;
  1579. }
  1580. return '<div class="'.$wrapClass.' col-sm-'.$sizeSm.' col-md-'.$sizeMd.' col-lg-'.$sizeLg.'">'.$labelBef.$field.$labelAft.'</div>';
  1581. }
  1582. // Tab Settings Generation
  1583. function printTabRow($data) {
  1584. $hidden = false;
  1585. if ($data===false) {
  1586. $hidden = true;
  1587. $data = array( // New Tab Defaults
  1588. 'id' => 'new',
  1589. 'name' => '',
  1590. 'url' => '',
  1591. 'icon' => 'fa-diamond',
  1592. 'iconurl' => '',
  1593. 'active' => 'true',
  1594. 'user' => 'true',
  1595. 'guest' => 'true',
  1596. 'window' => 'false',
  1597. 'defaultz' => '',
  1598. );
  1599. }
  1600. $image = '<span style="font: normal normal normal 30px/1 FontAwesome;" class="fa fa-hand-paper-o"></span>';
  1601. $output = '
  1602. <li id="tab-'.$data['id'].'" class="list-group-item" style="position: relative; left: 0px; top: 0px; '.($hidden?' display: none;':'').'">
  1603. <tab class="content-form form-inline">
  1604. <div class="row">
  1605. '.buildField(array(
  1606. 'type' => 'custom',
  1607. '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>',
  1608. ),12,1,1).'
  1609. '.buildField(array(
  1610. 'type' => 'hidden',
  1611. 'id' => 'tab-'.$data['id'].'-id',
  1612. 'name' => 'id['.$data['id'].']',
  1613. 'value' => $data['id'],
  1614. ),12,2,1).'
  1615. '.buildField(array(
  1616. 'type' => 'text',
  1617. 'id' => 'tab-'.$data['id'].'-name',
  1618. 'name' => 'name['.$data['id'].']',
  1619. 'required' => true,
  1620. 'placeholder' => 'Organizr Homepage',
  1621. 'labelTranslate' => 'TAB_NAME',
  1622. 'value' => $data['name'],
  1623. ),12,2,1).'
  1624. '.buildField(array(
  1625. 'type' => 'text',
  1626. 'id' => 'tab-'.$data['id'].'-url',
  1627. 'name' => 'url['.$data['id'].']',
  1628. 'required' => true,
  1629. 'placeholder' => 'homepage.php',
  1630. 'labelTranslate' => 'TAB_URL',
  1631. 'value' => $data['url'],
  1632. ),12,2,1).'
  1633. '.buildField(array(
  1634. 'type' => 'text',
  1635. 'id' => 'tab-'.$data['id'].'-iconurl',
  1636. 'name' => 'iconurl['.$data['id'].']',
  1637. 'placeholder' => 'images/organizr.png',
  1638. 'labelTranslate' => 'ICON_URL',
  1639. 'value' => $data['iconurl'],
  1640. ),12,2,1).'
  1641. '.buildField(array(
  1642. 'type' => 'custom',
  1643. 'id' => 'tab-'.$data['id'].'-icon',
  1644. 'name' => 'icon['.$data['id'].']',
  1645. '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>',
  1646. 'value' => $data['icon'],
  1647. ),12,1,1).'
  1648. '.buildField(array(
  1649. 'type' => 'checkbox',
  1650. 'labelTranslate' => 'ACTIVE',
  1651. 'name' => 'active['.$data['id'].']',
  1652. 'value' => $data['active'],
  1653. ),12,1,1).'
  1654. '.buildField(array(
  1655. 'type' => 'checkbox',
  1656. 'labelTranslate' => 'USER',
  1657. 'colour' => 'primary',
  1658. 'name' => 'user['.$data['id'].']',
  1659. 'value' => $data['user'],
  1660. ),12,1,1).'
  1661. '.buildField(array(
  1662. 'type' => 'checkbox',
  1663. 'labelTranslate' => 'GUEST',
  1664. 'colour' => 'warning',
  1665. 'name' => 'guest['.$data['id'].']',
  1666. 'value' => $data['guest'],
  1667. ),12,1,1).'
  1668. '.buildField(array(
  1669. 'type' => 'checkbox',
  1670. 'labelTranslate' => 'NO_IFRAME',
  1671. 'colour' => 'danger',
  1672. 'name' => 'window['.$data['id'].']',
  1673. 'value' => $data['window'],
  1674. ),12,1,1).'
  1675. '.buildField(array(
  1676. 'type' => 'radio',
  1677. 'labelTranslate' => 'DEFAULT',
  1678. 'name' => 'defaultz['.$data['id'].']',
  1679. 'value' => $data['defaultz'],
  1680. 'onclick' => "$('[type=radio][id!=\''+this.id+'\']').each(function() { this.checked=false; });",
  1681. ),12,1,1).'
  1682. '.buildField(array(
  1683. 'type' => 'button',
  1684. 'icon' => 'trash',
  1685. 'buttonType' => 'danger',
  1686. 'labelTranslate' => 'REMOVE',
  1687. 'onclick' => "$(this).parents('li').remove();",
  1688. ),12,1,1).'
  1689. </div>
  1690. </tab>
  1691. </li>
  1692. ';
  1693. return $output;
  1694. }
  1695. // Timezone array
  1696. function timezoneOptions() {
  1697. $output = array();
  1698. $timezones = array();
  1699. $regions = array(
  1700. 'Africa' => DateTimeZone::AFRICA,
  1701. 'America' => DateTimeZone::AMERICA,
  1702. 'Antarctica' => DateTimeZone::ANTARCTICA,
  1703. 'Arctic' => DateTimeZone::ARCTIC,
  1704. 'Asia' => DateTimeZone::ASIA,
  1705. 'Atlantic' => DateTimeZone::ATLANTIC,
  1706. 'Australia' => DateTimeZone::AUSTRALIA,
  1707. 'Europe' => DateTimeZone::EUROPE,
  1708. 'Indian' => DateTimeZone::INDIAN,
  1709. 'Pacific' => DateTimeZone::PACIFIC
  1710. );
  1711. foreach ($regions as $name => $mask) {
  1712. $zones = DateTimeZone::listIdentifiers($mask);
  1713. foreach($zones as $timezone) {
  1714. $time = new DateTime(NULL, new DateTimeZone($timezone));
  1715. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  1716. $output[$name]['optgroup'][substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm]['value'] = $timezone;
  1717. }
  1718. }
  1719. return $output;
  1720. }
  1721. // Build Database
  1722. function createSQLiteDB($path = false) {
  1723. if ($path === false) {
  1724. if (defined('DATABASE_LOCATION')) {
  1725. $path = DATABASE_LOCATION;
  1726. } else {
  1727. debug_out('No Path Specified!');
  1728. }
  1729. }
  1730. if (!is_file($path.'users.db') || filesize($path.'users.db') <= 0) {
  1731. if (!isset($GLOBALS['file_db'])) {
  1732. $GLOBALS['file_db'] = new PDO('sqlite:'.$path.'users.db');
  1733. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1734. }
  1735. // Create Users
  1736. $users = $GLOBALS['file_db']->query('CREATE TABLE `users` (
  1737. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1738. `username` TEXT UNIQUE,
  1739. `password` TEXT,
  1740. `email` TEXT,
  1741. `token` TEXT,
  1742. `role` TEXT,
  1743. `active` TEXT,
  1744. `last` TEXT,
  1745. `auth_service` TEXT DEFAULT \'internal\'
  1746. );');
  1747. // Create Tabs
  1748. $tabs = $GLOBALS['file_db']->query('CREATE TABLE `tabs` (
  1749. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1750. `order` INTEGER,
  1751. `users_id` INTEGER,
  1752. `name` TEXT,
  1753. `url` TEXT,
  1754. `defaultz` TEXT,
  1755. `active` TEXT,
  1756. `user` TEXT,
  1757. `guest` TEXT,
  1758. `icon` TEXT,
  1759. `iconurl` TEXT,
  1760. `window` TEXT
  1761. );');
  1762. // Create Options
  1763. $options = $GLOBALS['file_db']->query('CREATE TABLE `options` (
  1764. `id` INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
  1765. `users_id` INTEGER UNIQUE,
  1766. `title` TEXT UNIQUE,
  1767. `topbar` TEXT,
  1768. `bottombar` TEXT,
  1769. `sidebar` TEXT,
  1770. `hoverbg` TEXT,
  1771. `topbartext` TEXT,
  1772. `activetabBG` TEXT,
  1773. `activetabicon` TEXT,
  1774. `activetabtext` TEXT,
  1775. `inactiveicon` TEXT,
  1776. `inactivetext` TEXT,
  1777. `loading` TEXT,
  1778. `hovertext` TEXT
  1779. );');
  1780. writeLog("success", "database created/saved");
  1781. return $users && $tabs && $options;
  1782. } else {
  1783. writeLog("error", "database was unable to be created/saved");
  1784. return false;
  1785. }
  1786. }
  1787. // Upgrade Database
  1788. function updateSQLiteDB($db_path = false, $oldVerNum = false) {
  1789. if (!$db_path) {
  1790. if (defined('DATABASE_LOCATION')) {
  1791. $db_path = DATABASE_LOCATION;
  1792. } else {
  1793. debug_out('No Path Specified',1);
  1794. }
  1795. }
  1796. if (!isset($GLOBALS['file_db'])) {
  1797. $GLOBALS['file_db'] = new PDO('sqlite:'.$db_path.'users.db');
  1798. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1799. }
  1800. // Cache current DB
  1801. $cache = array();
  1802. foreach($GLOBALS['file_db']->query('SELECT name FROM sqlite_master WHERE type="table";') as $table) {
  1803. foreach($GLOBALS['file_db']->query('SELECT * FROM '.$table['name'].';') as $key => $row) {
  1804. foreach($row as $k => $v) {
  1805. if (is_string($k)) {
  1806. $cache[$table['name']][$key][$k] = $v;
  1807. }
  1808. }
  1809. }
  1810. }
  1811. // Remove Current Database
  1812. $GLOBALS['file_db'] = null;
  1813. $pathDigest = pathinfo($db_path.'users.db');
  1814. if (file_exists($db_path.'users.db')) {
  1815. rename($db_path.'users.db', $pathDigest['dirname'].'/'.$pathDigest['filename'].'['.date('Y-m-d_H-i-s').']'.($oldVerNum?'['.$oldVerNum.']':'').'.bak.db');
  1816. }
  1817. // Create New Database
  1818. $success = createSQLiteDB($db_path);
  1819. // Restore Items
  1820. if ($success) {
  1821. foreach($cache as $table => $tableData) {
  1822. if ($tableData) {
  1823. $queryBase = 'INSERT INTO '.$table.' (`'.implode('`,`',array_keys(current($tableData))).'`) values ';
  1824. $insertValues = array();
  1825. reset($tableData);
  1826. foreach($tableData as $key => $value) {
  1827. $insertValues[] = '('.implode(',',array_map(function($d) {
  1828. return (isset($d)?$GLOBALS['file_db']->quote($d):'null');
  1829. }, $value)).')';
  1830. }
  1831. $GLOBALS['file_db']->query($queryBase.implode(',',$insertValues).';');
  1832. }
  1833. }
  1834. writeLog("success", "database values have been updated");
  1835. return true;
  1836. } else {
  1837. writeLog("error", "database values unable to be updated");
  1838. return false;
  1839. }
  1840. }
  1841. // Commit colours to database
  1842. function updateDBOptions($values) {
  1843. if (!isset($GLOBALS['file_db'])) {
  1844. $GLOBALS['file_db'] = new PDO('sqlite:'.DATABASE_LOCATION.'users.db');
  1845. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1846. }
  1847. // Commit new values to database
  1848. if ($GLOBALS['file_db']->query('UPDATE options SET '.implode(',',array_map(function($d, $k) {
  1849. return '`'.$k.'` = '.(isset($d)?"'".addslashes($d)."'":'null');
  1850. }, $values, array_keys($values))).';')->rowCount()) {
  1851. return true;
  1852. } else if ($GLOBALS['file_db']->query('INSERT OR IGNORE INTO options (`'.implode('`,`',array_keys($values)).'`) VALUES (\''.implode("','",$values).'\');')->rowCount()) {
  1853. writeLog("success", "database values for options table have been updated");
  1854. return true;
  1855. } else {
  1856. writeLog("error", "database values for options table unable to be updated");
  1857. return false;
  1858. }
  1859. }
  1860. // Send AJAX notification
  1861. function sendNotification($success, $message = false, $send = true) {
  1862. $notifyExplode = explode("-", NOTIFYEFFECT);
  1863. if ($success) {
  1864. $msg = array(
  1865. 'html' => ($message?''.$message:'<strong>'.translate("SETTINGS_SAVED").'</strong>'),
  1866. 'icon' => 'floppy-o',
  1867. 'type' => 'success',
  1868. 'length' => '5000',
  1869. 'layout' => $notifyExplode[0],
  1870. 'effect' => $notifyExplode[1],
  1871. );
  1872. } else {
  1873. $msg = array(
  1874. 'html' => ($message?''.$message:'<strong>'.translate("SETTINGS_NOT_SAVED").'</strong>'),
  1875. 'icon' => 'floppy-o',
  1876. 'type' => 'failed',
  1877. 'length' => '5000',
  1878. 'layout' => $notifyExplode[0],
  1879. 'effect' => $notifyExplode[1],
  1880. );
  1881. }
  1882. // Send and kill script?
  1883. if ($send) {
  1884. header('Content-Type: application/json');
  1885. echo json_encode(array('notify'=>$msg));
  1886. die();
  1887. }
  1888. return $msg;
  1889. }
  1890. // Load colours from the database
  1891. function loadAppearance() {
  1892. if (!isset($GLOBALS['file_db'])) {
  1893. $GLOBALS['file_db'] = new PDO('sqlite:'.DATABASE_LOCATION.'users.db');
  1894. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1895. }
  1896. // Defaults
  1897. $defaults = array(
  1898. 'title' => 'Organizr',
  1899. 'topbartext' => '#66D9EF',
  1900. 'topbar' => '#333333',
  1901. 'bottombar' => '#333333',
  1902. 'sidebar' => '#393939',
  1903. 'hoverbg' => '#AD80FD',
  1904. 'activetabBG' => '#F92671',
  1905. 'activetabicon' => '#FFFFFF',
  1906. 'activetabtext' => '#FFFFFF',
  1907. 'inactiveicon' => '#66D9EF',
  1908. 'inactivetext' => '#66D9EF',
  1909. 'loading' => '#66D9EF',
  1910. 'hovertext' => '#000000',
  1911. );
  1912. // Database Lookup
  1913. $options = $GLOBALS['file_db']->query('SELECT * FROM options');
  1914. // Replace defaults with filled options
  1915. foreach($options as $row) {
  1916. foreach($defaults as $key => $value) {
  1917. if (isset($row[$key]) && $row[$key]) {
  1918. $defaults[$key] = $row[$key];
  1919. }
  1920. }
  1921. }
  1922. // Return the Results
  1923. return $defaults;
  1924. }
  1925. // Delete Database
  1926. function deleteDatabase() {
  1927. unset($_COOKIE['Organizr']);
  1928. setcookie('Organizr', '', time() - 3600, '/');
  1929. unset($_COOKIE['OrganizrU']);
  1930. setcookie('OrganizrU', '', time() - 3600, '/');
  1931. $GLOBALS['file_db'] = null;
  1932. unlink(DATABASE_LOCATION.'users.db');
  1933. foreach(glob(substr_replace($userdirpath, "", -1).'/*') as $file) {
  1934. if(is_dir($file)) {
  1935. rmdir($file);
  1936. } elseif (!is_dir($file)) {
  1937. unlink($file);
  1938. }
  1939. }
  1940. rmdir($userdirpath);
  1941. writeLog("success", "database has been deleted");
  1942. return true;
  1943. }
  1944. // Upgrade the installation
  1945. function upgradeInstall($branch = 'master') {
  1946. function downloadFile($url, $path){
  1947. ini_set('max_execution_time',0);
  1948. $folderPath = "upgrade/";
  1949. if(!mkdir($folderPath)){
  1950. writeLog("error", "organizr could not create upgrade folder");
  1951. }
  1952. $newfname = $folderPath . $path;
  1953. $file = fopen ($url, 'rb');
  1954. if ($file) {
  1955. $newf = fopen ($newfname, 'wb');
  1956. if ($newf) {
  1957. while(!feof($file)) {
  1958. fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
  1959. }
  1960. }
  1961. }else{
  1962. writeLog("error", "organizr could not download $url");
  1963. }
  1964. if ($file) {
  1965. fclose($file);
  1966. writeLog("success", "organizr finished downloading the github zip file");
  1967. }else{
  1968. writeLog("error", "organizr could not download the github zip file");
  1969. }
  1970. if ($newf) {
  1971. fclose($newf);
  1972. writeLog("success", "organizr created upgrade zip file from github zip file");
  1973. }else{
  1974. writeLog("error", "organizr could not create upgrade zip file from github zip file");
  1975. }
  1976. }
  1977. function unzipFile($zipFile){
  1978. $zip = new ZipArchive;
  1979. $extractPath = "upgrade/";
  1980. if($zip->open($extractPath . $zipFile) != "true"){
  1981. writeLog("error", "organizr could not unzip upgrade.zip");
  1982. }else{
  1983. writeLog("success", "organizr unzipped upgrade.zip");
  1984. }
  1985. /* Extract Zip File */
  1986. $zip->extractTo($extractPath);
  1987. $zip->close();
  1988. }
  1989. // Function to remove folders and files
  1990. function rrmdir($dir) {
  1991. if (is_dir($dir)) {
  1992. $files = scandir($dir);
  1993. foreach ($files as $file)
  1994. if ($file != "." && $file != "..") rrmdir("$dir/$file");
  1995. rmdir($dir);
  1996. }
  1997. else if (file_exists($dir)) unlink($dir);
  1998. }
  1999. // Function to Copy folders and files
  2000. function rcopy($src, $dst) {
  2001. if (is_dir ( $src )) {
  2002. if (!file_exists($dst)) : mkdir ( $dst ); endif;
  2003. $files = scandir ( $src );
  2004. foreach ( $files as $file )
  2005. if ($file != "." && $file != "..")
  2006. rcopy ( "$src/$file", "$dst/$file" );
  2007. } else if (file_exists ( $src ))
  2008. copy ( $src, $dst );
  2009. }
  2010. $url = 'https://github.com/causefx/Organizr/archive/'.$branch.'.zip';
  2011. $file = "upgrade.zip";
  2012. $source = __DIR__ . '/upgrade/Organizr-'.$branch.'/';
  2013. $cleanup = __DIR__ . "/upgrade/";
  2014. $destination = __DIR__ . "/";
  2015. downloadFile($url, $file);
  2016. unzipFile($file);
  2017. rcopy($source, $destination);
  2018. writeLog("success", "new organizr files copied");
  2019. rrmdir($cleanup);
  2020. writeLog("success", "organizr upgrade folder removed");
  2021. writeLog("success", "organizr has been updated");
  2022. return true;
  2023. }
  2024. // NzbGET Items
  2025. function nzbgetConnect($list = 'listgroups') {
  2026. $url = qualifyURL(NZBGETURL);
  2027. $api = curl_get($url.'/'.NZBGETUSERNAME.':'.NZBGETPASSWORD.'/jsonrpc/'.$list);
  2028. $api = json_decode($api, true);
  2029. $gotNZB = array();
  2030. foreach ($api['result'] AS $child) {
  2031. $downloadName = htmlentities($child['NZBName'], ENT_QUOTES);
  2032. $downloadStatus = $child['Status'];
  2033. $downloadCategory = $child['Category'];
  2034. if($list == "history"){ $downloadPercent = "100"; $progressBar = ""; }
  2035. if($list == "listgroups"){ $downloadPercent = (($child['FileSizeMB'] - $child['RemainingSizeMB']) / $child['FileSizeMB']) * 100; $progressBar = "progress-bar-striped active"; }
  2036. if($child['Health'] <= "750"){
  2037. $downloadHealth = "danger";
  2038. }elseif($child['Health'] <= "900"){
  2039. $downloadHealth = "warning";
  2040. }elseif($child['Health'] <= "1000"){
  2041. $downloadHealth = "success";
  2042. }
  2043. $gotNZB[] = '<tr>
  2044. <td class="col-xs-7 nzbtable-file-row">'.$downloadName.'</td>
  2045. <td class="col-xs-2 nzbtable nzbtable-row">'.$downloadStatus.'</td>
  2046. <td class="col-xs-1 nzbtable nzbtable-row">'.$downloadCategory.'</td>
  2047. <td class="col-xs-2 nzbtable nzbtable-row">
  2048. <div class="progress">
  2049. <div class="progress-bar progress-bar-'.$downloadHealth.' '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  2050. <p class="text-center">'.round($downloadPercent).'%</p>
  2051. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  2052. </div>
  2053. </div>
  2054. </td>
  2055. </tr>';
  2056. }
  2057. if ($gotNZB) {
  2058. return implode('',$gotNZB);
  2059. } else {
  2060. return '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>';
  2061. }
  2062. }
  2063. // Sabnzbd Items
  2064. function sabnzbdConnect($list = 'queue') {
  2065. $url = qualifyURL(SABNZBDURL);
  2066. $api = file_get_contents($url.'/api?mode='.$list.'&output=json&apikey='.SABNZBDKEY);
  2067. $api = json_decode($api, true);
  2068. $gotNZB = array();
  2069. foreach ($api[$list]['slots'] AS $child) {
  2070. if($list == "queue"){ $downloadName = $child['filename']; $downloadCategory = $child['cat']; $downloadPercent = (($child['mb'] - $child['mbleft']) / $child['mb']) * 100; $progressBar = "progress-bar-striped active"; }
  2071. if($list == "history"){ $downloadName = $child['name']; $downloadCategory = $child['category']; $downloadPercent = "100"; $progressBar = ""; }
  2072. $downloadStatus = $child['status'];
  2073. $gotNZB[] = '<tr>
  2074. <td>'.$downloadName.'</td>
  2075. <td>'.$downloadStatus.'</td>
  2076. <td>'.$downloadCategory.'</td>
  2077. <td>
  2078. <div class="progress">
  2079. <div class="progress-bar progress-bar-success '.$progressBar.'" role="progressbar" aria-valuenow="'.$downloadPercent.'" aria-valuemin="0" aria-valuemax="100" style="width: '.$downloadPercent.'%">
  2080. <p class="text-center">'.round($downloadPercent).'%</p>
  2081. <span class="sr-only">'.$downloadPercent.'% Complete</span>
  2082. </div>
  2083. </div>
  2084. </td>
  2085. </tr>';
  2086. }
  2087. if ($gotNZB) {
  2088. return implode('',$gotNZB);
  2089. } else {
  2090. return '<tr><td colspan="4"><p class="text-center">No Results</p></td></tr>';
  2091. }
  2092. }
  2093. // Apply new tab settings
  2094. function updateTabs($tabs) {
  2095. if (!isset($GLOBALS['file_db'])) {
  2096. $GLOBALS['file_db'] = new PDO('sqlite:'.DATABASE_LOCATION.'users.db');
  2097. $GLOBALS['file_db']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  2098. }
  2099. // Validate
  2100. if (!isset($tabs['defaultz'])) { $tabs['defaultz'][current(array_keys($tabs['name']))] = 'true'; }
  2101. if (isset($tabs['name']) && isset($tabs['url']) && is_array($tabs['name'])) {
  2102. // Clear Existing Tabs
  2103. $GLOBALS['file_db']->query("DELETE FROM tabs");
  2104. // Process New Tabs
  2105. $totalValid = 0;
  2106. foreach ($tabs['name'] as $key => $value) {
  2107. // Qualify
  2108. if (!$value || !isset($tabs['url']) || !$tabs['url'][$key]) { continue; }
  2109. $totalValid++;
  2110. $fields = array();
  2111. foreach(array('id','name','url','icon','iconurl','order') as $v) {
  2112. if (isset($tabs[$v]) && isset($tabs[$v][$key])) { $fields[$v] = $tabs[$v][$key]; }
  2113. }
  2114. foreach(array('active','user','guest','defaultz','window') as $v) {
  2115. if (isset($tabs[$v]) && isset($tabs[$v][$key])) { $fields[$v] = ($tabs[$v][$key]!=='false'?'true':'false'); }
  2116. }
  2117. $GLOBALS['file_db']->query('INSERT INTO tabs (`'.implode('`,`',array_keys($fields)).'`) VALUES (\''.implode("','",$fields).'\');');
  2118. }
  2119. writeLog("success", "tabs successfully saved");
  2120. return $totalValid;
  2121. } else {
  2122. writeLog("error", "tabs could not save");
  2123. return false;
  2124. }
  2125. writeLog("error", "tabs could not save");
  2126. return false;
  2127. }
  2128. // ==============
  2129. function clean($strin) {
  2130. $strout = null;
  2131. for ($i = 0; $i < strlen($strin); $i++) {
  2132. $ord = ord($strin[$i]);
  2133. if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
  2134. $strout .= "&amp;#{$ord};";
  2135. }
  2136. else {
  2137. switch ($strin[$i]) {
  2138. case '<':
  2139. $strout .= '&lt;';
  2140. break;
  2141. case '>':
  2142. $strout .= '&gt;';
  2143. break;
  2144. case '&':
  2145. $strout .= '&amp;';
  2146. break;
  2147. case '"':
  2148. $strout .= '&quot;';
  2149. break;
  2150. default:
  2151. $strout .= $strin[$i];
  2152. }
  2153. }
  2154. }
  2155. return $strout;
  2156. }
  2157. function registration_callback($username, $email, $userdir){
  2158. global $data;
  2159. $data = array($username, $email, $userdir);
  2160. }
  2161. function printArray($arrayName){
  2162. $messageCount = count($arrayName);
  2163. $i = 0;
  2164. foreach ( $arrayName as $item ) :
  2165. $i++;
  2166. if($i < $messageCount) :
  2167. echo "<small class='text-uppercase'>" . $item . "</small> & ";
  2168. elseif($i = $messageCount) :
  2169. echo "<small class='text-uppercase'>" . $item . "</small>";
  2170. endif;
  2171. endforeach;
  2172. }
  2173. function write_ini_file($content, $path) {
  2174. if (!$handle = fopen($path, 'w')) {
  2175. return false;
  2176. }
  2177. $success = fwrite($handle, trim($content));
  2178. fclose($handle);
  2179. return $success;
  2180. }
  2181. function gotTimezone(){
  2182. $regions = array(
  2183. 'Africa' => DateTimeZone::AFRICA,
  2184. 'America' => DateTimeZone::AMERICA,
  2185. 'Antarctica' => DateTimeZone::ANTARCTICA,
  2186. 'Arctic' => DateTimeZone::ARCTIC,
  2187. 'Asia' => DateTimeZone::ASIA,
  2188. 'Atlantic' => DateTimeZone::ATLANTIC,
  2189. 'Australia' => DateTimeZone::AUSTRALIA,
  2190. 'Europe' => DateTimeZone::EUROPE,
  2191. 'Indian' => DateTimeZone::INDIAN,
  2192. 'Pacific' => DateTimeZone::PACIFIC
  2193. );
  2194. $timezones = array();
  2195. foreach ($regions as $name => $mask) {
  2196. $zones = DateTimeZone::listIdentifiers($mask);
  2197. foreach($zones as $timezone) {
  2198. $time = new DateTime(NULL, new DateTimeZone($timezone));
  2199. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  2200. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  2201. }
  2202. }
  2203. print '<select name="timezone" id="timezone" class="form-control material input-sm" required>';
  2204. foreach($timezones as $region => $list) {
  2205. print '<optgroup label="' . $region . '">' . "\n";
  2206. foreach($list as $timezone => $name) {
  2207. if($timezone == TIMEZONE) : $selected = " selected"; else : $selected = ""; endif;
  2208. print '<option value="' . $timezone . '"' . $selected . '>' . $name . '</option>' . "\n";
  2209. }
  2210. print '</optgroup>' . "\n";
  2211. }
  2212. print '</select>';
  2213. }
  2214. function getTimezone(){
  2215. $regions = array(
  2216. 'Africa' => DateTimeZone::AFRICA,
  2217. 'America' => DateTimeZone::AMERICA,
  2218. 'Antarctica' => DateTimeZone::ANTARCTICA,
  2219. 'Arctic' => DateTimeZone::ARCTIC,
  2220. 'Asia' => DateTimeZone::ASIA,
  2221. 'Atlantic' => DateTimeZone::ATLANTIC,
  2222. 'Australia' => DateTimeZone::AUSTRALIA,
  2223. 'Europe' => DateTimeZone::EUROPE,
  2224. 'Indian' => DateTimeZone::INDIAN,
  2225. 'Pacific' => DateTimeZone::PACIFIC
  2226. );
  2227. $timezones = array();
  2228. foreach ($regions as $name => $mask) {
  2229. $zones = DateTimeZone::listIdentifiers($mask);
  2230. foreach($zones as $timezone) {
  2231. $time = new DateTime(NULL, new DateTimeZone($timezone));
  2232. $ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';
  2233. $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
  2234. }
  2235. }
  2236. print '<select name="timezone" id="timezone" class="form-control material" required>';
  2237. foreach($timezones as $region => $list) {
  2238. print '<optgroup label="' . $region . '">' . "\n";
  2239. foreach($list as $timezone => $name) {
  2240. print '<option value="' . $timezone . '">' . $name . '</option>' . "\n";
  2241. }
  2242. print '</optgroup>' . "\n";
  2243. }
  2244. print '</select>';
  2245. }
  2246. function explosion($string, $position){
  2247. $getWord = explode("|", $string);
  2248. return $getWord[$position];
  2249. }
  2250. function getServerPath() {
  2251. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  2252. $protocol = "https://";
  2253. } else {
  2254. $protocol = "http://";
  2255. }
  2256. return $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
  2257. }
  2258. function get_browser_name() {
  2259. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  2260. if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
  2261. elseif (strpos($user_agent, 'Edge')) return 'Edge';
  2262. elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
  2263. elseif (strpos($user_agent, 'Safari')) return 'Safari';
  2264. elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
  2265. elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
  2266. return 'Other';
  2267. }
  2268. function getSickrageCalendarWanted($array){
  2269. $array = json_decode($array, true);
  2270. $gotCalendar = "";
  2271. $i = 0;
  2272. foreach($array['data']['missed'] AS $child) {
  2273. $i++;
  2274. $seriesName = $child['show_name'];
  2275. $episodeID = $child['tvdbid'];
  2276. $episodeAirDate = $child['airdate'];
  2277. $episodeAirDateTime = explode(" ",$child['airs']);
  2278. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  2279. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  2280. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2281. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  2282. $downloaded = "0";
  2283. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  2284. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  2285. }
  2286. foreach($array['data']['today'] AS $child) {
  2287. $i++;
  2288. $seriesName = $child['show_name'];
  2289. $episodeID = $child['tvdbid'];
  2290. $episodeAirDate = $child['airdate'];
  2291. $episodeAirDateTime = explode(" ",$child['airs']);
  2292. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  2293. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  2294. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2295. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  2296. $downloaded = "0";
  2297. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  2298. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  2299. }
  2300. foreach($array['data']['soon'] AS $child) {
  2301. $i++;
  2302. $seriesName = $child['show_name'];
  2303. $episodeID = $child['tvdbid'];
  2304. $episodeAirDate = $child['airdate'];
  2305. $episodeAirDateTime = explode(" ",$child['airs']);
  2306. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  2307. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  2308. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2309. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  2310. $downloaded = "0";
  2311. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  2312. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  2313. }
  2314. foreach($array['data']['later'] AS $child) {
  2315. $i++;
  2316. $seriesName = $child['show_name'];
  2317. $episodeID = $child['tvdbid'];
  2318. $episodeAirDate = $child['airdate'];
  2319. $episodeAirDateTime = explode(" ",$child['airs']);
  2320. $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
  2321. $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
  2322. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2323. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  2324. $downloaded = "0";
  2325. if($downloaded == "0" && isset($unaired)){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg";}else{ $downloaded = "red-bg"; }
  2326. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  2327. }
  2328. if ($i != 0){ return $gotCalendar; }
  2329. }
  2330. function getSickrageCalendarHistory($array){
  2331. $array = json_decode($array, true);
  2332. $gotCalendar = "";
  2333. $i = 0;
  2334. foreach($array['data'] AS $child) {
  2335. $i++;
  2336. $seriesName = $child['show_name'];
  2337. $episodeID = $child['tvdbid'];
  2338. $episodeAirDate = $child['date'];
  2339. $downloaded = "green-bg";
  2340. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  2341. }
  2342. if ($i != 0){ return $gotCalendar; }
  2343. }
  2344. function getSonarrCalendar($array){
  2345. $array = json_decode($array, true);
  2346. $gotCalendar = "";
  2347. $i = 0;
  2348. foreach($array AS $child) {
  2349. $i++;
  2350. $seriesName = $child['series']['title'];
  2351. $episodeID = $child['series']['tvdbId'];
  2352. if(!isset($episodeID)){ $episodeID = ""; }
  2353. $episodeName = htmlentities($child['title'], ENT_QUOTES);
  2354. if($child['episodeNumber'] == "1"){ $episodePremier = "true"; }else{ $episodePremier = "false"; }
  2355. $episodeAirDate = $child['airDateUtc'];
  2356. $episodeAirDate = strtotime($episodeAirDate);
  2357. $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
  2358. if (new DateTime() < new DateTime($episodeAirDate)) { $unaired = true; }
  2359. $downloaded = $child['hasFile'];
  2360. 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"; }
  2361. $gotCalendar .= "{ title: \"$seriesName\", start: \"$episodeAirDate\", className: \"$downloaded\", imagetype: \"tv\", url: \"https://thetvdb.com/?tab=series&id=$episodeID\" }, \n";
  2362. }
  2363. if ($i != 0){ return $gotCalendar; }
  2364. }
  2365. function getRadarrCalendar($array){
  2366. $array = json_decode($array, true);
  2367. $gotCalendar = "";
  2368. $i = 0;
  2369. foreach($array AS $child) {
  2370. if(isset($child['inCinemas'])){
  2371. $i++;
  2372. $movieName = $child['title'];
  2373. $movieID = $child['tmdbId'];
  2374. if(!isset($movieID)){ $movieID = ""; }
  2375. if(isset($child['inCinemas']) && isset($child['physicalRelease'])){
  2376. $physicalRelease = $child['physicalRelease'];
  2377. $physicalRelease = strtotime($physicalRelease);
  2378. $physicalRelease = date("Y-m-d", $physicalRelease);
  2379. if (new DateTime() < new DateTime($physicalRelease)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  2380. $downloaded = $child['hasFile'];
  2381. if($downloaded == "0" && $notReleased == "true"){ $downloaded = "indigo-bg"; }elseif($downloaded == "1"){ $downloaded = "green-bg"; }else{ $downloaded = "red-bg"; }
  2382. }else{
  2383. $physicalRelease = $child['inCinemas'];
  2384. $downloaded = "light-blue-bg";
  2385. }
  2386. $gotCalendar .= "{ title: \"$movieName\", start: \"$physicalRelease\", className: \"$downloaded\", imagetype: \"film\", url: \"https://www.themoviedb.org/movie/$movieID\" }, \n";
  2387. }
  2388. }
  2389. if ($i != 0){ return $gotCalendar; }
  2390. }
  2391. function getHeadphonesCalendar($url, $key, $list){
  2392. $url = qualifyURL(HEADPHONESURL);
  2393. $api = curl_get($url."/api?apikey=".$key."&cmd=$list");
  2394. $api = json_decode($api, true);
  2395. $i = 0;
  2396. $gotCalendar = "";
  2397. foreach($api AS $child) {
  2398. if($child['Status'] == "Wanted"){
  2399. $i++;
  2400. $albumName = addslashes($child['AlbumTitle']);
  2401. $albumArtist = htmlentities($child['ArtistName'], ENT_QUOTES);
  2402. $albumDate = $child['ReleaseDate'];
  2403. $albumID = $child['AlbumID'];
  2404. $albumDate = strtotime($albumDate);
  2405. $albumDate = date("Y-m-d", $albumDate);
  2406. $albumStatus = $child['Status'];
  2407. if (new DateTime() < new DateTime($albumDate)) { $notReleased = "true"; }else{ $notReleased = "false"; }
  2408. if($albumStatus == "Wanted" && $notReleased == "true"){ $albumStatusColor = "indigo-bg"; }elseif($albumStatus == "Downloaded"){ $albumStatusColor = "green-bg"; }else{ $albumStatusColor = "red-bg"; }
  2409. $gotCalendar .= "{ title: \"$albumArtist - $albumName\", start: \"$albumDate\", className: \"$albumStatusColor\", imagetype: \"music\", url: \"https://musicbrainz.org/release-group/$albumID\" }, \n";
  2410. }
  2411. }
  2412. if ($i != 0){ return $gotCalendar; }
  2413. }
  2414. function checkRootPath($string){
  2415. if($string == "\\" || $string == "/"){
  2416. return "/";
  2417. }else{
  2418. return str_replace("\\", "/", $string) . "/";
  2419. }
  2420. }
  2421. function writeLog($type, $message){
  2422. $message = date("Y-m-d H:i:s")."|".$type."|".$message."\n";
  2423. file_put_contents("org.log", $message, FILE_APPEND | LOCK_EX);
  2424. }
  2425. function readLog(){
  2426. $log = file("org.log");
  2427. $log = array_reverse($log);
  2428. foreach($log as $line){
  2429. $line = explode("|", $line);
  2430. $line[1] = ($line[1] == "error") ? '<span class="label label-danger">Error</span>' : '<span class="label label-primary">Success</span>';
  2431. echo "<tr><td>".$line[0]."</td><td>".$line[2]."</td><td>".$line[1]."</td></tr>";
  2432. }
  2433. }
  2434. function buildStream($array){
  2435. $result = "";
  2436. if (array_key_exists('platform', $array)) {
  2437. $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>';
  2438. }
  2439. if (array_key_exists('device', $array)) {
  2440. $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>';
  2441. }
  2442. if (array_key_exists('stream', $array)) {
  2443. $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>';
  2444. }
  2445. if (array_key_exists('video', $array)) {
  2446. $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>';
  2447. }
  2448. if (array_key_exists('audio', $array)) {
  2449. $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>';
  2450. }
  2451. return $result;
  2452. }
  2453. function streamType($value){
  2454. if($value == "transcode" || $value == "Transcode"){
  2455. return "Transcode";
  2456. }elseif($value == "copy" || $value == "DirectStream"){
  2457. return "Direct Stream";
  2458. }elseif($value == "directplay" || $value == "DirectPlay"){
  2459. return "Direct Play";
  2460. }else{
  2461. return "Direct Play";
  2462. }
  2463. }
  2464. function getPlatform($platform){
  2465. $allPlatforms = array(
  2466. "Chrome" => "chrome.png",
  2467. "tvOS" => "atv.png",
  2468. "iOS" => "ios.png",
  2469. "Xbox One" => "xbox.png",
  2470. "Mystery 4" => "playstation.png",
  2471. "Samsung" => "samsung.png",
  2472. "Roku" => "roku.png",
  2473. "Emby for iOS" => "ios.png",
  2474. "Emby Mobile" => "emby.png",
  2475. "Emby Theater" => "emby.png",
  2476. );
  2477. if (array_key_exists($platform, $allPlatforms)) {
  2478. return $allPlatforms[$platform];
  2479. }else{
  2480. return "pmp.png";
  2481. }
  2482. }
  2483. function getServer(){
  2484. $server = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : $_SERVER["SERVER_NAME"];
  2485. return $server;
  2486. }
  2487. function prettyPrint($a) {
  2488. echo "HEADERS: <pre>";
  2489. print_r($a);
  2490. echo "</pre>";
  2491. echo "<br/>";
  2492. }
  2493. function checkFrame($array, $url){
  2494. if(array_key_exists("x-frame-options", $array)){
  2495. if($array['x-frame-options'] == "deny"){
  2496. return false;
  2497. }elseif($array['x-frame-options'] == "sameorgin"){
  2498. $digest = parse_url($url);
  2499. $host = (isset($digest['host'])?$digest['host']:'');
  2500. if(getServer() == $host){
  2501. return true;
  2502. }else{
  2503. return false;
  2504. }
  2505. }
  2506. }else{
  2507. if(!$array){
  2508. return false;
  2509. }
  2510. return true;
  2511. }
  2512. }
  2513. function frameTest($url){
  2514. $array = array_change_key_case(get_headers(qualifyURL($url), 1));
  2515. $url = qualifyURL($url);
  2516. if(checkFrame($array, $url)){
  2517. return true;
  2518. }else{
  2519. return false;
  2520. }
  2521. }
  2522. function sendResult($result, $icon = "floppy-o", $message = false, $success = "WAS_SUCCESSFUL", $fail = "HAS_FAILED", $send = true) {
  2523. $notifyExplode = explode("-", NOTIFYEFFECT);
  2524. if ($result) {
  2525. $msg = array(
  2526. 'html' => ($message?''.$message.' <strong>'.translate($success).'</strong>':'<strong>'.translate($success).'</strong>'),
  2527. 'icon' => $icon,
  2528. 'type' => 'success',
  2529. 'length' => '5000',
  2530. 'layout' => $notifyExplode[0],
  2531. 'effect' => $notifyExplode[1],
  2532. );
  2533. } else {
  2534. $msg = array(
  2535. 'html' => ($message?''.$message.' <strong>'.translate($fail).'</strong>':'<strong>'.translate($fail).'</strong>'),
  2536. 'icon' => $icon,
  2537. 'type' => 'error',
  2538. 'length' => '5000',
  2539. 'layout' => $notifyExplode[0],
  2540. 'effect' => $notifyExplode[1],
  2541. );
  2542. }
  2543. // Send and kill script?
  2544. if ($send) {
  2545. header('Content-Type: application/json');
  2546. echo json_encode(array('notify'=>$msg));
  2547. die();
  2548. }
  2549. return $msg;
  2550. }
  2551. function buildHomepageNotice($layout, $type, $title, $message){
  2552. switch ($layout) {
  2553. case 'elegant':
  2554. return '
  2555. <div id="homepageNotice" class="row">
  2556. <div class="col-lg-12">
  2557. <div class="content-box big-box box-shadow panel-box panel-'.$type.'">
  2558. <div class="content-title i-block">
  2559. <h4 class="zero-m"><strong>'.$title.'</strong></h4>
  2560. <div class="content-tools i-block pull-right">
  2561. <a class="close-btn">
  2562. <i class="fa fa-times"></i>
  2563. </a>
  2564. </div>
  2565. </div>
  2566. '.$message.'
  2567. </div>
  2568. </div>
  2569. </div>
  2570. ';
  2571. break;
  2572. case 'basic':
  2573. return '
  2574. <div id="homepageNotice" class="row">
  2575. <div class="col-lg-12">
  2576. <div class="panel panel-'.$type.'">
  2577. <div class="panel-heading">
  2578. <h3 class="panel-title">'.$title.'</h3>
  2579. </div>
  2580. <div class="panel-body">
  2581. '.$message.'
  2582. </div>
  2583. </div>
  2584. </div>
  2585. </div>
  2586. ';
  2587. break;
  2588. case 'jumbotron';
  2589. return '
  2590. <div id="homepageNotice" class="row">
  2591. <div class="col-lg-12">
  2592. <div class="jumbotron">
  2593. <div class="container">
  2594. <h1>'.$title.'</h1>
  2595. <p>'.$message.'</p>
  2596. </div>
  2597. </div>
  2598. </div>
  2599. </div>
  2600. ';
  2601. }
  2602. }
  2603. function embyArray($array, $type) {
  2604. $key = ($type == "video" ? "Height" : "Channels");
  2605. if (array_key_exists($key, $array)) {
  2606. switch ($type) {
  2607. case "video":
  2608. $codec = $array["Codec"];
  2609. $height = $array["Height"];
  2610. $width = $array["Width"];
  2611. break;
  2612. default:
  2613. $codec = $array["Codec"];
  2614. $channels = $array["Channels"];
  2615. }
  2616. return ($type == "video" ? "(".$codec.") (".$width."x".$height.")" : "(".$codec.") (".$channels."ch)");
  2617. }
  2618. foreach ($array as $element) {
  2619. if (is_array($element)) {
  2620. if (embyArray($element, $type)) {
  2621. return embyArray($element, $type);
  2622. }
  2623. }
  2624. }
  2625. }
  2626. // Get Now Playing Streams From Plex
  2627. function searchPlex($query){
  2628. $address = qualifyURL(PLEXURL);
  2629. // Perform API requests
  2630. $api = @curl_get($address."/search?query=".rawurlencode($query)."&X-Plex-Token=".PLEXTOKEN);
  2631. $api = simplexml_load_string($api);
  2632. $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>";
  2633. $items = "";
  2634. $albums = $movies = $shows = 0;
  2635. $style = 'style="vertical-align: middle"';
  2636. foreach($api AS $child) {
  2637. if($child['type'] != "artist" && $child['type'] != "episode" && isset($child['librarySectionID'])){
  2638. $time = (string)$child['addedAt'];
  2639. $time = new DateTime("@$time");
  2640. $results = array(
  2641. "title" => (string)$child['title'],
  2642. "image" => (string)$child['thumb'],
  2643. "type" => (string)ucwords($child['type']),
  2644. "year" => (string)$child['year'],
  2645. "key" => (string)$child['ratingKey']."-search",
  2646. "genre" => (string)$child->Genre['tag'],
  2647. "added" => $time->format('Y-m-d'),
  2648. "extra" => "",
  2649. );
  2650. switch ($child['type']){
  2651. case "album":
  2652. $push = array(
  2653. "title" => (string)$child['parentTitle']." - ".(string)$child['title'],
  2654. );
  2655. $results = array_replace($results,$push);
  2656. $albums++;
  2657. break;
  2658. case "movie":
  2659. $push = array(
  2660. "extra" => "Content Rating: ".(string)$child['contentRating']."<br/>Movie Rating: ".(string)$child['rating'],
  2661. );
  2662. $results = array_replace($results,$push);
  2663. $movies++;
  2664. break;
  2665. case "show":
  2666. $push = array(
  2667. "extra" => "Seasons: ".(string)$child['childCount']."<br/>Episodes: ".(string)$child['leafCount'],
  2668. );
  2669. $results = array_replace($results,$push);
  2670. $shows++;
  2671. break;
  2672. }
  2673. if (file_exists('images/cache/'.$results['key'].'.jpg')){ $image_url = 'images/cache/'.$results['key'].'.jpg'; }
  2674. if (file_exists('images/cache/'.$results['key'].'.jpg') && (time() - 604800) > filemtime('images/cache/'.$results['key'].'.jpg') || !file_exists('images/cache/'.$results['key'].'.jpg')) {
  2675. $image_url = 'ajax.php?a=plex-image&img='.$results['image'].'&height=150&width=100&key='.$results['key'];
  2676. }
  2677. if(!$results['image']){ $image_url = "images/no-search.png"; $key = "no-search"; }
  2678. $items .= '<tr>
  2679. <th scope="row"><img src="'.$image_url.'"></th>
  2680. <td class="col-xs-2 nzbtable nzbtable-row"'.$style.'>'.$results['title'].'</td>
  2681. <td class="col-xs-3 nzbtable nzbtable-row"'.$style.'>'.$results['genre'].'</td>
  2682. <td class="col-xs-1 nzbtable nzbtable-row"'.$style.'>'.$results['year'].'</td>
  2683. <td class="col-xs-1 nzbtable nzbtable-row"'.$style.'>'.$results['type'].'</td>
  2684. <td class="col-xs-3 nzbtable nzbtable-row"'.$style.'>'.$results['added'].'</td>
  2685. <td class="col-xs-2 nzbtable nzbtable-row"'.$style.'>'.$results['extra'].'</td>
  2686. </tr>';
  2687. }
  2688. }
  2689. $totals = '<div style="margin: 10px;" class="sort-todo pull-right">
  2690. <span class="badge gray-bg"><i class="fa fa-film fa-2x white"></i><strong style="
  2691. font-size: 23px;
  2692. ">&nbsp;'.$movies.'</strong></span>
  2693. <span class="badge gray-bg"><i class="fa fa-tv fa-2x white"></i><strong style="
  2694. font-size: 23px;
  2695. ">&nbsp;'.$shows.'</strong></span>
  2696. <span class="badge gray-bg"><i class="fa fa-music fa-2x white"></i><strong style="
  2697. font-size: 23px;
  2698. ">&nbsp;'.$albums.'</strong></span>
  2699. </div>';
  2700. return (!empty($items) ? $totals.$pre.$items."</div></table>" : "<h2 class='text-center'>No Results for $query</h2>" );
  2701. }
  2702. // Always run this
  2703. dependCheck();