plugin.php 17 KB

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