myplex.php 2.3 KB

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