organizr-functions.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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->setResponse(500, $e->getMessage());
  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->setResponse(500, $e->getMessage());
  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. return true;
  209. default:
  210. return false;
  211. }
  212. } elseif ($type == 'cert') {
  213. switch ($ext) {
  214. case 'pem':
  215. return true;
  216. default:
  217. return false;
  218. }
  219. }
  220. }
  221. public function getImages()
  222. {
  223. $allIconsPrep = array();
  224. $allIcons = array();
  225. $ignore = array(".", "..", "._.DS_Store", ".DS_Store", ".pydio_id", "index.html");
  226. $dirname = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'tabs' . DIRECTORY_SEPARATOR;
  227. $path = 'plugins/images/tabs/';
  228. $images = scandir($dirname);
  229. foreach ($images as $image) {
  230. if (!in_array($image, $ignore)) {
  231. $allIconsPrep[$image] = array(
  232. 'path' => $path,
  233. 'name' => $image
  234. );
  235. }
  236. }
  237. $dirname = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'userTabs' . DIRECTORY_SEPARATOR;
  238. $path = 'data/userTabs/';
  239. $images = scandir($dirname);
  240. foreach ($images as $image) {
  241. if (!in_array($image, $ignore)) {
  242. $allIconsPrep[$image] = array(
  243. 'path' => $path,
  244. 'name' => $image
  245. );
  246. }
  247. }
  248. ksort($allIconsPrep);
  249. foreach ($allIconsPrep as $item) {
  250. $allIcons[] = $item['path'] . $item['name'];
  251. }
  252. return $allIcons;
  253. }
  254. public function imageSelect($form)
  255. {
  256. $i = 1;
  257. $images = $this->getImages();
  258. $return = '<select class="form-control tabIconImageList" id="' . $form . '-chooseImage" name="chooseImage"><option lang="en">Select or type Icon</option>';
  259. foreach ($images as $image) {
  260. $i++;
  261. $return .= '<option value="' . $image . '">' . basename($image) . '</option>';
  262. }
  263. return $return . '</select>';
  264. }
  265. public function getThemes()
  266. {
  267. $themes = array();
  268. foreach (glob(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'css' . DIRECTORY_SEPARATOR . 'themes' . DIRECTORY_SEPARATOR . "*.css") as $filename) {
  269. $themes[] = array(
  270. 'name' => preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename)),
  271. 'value' => preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename))
  272. );
  273. }
  274. return $themes;
  275. }
  276. public function getSounds()
  277. {
  278. $sounds = array();
  279. foreach (glob(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'sounds' . DIRECTORY_SEPARATOR . 'default' . DIRECTORY_SEPARATOR . "*.mp3") as $filename) {
  280. $sounds[] = array(
  281. 'name' => preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename)),
  282. 'value' => preg_replace('/\\.[^.\\s]{3,4}$/', '', 'plugins/sounds/default/' . basename($filename) . '.mp3')
  283. );
  284. }
  285. foreach (glob(dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'sounds' . DIRECTORY_SEPARATOR . 'custom' . DIRECTORY_SEPARATOR . "*.mp3") as $filename) {
  286. $sounds[] = array(
  287. 'name' => preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($filename)),
  288. 'value' => preg_replace('/\\.[^.\\s]{3,4}$/', '', 'plugins/sounds/custom/' . basename($filename) . '.mp3')
  289. );
  290. }
  291. return $sounds;
  292. }
  293. public function getBranches()
  294. {
  295. return array(
  296. array(
  297. 'name' => 'Develop',
  298. 'value' => 'v2-develop'
  299. ),
  300. array(
  301. 'name' => 'Master',
  302. 'value' => 'v2-master'
  303. )
  304. );
  305. }
  306. public function getSettingsTabs()
  307. {
  308. return array(
  309. array(
  310. 'name' => 'Tab Editor',
  311. 'value' => '0'
  312. ),
  313. array(
  314. 'name' => 'Customize',
  315. 'value' => '1'
  316. ),
  317. array(
  318. 'name' => 'User Management',
  319. 'value' => '2'
  320. ),
  321. array(
  322. 'name' => 'Image Manager',
  323. 'value' => '3'
  324. ),
  325. array(
  326. 'name' => 'Plugins',
  327. 'value' => '4'
  328. ),
  329. array(
  330. 'name' => 'System Settings',
  331. 'value' => '5'
  332. )
  333. );
  334. }
  335. public function getAuthTypes()
  336. {
  337. return array(
  338. array(
  339. 'name' => 'Organizr DB',
  340. 'value' => 'internal'
  341. ),
  342. array(
  343. 'name' => 'Organizr DB + Backend',
  344. 'value' => 'both'
  345. ),
  346. array(
  347. 'name' => 'Backend Only',
  348. 'value' => 'external'
  349. )
  350. );
  351. }
  352. public function getLDAPOptions()
  353. {
  354. return array(
  355. array(
  356. 'name' => 'Active Directory',
  357. 'value' => '1'
  358. ),
  359. array(
  360. 'name' => 'OpenLDAP',
  361. 'value' => '2'
  362. ),
  363. array(
  364. 'name' => 'Free IPA',
  365. 'value' => '3'
  366. ),
  367. );
  368. }
  369. public function getAuthBackends()
  370. {
  371. $backendOptions = array();
  372. $backendOptions[] = array(
  373. 'name' => 'Choose Backend',
  374. 'value' => false,
  375. 'disabled' => true
  376. );
  377. foreach (array_filter(get_class_methods('Organizr'), function ($v) {
  378. return strpos($v, 'plugin_auth_') === 0;
  379. }) as $value) {
  380. $name = str_replace('plugin_auth_', '', $value);
  381. if ($name == 'ldap') {
  382. if (!function_exists('ldap_connect')) {
  383. continue;
  384. }
  385. }
  386. if ($name == 'ldap_disabled') {
  387. if (function_exists('ldap_connect')) {
  388. continue;
  389. }
  390. }
  391. if (strpos($name, 'disabled') === false) {
  392. $backendOptions[] = array(
  393. 'name' => ucwords(str_replace('_', ' ', $name)),
  394. 'value' => $name
  395. );
  396. } else {
  397. $backendOptions[] = array(
  398. 'name' => $this->$value(),
  399. 'value' => 'none',
  400. 'disabled' => true,
  401. );
  402. }
  403. }
  404. ksort($backendOptions);
  405. return $backendOptions;
  406. }
  407. public function importUserButtons()
  408. {
  409. $emptyButtons = '
  410. <div class="col-md-12">
  411. <div class="white-box bg-org">
  412. <h3 class="box-title m-0" lang="en">Currently User import is available for Plex only.</h3> </div>
  413. </div>
  414. ';
  415. $buttons = '';
  416. if (!empty($this->config['plexToken'])) {
  417. $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>';
  418. }
  419. if (!empty($this->config['jellyfinURL']) && !empty($this->config['jellyfinToken'])) {
  420. $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>';
  421. }
  422. if (!empty($this->config['embyURL']) && !empty($this->config['embyToken'])) {
  423. $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>';
  424. }
  425. return ($buttons !== '') ? $buttons : $emptyButtons;
  426. }
  427. public function getHomepageMediaImage()
  428. {
  429. $refresh = false;
  430. $cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  431. if (!file_exists($cacheDirectory)) {
  432. mkdir($cacheDirectory, 0777, true);
  433. }
  434. @$image_url = $_GET['img'];
  435. @$key = $_GET['key'];
  436. @$image_height = $_GET['height'];
  437. @$image_width = $_GET['width'];
  438. @$source = $_GET['source'];
  439. @$itemType = $_GET['type'];
  440. if (strpos($key, '$') !== false) {
  441. $key = explode('$', $key)[0];
  442. $refresh = true;
  443. }
  444. switch ($source) {
  445. case 'plex':
  446. $plexAddress = $this->qualifyURL($this->config['plexURL']);
  447. $image_src = $plexAddress . '/photo/:/transcode?height=' . $image_height . '&width=' . $image_width . '&upscale=1&url=' . $image_url . '&X-Plex-Token=' . $this->config['plexToken'];
  448. break;
  449. case 'emby':
  450. $embyAddress = $this->qualifyURL($this->config['embyURL']);
  451. $imgParams = array();
  452. if (isset($_GET['height'])) {
  453. $imgParams['height'] = 'maxHeight=' . $_GET['height'];
  454. }
  455. if (isset($_GET['width'])) {
  456. $imgParams['width'] = 'maxWidth=' . $_GET['width'];
  457. }
  458. $image_src = $embyAddress . '/Items/' . $image_url . '/Images/' . $itemType . '?' . implode('&', $imgParams);
  459. break;
  460. case 'jellyfin':
  461. $jellyfinAddress = $this->qualifyURL($this->config['jellyfinURL']);
  462. $imgParams = array();
  463. if (isset($_GET['height'])) {
  464. $imgParams['height'] = 'maxHeight=' . $_GET['height'];
  465. }
  466. if (isset($_GET['width'])) {
  467. $imgParams['width'] = 'maxWidth=' . $_GET['width'];
  468. }
  469. $image_src = $jellyfinAddress . '/Items/' . $image_url . '/Images/' . $itemType . '?' . implode('&', $imgParams);
  470. break;
  471. default:
  472. # code...
  473. break;
  474. }
  475. if (strpos($key, '-') !== false) {
  476. $noImage = 'no-' . explode('-', $key)[1] . '.png';
  477. } else {
  478. $noImage = 'no-np.png';
  479. }
  480. $noImage = $this->root . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'homepage' . DIRECTORY_SEPARATOR . $noImage;
  481. if (isset($image_url) && isset($image_height) && isset($image_width) && isset($image_src)) {
  482. $cachefile = $cacheDirectory . $key . '.jpg';
  483. $cachetime = 604800;
  484. // Serve from the cache if it is younger than $cachetime
  485. if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile)) && $refresh == false) {
  486. header('Content-type: image/jpeg');
  487. if (filesize($cachefile) > 0) {
  488. @readfile($cachefile);
  489. } else {
  490. @readfile($noImage);
  491. }
  492. exit;
  493. }
  494. $options = array('verify' => false);
  495. $response = Requests::get($image_src, array(), $options);
  496. if ($response->success) {
  497. ob_start(); // Start the output buffer
  498. header('Content-type: image/jpeg');
  499. echo $response->body;
  500. // Cache the output to a file
  501. $fp = fopen($cachefile, 'wb');
  502. fwrite($fp, ob_get_contents());
  503. fclose($fp);
  504. ob_end_flush(); // Send the output to the browser
  505. die();
  506. } else {
  507. header('Content-type: image/jpeg');
  508. @readfile($noImage);
  509. }
  510. } else {
  511. header('Content-type: image/jpeg');
  512. @readfile($noImage);
  513. }
  514. }
  515. public function cacheImage($url, $name, $extension = 'jpg')
  516. {
  517. $cacheDirectory = $this->root . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
  518. if (!file_exists($cacheDirectory)) {
  519. mkdir($cacheDirectory, 0777, true);
  520. }
  521. $cacheFile = $cacheDirectory . $name . '.' . $extension;
  522. $cacheTime = 604800;
  523. if ((file_exists($cacheFile) && (time() - $cacheTime) > filemtime($cacheFile)) || !file_exists($cacheFile)) {
  524. @copy($url, $cacheFile);
  525. }
  526. }
  527. public function checkFrame($array, $url)
  528. {
  529. if (array_key_exists("x-frame-options", $array)) {
  530. if (gettype($array['x-frame-options']) == 'array') {
  531. $array['x-frame-options'] = $array['x-frame-options'][0];
  532. }
  533. $array['x-frame-options'] = strtolower($array['x-frame-options']);
  534. if ($array['x-frame-options'] == "deny") {
  535. return false;
  536. } elseif ($array['x-frame-options'] == "sameorgin") {
  537. $digest = parse_url($url);
  538. $host = ($digest['host'] ?? '');
  539. if ($this->getServer() == $host) {
  540. return true;
  541. } else {
  542. return false;
  543. }
  544. } elseif (strpos($array['x-frame-options'], 'allow-from') !== false) {
  545. $explodeServers = explode(' ', $array['x-frame-options']);
  546. $allowed = false;
  547. foreach ($explodeServers as $server) {
  548. $digest = parse_url($server);
  549. $host = ($digest['host'] ?? '');
  550. if ($this->getServer() == $host) {
  551. $allowed = true;
  552. }
  553. }
  554. return $allowed;
  555. } else {
  556. return false;
  557. }
  558. } else {
  559. if (!$array) {
  560. return false;
  561. }
  562. return true;
  563. }
  564. }
  565. public function frameTest($url)
  566. {
  567. if (!$url || $url == '') {
  568. $this->setAPIResponse('error', 'URL not supplied', 404);
  569. return false;
  570. }
  571. $array = array_change_key_case(get_headers($this->qualifyURL($url), 1));
  572. $url = $this->qualifyURL($url);
  573. if ($this->checkFrame($array, $url)) {
  574. $this->setAPIResponse('success', 'URL approved for iFrame', 200);
  575. return true;
  576. } else {
  577. $this->setAPIResponse('error', 'URL failed approval for iFrame', 409);
  578. return false;
  579. }
  580. }
  581. public function groupSelect()
  582. {
  583. $groups = $this->getAllGroups();
  584. $select = array();
  585. foreach ($groups as $key => $value) {
  586. $select[] = array(
  587. 'name' => $value['group'],
  588. 'value' => $value['group_id']
  589. );
  590. }
  591. return $select;
  592. }
  593. public function showLogin()
  594. {
  595. if ($this->config['hideRegistration'] == false) {
  596. 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>';
  597. }
  598. }
  599. public function checkoAuth()
  600. {
  601. return $this->config['plexoAuth'] && $this->config['authBackend'] == 'plex' && $this->config['authType'] !== 'internal';
  602. }
  603. public function checkoAuthOnly()
  604. {
  605. return $this->config['plexoAuth'] && $this->config['authBackend'] == 'plex' && $this->config['authType'] == 'external';
  606. }
  607. public function showoAuth()
  608. {
  609. $buttons = '';
  610. if ($this->config['plexoAuth'] && $this->config['authBackend'] == 'plex' && $this->config['authType'] !== 'internal') {
  611. $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>';
  612. }
  613. return ($buttons) ? '
  614. <div class="panel">
  615. <div class="panel-heading bg-org" id="plex-login-heading" role="tab">
  616. <a class="panel-title" data-toggle="collapse" href="#plex-login-collapse" data-parent="#login-panels" aria-expanded="false" aria-controls="organizr-login-collapse">
  617. <img class="lazyload loginTitle" data-src="plugins/images/tabs/plex.png"> &nbsp;
  618. <span class="text-uppercase fw300" lang="en">Login with Plex</span>
  619. </a>
  620. </div>
  621. <div class="panel-collapse collapse in" id="plex-login-collapse" aria-labelledby="plex-login-heading" role="tabpanel">
  622. <div class="panel-body">
  623. <div class="row">
  624. <div class="col-xs-12 col-sm-12 col-md-12 text-center">
  625. <div class="social m-b-0">' . $buttons . '</div>
  626. </div>
  627. </div>
  628. </div>
  629. </div>
  630. </div>
  631. ' : '';
  632. }
  633. public function logoOrText()
  634. {
  635. $showLogo = $this->config['minimalLoginScreen'] ? '' : 'visible-xs';
  636. if ($this->config['useLogoLogin'] == false) {
  637. $html = '<h1>' . $this->config['title'] . '</h1>';
  638. } else {
  639. $html = '<img class="loginLogo" src="' . $this->config['loginLogo'] . '" alt="Home" />';
  640. }
  641. return '<a href="javascript:void(0)" class="text-center db ' . $showLogo . '" id="login-logo">' . $html . '</a>';
  642. }
  643. public function settingsDocker()
  644. {
  645. $type = ($this->docker) ? 'Official Docker' : 'Native';
  646. 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>';
  647. }
  648. public function settingsPathChecks()
  649. {
  650. $paths = $this->pathsWritable($this->paths);
  651. $items = '';
  652. $type = (array_search(false, $paths)) ? 'Not Writable' : 'Writable';
  653. $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>';
  654. foreach ($paths as $k => $v) {
  655. $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>';
  656. }
  657. return $result . $items;
  658. }
  659. public function pathsWritable($paths)
  660. {
  661. $results = array();
  662. foreach ($paths as $k => $v) {
  663. $results[$k] = [
  664. 'writable' => is_writable($v),
  665. 'path' => $v
  666. ];
  667. }
  668. return $results;
  669. }
  670. public function clearTautulliTokens()
  671. {
  672. foreach (array_keys($_COOKIE) as $k => $v) {
  673. if (strpos($v, 'tautulli') !== false) {
  674. $this->coookie('delete', $v);
  675. }
  676. }
  677. }
  678. public function clearJellyfinTokens()
  679. {
  680. foreach (array_keys($_COOKIE) as $k => $v) {
  681. if (strpos($v, 'user-') !== false) {
  682. $this->coookie('delete', $v);
  683. }
  684. }
  685. $this->coookie('delete', 'jellyfin_credentials');
  686. }
  687. public function clearKomgaToken()
  688. {
  689. if (isset($_COOKIE['komga_token'])) {
  690. try {
  691. $url = $this->qualifyURL($this->config['komgaURL']);
  692. $options = $this->requestOptions($url, 60000, true, false);
  693. $response = Requests::post($url . '/api/v1/users/logout', ['X-Auth-Token' => $_COOKIE['komga_token']], $options);
  694. if ($response->success) {
  695. $this->writeLog('success', 'Komga Token Function - Logged User out', 'SYSTEM');
  696. } else {
  697. $this->writeLog('error', 'Komga Token Function - Unable to Logged User out', 'SYSTEM');
  698. }
  699. } catch (Requests_Exception $e) {
  700. $this->writeLog('error', 'Komga Token Function - Error: ' . $e->getMessage(), 'SYSTEM');
  701. }
  702. $this->coookie('delete', 'komga_token');
  703. }
  704. }
  705. public function analyzeIP($ip)
  706. {
  707. if (strpos($ip, '/') !== false) {
  708. $explodeIP = explode('/', $ip);
  709. $prefix = $explodeIP[1];
  710. $start_ip = $explodeIP[0];
  711. $ip_count = 1 << (32 - $prefix);
  712. $start_ip_long = ip2long($start_ip);
  713. $last_ip_long = ip2long($start_ip) + $ip_count - 1;
  714. } elseif (substr_count($ip, '.') == 3) {
  715. $start_ip_long = ip2long($ip);
  716. $last_ip_long = ip2long($ip);
  717. }
  718. return (isset($start_ip_long) && isset($last_ip_long)) ? array('from' => $start_ip_long, 'to' => $last_ip_long) : false;
  719. }
  720. public function authProxyRangeCheck($from, $to)
  721. {
  722. $approved = false;
  723. $userIP = ip2long($_SERVER['REMOTE_ADDR']);
  724. $low = $from;
  725. $high = $to;
  726. if ($userIP <= $high && $low <= $userIP) {
  727. $approved = true;
  728. }
  729. $this->logger->debug('authProxy range check', ['server_ip' => ['long' => $userIP, 'short' => long2ip($userIP)], 'range_from' => ['long' => $from, 'short' => long2ip($from)], 'range_to' => ['long' => $to, 'short' => long2ip($to)], 'approved' => $approved]);
  730. return $approved;
  731. }
  732. public function userDefinedIdReplacementLink($link, $variables)
  733. {
  734. return strtr($link, $variables);
  735. }
  736. public function requestOptions($url, $timeout = null, $override = false, $customCertificate = false, $extras = null)
  737. {
  738. $options = [];
  739. if (is_numeric($timeout)) {
  740. if ($timeout >= 1000) {
  741. $timeout = $timeout / 1000;
  742. }
  743. $options = array_merge($options, array('timeout' => $timeout));
  744. }
  745. if ($customCertificate) {
  746. if ($this->hasCustomCert()) {
  747. $options = array_merge($options, array('verify' => $this->getCustomCert(), 'verifyname' => false));
  748. }
  749. }
  750. if ($this->localURL($url, $override)) {
  751. $options = array_merge($options, array('verify' => false, 'verifyname' => false));
  752. }
  753. if ($extras) {
  754. if (gettype($extras) == 'array') {
  755. $options = array_merge($options, $extras);
  756. }
  757. }
  758. return $options;
  759. }
  760. public function showHTML(string $title = 'Organizr Alert', string $notice = '', bool $autoClose = false)
  761. {
  762. $close = $autoClose ? 'onLoad="setTimeout(\'closemyself()\',3000);"' : '';
  763. $closeMessage = $autoClose ? '<p><sup>(This window will close automatically)</sup></p>' : '';
  764. return
  765. '<!DOCTYPE html>
  766. <html lang="en">
  767. <head>
  768. <link rel="stylesheet" href="' . $this->getServerPath() . '/css/mvp.css">
  769. <meta charset="utf-8">
  770. <meta name="description" content="Trakt OAuth">
  771. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  772. <title>' . $title . '</title>
  773. </head>
  774. <script language=javascript>
  775. function closemyself() {
  776. window.opener=self;
  777. window.close();
  778. }
  779. </script>
  780. <body ' . $close . '>
  781. <main>
  782. <section>
  783. <aside>
  784. <h3>' . $title . '</h3>
  785. <p>' . $notice . '</p>
  786. ' . $closeMessage . '
  787. </aside>
  788. </section>
  789. </main>
  790. </body>
  791. </html>';
  792. }
  793. public function buildSettingsMenus($menuItems, $menuName)
  794. {
  795. $selectMenuItems = '';
  796. $unorderedListMenuItems = '';
  797. $menuNameLower = strtolower(str_replace(' ', '-', $menuName));
  798. foreach ($menuItems as $menuItem) {
  799. $anchorShort = str_replace('-anchor', '', $menuItem['anchor']);
  800. $active = ($menuItem['active']) ? 'active' : '';
  801. $apiPage = ($menuItem['api']) ? 'loadSettingsPage2(\'' . $menuItem['api'] . '\',\'#' . $anchorShort . '\',\'' . $menuItem['name'] . '\');' : '';
  802. $onClick = (isset($menuItem['onclick'])) ? $menuItem['onclick'] : '';
  803. $selectMenuItems .= '<option value="#' . $menuItem['anchor'] . '" lang="en">' . $menuItem['name'] . '</option>';
  804. $unorderedListMenuItems .= '
  805. <li onclick="changeSettingsMenu(\'Settings::' . $menuName . '::' . $menuItem['name'] . '\'); ' . $apiPage . $onClick . '" role="presentation" class="' . $active . '">
  806. <a id="' . $menuItem['anchor'] . '" href="#' . $anchorShort . '" aria-controls="home" role="tab" data-toggle="tab" aria-expanded="true">
  807. <span lang="en">' . $menuItem['name'] . '</span>
  808. </a>
  809. </li>';
  810. }
  811. $selectMenu = '<select class="form-control settings-dropdown-box ' . $menuNameLower . '-menu w-100 visible-xs">' . $selectMenuItems . '</select>';
  812. $unorderedListMenu = '<ul class="nav customtab2 nav-tabs nav-non-mobile hidden-xs" data-dropdown="' . $menuNameLower . '-menu" role="tablist">' . $unorderedListMenuItems . '</ul>';
  813. return $selectMenu . $unorderedListMenu;
  814. }
  815. public function isJSON($string)
  816. {
  817. return is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE);
  818. }
  819. }