organizr-functions.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. <?php
  2. trait OrganizrFunctions
  3. {
  4. public function docs($path): string
  5. {
  6. return 'https://organizr.gitbook.io/organizr/' . $path;
  7. }
  8. public function loadResources($files = [], $rootPath = '')
  9. {
  10. $scripts = '';
  11. if (count($files) > 0) {
  12. foreach ($files as $file) {
  13. if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'js') {
  14. $scripts .= $this->loadJavaResource($file, $rootPath);
  15. } elseif (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'css') {
  16. $scripts .= $this->loadStyleResource($file, $rootPath);
  17. }
  18. }
  19. }
  20. return $scripts;
  21. }
  22. public function loadJavaResource($file = '', $rootPath = '')
  23. {
  24. return ($file !== '') ? '<script src="' . $rootPath . $file . '?v=' . trim($this->fileHash) . '"></script>' . "\n" : '';
  25. }
  26. public function loadStyleResource($file = '', $rootPath = '')
  27. {
  28. return ($file !== '') ? '<link href="' . $rootPath . $file . '?v=' . trim($this->fileHash) . '" rel="stylesheet">' . "\n" : '';
  29. }
  30. public function loadDefaultJavascriptFiles()
  31. {
  32. $javaFiles = [
  33. 'js/jquery-2.2.4.min.js',
  34. 'bootstrap/dist/js/bootstrap.min.js',
  35. 'plugins/bower_components/sidebar-nav/dist/sidebar-nav.min.js',
  36. 'js/jquery.slimscroll.js',
  37. 'plugins/bower_components/styleswitcher/jQuery.style.switcher.js',
  38. 'plugins/bower_components/moment/moment.js',
  39. 'plugins/bower_components/moment/moment-timezone.js',
  40. 'plugins/bower_components/jquery-wizard-master/dist/jquery-wizard.min.js',
  41. 'plugins/bower_components/jquery-wizard-master/libs/formvalidation/formValidation.min.js',
  42. 'plugins/bower_components/jquery-wizard-master/libs/formvalidation/bootstrap.min.js',
  43. 'js/bowser.min.js',
  44. 'js/jasny-bootstrap.js'
  45. ];
  46. $scripts = '';
  47. foreach ($javaFiles as $file) {
  48. $scripts .= '<script src="' . $file . '?v=' . trim($this->fileHash) . '"></script>' . "\n";
  49. }
  50. return $scripts;
  51. }
  52. public function loadJavascriptFile($file)
  53. {
  54. return '<script>loadJavascript("' . $file . '?v=' . trim($this->fileHash) . '");' . "</script>\n";
  55. }
  56. public function embyJoinAPI($array)
  57. {
  58. $username = ($array['username']) ?? null;
  59. $email = ($array['email']) ?? null;
  60. $password = ($array['password']) ?? null;
  61. if (!$username) {
  62. $this->setAPIResponse('error', 'Username not supplied', 422);
  63. return false;
  64. }
  65. if (!$email) {
  66. $this->setAPIResponse('error', 'Email not supplied', 422);
  67. return false;
  68. }
  69. if (!$password) {
  70. $this->setAPIResponse('error', 'Password not supplied', 422);
  71. return false;
  72. }
  73. return $this->embyJoin($username, $email, $password);
  74. }
  75. public function embyJoin($username, $email, $password)
  76. {
  77. try {
  78. #create user in emby.
  79. $headers = array(
  80. "Accept" => "application/json"
  81. );
  82. $data = array();
  83. $url = $this->config['embyURL'] . '/emby/Users/New?name=' . $username . '&api_key=' . $this->config['embyToken'];
  84. $response = Requests::Post($url, $headers, json_encode($data), array());
  85. $response = $response->body;
  86. //return($response);
  87. $response = json_decode($response, true);
  88. //return($response);
  89. $userID = $response["Id"];
  90. //return($userID);
  91. #authenticate as user to update password.
  92. //randomizer four digits of DeviceId
  93. // I dont think ther would be security problems with hardcoding deviceID but randomizing it would mitigate any issue.
  94. $deviceIdSeceret = rand(0, 9) . "" . rand(0, 9) . "" . rand(0, 9) . "" . rand(0, 9);
  95. //hardcoded device id with the first three digits random 0-9,0-9,0-9,0-9
  96. $embyAuthHeader = 'MediaBrowser Client="Emby Mobile", Device="Firefox", DeviceId="' . $deviceIdSeceret . 'aWxssS81LgAggFdpbmRvd3MgTlQgMTAuMDsgV2luNjxx7IHf2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzcyLjAuMzYyNi4xMTkgU2FmYXJpLzUzNy4zNnwxNTUxNTczMTAyNDI4", Version="4.0.2.0"';
  97. $headers = array(
  98. "Accept" => "application/json",
  99. "Content-Type" => "application/json",
  100. "X-Emby-Authorization" => $embyAuthHeader
  101. );
  102. $data = array(
  103. "Pw" => "",
  104. "Username" => $username
  105. );
  106. $url = $this->config['embyURL'] . '/emby/Users/AuthenticateByName';
  107. $response = Requests::Post($url, $headers, json_encode($data), array());
  108. $response = $response->body;
  109. $response = json_decode($response, true);
  110. $userToken = $response["AccessToken"];
  111. #update password
  112. $embyAuthHeader = 'MediaBrowser Client="Emby Mobile", Device="Firefox", Token="' . $userToken . '", DeviceId="' . $deviceIdSeceret . 'aWxssS81LgAggFdpbmRvd3MgTlQgMTAuMDsgV2luNjxx7IHf2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzcyLjAuMzYyNi4xMTkgU2FmYXJpLzUzNy4zNnwxNTUxNTczMTAyNDI4", Version="4.0.2.0"';
  113. $headers = array(
  114. "Accept" => "application/json",
  115. "Content-Type" => "application/json",
  116. "X-Emby-Authorization" => $embyAuthHeader
  117. );
  118. $data = array(
  119. "CurrentPw" => "",
  120. "NewPw" => $password,
  121. "Id" => $userID
  122. );
  123. $url = $this->config['embyURL'] . '/emby/Users/' . $userID . '/Password';
  124. Requests::Post($url, $headers, json_encode($data), array());
  125. #update config
  126. $headers = array(
  127. "Accept" => "application/json",
  128. "Content-Type" => "application/json"
  129. );
  130. $url = $this->config['embyURL'] . '/emby/Users/' . $userID . '/Policy?api_key=' . $this->config['embyToken'];
  131. $response = Requests::Post($url, $headers, $this->getEmbyTemplateUserJson(), array());
  132. #add emby.media
  133. try {
  134. #seperate because this is not required
  135. $headers = array(
  136. "Accept" => "application/json",
  137. "X-Emby-Authorization" => $embyAuthHeader
  138. );
  139. $data = array(
  140. "ConnectUsername " => $email
  141. );
  142. $url = $this->config['embyURL'] . '/emby/Users/' . $userID . '/Connect/Link';
  143. Requests::Post($url, $headers, json_encode($data), array());
  144. } catch (Requests_Exception $e) {
  145. $this->writeLog('error', 'Emby Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  146. $this->setAPIResponse('error', $e->getMessage(), 500);
  147. return false;
  148. }
  149. $this->setAPIResponse('success', 'User has joined Emby', 200);
  150. return true;
  151. } catch (Requests_Exception $e) {
  152. $this->writeLog('error', 'Emby create Function - Error: ' . $e->getMessage(), 'SYSTEM');
  153. $this->setAPIResponse('error', $e->getMessage(), 500);
  154. return false;
  155. }
  156. }
  157. /*loads users from emby and returns a correctly formated policy for a new user.
  158. */
  159. public function getEmbyTemplateUserJson()
  160. {
  161. $headers = array(
  162. "Accept" => "application/json"
  163. );
  164. $data = array();
  165. $url = $this->config['embyURL'] . '/emby/Users?api_key=' . $this->config['embyToken'];
  166. $response = Requests::Get($url, $headers, array());
  167. $response = $response->body;
  168. $response = json_decode($response, true);
  169. //error_Log("response ".json_encode($response));
  170. $this->writeLog('error', 'userList:' . json_encode($response), 'SYSTEM');
  171. //$correct stores the template users object
  172. $correct = null;
  173. foreach ($response as $element) {
  174. if ($element['Name'] == $this->config['INVITES-EmbyTemplate']) {
  175. $correct = $element;
  176. }
  177. }
  178. $this->writeLog('error', 'Correct user:' . json_encode($correct), 'SYSTEM');
  179. if ($correct == null) {
  180. //return empty JSON if user incorrectly configured template
  181. return "{}";
  182. }
  183. //select policy section and remove possibly dangerous rows.
  184. $policy = $correct['Policy'];
  185. //writeLog('error', 'policy update'.$policy, 'SYSTEM');
  186. unset($policy['AuthenticationProviderId']);
  187. unset($policy['InvalidLoginAttemptCount']);
  188. unset($policy['DisablePremiumFeatures']);
  189. unset($policy['DisablePremiumFeatures']);
  190. return (json_encode($policy));
  191. }
  192. public function checkHostPrefix($s)
  193. {
  194. if (empty($s)) {
  195. return $s;
  196. }
  197. return (substr($s, -1, 1) == '\\') ? $s : $s . '\\';
  198. }
  199. public function approvedFileExtension($filename, $type = 'image')
  200. {
  201. $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  202. if ($type == 'image') {
  203. switch ($ext) {
  204. case 'gif':
  205. case 'png':
  206. case 'jpeg':
  207. case 'jpg':
  208. case 'svg':
  209. return true;
  210. default:
  211. return false;
  212. }
  213. } elseif ($type == 'cert') {
  214. switch ($ext) {
  215. case 'pem':
  216. return true;
  217. default:
  218. return false;
  219. }
  220. }
  221. }
  222. public function getImages()
  223. {
  224. $allIconsPrep = array();
  225. $allIcons = array();
  226. $ignore = array(".", "..", "._.DS_Store", ".DS_Store", ".pydio_id", "index.html");
  227. $dirname = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'tabs' . DIRECTORY_SEPARATOR;
  228. $path = 'plugins/images/tabs/';
  229. $images = scandir($dirname);
  230. foreach ($images as $image) {
  231. if (!in_array($image, $ignore)) {
  232. $allIconsPrep[$image] = array(
  233. 'path' => $path,
  234. 'name' => $image
  235. );
  236. }
  237. }
  238. $dirname = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR;
  239. $path = 'plugins/images/userTabs/';
  240. $images = scandir($dirname);
  241. foreach ($images as $image) {
  242. if (!in_array($image, $ignore)) {
  243. $allIconsPrep[$image] = array(
  244. 'path' => $path,
  245. 'name' => $image
  246. );
  247. }
  248. }
  249. ksort($allIconsPrep);
  250. foreach ($allIconsPrep as $item) {
  251. $allIcons[] = $item['path'] . $item['name'];
  252. }
  253. return $allIcons;
  254. }
  255. public function imageSelect($form)
  256. {
  257. $i = 1;
  258. $images = $this->getImages();
  259. $return = '<select class="form-control tabIconImageList" id="' . $form . '-chooseImage" name="chooseImage"><option lang="en">Select or type Icon</option>';
  260. foreach ($images as $image) {
  261. $i++;
  262. $return .= '<option value="' . $image . '">' . basename($image) . '</option>';
  263. }
  264. return $return . '</select>';
  265. }
  266. public function getThemes()
  267. {
  268. $themes = array();
  269. foreach (glob(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . "*.css") as $filename) {
  270. $themes[] = array(
  271. 'name' => preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename)),
  272. 'value' => preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename))
  273. );
  274. }
  275. return $themes;
  276. }
  277. public function getSounds()
  278. {
  279. $sounds = array();
  280. foreach (glob(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'sounds' . DIRECTORY_SEPARATOR . 'default' . DIRECTORY_SEPARATOR . "*.mp3") as $filename) {
  281. $sounds[] = array(
  282. 'name' => preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename)),
  283. 'value' => preg_replace('/\\.[^.\\s]{3,4}$/', '', 'plugins/sounds/default/' . basename($filename) . '.mp3')
  284. );
  285. }
  286. foreach (glob(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'sounds' . DIRECTORY_SEPARATOR . 'custom' . DIRECTORY_SEPARATOR . "*.mp3") as $filename) {
  287. $sounds[] = array(
  288. 'name' => preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename)),
  289. 'value' => preg_replace('/\\.[^.\\s]{3,4}$/', '', 'plugins/sounds/custom/' . basename($filename) . '.mp3')
  290. );
  291. }
  292. return $sounds;
  293. }
  294. public function getBranches()
  295. {
  296. return array(
  297. array(
  298. 'name' => 'Develop',
  299. 'value' => 'v2-develop'
  300. ),
  301. array(
  302. 'name' => 'Master',
  303. 'value' => 'v2-master'
  304. )
  305. );
  306. }
  307. public function getSettingsTabs()
  308. {
  309. return array(
  310. array(
  311. 'name' => 'Tab Editor',
  312. 'value' => '0'
  313. ),
  314. array(
  315. 'name' => 'Customize',
  316. 'value' => '1'
  317. ),
  318. array(
  319. 'name' => 'User Management',
  320. 'value' => '2'
  321. ),
  322. array(
  323. 'name' => 'Image Manager',
  324. 'value' => '3'
  325. ),
  326. array(
  327. 'name' => 'Plugins',
  328. 'value' => '4'
  329. ),
  330. array(
  331. 'name' => 'System Settings',
  332. 'value' => '5'
  333. )
  334. );
  335. }
  336. public function getAuthTypes()
  337. {
  338. return array(
  339. array(
  340. 'name' => 'Organizr DB',
  341. 'value' => 'internal'
  342. ),
  343. array(
  344. 'name' => 'Organizr DB + Backend',
  345. 'value' => 'both'
  346. ),
  347. array(
  348. 'name' => 'Backend Only',
  349. 'value' => 'external'
  350. )
  351. );
  352. }
  353. public function getLDAPOptions()
  354. {
  355. return array(
  356. array(
  357. 'name' => 'Active Directory',
  358. 'value' => '1'
  359. ),
  360. array(
  361. 'name' => 'OpenLDAP',
  362. 'value' => '2'
  363. ),
  364. array(
  365. 'name' => 'Free IPA',
  366. 'value' => '3'
  367. ),
  368. );
  369. }
  370. public function getAuthBackends()
  371. {
  372. $backendOptions = array();
  373. $backendOptions[] = array(
  374. 'name' => 'Choose Backend',
  375. 'value' => false,
  376. 'disabled' => true
  377. );
  378. foreach (array_filter(get_class_methods('Organizr'), function ($v) {
  379. return strpos($v, 'plugin_auth_') === 0;
  380. }) as $value) {
  381. $name = str_replace('plugin_auth_', '', $value);
  382. if ($name == 'ldap') {
  383. if (!function_exists('ldap_connect')) {
  384. continue;
  385. }
  386. }
  387. if ($name == 'ldap_disabled') {
  388. if (function_exists('ldap_connect')) {
  389. continue;
  390. }
  391. }
  392. if (strpos($name, 'disabled') === false) {
  393. $backendOptions[] = array(
  394. 'name' => ucwords(str_replace('_', ' ', $name)),
  395. 'value' => $name
  396. );
  397. } else {
  398. $backendOptions[] = array(
  399. 'name' => $this->$value(),
  400. 'value' => 'none',
  401. 'disabled' => true,
  402. );
  403. }
  404. }
  405. ksort($backendOptions);
  406. return $backendOptions;
  407. }
  408. public function importUserButtons()
  409. {
  410. $emptyButtons = '
  411. <div class="col-md-12">
  412. <div class="white-box bg-org">
  413. <h3 class="box-title m-0" lang="en">Currently User import is available for Plex only.</h3> </div>
  414. </div>
  415. ';
  416. $buttons = '';
  417. if (!empty($this->config['plexToken'])) {
  418. $buttons .= '<button class="btn m-b-20 m-r-20 bg-plex text-muted waves-effect waves-light importUsersButton" onclick="importUsers(\'plex\')" type="button"><span class="btn-label"><i class="mdi mdi-plex"></i></span><span lang="en">Import Plex Users</span></button>';
  419. }
  420. if (!empty($this->config['jellyfinURL']) && !empty($this->config['jellyfinToken'])) {
  421. $buttons .= '<button class="btn m-b-20 m-r-20 bg-primary text-muted waves-effect waves-light importUsersButton" onclick="importUsers(\'jellyfin\')" type="button"><span class="btn-label"><i class="mdi mdi-fish"></i></span><span lang="en">Import Jellyfin Users</span></button>';
  422. }
  423. if (!empty($this->config['embyURL']) && !empty($this->config['embyToken'])) {
  424. $buttons .= '<button class="btn m-b-20 m-r-20 bg-emby text-muted waves-effect waves-light importUsersButton" onclick="importUsers(\'emby\')" type="button"><span class="btn-label"><i class="mdi mdi-emby"></i></span><span lang="en">Import Emby Users</span></button>';
  425. }
  426. return ($buttons !== '') ? $buttons : $emptyButtons;
  427. }
  428. public function getHomepageMediaImage()
  429. {
  430. $refresh = false;
  431. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  432. if (!file_exists($cacheDirectory)) {
  433. mkdir($cacheDirectory, 0777, true);
  434. }
  435. @$image_url = $_GET['img'];
  436. @$key = $_GET['key'];
  437. @$image_height = $_GET['height'];
  438. @$image_width = $_GET['width'];
  439. @$source = $_GET['source'];
  440. @$itemType = $_GET['type'];
  441. if (strpos($key, '$') !== false) {
  442. $key = explode('$', $key)[0];
  443. $refresh = true;
  444. }
  445. switch ($source) {
  446. case 'plex':
  447. $plexAddress = $this->qualifyURL($this->config['plexURL']);
  448. $image_src = $plexAddress . '/photo/:/transcode?height=' . $image_height . '&width=' . $image_width . '&upscale=1&url=' . $image_url . '&X-Plex-Token=' . $this->config['plexToken'];
  449. break;
  450. case 'emby':
  451. $embyAddress = $this->qualifyURL($this->config['embyURL']);
  452. $imgParams = array();
  453. if (isset($_GET['height'])) {
  454. $imgParams['height'] = 'maxHeight=' . $_GET['height'];
  455. }
  456. if (isset($_GET['width'])) {
  457. $imgParams['width'] = 'maxWidth=' . $_GET['width'];
  458. }
  459. $image_src = $embyAddress . '/Items/' . $image_url . '/Images/' . $itemType . '?' . implode('&', $imgParams);
  460. break;
  461. case 'jellyfin':
  462. $jellyfinAddress = $this->qualifyURL($this->config['jellyfinURL']);
  463. $imgParams = array();
  464. if (isset($_GET['height'])) {
  465. $imgParams['height'] = 'maxHeight=' . $_GET['height'];
  466. }
  467. if (isset($_GET['width'])) {
  468. $imgParams['width'] = 'maxWidth=' . $_GET['width'];
  469. }
  470. $image_src = $jellyfinAddress . '/Items/' . $image_url . '/Images/' . $itemType . '?' . implode('&', $imgParams);
  471. break;
  472. default:
  473. # code...
  474. break;
  475. }
  476. if (isset($image_url) && isset($image_height) && isset($image_width) && isset($image_src)) {
  477. $cachefile = $cacheDirectory . $key . '.jpg';
  478. $cachetime = 604800;
  479. // Serve from the cache if it is younger than $cachetime
  480. if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile) && $refresh == false) {
  481. header("Content-type: image/jpeg");
  482. @readfile($cachefile);
  483. exit;
  484. }
  485. ob_start(); // Start the output buffer
  486. header('Content-type: image/jpeg');
  487. $options = array('verify' => false);
  488. $response = Requests::get($image_src, array(), $options);
  489. if ($response->success) {
  490. echo $response->body;
  491. }
  492. // Cache the output to a file
  493. $fp = fopen($cachefile, 'wb');
  494. fwrite($fp, ob_get_contents());
  495. fclose($fp);
  496. ob_end_flush(); // Send the output to the browser
  497. die();
  498. } else {
  499. die($this->showHTML('Invalid Request', 'No image returned'));
  500. }
  501. }
  502. public function cacheImage($url, $name, $extension = 'jpg')
  503. {
  504. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  505. if (!file_exists($cacheDirectory)) {
  506. mkdir($cacheDirectory, 0777, true);
  507. }
  508. $cacheFile = $cacheDirectory . $name . '.' . $extension;
  509. $cacheTime = 604800;
  510. if ((file_exists($cacheFile) && (time() - $cacheTime) > filemtime($cacheFile)) || !file_exists($cacheFile)) {
  511. @copy($url, $cacheFile);
  512. }
  513. }
  514. public function checkFrame($array, $url)
  515. {
  516. if (array_key_exists("x-frame-options", $array)) {
  517. if (gettype($array['x-frame-options']) == 'array') {
  518. $array['x-frame-options'] = $array['x-frame-options'][0];
  519. }
  520. $array['x-frame-options'] = strtolower($array['x-frame-options']);
  521. if ($array['x-frame-options'] == "deny") {
  522. return false;
  523. } elseif ($array['x-frame-options'] == "sameorgin") {
  524. $digest = parse_url($url);
  525. $host = ($digest['host'] ?? '');
  526. if ($this->getServer() == $host) {
  527. return true;
  528. } else {
  529. return false;
  530. }
  531. } elseif (strpos($array['x-frame-options'], 'allow-from') !== false) {
  532. $explodeServers = explode(' ', $array['x-frame-options']);
  533. $allowed = false;
  534. foreach ($explodeServers as $server) {
  535. $digest = parse_url($server);
  536. $host = ($digest['host'] ?? '');
  537. if ($this->getServer() == $host) {
  538. $allowed = true;
  539. }
  540. }
  541. return $allowed;
  542. } else {
  543. return false;
  544. }
  545. } else {
  546. if (!$array) {
  547. return false;
  548. }
  549. return true;
  550. }
  551. }
  552. public function frameTest($url)
  553. {
  554. if (!$url || $url == '') {
  555. $this->setAPIResponse('error', 'URL not supplied', 404);
  556. return false;
  557. }
  558. $array = array_change_key_case(get_headers($this->qualifyURL($url), 1));
  559. $url = $this->qualifyURL($url);
  560. if ($this->checkFrame($array, $url)) {
  561. $this->setAPIResponse('success', 'URL approved for iFrame', 200);
  562. return true;
  563. } else {
  564. $this->setAPIResponse('error', 'URL failed approval for iFrame', 409);
  565. return false;
  566. }
  567. }
  568. public function groupSelect()
  569. {
  570. $groups = $this->getAllGroups();
  571. $select = array();
  572. foreach ($groups as $key => $value) {
  573. $select[] = array(
  574. 'name' => $value['group'],
  575. 'value' => $value['group_id']
  576. );
  577. }
  578. return $select;
  579. }
  580. public function showLogin()
  581. {
  582. if ($this->config['hideRegistration'] == false) {
  583. return '<p><span lang="en">Don\'t have an account?</span><a href="#" class="text-primary m-l-5 to-register"><b lang="en">Sign Up</b></a></p>';
  584. }
  585. }
  586. public function checkoAuth()
  587. {
  588. return $this->config['plexoAuth'] && $this->config['authBackend'] == 'plex' && $this->config['authType'] !== 'internal';
  589. }
  590. public function checkoAuthOnly()
  591. {
  592. return $this->config['plexoAuth'] && $this->config['authBackend'] == 'plex' && $this->config['authType'] == 'external';
  593. }
  594. public function showoAuth()
  595. {
  596. $buttons = '';
  597. if ($this->config['plexoAuth'] && $this->config['authBackend'] == 'plex' && $this->config['authType'] !== 'internal') {
  598. $buttons .= '<a href="javascript:void(0)" onclick="oAuthStart(\'plex\')" class="btn btn-lg btn-block text-uppercase waves-effect waves-light bg-plex text-muted" data-toggle="tooltip" title="" data-original-title="Login with Plex"> <span>Login</span><i aria-hidden="true" class="mdi mdi-plex m-l-5"></i> </a>';
  599. }
  600. return ($buttons) ? '
  601. <div class="panel">
  602. <div class="panel-heading bg-org" id="plex-login-heading" role="tab">
  603. <a class="panel-title" data-toggle="collapse" href="#plex-login-collapse" data-parent="#login-panels" aria-expanded="false" aria-controls="organizr-login-collapse">
  604. <img class="lazyload loginTitle" data-src="plugins/images/tabs/plex.png"> &nbsp;
  605. <span class="text-uppercase fw300" lang="en">Login with Plex</span>
  606. </a>
  607. </div>
  608. <div class="panel-collapse collapse in" id="plex-login-collapse" aria-labelledby="plex-login-heading" role="tabpanel">
  609. <div class="panel-body">
  610. <div class="row">
  611. <div class="col-xs-12 col-sm-12 col-md-12 text-center">
  612. <div class="social m-b-0">' . $buttons . '</div>
  613. </div>
  614. </div>
  615. </div>
  616. </div>
  617. </div>
  618. ' : '';
  619. }
  620. public function logoOrText()
  621. {
  622. $showLogo = $this->config['minimalLoginScreen'] ? '' : 'visible-xs';
  623. if ($this->config['useLogoLogin'] == false) {
  624. $html = '<h1>' . $this->config['title'] . '</h1>';
  625. } else {
  626. $html = '<img class="loginLogo" src="' . $this->config['loginLogo'] . '" alt="Home" />';
  627. }
  628. return '<a href="javascript:void(0)" class="text-center db ' . $showLogo . '" id="login-logo">' . $html . '</a>';
  629. }
  630. public function settingsDocker()
  631. {
  632. $type = ($this->docker) ? 'Official Docker' : 'Native';
  633. return '<li><div class="bg-info"><i class="mdi mdi-flag mdi-24px text-white"></i></div><span class="text-muted hidden-xs m-t-10" lang="en">Install Type</span> ' . $type . '</li>';
  634. }
  635. public function settingsPathChecks()
  636. {
  637. $paths = $this->pathsWritable($this->paths);
  638. $items = '';
  639. $type = (array_search(false, $paths)) ? 'Not Writable' : 'Writable';
  640. $result = '<li class="mouse" onclick="toggleWritableFolders();"><div class="bg-info"><i class="mdi mdi-folder mdi-24px text-white"></i></div><span class="text-muted hidden-xs m-t-10" lang="en">Organizr Paths</span> ' . $type . '</li>';
  641. foreach ($paths as $k => $v) {
  642. $items .= '<li class="folders-writable hidden"><div class="bg-primary"><i class="mdi mdi-folder mdi-24px text-white"></i></div><a tabindex="0" type="button" class="btn btn-default btn-outline popover-info pull-right clipboard" lang="en" data-container="body" title="" data-toggle="popover" data-placement="left" data-content="' . $v['path'] . '" data-original-title="File Path" data-clipboard-text="' . $v['path'] . '">' . $k . '</a> ' . (($v['writable']) ? 'Writable' : 'Not Writable') . '</li>';
  643. }
  644. return $result . $items;
  645. }
  646. public function pathsWritable($paths)
  647. {
  648. $results = array();
  649. foreach ($paths as $k => $v) {
  650. $results[$k] = [
  651. 'writable' => is_writable($v),
  652. 'path' => $v
  653. ];
  654. }
  655. return $results;
  656. }
  657. public function clearTautulliTokens()
  658. {
  659. foreach (array_keys($_COOKIE) as $k => $v) {
  660. if (strpos($v, 'tautulli') !== false) {
  661. $this->coookie('delete', $v);
  662. }
  663. }
  664. }
  665. public function clearJellyfinTokens()
  666. {
  667. foreach (array_keys($_COOKIE) as $k => $v) {
  668. if (strpos($v, 'user-') !== false) {
  669. $this->coookie('delete', $v);
  670. }
  671. }
  672. $this->coookie('delete', 'jellyfin_credentials');
  673. }
  674. public function clearKomgaToken()
  675. {
  676. if (isset($_COOKIE['komga_token'])) {
  677. try {
  678. $url = $this->qualifyURL($this->config['komgaURL']);
  679. $options = $this->requestOptions($url, 60000, true, false);
  680. $response = Requests::post($url . '/api/v1/users/logout', ['X-Auth-Token' => $_COOKIE['komga_token']], $options);
  681. if ($response->success) {
  682. $this->writeLog('success', 'Komga Token Function - Logged User out', 'SYSTEM');
  683. } else {
  684. $this->writeLog('error', 'Komga Token Function - Unable to Logged User out', 'SYSTEM');
  685. }
  686. } catch (Requests_Exception $e) {
  687. $this->writeLog('error', 'Komga Token Function - Error: ' . $e->getMessage(), 'SYSTEM');
  688. }
  689. $this->coookie('delete', 'komga_token');
  690. }
  691. }
  692. public function analyzeIP($ip)
  693. {
  694. if (strpos($ip, '/') !== false) {
  695. $explodeIP = explode('/', $ip);
  696. $prefix = $explodeIP[1];
  697. $start_ip = $explodeIP[0];
  698. $ip_count = 1 << (32 - $prefix);
  699. $start_ip_long = ip2long($start_ip);
  700. $last_ip_long = ip2long($start_ip) + $ip_count - 1;
  701. } elseif (substr_count($ip, '.') == 3) {
  702. $start_ip_long = ip2long($ip);
  703. $last_ip_long = ip2long($ip);
  704. }
  705. return (isset($start_ip_long) && isset($last_ip_long)) ? array('from' => $start_ip_long, 'to' => $last_ip_long) : false;
  706. }
  707. public function authProxyRangeCheck($from, $to)
  708. {
  709. $approved = false;
  710. $userIP = ip2long($_SERVER['REMOTE_ADDR']);
  711. $low = $from;
  712. $high = $to;
  713. if ($userIP <= $high && $low <= $userIP) {
  714. $approved = true;
  715. }
  716. return $approved;
  717. }
  718. public function userDefinedIdReplacementLink($link, $variables)
  719. {
  720. return strtr($link, $variables);
  721. }
  722. public function requestOptions($url, $timeout = null, $override = false, $customCertificate = false, $extras = null)
  723. {
  724. $options = [];
  725. if (is_numeric($timeout)) {
  726. if ($timeout >= 1000) {
  727. $timeout = $timeout / 1000;
  728. }
  729. $options = array_merge($options, array('timeout' => $timeout));
  730. }
  731. if ($customCertificate) {
  732. if ($this->hasCustomCert()) {
  733. $options = array_merge($options, array('verify' => $this->getCustomCert(), 'verifyname' => false));
  734. }
  735. }
  736. if ($this->localURL($url, $override)) {
  737. $options = array_merge($options, array('verify' => false, 'verifyname' => false));
  738. }
  739. if ($extras) {
  740. if (gettype($extras) == 'array') {
  741. $options = array_merge($options, $extras);
  742. }
  743. }
  744. return $options;
  745. }
  746. public function showHTML(string $title = 'Organizr Alert', string $notice = '')
  747. {
  748. return
  749. '<!DOCTYPE html>
  750. <html lang="en">
  751. <head>
  752. <link rel="stylesheet" href="' . $this->getServerPath() . '/css/mvp.css">
  753. <meta charset="utf-8">
  754. <meta name="description" content="Trakt OAuth">
  755. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  756. <title>' . $title . '</title>
  757. </head>
  758. <body>
  759. <main>
  760. <section>
  761. <aside>
  762. <h3>' . $title . '</h3>
  763. <p>' . $notice . '</p>
  764. </aside>
  765. </section>
  766. </main>
  767. </body>
  768. </html>';
  769. }
  770. public function buildSettingsMenus($menuItems, $menuName)
  771. {
  772. $selectMenuItems = '';
  773. $unorderedListMenuItems = '';
  774. $menuNameLower = strtolower(str_replace(' ', '-', $menuName));
  775. foreach ($menuItems as $menuItem) {
  776. $anchorShort = str_replace('-anchor', '', $menuItem['anchor']);
  777. $active = ($menuItem['active']) ? 'active' : '';
  778. $apiPage = ($menuItem['api']) ? 'loadSettingsPage2(\'' . $menuItem['api'] . '\',\'#' . $anchorShort . '\',\'' . $menuItem['name'] . '\');' : '';
  779. $onClick = (isset($menuItem['onclick'])) ? $menuItem['onclick'] : '';
  780. $selectMenuItems .= '<option value="#' . $menuItem['anchor'] . '" lang="en">' . $menuItem['name'] . '</option>';
  781. $unorderedListMenuItems .= '
  782. <li onclick="changeSettingsMenu(\'Settings::' . $menuName . '::' . $menuItem['name'] . '\'); ' . $apiPage . $onClick . '" role="presentation" class="' . $active . '">
  783. <a id="' . $menuItem['anchor'] . '" href="#' . $anchorShort . '" aria-controls="home" role="tab" data-toggle="tab" aria-expanded="true">
  784. <span lang="en">' . $menuItem['name'] . '</span>
  785. </a>
  786. </li>';
  787. }
  788. $selectMenu = '<select class="form-control settings-dropdown-box ' . $menuNameLower . '-menu w-100 visible-xs">' . $selectMenuItems . '</select>';
  789. $unorderedListMenu = '<ul class="nav customtab2 nav-tabs nav-non-mobile hidden-xs" data-dropdown="' . $menuNameLower . '-menu" role="tablist">' . $unorderedListMenuItems . '</ul>';
  790. return $selectMenu . $unorderedListMenu;
  791. }
  792. public function isJSON($string)
  793. {
  794. return is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE);
  795. }
  796. }