plugin.php 16 KB

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