organizr-functions.php 31 KB

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