organizr-functions.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  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. $ctx = stream_context_create(array(
  524. 'http' => array(
  525. 'timeout' =>5 ,
  526. 'protocol_version' => 1.1,
  527. 'header' => 'Connection: close'
  528. )
  529. ));
  530. if ((file_exists($cacheFile) && (time() - $cacheTime) > filemtime($cacheFile)) || !file_exists($cacheFile)) {
  531. @copy($url, $cacheFile, $ctx);
  532. }
  533. }
  534. public function checkFrame($array, $url)
  535. {
  536. if (array_key_exists("x-frame-options", $array)) {
  537. if (gettype($array['x-frame-options']) == 'array') {
  538. $array['x-frame-options'] = $array['x-frame-options'][0];
  539. }
  540. $array['x-frame-options'] = strtolower($array['x-frame-options']);
  541. if ($array['x-frame-options'] == "deny") {
  542. return false;
  543. } elseif ($array['x-frame-options'] == "sameorgin") {
  544. $digest = parse_url($url);
  545. $host = ($digest['host'] ?? '');
  546. if ($this->getServer() == $host) {
  547. return true;
  548. } else {
  549. return false;
  550. }
  551. } elseif (strpos($array['x-frame-options'], 'allow-from') !== false) {
  552. $explodeServers = explode(' ', $array['x-frame-options']);
  553. $allowed = false;
  554. foreach ($explodeServers as $server) {
  555. $digest = parse_url($server);
  556. $host = ($digest['host'] ?? '');
  557. if ($this->getServer() == $host) {
  558. $allowed = true;
  559. }
  560. }
  561. return $allowed;
  562. } else {
  563. return false;
  564. }
  565. } else {
  566. if (!$array) {
  567. return false;
  568. }
  569. return true;
  570. }
  571. }
  572. public function frameTest($url)
  573. {
  574. if (!$url || $url == '') {
  575. $this->setAPIResponse('error', 'URL not supplied', 404);
  576. return false;
  577. }
  578. $array = array_change_key_case(get_headers($this->qualifyURL($url), 1));
  579. $url = $this->qualifyURL($url);
  580. if ($this->checkFrame($array, $url)) {
  581. $this->setAPIResponse('success', 'URL approved for iFrame', 200);
  582. return true;
  583. } else {
  584. $this->setAPIResponse('error', 'URL failed approval for iFrame', 409);
  585. return false;
  586. }
  587. }
  588. public function groupSelect()
  589. {
  590. $groups = $this->getAllGroups();
  591. $select = array();
  592. foreach ($groups as $key => $value) {
  593. $select[] = array(
  594. 'name' => $value['group'],
  595. 'value' => $value['group_id']
  596. );
  597. }
  598. return $select;
  599. }
  600. public function showLogin()
  601. {
  602. if ($this->config['hideRegistration'] == false) {
  603. 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>';
  604. }
  605. }
  606. public function checkoAuth()
  607. {
  608. return $this->config['plexoAuth'] && $this->config['authBackend'] == 'plex' && $this->config['authType'] !== 'internal';
  609. }
  610. public function checkoAuthOnly()
  611. {
  612. return $this->config['plexoAuth'] && $this->config['authBackend'] == 'plex' && $this->config['authType'] == 'external';
  613. }
  614. public function showoAuth()
  615. {
  616. $buttons = '';
  617. if ($this->config['plexoAuth'] && $this->config['authBackend'] == 'plex' && $this->config['authType'] !== 'internal') {
  618. $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>';
  619. }
  620. return ($buttons) ? '
  621. <div class="panel">
  622. <div class="panel-heading bg-org" id="plex-login-heading" role="tab">
  623. <a class="panel-title" data-toggle="collapse" href="#plex-login-collapse" data-parent="#login-panels" aria-expanded="false" aria-controls="organizr-login-collapse">
  624. <img class="lazyload loginTitle" data-src="plugins/images/tabs/plex.png"> &nbsp;
  625. <span class="text-uppercase fw300" lang="en">Login with Plex</span>
  626. </a>
  627. </div>
  628. <div class="panel-collapse collapse in" id="plex-login-collapse" aria-labelledby="plex-login-heading" role="tabpanel">
  629. <div class="panel-body">
  630. <div class="row">
  631. <div class="col-xs-12 col-sm-12 col-md-12 text-center">
  632. <div class="social m-b-0">' . $buttons . '</div>
  633. </div>
  634. </div>
  635. </div>
  636. </div>
  637. </div>
  638. ' : '';
  639. }
  640. public function logoOrText()
  641. {
  642. $showLogo = $this->config['minimalLoginScreen'] ? '' : 'visible-xs';
  643. if ($this->config['useLogoLogin'] == false) {
  644. $html = '<h1>' . $this->config['title'] . '</h1>';
  645. } else {
  646. $html = '<img class="loginLogo" src="' . $this->config['loginLogo'] . '" alt="Home" />';
  647. }
  648. return '<a href="javascript:void(0)" class="text-center db ' . $showLogo . '" id="login-logo">' . $html . '</a>';
  649. }
  650. public function settingsDocker()
  651. {
  652. $type = ($this->docker) ? 'Official Docker' : 'Native';
  653. 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>';
  654. }
  655. public function settingsPathChecks()
  656. {
  657. $paths = $this->pathsWritable($this->paths);
  658. $items = '';
  659. $type = (array_search(false, $paths)) ? 'Not Writable' : 'Writable';
  660. $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>';
  661. foreach ($paths as $k => $v) {
  662. $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>';
  663. }
  664. return $result . $items;
  665. }
  666. public function pathsWritable($paths)
  667. {
  668. $results = array();
  669. foreach ($paths as $k => $v) {
  670. $results[$k] = [
  671. 'writable' => is_writable($v),
  672. 'path' => $v
  673. ];
  674. }
  675. return $results;
  676. }
  677. public function clearTautulliTokens()
  678. {
  679. foreach (array_keys($_COOKIE) as $k => $v) {
  680. if (strpos($v, 'tautulli') !== false) {
  681. $this->coookie('delete', $v);
  682. }
  683. }
  684. }
  685. public function clearJellyfinTokens()
  686. {
  687. foreach (array_keys($_COOKIE) as $k => $v) {
  688. if (strpos($v, 'user-') !== false) {
  689. $this->coookie('delete', $v);
  690. }
  691. }
  692. $this->coookie('delete', 'jellyfin_credentials');
  693. }
  694. public function clearKomgaToken()
  695. {
  696. if (isset($_COOKIE['komga_token'])) {
  697. try {
  698. $url = $this->qualifyURL($this->config['komgaURL']);
  699. $options = $this->requestOptions($url, 60000, true, false);
  700. $response = Requests::post($url . '/api/v1/users/logout', ['X-Auth-Token' => $_COOKIE['komga_token']], $options);
  701. if ($response->success) {
  702. $this->writeLog('success', 'Komga Token Function - Logged User out', 'SYSTEM');
  703. } else {
  704. $this->writeLog('error', 'Komga Token Function - Unable to Logged User out', 'SYSTEM');
  705. }
  706. } catch (Requests_Exception $e) {
  707. $this->writeLog('error', 'Komga Token Function - Error: ' . $e->getMessage(), 'SYSTEM');
  708. }
  709. $this->coookie('delete', 'komga_token');
  710. }
  711. }
  712. public function analyzeIP($ip)
  713. {
  714. if (strpos($ip, '/') !== false) {
  715. $explodeIP = explode('/', $ip);
  716. $prefix = $explodeIP[1];
  717. $start_ip = $explodeIP[0];
  718. $ip_count = 1 << (32 - $prefix);
  719. $start_ip_long = ip2long($start_ip);
  720. $last_ip_long = ip2long($start_ip) + $ip_count - 1;
  721. } elseif (substr_count($ip, '.') == 3) {
  722. $start_ip_long = ip2long($ip);
  723. $last_ip_long = ip2long($ip);
  724. }
  725. return (isset($start_ip_long) && isset($last_ip_long)) ? array('from' => $start_ip_long, 'to' => $last_ip_long) : false;
  726. }
  727. public function authProxyRangeCheck($from, $to)
  728. {
  729. $approved = false;
  730. $userIP = ip2long($_SERVER['REMOTE_ADDR']);
  731. $low = $from;
  732. $high = $to;
  733. if ($userIP <= $high && $low <= $userIP) {
  734. $approved = true;
  735. }
  736. $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]);
  737. return $approved;
  738. }
  739. public function userDefinedIdReplacementLink($link, $variables)
  740. {
  741. return strtr($link, $variables);
  742. }
  743. public function requestOptions($url, $timeout = null, $override = false, $customCertificate = false, $extras = null)
  744. {
  745. $options = [];
  746. if (is_numeric($timeout)) {
  747. if ($timeout >= 1000) {
  748. $timeout = $timeout / 1000;
  749. }
  750. $options = array_merge($options, array('timeout' => $timeout));
  751. }
  752. if ($customCertificate) {
  753. if ($this->hasCustomCert()) {
  754. $options = array_merge($options, array('verify' => $this->getCustomCert(), 'verifyname' => false));
  755. }
  756. }
  757. if ($this->localURL($url, $override)) {
  758. $options = array_merge($options, array('verify' => false, 'verifyname' => false));
  759. }
  760. if ($extras) {
  761. if (gettype($extras) == 'array') {
  762. $options = array_merge($options, $extras);
  763. }
  764. }
  765. return $options;
  766. }
  767. public function showHTML(string $title = 'Organizr Alert', string $notice = '', bool $autoClose = false)
  768. {
  769. $close = $autoClose ? 'onLoad="setTimeout(\'closemyself()\',3000);"' : '';
  770. $closeMessage = $autoClose ? '<p><sup>(This window will close automatically)</sup></p>' : '';
  771. return
  772. '<!DOCTYPE html>
  773. <html lang="en">
  774. <head>
  775. <link rel="stylesheet" href="' . $this->getServerPath() . '/css/mvp.css">
  776. <meta charset="utf-8">
  777. <meta name="description" content="Trakt OAuth">
  778. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  779. <title>' . $title . '</title>
  780. </head>
  781. <script language=javascript>
  782. function closemyself() {
  783. window.opener=self;
  784. window.close();
  785. }
  786. </script>
  787. <body ' . $close . '>
  788. <main>
  789. <section>
  790. <aside>
  791. <h3>' . $title . '</h3>
  792. <p>' . $notice . '</p>
  793. ' . $closeMessage . '
  794. </aside>
  795. </section>
  796. </main>
  797. </body>
  798. </html>';
  799. }
  800. public function buildSettingsMenus($menuItems, $menuName)
  801. {
  802. $selectMenuItems = '';
  803. $unorderedListMenuItems = '';
  804. $menuNameLower = strtolower(str_replace(' ', '-', $menuName));
  805. foreach ($menuItems as $menuItem) {
  806. $anchorShort = str_replace('-anchor', '', $menuItem['anchor']);
  807. $active = ($menuItem['active']) ? 'active' : '';
  808. $apiPage = ($menuItem['api']) ? 'loadSettingsPage2(\'' . $menuItem['api'] . '\',\'#' . $anchorShort . '\',\'' . $menuItem['name'] . '\');' : '';
  809. $onClick = (isset($menuItem['onclick'])) ? $menuItem['onclick'] : '';
  810. $selectMenuItems .= '<option value="#' . $menuItem['anchor'] . '" lang="en">' . $menuItem['name'] . '</option>';
  811. $unorderedListMenuItems .= '
  812. <li onclick="changeSettingsMenu(\'Settings::' . $menuName . '::' . $menuItem['name'] . '\'); ' . $apiPage . $onClick . '" role="presentation" class="' . $active . '">
  813. <a id="' . $menuItem['anchor'] . '" href="#' . $anchorShort . '" aria-controls="home" role="tab" data-toggle="tab" aria-expanded="true">
  814. <span lang="en">' . $menuItem['name'] . '</span>
  815. </a>
  816. </li>';
  817. }
  818. $selectMenu = '<select class="form-control settings-dropdown-box ' . $menuNameLower . '-menu w-100 visible-xs">' . $selectMenuItems . '</select>';
  819. $unorderedListMenu = '<ul class="nav customtab2 nav-tabs nav-non-mobile hidden-xs" data-dropdown="' . $menuNameLower . '-menu" role="tablist">' . $unorderedListMenuItems . '</ul>';
  820. return $selectMenu . $unorderedListMenu;
  821. }
  822. public function isJSON($string)
  823. {
  824. return is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE);
  825. }
  826. }