Exemplo n.º 1
0
 /**
  * This method is called there is activity in the API socket.
  */
 public function onApiActivity($type)
 {
     /* Accept incoming requests and handle them as child processes */
     $client = @stream_socket_accept($this->apisocket);
     if ($client !== false) {
         $clientHandler = new ClientHandler($client, $this->logger);
         // Read the input from the client
         $apiRequest = $clientHandler->readPacket();
         if ($apiRequest->version != API_VERSION) {
             $clientHandler->writePacket(new APIResponse(API_INVALID_VERSION, "API version must be: " . API_VERSION));
             return;
         }
         $userPassword = $this->preferences->get($apiRequest->username, 'apipassword');
         $isSuperAdmin = $apiRequest->username == $this->chatBot->vars['SuperAdmin'];
         $fromLocalHost = $clientHandler->getClientAddress() == '127.0.0.1';
         // password is not needed for superadmin from 'localhost' if the superadmin hasn't set password yet
         $noPasswordNeeded = $isSuperAdmin && $fromLocalHost && !$userPassword;
         if (!$noPasswordNeeded) {
             if ($userPassword === false) {
                 $clientHandler->writePacket(new APIResponse(API_UNSET_PASSWORD, "Password has not been set for this user."));
                 return;
             } else {
                 if ($userPassword != $apiRequest->password) {
                     $clientHandler->writePacket(new APIResponse(API_INVALID_PASSWORD, "Password was incorrect."));
                     return;
                 }
             }
         }
         if ($apiRequest->type == API_SIMPLE_MSG) {
             $type = 'msg';
             $apiReply = new APISimpleReply();
         } else {
             if ($apiRequest->type == API_ADVANCED_MSG) {
                 $type = 'api';
                 $apiReply = new APIAdvancedReply();
             } else {
                 $clientHandler->writePacket(new APIResponse(API_INVALID_REQUEST_TYPE, "Invalid request type."));
                 return;
             }
         }
         try {
             $responseCode = $this->process($type, $apiRequest->command, $apiRequest->username, $apiReply);
             $response = new APIResponse($responseCode, $apiReply->getOutput());
         } catch (APIException $e) {
             $response = new APIResponse(API_EXCEPTION, $e->getResponseMessage());
         } catch (Exception $e) {
             $response = new APIResponse(API_EXCEPTION, $e->getMessage());
         }
         $clientHandler->writePacket($response);
     }
 }