4
0

plugin.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. <?php
  2. // PLUGIN INFORMATION
  3. $GLOBALS['plugins']['Invites'] = array( // Plugin Name
  4. 'name' => 'Invites', // Plugin Name
  5. 'author' => 'CauseFX', // Who wrote the plugin
  6. 'category' => 'Management', // One to Two Word Description
  7. 'link' => '', // Link to plugin info
  8. 'license' => 'personal', // License Type use , for multiple
  9. 'idPrefix' => 'INVITES', // html element id prefix
  10. 'configPrefix' => 'INVITES', // config file prefix for array items without the hyphen
  11. 'version' => '1.1.0', // SemVer of plugin
  12. 'image' => 'api/plugins/invites/logo.png', // 1:1 non transparent image for plugin
  13. 'settings' => true, // does plugin need a settings modal?
  14. 'bind' => true, // use default bind to make settings page - true or false
  15. 'api' => 'api/v2/plugins/invites/settings', // api route for settings page
  16. 'homepage' => false // Is plugin for use on homepage? true or false
  17. );
  18. class Invites extends Organizr
  19. {
  20. public function __construct()
  21. {
  22. parent::__construct();
  23. $this->_pluginUpgradeCheck();
  24. }
  25. public function _pluginUpgradeCheck()
  26. {
  27. if ($this->hasDB()) {
  28. $compare = new Composer\Semver\Comparator;
  29. $oldVer = $this->config['INVITES-dbVersion'];
  30. // Upgrade check start for version below
  31. $versionCheck = '1.1.0';
  32. if ($compare->lessThan($oldVer, $versionCheck)) {
  33. $oldVer = $versionCheck;
  34. $this->_pluginUpgradeToVersion($versionCheck);
  35. }
  36. // End Upgrade check start for version above
  37. // Update config.php version if different to the installed version
  38. if ($GLOBALS['plugins']['Invites']['version'] !== $this->config['INVITES-dbVersion']) {
  39. $this->updateConfig(array('INVITES-dbVersion' => $oldVer));
  40. $this->setLoggerChannel('Invites Plugin');
  41. $this->logger->debug('Updated INVITES-dbVersion to ' . $oldVer);
  42. }
  43. return true;
  44. }
  45. }
  46. public function _pluginUpgradeToVersion($version = '1.1.0')
  47. {
  48. switch ($version) {
  49. case '1.1.0':
  50. $this->_addInvitedByColumnToDatabase();
  51. break;
  52. }
  53. $this->setResponse(200, 'Ran plugin update function for version: ' . $version);
  54. return true;
  55. }
  56. public function _addInvitedByColumnToDatabase()
  57. {
  58. $addColumn = $this->addColumnToDatabase('invites', 'invitedby', 'TEXT');
  59. $this->setLoggerChannel('Invites Plugin');
  60. if ($addColumn) {
  61. $this->logger->info('Updated Invites Database');
  62. } else {
  63. $this->logger->warning('Could not update Invites Database');
  64. }
  65. }
  66. public function _invitesPluginGetCodes()
  67. {
  68. if ($this->qualifyRequest(1, false)) {
  69. $response = [
  70. array(
  71. 'function' => 'fetchAll',
  72. 'query' => 'SELECT * FROM invites'
  73. )
  74. ];
  75. } else {
  76. $response = [
  77. array(
  78. 'function' => 'fetchAll',
  79. 'query' => array(
  80. 'SELECT * FROM invites WHERE invitedby = ?',
  81. $this->user['username']
  82. )
  83. )
  84. ];
  85. }
  86. return $this->processQueries($response);
  87. }
  88. public function _invitesPluginCreateCode($array)
  89. {
  90. $code = ($array['code']) ?? null;
  91. $username = ($array['username']) ?? null;
  92. $email = ($array['email']) ?? null;
  93. $invites = $this->_invitesPluginGetCodes();
  94. $inviteCount = count($invites);
  95. if (!$this->qualifyRequest(1, false)) {
  96. if ($this->config['INVITES-maximum-invites'] != 0 && $inviteCount >= $this->config['INVITES-maximum-invites']) {
  97. $this->setAPIResponse('error', 'Maximum number of invites reached', 409);
  98. return false;
  99. }
  100. }
  101. if (!$code) {
  102. $this->setAPIResponse('error', 'Code not supplied', 409);
  103. return false;
  104. }
  105. if (!$username) {
  106. $this->setAPIResponse('error', 'Username not supplied', 409);
  107. return false;
  108. }
  109. if (!$email) {
  110. $this->setAPIResponse('error', 'Email not supplied', 409);
  111. return false;
  112. }
  113. $newCode = [
  114. 'code' => $code,
  115. 'email' => $email,
  116. 'username' => $username,
  117. 'valid' => 'Yes',
  118. 'type' => $this->config['INVITES-type-include'],
  119. 'invitedby' => $this->user['username'],
  120. 'date' => gmdate('Y-m-d H:i:s')
  121. ];
  122. $response = [
  123. array(
  124. 'function' => 'query',
  125. 'query' => array(
  126. 'INSERT INTO [invites]',
  127. $newCode
  128. )
  129. )
  130. ];
  131. $query = $this->processQueries($response);
  132. if ($query) {
  133. $this->setLoggerChannel('Invites')->info('Added Invite [' . $code . ']');
  134. if ($this->config['PHPMAILER-enabled']) {
  135. $PhpMailer = new PhpMailer();
  136. $emailTemplate = array(
  137. 'type' => 'invite',
  138. 'body' => $this->config['PHPMAILER-emailTemplateInviteUser'],
  139. 'subject' => $this->config['PHPMAILER-emailTemplateInviteUserSubject'],
  140. 'user' => $username,
  141. 'password' => null,
  142. 'inviteCode' => $code,
  143. );
  144. $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
  145. $sendEmail = array(
  146. 'to' => $email,
  147. 'subject' => $emailTemplate['subject'],
  148. 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
  149. );
  150. $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
  151. }
  152. $this->setAPIResponse('success', 'Invite Code: ' . $code . ' has been created', 200);
  153. return true;
  154. } else {
  155. return false;
  156. }
  157. }
  158. public function _invitesPluginVerifyCode($code)
  159. {
  160. $response = [
  161. array(
  162. 'function' => 'fetchAll',
  163. 'query' => array(
  164. 'SELECT * FROM invites WHERE valid = "Yes" AND code = ? COLLATE NOCASE',
  165. $code
  166. )
  167. )
  168. ];
  169. if ($this->processQueries($response)) {
  170. $this->setAPIResponse('success', 'Code has been verified', 200);
  171. return true;
  172. } else {
  173. $this->setAPIResponse('error', 'Code is invalid', 401);
  174. return false;
  175. }
  176. }
  177. public function _invitesPluginDeleteCode($code)
  178. {
  179. if ($this->qualifyRequest(1, false)) {
  180. $response = [
  181. array(
  182. 'function' => 'fetch',
  183. 'query' => array(
  184. 'SELECT * FROM invites WHERE code = ? COLLATE NOCASE',
  185. $code
  186. )
  187. )
  188. ];
  189. } else {
  190. if ($this->config['INVITES-allow-delete']) {
  191. $response = [
  192. array(
  193. 'function' => 'fetch',
  194. 'query' => array(
  195. 'SELECT * FROM invites WHERE invitedby = ? AND code = ? COLLATE NOCASE',
  196. $this->user['username'],
  197. $code
  198. )
  199. )
  200. ];
  201. } else {
  202. $this->setAPIResponse('error', 'You are not permitted to delete invites.', 409);
  203. return false;
  204. }
  205. }
  206. $info = $this->processQueries($response);
  207. if (!$info) {
  208. $this->setAPIResponse('error', 'Code not found', 404);
  209. return false;
  210. }
  211. $response = [
  212. array(
  213. 'function' => 'query',
  214. 'query' => array(
  215. 'DELETE FROM invites WHERE code = ? COLLATE NOCASE',
  216. $code
  217. )
  218. )
  219. ];
  220. $this->setAPIResponse('success', 'Code has been deleted', 200);
  221. return $this->processQueries($response);
  222. }
  223. public function _invitesPluginUseCode($code, $array)
  224. {
  225. $code = ($code) ?? null;
  226. $usedBy = ($array['usedby']) ?? null;
  227. $now = date("Y-m-d H:i:s");
  228. $currentIP = $this->userIP();
  229. if ($this->_invitesPluginVerifyCode($code)) {
  230. $updateCode = [
  231. 'valid' => 'No',
  232. 'usedby' => $usedBy,
  233. 'dateused' => $now,
  234. 'ip' => $currentIP
  235. ];
  236. $response = [
  237. array(
  238. 'function' => 'query',
  239. 'query' => array(
  240. 'UPDATE invites SET',
  241. $updateCode,
  242. 'WHERE code=? COLLATE NOCASE',
  243. $code
  244. )
  245. )
  246. ];
  247. $query = $this->processQueries($response);
  248. $this->setLoggerChannel('Invites')->info('Invite Used [' . $code . ']');
  249. return $this->_invitesPluginAction($usedBy, 'share', $this->config['INVITES-type-include']);
  250. } else {
  251. return false;
  252. }
  253. }
  254. public function _invitesPluginLibraryList($type = null)
  255. {
  256. switch ($type) {
  257. case 'plex':
  258. if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
  259. $url = 'https://plex.tv/api/servers/' . $this->config['plexID'];
  260. try {
  261. $headers = array(
  262. "Accept" => "application/json",
  263. "X-Plex-Token" => $this->config['plexToken']
  264. );
  265. $response = Requests::get($url, $headers, array());
  266. libxml_use_internal_errors(true);
  267. if ($response->success) {
  268. $libraryList = array();
  269. $plex = simplexml_load_string($response->body);
  270. foreach ($plex->Server->Section as $child) {
  271. $libraryList['libraries'][(string)$child['title']] = (string)$child['id'];
  272. }
  273. if ($this->config['INVITES-plexLibraries'] !== '') {
  274. $noLongerId = 0;
  275. $libraries = explode(',', $this->config['INVITES-plexLibraries']);
  276. foreach ($libraries as $child) {
  277. if (!$this->search_for_value($child, $libraryList)) {
  278. $libraryList['libraries']['No Longer Exists - ' . $noLongerId] = $child;
  279. $noLongerId++;
  280. }
  281. }
  282. }
  283. $libraryList = array_change_key_case($libraryList, CASE_LOWER);
  284. return $libraryList;
  285. }
  286. } catch (Requests_Exception $e) {
  287. $this->setLoggerChannel('Plex')->error($e);
  288. return false;
  289. };
  290. }
  291. break;
  292. default:
  293. # code...
  294. break;
  295. }
  296. return false;
  297. }
  298. public function _invitesPluginGetSettings()
  299. {
  300. if ($this->config['plexID'] !== '' && $this->config['plexToken'] !== '' && $this->config['INVITES-type-include'] == 'plex') {
  301. $loop = $this->_invitesPluginLibraryList($this->config['INVITES-type-include'])['libraries'];
  302. foreach ($loop as $key => $value) {
  303. $libraryList[] = array(
  304. 'name' => $key,
  305. 'value' => $value
  306. );
  307. }
  308. } else {
  309. $libraryList = array(
  310. array(
  311. 'name' => 'Refresh page to update List',
  312. 'value' => '',
  313. 'disabled' => true,
  314. ),
  315. );
  316. }
  317. return array(
  318. 'Backend' => array(
  319. array(
  320. 'type' => 'select',
  321. 'name' => 'INVITES-type-include',
  322. 'label' => 'Media Server',
  323. 'value' => $this->config['INVITES-type-include'],
  324. 'options' => array(
  325. array(
  326. 'name' => 'N/A',
  327. 'value' => 'n/a'
  328. ),
  329. array(
  330. 'name' => 'Plex',
  331. 'value' => 'plex'
  332. ),
  333. array(
  334. 'name' => 'Emby',
  335. 'value' => 'emby'
  336. )
  337. )
  338. ),
  339. array(
  340. 'type' => 'select',
  341. 'name' => 'INVITES-Auth-include',
  342. 'label' => 'Minimum Authentication',
  343. 'value' => $this->config['INVITES-Auth-include'],
  344. 'options' => $this->groupSelect()
  345. ),
  346. array(
  347. 'type' => 'switch',
  348. 'name' => 'INVITES-allow-delete-include',
  349. 'label' => 'Allow users to delete invites',
  350. 'help' => 'This must be disabled to enforce invitation limits.',
  351. 'value' => $this->config['INVITES-allow-delete-include']
  352. ),
  353. array(
  354. 'type' => 'number',
  355. 'name' => 'INVITES-maximum-invites',
  356. 'label' => 'Maximum number of invites permitted for users.',
  357. 'help' => 'Set to 0 to disable the limit.',
  358. 'value' => $this->config['INVITES-maximum-invites'],
  359. 'placeholder' => '0'
  360. ),
  361. ),
  362. 'Plex Settings' => array(
  363. array(
  364. 'type' => 'password-alt',
  365. 'name' => 'plexToken',
  366. 'label' => 'Plex Token',
  367. 'value' => $this->config['plexToken'],
  368. 'placeholder' => 'Use Get Token Button'
  369. ),
  370. array(
  371. 'type' => 'button',
  372. 'label' => 'Get Plex Token',
  373. 'icon' => 'fa fa-ticket',
  374. 'text' => 'Retrieve',
  375. 'attr' => 'onclick="PlexOAuth(oAuthSuccess,oAuthError, null, \'#INVITES-settings-items [name=plexToken]\')"'
  376. ),
  377. array(
  378. 'type' => 'password-alt',
  379. 'name' => 'plexID',
  380. 'label' => 'Plex Machine',
  381. 'value' => $this->config['plexID'],
  382. 'placeholder' => 'Use Get Plex Machine Button'
  383. ),
  384. array(
  385. 'type' => 'button',
  386. 'label' => 'Get Plex Machine',
  387. 'icon' => 'fa fa-id-badge',
  388. 'text' => 'Retrieve',
  389. 'attr' => 'onclick="showPlexMachineForm(\'#INVITES-settings-items [name=plexID]\')"'
  390. ),
  391. array(
  392. 'type' => 'select2',
  393. 'class' => 'select2-multiple',
  394. 'id' => 'invite-select-' . $this->random_ascii_string(6),
  395. 'name' => 'INVITES-plexLibraries',
  396. 'label' => 'Libraries',
  397. 'value' => $this->config['INVITES-plexLibraries'],
  398. 'options' => $libraryList
  399. ),
  400. array(
  401. 'type' => 'text',
  402. 'name' => 'INVITES-plex-tv-labels',
  403. 'label' => 'TV Labels (comma separated)',
  404. 'value' => $this->config['INVITES-plex-tv-labels'],
  405. 'placeholder' => 'All'
  406. ),
  407. array(
  408. 'type' => 'text',
  409. 'name' => 'INVITES-plex-movies-labels',
  410. 'label' => 'Movies Labels (comma separated)',
  411. 'value' => $this->config['INVITES-plex-movies-labels'],
  412. 'placeholder' => 'All'
  413. ),
  414. array(
  415. 'type' => 'text',
  416. 'name' => 'INVITES-plex-music-labels',
  417. 'label' => 'Music Labels (comma separated)',
  418. 'value' => $this->config['INVITES-plex-music-labels'],
  419. 'placeholder' => 'All'
  420. ),
  421. ),
  422. 'Emby Settings' => array(
  423. array(
  424. 'type' => 'password-alt',
  425. 'name' => 'embyToken',
  426. 'label' => 'Emby API key',
  427. 'value' => $this->config['embyToken'],
  428. 'placeholder' => 'enter key from emby'
  429. ),
  430. array(
  431. 'type' => 'text',
  432. 'name' => 'embyURL',
  433. 'label' => 'Emby server adress',
  434. 'value' => $this->config['embyURL'],
  435. 'placeholder' => 'localhost:8086'
  436. ),
  437. array(
  438. 'type' => 'text',
  439. 'name' => 'INVITES-EmbyTemplate',
  440. 'label' => 'Emby User to be used as template for new users',
  441. 'value' => $this->config['INVITES-EmbyTemplate'],
  442. 'placeholder' => 'AdamSmith'
  443. )
  444. ),
  445. 'FYI' => array(
  446. array(
  447. 'type' => 'html',
  448. 'label' => 'Note',
  449. 'html' => '<span lang="en">After enabling for the first time, please reload the page - Menu is located under User menu on top right</span>'
  450. )
  451. )
  452. );
  453. }
  454. public function _invitesPluginAction($username, $action = null, $type = null)
  455. {
  456. if ($action == null) {
  457. $this->setAPIResponse('error', 'No Action supplied', 409);
  458. return false;
  459. }
  460. switch ($type) {
  461. case 'plex':
  462. if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
  463. $url = "https://plex.tv/api/servers/" . $this->config['plexID'] . "/shared_servers/";
  464. if ($this->config['INVITES-plexLibraries'] !== "") {
  465. $libraries = explode(',', $this->config['INVITES-plexLibraries']);
  466. } else {
  467. $libraries = '';
  468. }
  469. if ($this->config['INVITES-plex-tv-labels'] !== "") {
  470. $tv_labels = "label=" . $this->config['INVITES-plex-tv-labels'];
  471. } else {
  472. $tv_labels = "";
  473. }
  474. if ($this->config['INVITES-plex-movies-labels'] !== "") {
  475. $movies_labels = "label=" . $this->config['INVITES-plex-movies-labels'];
  476. } else {
  477. $movies_labels = "";
  478. }
  479. if ($this->config['INVITES-plex-music-labels'] !== "") {
  480. $music_labels = "label=" . $this->config['INVITES-plex-music-labels'];
  481. } else {
  482. $music_labels = "";
  483. }
  484. $headers = array(
  485. "Accept" => "application/json",
  486. "Content-Type" => "application/json",
  487. "X-Plex-Token" => $this->config['plexToken']
  488. );
  489. $data = array(
  490. "server_id" => $this->config['plexID'],
  491. "shared_server" => array(
  492. "library_section_ids" => $libraries,
  493. "invited_email" => $username
  494. ),
  495. "sharing_settings" => array(
  496. "filterTelevision" => $tv_labels,
  497. "filterMovies" => $movies_labels,
  498. "filterMusic" => $music_labels
  499. )
  500. );
  501. try {
  502. switch ($action) {
  503. case 'share':
  504. $response = Requests::post($url, $headers, json_encode($data), array());
  505. break;
  506. case 'unshare':
  507. $id = (is_numeric($username) ? $username : $this->_invitesPluginConvertPlexName($username, "id"));
  508. $url = $url . $id;
  509. $response = Requests::delete($url, $headers, array());
  510. break;
  511. default:
  512. $this->setAPIResponse('error', 'No Action supplied', 409);
  513. return false;
  514. }
  515. if ($response->success) {
  516. $this->setLoggerChannel('Invites')->info('Plex User now has access to system');
  517. $this->setAPIResponse('success', 'Plex User now has access to system', 200);
  518. return true;
  519. } else {
  520. switch ($response->status_code) {
  521. case 400:
  522. $this->setLoggerChannel('Plex')->warning('Plex User already has access');
  523. $this->setAPIResponse('error', 'Plex User already has access', 409);
  524. return false;
  525. case 401:
  526. $this->setLoggerChannel('Plex')->warning('Incorrect Token');
  527. $this->setAPIResponse('error', 'Incorrect Token', 409);
  528. return false;
  529. case 404:
  530. $this->setLoggerChannel('Plex')->warning('Libraries not setup correctly');
  531. $this->setAPIResponse('error', 'Libraries not setup correct', 409);
  532. return false;
  533. default:
  534. $this->setLoggerChannel('Plex')->warning('An error occurred [' . $response->status_code . ']');
  535. $this->setAPIResponse('error', 'An Error Occurred', 409);
  536. return false;
  537. }
  538. }
  539. } catch (Requests_Exception $e) {
  540. $this->setLoggerChannel('Plex')->error($e);
  541. $this->setAPIResponse('error', $e->getMessage(), 409);
  542. return false;
  543. }
  544. } else {
  545. $this->setLoggerChannel('Plex')->warning('Plex Token/ID not set');
  546. $this->setAPIResponse('error', 'Plex Token/ID not set', 409);
  547. return false;
  548. }
  549. break;
  550. case 'emby':
  551. try {
  552. #add emby user to system
  553. $this->setAPIResponse('success', 'User now has access to system', 200);
  554. return true;
  555. } catch (Requests_Exception $e) {
  556. $this->setLoggerChannel('Emby')->error($e);
  557. $this->setAPIResponse('error', $e->getMessage(), 409);
  558. return false;
  559. }
  560. default:
  561. return false;
  562. }
  563. return false;
  564. }
  565. public function _invitesPluginConvertPlexName($user, $type)
  566. {
  567. $array = $this->userList('plex');
  568. switch ($type) {
  569. case "username":
  570. case "u":
  571. $plexUser = array_search($user, $array['users']);
  572. break;
  573. case "id":
  574. if (array_key_exists(strtolower($user), $array['users'])) {
  575. $plexUser = $array['users'][strtolower($user)];
  576. }
  577. break;
  578. default:
  579. $plexUser = false;
  580. }
  581. return (!empty($plexUser) ? $plexUser : null);
  582. }
  583. }