functions.php 99 KB

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