functions.php 127 KB

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