plugin.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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. ];
  121. $response = [
  122. array(
  123. 'function' => 'query',
  124. 'query' => array(
  125. 'INSERT INTO [invites]',
  126. $newCode
  127. )
  128. )
  129. ];
  130. $query = $this->processQueries($response);
  131. if ($query) {
  132. $this->writeLog('success', 'Invite Management Function - Added Invite [' . $code . ']', $this->user['username']);
  133. if ($this->config['PHPMAILER-enabled']) {
  134. $PhpMailer = new PhpMailer();
  135. $emailTemplate = array(
  136. 'type' => 'invite',
  137. 'body' => $this->config['PHPMAILER-emailTemplateInviteUser'],
  138. 'subject' => $this->config['PHPMAILER-emailTemplateInviteUserSubject'],
  139. 'user' => $username,
  140. 'password' => null,
  141. 'inviteCode' => $code,
  142. );
  143. $emailTemplate = $PhpMailer->_phpMailerPluginEmailTemplate($emailTemplate);
  144. $sendEmail = array(
  145. 'to' => $email,
  146. 'subject' => $emailTemplate['subject'],
  147. 'body' => $PhpMailer->_phpMailerPluginBuildEmail($emailTemplate),
  148. );
  149. $PhpMailer->_phpMailerPluginSendEmail($sendEmail);
  150. }
  151. $this->setAPIResponse('success', 'Invite Code: ' . $code . ' has been created', 200);
  152. return true;
  153. } else {
  154. return false;
  155. }
  156. }
  157. public function _invitesPluginVerifyCode($code)
  158. {
  159. $response = [
  160. array(
  161. 'function' => 'fetchAll',
  162. 'query' => array(
  163. 'SELECT * FROM invites WHERE valid = "Yes" AND code = ? COLLATE NOCASE',
  164. $code
  165. )
  166. )
  167. ];
  168. if ($this->processQueries($response)) {
  169. $this->setAPIResponse('success', 'Code has been verified', 200);
  170. return true;
  171. } else {
  172. $this->setAPIResponse('error', 'Code is invalid', 401);
  173. return false;
  174. }
  175. }
  176. public function _invitesPluginDeleteCode($code)
  177. {
  178. if ($this->qualifyRequest(1, false)) {
  179. $response = [
  180. array(
  181. 'function' => 'fetch',
  182. 'query' => array(
  183. 'SELECT * FROM invites WHERE code = ? COLLATE NOCASE',
  184. $code
  185. )
  186. )
  187. ];
  188. } else {
  189. if ($this->config['INVITES-allow-delete']) {
  190. $response = [
  191. array(
  192. 'function' => 'fetch',
  193. 'query' => array(
  194. 'SELECT * FROM invites WHERE invitedby = ? AND code = ? COLLATE NOCASE',
  195. $this->user['username'],
  196. $code
  197. )
  198. )
  199. ];
  200. } else {
  201. $this->setAPIResponse('error', 'You are not permitted to delete invites.', 409);
  202. return false;
  203. }
  204. }
  205. $info = $this->processQueries($response);
  206. if (!$info) {
  207. $this->setAPIResponse('error', 'Code not found', 404);
  208. return false;
  209. }
  210. $response = [
  211. array(
  212. 'function' => 'query',
  213. 'query' => array(
  214. 'DELETE FROM invites WHERE code = ? COLLATE NOCASE',
  215. $code
  216. )
  217. )
  218. ];
  219. $this->setAPIResponse('success', 'Code has been deleted', 200);
  220. return $this->processQueries($response);
  221. }
  222. public function _invitesPluginUseCode($code, $array)
  223. {
  224. $code = ($code) ?? null;
  225. $usedBy = ($array['usedby']) ?? null;
  226. $now = date("Y-m-d H:i:s");
  227. $currentIP = $this->userIP();
  228. if ($this->_invitesPluginVerifyCode($code)) {
  229. $updateCode = [
  230. 'valid' => 'No',
  231. 'usedby' => $usedBy,
  232. 'dateused' => $now,
  233. 'ip' => $currentIP
  234. ];
  235. $response = [
  236. array(
  237. 'function' => 'query',
  238. 'query' => array(
  239. 'UPDATE invites SET',
  240. $updateCode,
  241. 'WHERE code=? COLLATE NOCASE',
  242. $code
  243. )
  244. )
  245. ];
  246. $query = $this->processQueries($response);
  247. $this->writeLog('success', 'Invite Management Function - Invite Used [' . $code . ']', 'SYSTEM');
  248. return $this->_invitesPluginAction($usedBy, 'share', $this->config['INVITES-type-include']);
  249. } else {
  250. return false;
  251. }
  252. }
  253. public function _invitesPluginLibraryList($type = null)
  254. {
  255. switch ($type) {
  256. case 'plex':
  257. if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
  258. $url = 'https://plex.tv/api/servers/' . $this->config['plexID'];
  259. try {
  260. $headers = array(
  261. "Accept" => "application/json",
  262. "X-Plex-Token" => $this->config['plexToken']
  263. );
  264. $response = Requests::get($url, $headers, array());
  265. libxml_use_internal_errors(true);
  266. if ($response->success) {
  267. $libraryList = array();
  268. $plex = simplexml_load_string($response->body);
  269. foreach ($plex->Server->Section as $child) {
  270. $libraryList['libraries'][(string)$child['title']] = (string)$child['id'];
  271. }
  272. if ($this->config['INVITES-plexLibraries'] !== '') {
  273. $noLongerId = 0;
  274. $libraries = explode(',', $this->config['INVITES-plexLibraries']);
  275. foreach ($libraries as $child) {
  276. if (!$this->search_for_value($child, $libraryList)) {
  277. $libraryList['libraries']['No Longer Exists - ' . $noLongerId] = $child;
  278. $noLongerId++;
  279. }
  280. }
  281. }
  282. $libraryList = array_change_key_case($libraryList, CASE_LOWER);
  283. return $libraryList;
  284. }
  285. } catch (Requests_Exception $e) {
  286. $this->writeLog('error', 'Plex Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
  287. return false;
  288. };
  289. }
  290. break;
  291. default:
  292. # code...
  293. break;
  294. }
  295. return false;
  296. }
  297. public function _invitesPluginGetSettings()
  298. {
  299. if ($this->config['plexID'] !== '' && $this->config['plexToken'] !== '' && $this->config['INVITES-type-include'] == 'plex') {
  300. $loop = $this->_invitesPluginLibraryList($this->config['INVITES-type-include'])['libraries'];
  301. foreach ($loop as $key => $value) {
  302. $libraryList[] = array(
  303. 'name' => $key,
  304. 'value' => $value
  305. );
  306. }
  307. } else {
  308. $libraryList = array(
  309. array(
  310. 'name' => 'Refresh page to update List',
  311. 'value' => '',
  312. 'disabled' => true,
  313. ),
  314. );
  315. }
  316. return array(
  317. 'Backend' => array(
  318. array(
  319. 'type' => 'select',
  320. 'name' => 'INVITES-type-include',
  321. 'label' => 'Media Server',
  322. 'value' => $this->config['INVITES-type-include'],
  323. 'options' => array(
  324. array(
  325. 'name' => 'N/A',
  326. 'value' => 'n/a'
  327. ),
  328. array(
  329. 'name' => 'Plex',
  330. 'value' => 'plex'
  331. ),
  332. array(
  333. 'name' => 'Emby',
  334. 'value' => 'emby'
  335. )
  336. )
  337. ),
  338. array(
  339. 'type' => 'select',
  340. 'name' => 'INVITES-Auth-include',
  341. 'label' => 'Minimum Authentication',
  342. 'value' => $this->config['INVITES-Auth-include'],
  343. 'options' => $this->groupSelect()
  344. ),
  345. array(
  346. 'type' => 'switch',
  347. 'name' => 'INVITES-allow-delete-include',
  348. 'label' => 'Allow users to delete invites',
  349. 'help' => 'This must be disabled to enforce invitation limits.',
  350. 'value' => $this->config['INVITES-allow-delete-include']
  351. ),
  352. array(
  353. 'type' => 'number',
  354. 'name' => 'INVITES-maximum-invites',
  355. 'label' => 'Maximum number of invites permitted for users.',
  356. 'help' => 'Set to 0 to disable the limit.',
  357. 'value' => $this->config['INVITES-maximum-invites'],
  358. 'placeholder' => '0'
  359. ),
  360. ),
  361. 'Plex Settings' => array(
  362. array(
  363. 'type' => 'password-alt',
  364. 'name' => 'plexToken',
  365. 'label' => 'Plex Token',
  366. 'value' => $this->config['plexToken'],
  367. 'placeholder' => 'Use Get Token Button'
  368. ),
  369. array(
  370. 'type' => 'button',
  371. 'label' => 'Get Plex Token',
  372. 'icon' => 'fa fa-ticket',
  373. 'text' => 'Retrieve',
  374. 'attr' => 'onclick="PlexOAuth(oAuthSuccess,oAuthError, null, \'#INVITES-settings-items [name=plexToken]\')"'
  375. ),
  376. array(
  377. 'type' => 'password-alt',
  378. 'name' => 'plexID',
  379. 'label' => 'Plex Machine',
  380. 'value' => $this->config['plexID'],
  381. 'placeholder' => 'Use Get Plex Machine Button'
  382. ),
  383. array(
  384. 'type' => 'button',
  385. 'label' => 'Get Plex Machine',
  386. 'icon' => 'fa fa-id-badge',
  387. 'text' => 'Retrieve',
  388. 'attr' => 'onclick="showPlexMachineForm(\'#INVITES-settings-items [name=plexID]\')"'
  389. ),
  390. array(
  391. 'type' => 'select2',
  392. 'class' => 'select2-multiple',
  393. 'id' => 'invite-select-' . $this->random_ascii_string(6),
  394. 'name' => 'INVITES-plexLibraries',
  395. 'label' => 'Libraries',
  396. 'value' => $this->config['INVITES-plexLibraries'],
  397. 'options' => $libraryList
  398. ),
  399. array(
  400. 'type' => 'text',
  401. 'name' => 'INVITES-plex-tv-labels',
  402. 'label' => 'TV Labels (comma separated)',
  403. 'value' => $this->config['INVITES-plex-tv-labels'],
  404. 'placeholder' => 'All'
  405. ),
  406. array(
  407. 'type' => 'text',
  408. 'name' => 'INVITES-plex-movies-labels',
  409. 'label' => 'Movies Labels (comma separated)',
  410. 'value' => $this->config['INVITES-plex-movies-labels'],
  411. 'placeholder' => 'All'
  412. ),
  413. array(
  414. 'type' => 'text',
  415. 'name' => 'INVITES-plex-music-labels',
  416. 'label' => 'Music Labels (comma separated)',
  417. 'value' => $this->config['INVITES-plex-music-labels'],
  418. 'placeholder' => 'All'
  419. ),
  420. ),
  421. 'Emby Settings' => array(
  422. array(
  423. 'type' => 'password-alt',
  424. 'name' => 'embyToken',
  425. 'label' => 'Emby API key',
  426. 'value' => $this->config['embyToken'],
  427. 'placeholder' => 'enter key from emby'
  428. ),
  429. array(
  430. 'type' => 'text',
  431. 'name' => 'embyURL',
  432. 'label' => 'Emby server adress',
  433. 'value' => $this->config['embyURL'],
  434. 'placeholder' => 'localhost:8086'
  435. ),
  436. array(
  437. 'type' => 'text',
  438. 'name' => 'INVITES-EmbyTemplate',
  439. 'label' => 'Emby User to be used as template for new users',
  440. 'value' => $this->config['INVITES-EmbyTemplate'],
  441. 'placeholder' => 'AdamSmith'
  442. )
  443. ),
  444. 'FYI' => array(
  445. array(
  446. 'type' => 'html',
  447. 'label' => 'Note',
  448. 'html' => '<span lang="en">After enabling for the first time, please reload the page - Menu is located under User menu on top right</span>'
  449. )
  450. )
  451. );
  452. }
  453. public function _invitesPluginAction($username, $action = null, $type = null)
  454. {
  455. if ($action == null) {
  456. $this->setAPIResponse('error', 'No Action supplied', 409);
  457. return false;
  458. }
  459. switch ($type) {
  460. case 'plex':
  461. if (!empty($this->config['plexToken']) && !empty($this->config['plexID'])) {
  462. $url = "https://plex.tv/api/servers/" . $this->config['plexID'] . "/shared_servers/";
  463. if ($this->config['INVITES-plexLibraries'] !== "") {
  464. $libraries = explode(',', $this->config['INVITES-plexLibraries']);
  465. } else {
  466. $libraries = '';
  467. }
  468. if ($this->config['INVITES-plex-tv-labels'] !== "") {
  469. $tv_labels = "label=" . $this->config['INVITES-plex-tv-labels'];
  470. } else {
  471. $tv_labels = "";
  472. }
  473. if ($this->config['INVITES-plex-movies-labels'] !== "") {
  474. $movies_labels = "label=" . $this->config['INVITES-plex-movies-labels'];
  475. } else {
  476. $movies_labels = "";
  477. }
  478. if ($this->config['INVITES-plex-music-labels'] !== "") {
  479. $music_labels = "label=" . $this->config['INVITES-plex-music-labels'];
  480. } else {
  481. $music_labels = "";
  482. }
  483. $headers = array(
  484. "Accept" => "application/json",
  485. "Content-Type" => "application/json",
  486. "X-Plex-Token" => $this->config['plexToken']
  487. );
  488. $data = array(
  489. "server_id" => $this->config['plexID'],
  490. "shared_server" => array(
  491. "library_section_ids" => $libraries,
  492. "invited_email" => $username
  493. ),
  494. "sharing_settings" => array(
  495. "filterTelevision" => $tv_labels,
  496. "filterMovies" => $movies_labels,
  497. "filterMusic" => $music_labels
  498. )
  499. );
  500. try {
  501. switch ($action) {
  502. case 'share':
  503. $response = Requests::post($url, $headers, json_encode($data), array());
  504. break;
  505. case 'unshare':
  506. $id = (is_numeric($username) ? $username : $this->_invitesPluginConvertPlexName($username, "id"));
  507. $url = $url . $id;
  508. $response = Requests::delete($url, $headers, array());
  509. break;
  510. default:
  511. $this->setAPIResponse('error', 'No Action supplied', 409);
  512. return false;
  513. }
  514. if ($response->success) {
  515. $this->writeLog('success', 'Plex Invite Function - Plex User now has access to system', $username);
  516. $this->setAPIResponse('success', 'Plex User now has access to system', 200);
  517. return true;
  518. } else {
  519. switch ($response->status_code) {
  520. case 400:
  521. $this->writeLog('error', 'Plex Invite Function - Plex User already has access', $username);
  522. $this->setAPIResponse('error', 'Plex User already has access', 409);
  523. return false;
  524. case 401:
  525. $this->writeLog('error', 'Plex Invite Function - Incorrect Token', 'SYSTEM');
  526. $this->setAPIResponse('error', 'Incorrect Token', 409);
  527. return false;
  528. case 404:
  529. $this->writeLog('error', 'Plex Invite Function - Libraries not setup correct [' . $this->config['INVITES-plexLibraries'] . ']', 'SYSTEM');
  530. $this->setAPIResponse('error', 'Libraries not setup correct', 409);
  531. return false;
  532. default:
  533. $this->writeLog('error', 'Plex Invite Function - An error occurred [' . $response->status_code . ']', $username);
  534. $this->setAPIResponse('error', 'An Error Occurred', 409);
  535. return false;
  536. }
  537. }
  538. } catch (Requests_Exception $e) {
  539. $this->writeLog('error', 'Plex Invite Function - Error: ' . $e->getMessage(), 'SYSTEM');
  540. $this->setAPIResponse('error', $e->getMessage(), 409);
  541. return false;
  542. };
  543. } else {
  544. $this->writeLog('error', 'Plex Invite Function - Plex Token/ID not set', 'SYSTEM');
  545. $this->setAPIResponse('error', 'Plex Token/ID not set', 409);
  546. return false;
  547. }
  548. break;
  549. case 'emby':
  550. try {
  551. #add emby user to system
  552. $this->setAPIResponse('success', 'User now has access to system', 200);
  553. return true;
  554. } catch (Requests_Exception $e) {
  555. $this->writeLog('error', 'Emby Invite Function - Error: ' . $e->getMessage(), 'SYSTEM');
  556. $this->setAPIResponse('error', $e->getMessage(), 409);
  557. return false;
  558. }
  559. default:
  560. return false;
  561. }
  562. return false;
  563. }
  564. public function _invitesPluginConvertPlexName($user, $type)
  565. {
  566. $array = $this->userList('plex');
  567. switch ($type) {
  568. case "username":
  569. case "u":
  570. $plexUser = array_search($user, $array['users']);
  571. break;
  572. case "id":
  573. if (array_key_exists(strtolower($user), $array['users'])) {
  574. $plexUser = $array['users'][strtolower($user)];
  575. }
  576. break;
  577. default:
  578. $plexUser = false;
  579. }
  580. return (!empty($plexUser) ? $plexUser : null);
  581. }
  582. }