Guest User

Untitled

a guest
Jun 3rd, 2016
78
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. class MinecraftRconException extends Exception
  3. {
  4. // Exception thrown by MinecraftRcon class
  5. }
  6.  
  7. class MinecraftRcon
  8. {
  9.  
  10. //
  11. const SERVERDATA_EXECCOMMAND = 2;
  12. const SERVERDATA_AUTH = 3;
  13.  
  14. //
  15. const SERVERDATA_RESPONSE_VALUE = 0;
  16. const SERVERDATA_AUTH_RESPONSE = 2;
  17.  
  18. private $Socket;
  19. private $RequestId;
  20.  
  21. public function __destruct( )
  22. {
  23. $this->Disconnect( );
  24. }
  25.  
  26. public function Connect( $Ip, $Port = 25575, $Password, $Timeout = 3 )
  27. {
  28. $this->RequestId = 0;
  29.  
  30. if( $this->Socket = FSockOpen( $Ip, (int)$Port ) )
  31. {
  32. Socket_Set_TimeOut( $this->Socket, $Timeout );
  33.  
  34. if( !$this->Auth( $Password ) )
  35. {
  36. $this->Disconnect( );
  37.  
  38. throw new MinecraftRconException( "Authorization failed." );
  39. }
  40. }
  41. else
  42. {
  43. throw new MinecraftRconException( "Can't open socket." );
  44. }
  45. }
  46.  
  47. public function Disconnect( )
  48. {
  49. if( $this->Socket )
  50. {
  51. FClose( $this->Socket );
  52.  
  53. $this->Socket = null;
  54. }
  55. }
  56.  
  57. public function Command( $String )
  58. {
  59. if( !$this->WriteData( self :: SERVERDATA_EXECCOMMAND, $String ) )
  60. {
  61. return false;
  62. }
  63.  
  64. $Data = $this->ReadData( );
  65.  
  66. if( $Data[ 'RequestId' ] < 1 || $Data[ 'Response' ] != self :: SERVERDATA_RESPONSE_VALUE )
  67. {
  68. return false;
  69. }
  70.  
  71. return $Data[ 'String' ];
  72. }
  73.  
  74. private function Auth( $Password )
  75. {
  76. if( !$this->WriteData( self :: SERVERDATA_AUTH, $Password ) )
  77. {
  78. return false;
  79. }
  80.  
  81. $Data = $this->ReadData( );
  82.  
  83. return $Data[ 'RequestId' ] > -1 && $Data[ 'Response' ] == self :: SERVERDATA_AUTH_RESPONSE;
  84. }
  85.  
  86. private function ReadData( )
  87. {
  88. $Packet = Array( );
  89.  
  90. $Size = FRead( $this->Socket, 4 );
  91. $Size = UnPack( 'V1Size', $Size );
  92. $Size = $Size[ 'Size' ];
  93.  
  94. // TODO: Add multiple packets (Source)
  95.  
  96. $Packet = FRead( $this->Socket, $Size );
  97. $Packet = UnPack( 'V1RequestId/V1Response/a*String/a*String2', $Packet );
  98.  
  99. return $Packet;
  100. }
  101.  
  102. private function WriteData( $Command, $String = "" )
  103. {
  104. // Pack the packet together
  105. $Data = Pack( 'VV', $this->RequestId++, $Command ) . $String . "\x00\x00\x00";
  106.  
  107. // Prepend packet length
  108. $Data = Pack( 'V', StrLen( $Data ) ) . $Data;
  109.  
  110. $Length = StrLen( $Data );
  111.  
  112. return $Length === FWrite( $this->Socket, $Data, $Length );
  113. }
  114. }
  115. ?>
RAW Paste Data