myplex.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?
  2. function myplexToken($username, $password) {
  3. global $PLEX_PRODUCT;
  4. global $PLEX_VERSION;
  5. global $PLEX_ID;
  6. global $PLEX_AUTH_URL;
  7. $username = preg_replace('/\W/', '_', $username);
  8. $token = false;
  9. # Construct the headers
  10. $headers = array(
  11. 'X-Plex-Product: ' . $PLEX_PRODUCT,
  12. #'X-Plex-Device: Foo',
  13. #'X-Plex-Platform: Bar',
  14. #'X-Plex-Platform-Version: Baz',
  15. 'X-Plex-Version: ' . $PLEX_VERSION,
  16. 'X-Plex-Client-Identifier: ' . $PLEX_ID,
  17. );
  18. # Configure the request
  19. $ch = curl_init();
  20. curl_setopt($ch, CURLOPT_URL, $PLEX_AUTH_URL);
  21. curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
  22. curl_setopt($ch, CURLOPT_TIMEOUT, 4);
  23. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  24. curl_setopt($ch, CURLOPT_POST, 0);
  25. curl_setopt($ch, CURLOPT_POSTFIELDS, '');
  26. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  27. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  28. # POST
  29. if ($body = curl_exec($ch)) {
  30. $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  31. if ($code >= 200 & $code <= 299) {
  32. if (preg_match('/\<authentication\-token\>(\w+)\<\/authentication\-token\>/i', $body, $matches)) {
  33. $token = $matches[1];
  34. }
  35. }
  36. }
  37. # Cleanup cURL
  38. curl_close($ch);
  39. return $token;
  40. }
  41. function myplexValidTokens() {
  42. global $PLEX_TOKENS_URL;
  43. $tokens = array();
  44. $body = @file($PLEX_TOKENS_URL);
  45. foreach ($body as $line) {
  46. if (preg_match('/\<access_token\s+([^\>]*)\>/', $line, $matches)) {
  47. $attrs = $matches[1];
  48. if (preg_match('/\btoken\=\"(\w+)\"/', $attrs, $matches)) {
  49. $tokens[$matches[1]] = 1;
  50. }
  51. }
  52. }
  53. return $tokens;
  54. }
  55. function myplexServerToken($userToken) {
  56. global $PLEX_SERVERS_URL;
  57. global $PLEX_SERVER_NAME;
  58. $token = false;
  59. $body = @file($PLEX_SERVERS_URL . $userToken);
  60. foreach ($body as $line) {
  61. if (preg_match('/\<Server\s+([^\>]*)\>/', $line, $matches)) {
  62. $attrs = $matches[1];
  63. if (preg_match('/\bname\=\"(\w+)\"/', $attrs, $matches)) {
  64. if ($matches[1] == $PLEX_SERVER_NAME) {
  65. if (preg_match('/\baccessToken\=\"(\w+)\"/', $attrs, $matches)) {
  66. $token = $matches[1];
  67. }
  68. }
  69. }
  70. }
  71. }
  72. return $token;
  73. }
  74. function myplexAuthorize($token) {
  75. $tokens = myplexValidTokens();
  76. $serverToken = myplexServerToken($token);
  77. return ($tokens[$serverToken] ? true : false);
  78. }
  79. ?>