Example #1
0
 /**
  * Gets default search criteria according environment scope
  *
  * @return array Returns array of the search criteria
  */
 private function getDefaultCriteria()
 {
     $environment = $this->getEnvironment();
     $criteria = [['envId' => $environment->id]];
     if (!$this->hasPermissions(Acl::RESOURCE_FARMS)) {
         $where = [];
         $farm = new Farm();
         $farmTeam = new FarmTeam();
         if ($this->hasPermissions(Acl::RESOURCE_OWN_FARMS)) {
             $where[] = "{$farm->columnOwnerId()} = " . $farm->qstr('ownerId', $this->getUser()->id);
         }
         if ($this->hasPermissions(Acl::RESOURCE_TEAM_FARMS)) {
             $join[] = "\n                    LEFT JOIN {$farmTeam->table('ft')} ON {$farmTeam->columnFarmId('ft')} = {$farm->columnId()}\n                    LEFT JOIN `account_team_users` `atu` ON `atu`.`team_id` = {$farmTeam->columnTeamId('ft')}\n                    LEFT JOIN `account_team_envs` `ate` ON `ate`.`team_id` = {$farmTeam->columnTeamId('ft')} AND `ate`.`env_id` = {$farm->columnEnvId()}\n                ";
             $where[] = "`atu`.`user_id` = " . $farmTeam->db()->qstr($this->getUser()->id) . " AND `ate`.`team_id` IS NOT NULL";
         }
         if (!empty($where)) {
             $criteria[Farm::STMT_WHERE] = '(' . join(' OR ', $where) . ')';
         }
         if (!empty($join)) {
             if (empty($criteria[Farm::STMT_FROM])) {
                 $criteria[Farm::STMT_FROM] = $farm->table();
             }
             $criteria[Farm::STMT_FROM] .= implode(' ', $join);
         }
     }
     return $criteria;
 }
Example #2
0
 /**
  * Fill information about Farm/FarmRole for each object based on cloudServerId.
  * cloudServerId could be empty or didn't exist in our database.
  *
  * @param   array[]   $data   Array of arrays
  */
 private function applyFarmRoleInfo(&$data)
 {
     $cloudServerIds = [];
     foreach ($data as $row) {
         if ($row['cloudServerId']) {
             $cloudServerIds[] = $row['cloudServerId'];
         }
     }
     if (empty($cloudServerIds)) {
         return;
     }
     $server = new Entity\Server();
     $history = new Entity\Server\History();
     $farm = new Entity\Farm();
     $farmRole = new Entity\FarmRole();
     $cloudServerIds = join(",", array_map(function ($serverId) {
         return $this->db->qstr($serverId);
     }, $cloudServerIds));
     $sql = "\n            SELECT {$farm->columnId} AS farmId, {$farm->columnName} AS farmName, {$farmRole->columnId} AS farmRoleId,\n                {$farmRole->columnAlias} AS farmRoleName, {$server->columnServerId} AS serverId, {$server->columnIndex} AS serverIndex,\n                {$history->columnCloudServerId} AS cloudServerId FROM {$server->table()}\n            JOIN {$history->table()} ON {$server->columnServerId} = {$history->columnServerId}\n            JOIN {$farm->table()} ON {$server->columnFarmId} = {$farm->columnId}\n            JOIN {$farmRole->table()} ON {$server->columnFarmRoleId} = {$farmRole->columnId}\n            WHERE {$server->columnEnvId} = ? AND {$history->columnCloudServerId} IN ({$cloudServerIds})\n        ";
     $result = [];
     foreach ($this->db->Execute($sql, [$this->getEnvironmentId()]) as $row) {
         $result[$row['cloudServerId']] = $row;
     }
     foreach ($data as &$row) {
         if (!empty($row['cloudServerId']) && !empty($result[$row['cloudServerId']])) {
             $row = array_merge($row, $result[$row['cloudServerId']]);
         }
     }
 }
Example #3
0
 /**
  * Gets Default search criteria for the Environment scope
  *
  * @return array Returns array of the default search criteria for the Environment scope
  */
 private function getDefaultCriteria()
 {
     $server = new Server();
     $defaultCondition = sprintf("{$server->columnAccountId()} = %d AND {$server->columnEnvId()} = %d ", $this->getUser()->accountId, $this->getEnvironment()->id);
     $and = " AND {$server->columnFarmId()} IS NOT NULL ";
     if (!$this->hasPermissions(Acl::RESOURCE_FARMS)) {
         $where = [];
         $farm = new Farm();
         $farmTeam = new FarmTeam();
         $join[] = " LEFT JOIN {$farm->table('f')} ON {$farm->columnId('f')} = {$server->columnFarmId()}";
         if ($this->hasPermissions(Acl::RESOURCE_OWN_FARMS)) {
             $where[] = "{$farm->columnOwnerId('f')} = " . $farm->qstr('ownerId', $this->getUser()->id);
         }
         if ($this->hasPermissions(Acl::RESOURCE_TEAM_FARMS)) {
             $join[] = "\n                    LEFT JOIN {$farmTeam->table('ft')} ON {$farmTeam->columnFarmId('ft')} = {$farm->columnId('f')}\n                    LEFT JOIN `account_team_users` `atu` ON `atu`.`team_id` = {$farmTeam->columnTeamId('ft')}\n                    LEFT JOIN `account_team_envs` `ate` ON `ate`.`team_id` = {$farmTeam->columnTeamId('ft')} AND `ate`.`env_id` = {$farm->columnEnvId('f')}\n                ";
             $where[] = "`atu`.`user_id` = " . $farmTeam->db()->qstr($this->getUser()->id) . " AND `ate`.`team_id` IS NOT NULL";
         }
         if (!empty($where)) {
             $criteria[Farm::STMT_WHERE] = '(' . $defaultCondition . $and . ' AND ' . join(' OR ', $where) . ')';
         }
         $criteria[Farm::STMT_FROM] = $server->table() . implode(' ', $join);
     }
     // add Temporary and Importing Servers to response
     if ($this->hasPermissions(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_MANAGE)) {
         $extraCondition = sprintf("({$defaultCondition} AND {$server->columnFarmId()} IS NULL AND {$server->columnStatus()} IN ('%s', '%s'))", Server::STATUS_IMPORTING, Server::STATUS_TEMPORARY);
         if (empty($criteria[Farm::STMT_WHERE]) && $this->hasPermissions(Acl::RESOURCE_FARMS)) {
             $criteria[Farm::STMT_WHERE] = "(({$defaultCondition}{$and}) OR {$extraCondition})";
         } else {
             if (empty($criteria[Farm::STMT_WHERE])) {
                 $criteria[Farm::STMT_WHERE] = "{$extraCondition}";
             } else {
                 $criteria[Farm::STMT_WHERE] = "({$criteria[Farm::STMT_WHERE]} OR {$extraCondition})";
             }
         }
     }
     if (empty($criteria[Farm::STMT_WHERE])) {
         $criteria[Farm::STMT_WHERE] = $defaultCondition;
     }
     return $criteria;
 }
Example #4
0
File: Logs.php Project: scalr/scalr
 /**
  * @param   int         $farmId
  * @param   string      $serverId
  * @param   string      $eventId
  * @param   int         $scriptId
  * @param   string      $eventServerId
  * @param   int         $schedulerId
  * @param   string      $byDate
  * @param   string      $fromTime
  * @param   string      $toTime
  * @param   string      $status
  * @param   string      $event
  * @param   JsonData    $sort
  * @param   int         $start
  * @param   int         $limit
  * @param   string      $query
  * @throws  Scalr_Exception_Core
  * @throws  Scalr_Exception_InsufficientPermissions
  */
 public function xListOrchestrationLogsAction($farmId = 0, $serverId = '', $eventId = '', $scriptId = 0, $eventServerId = '', $schedulerId = 0, $byDate = '', $fromTime = '', $toTime = '', $status = '', $event = '', JsonData $sort, $start = 0, $limit = 20, $query = '')
 {
     $this->request->restrictAccess(Acl::RESOURCE_LOGS_ORCHESTRATION_LOGS);
     $o = new Entity\OrchestrationLog();
     $f = new Entity\Farm();
     $criteria = [Entity\Farm::STMT_FROM => "{$o->table()} JOIN {$f->table('f')} ON {$f->columnId('f')} = {$o->columnFarmId}", Entity\Farm::STMT_WHERE => $this->request->getFarmSqlQuery() . " AND {$f->columnEnvId('f')} = " . $this->db->qstr($this->getEnvironmentId())];
     if ($farmId) {
         $criteria[] = ['farmId' => $farmId];
     }
     if ($serverId) {
         $criteria[] = ['serverId' => $serverId];
     }
     if ($eventId) {
         $criteria[] = ['eventId' => $eventId];
     }
     if ($eventServerId) {
         $criteria[] = ['eventServerId' => $eventServerId];
     }
     if ($scriptId) {
         /* @var $script Script */
         $script = Script::findPk($scriptId);
         if ($script && $this->request->hasPermissions($script)) {
             $scriptName = preg_replace("/[^A-Za-z0-9]+/", "_", $script->name);
             $criteria[] = ['scriptName' => $scriptName];
         }
     }
     if ($query || $event) {
         $logEntity = new OrchestrationLog();
         $eventEntity = new Event();
         $criteria[AbstractEntity::STMT_FROM] = $criteria[AbstractEntity::STMT_FROM] . "\n                LEFT JOIN {$eventEntity->table('e')}\n                ON {$logEntity->columnEventId} = {$eventEntity->columnEventId('e')}\n            ";
         if ($event && $query) {
             $query = $this->db->qstr('%' . $query . '%');
             $criteria[AbstractEntity::STMT_WHERE] = $criteria[AbstractEntity::STMT_WHERE] . " AND (\n                    {$eventEntity->columnType('e')} = {$this->db->qstr($event)}\n                    OR ({$logEntity->columnType} LIKE {$query}\n                    AND {$logEntity->columnScriptName} LIKE {$query})\n                )";
         } else {
             if ($event) {
                 $criteria[AbstractEntity::STMT_WHERE] = $criteria[AbstractEntity::STMT_WHERE] . " AND (\n                    {$eventEntity->columnType('e')} = {$this->db->qstr($event)}\n                )";
             } else {
                 $query = $this->db->qstr('%' . $query . '%');
                 $criteria[AbstractEntity::STMT_WHERE] = $criteria[AbstractEntity::STMT_WHERE] . " AND (\n                    ({$eventEntity->columnType('e')} LIKE {$query}\n                    OR {$logEntity->columnType} LIKE {$query}\n                    OR {$logEntity->columnScriptName} LIKE {$query})\n                )";
             }
         }
     }
     if ($schedulerId) {
         $criteria[] = ['taskId' => $schedulerId];
     }
     if ($byDate) {
         try {
             $tz = $this->user->getSetting(Scalr_Account_User::SETTING_UI_TIMEZONE) ?: 'UTC';
             $tz = new DateTimeZone($tz);
             $dtS = new DateTime($byDate, $tz);
             $dtE = new DateTime($byDate, $tz);
             if ($fromTime) {
                 $dtS = DateTime::createFromFormat('Y-m-d H:i', "{$byDate} {$fromTime}", $tz);
             }
             if ($toTime) {
                 $dtE = DateTime::createFromFormat('Y-m-d H:i', "{$byDate} {$toTime}", $tz);
             } else {
                 $dtE = $dtE->add(new DateInterval('P1D'));
             }
             if ($dtS && $dtE) {
                 Scalr_Util_DateTime::convertTimeZone($dtS);
                 Scalr_Util_DateTime::convertTimeZone($dtE);
                 $criteria[] = ['added' => ['$gt' => $dtS]];
                 $criteria[] = ['added' => ['$lt' => $dtE]];
             }
         } catch (Exception $e) {
         }
     }
     if ($status === 'success') {
         $criteria[] = ['execExitCode' => 0];
     } else {
         if ($status === 'failure') {
             $criteria[] = ['execExitCode' => ['$ne' => 0]];
         }
     }
     $logs = OrchestrationLog::find($criteria, null, Scalr\UI\Utils::convertOrder($sort, ['id' => false], ['id', 'added']), $limit, $start, true);
     $data = $this->prepareOrchestrationLogData($logs);
     $this->response->data(['data' => $data, 'total' => $logs->totalNumber]);
 }
Example #5
0
 public function _timezone($from, $to, $action)
 {
     switch ($action) {
         case static::ACT_CONVERT_TO_OBJECT:
             /* @var $from Farm */
             $to->timezone = $from->settings[FarmSetting::TIMEZONE];
             break;
         case static::ACT_CONVERT_TO_ENTITY:
             /* @var $to Farm */
             if (!in_array($from->timezone, DateTimeZone::listIdentifiers())) {
                 throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Unknown timezone");
             }
             $to->settings[FarmSetting::TIMEZONE] = $from->timezone;
             break;
         case static::ACT_GET_FILTER_CRITERIA:
             $farm = new Farm();
             $farmSetting = new FarmSetting();
             return [AbstractEntity::STMT_FROM => $farm->table() . " LEFT JOIN " . $farmSetting->table() . " ON {$farmSetting->columnFarmId} = {$farm->columnId}", AbstractEntity::STMT_WHERE => "({$farmSetting->columnName} = '" . FarmSetting::TIMEZONE . "' AND {$farmSetting->columnValue} = " . $farmSetting->qstr('value', $from->timezone) . ")"];
     }
 }
Example #6
0
 /**
  * @param   int         $farmId
  * @param   int         $expirePeriod
  * @param   bool        $manageable
  * @param   string      $owner
  * @param   int         $chefServerId
  * @param   string      $projectId
  * @param   int         $status
  * @throws  Exception
  * @throws  Scalr_Exception_Core
  * @throws  Scalr_Exception_InsufficientPermissions
  */
 public function xListFarmsAction($farmId = null, $expirePeriod = null, $manageable = false, $owner = null, $chefServerId = null, $projectId = null, $status = null)
 {
     $this->request->restrictAccess([Acl::RESOURCE_FARMS, Acl::RESOURCE_TEAM_FARMS, Acl::RESOURCE_OWN_FARMS]);
     $governance = new Scalr_Governance($this->getEnvironmentId());
     $leaseStatus = $governance->isEnabled(Scalr_Governance::CATEGORY_GENERAL, Scalr_Governance::GENERAL_LEASE);
     $f = new Entity\Farm();
     $sql = "\n            SELECT {$f->fields('f')}, au.email AS ownerEmail,\n                (SELECT " . Entity\Farm::getUserTeamOwnershipSql($this->getUser()->id) . ") AS farmTeamIdPerm,\n                GROUP_CONCAT(DISTINCT at.name SEPARATOR ', ') AS farmTeams,\n                GROUP_CONCAT(DISTINCT behavior) AS behaviors,\n                (SELECT COUNT(*) FROM farm_roles WHERE farmid = f.id) AS rolesCnt,\n                (SELECT COUNT(*) FROM dns_zones WHERE farm_id = f.id) AS zonesCnt,\n                (SELECT COUNT(*) FROM server_alerts WHERE farm_id= f.id AND status = ?) AS alertsCnt,\n                (SELECT COUNT(*) FROM servers WHERE farm_id = f.id AND status IN (?,?,?,?,?)) AS runningServers,\n                (SELECT COUNT(*) FROM servers WHERE farm_id = f.id AND status IN (?,?)) AS suspendedServers,\n                (SELECT COUNT(*) FROM servers WHERE farm_id = f.id AND status IN (?,?)) AS nonRunningServers\n            FROM {$f->table('f')}\n            LEFT JOIN account_users au ON au.id = f.created_by_id\n            LEFT JOIN farm_teams ft ON ft.farm_id = {$f->columnId('f')}\n            LEFT JOIN account_teams at ON at.id = ft.team_id\n            LEFT JOIN farm_roles fr ON fr.farmid = {$f->columnId('f')}\n            LEFT JOIN role_behaviors rb ON rb.role_id = fr.role_id\n            WHERE {$f->columnEnvId('f')} = ?\n            AND :FILTER:\n            AND " . $this->request->getFarmSqlQuery($manageable ? Acl::PERM_FARMS_UPDATE : null);
     $args = [Entity\Server\Alert::STATUS_FAILED, Entity\Server::STATUS_PENDING, Entity\Server::STATUS_INIT, Entity\Server::STATUS_RUNNING, Entity\Server::STATUS_TEMPORARY, Entity\Server::STATUS_RESUMING, Entity\Server::STATUS_SUSPENDED, Entity\Server::STATUS_PENDING_SUSPEND, Entity\Server::STATUS_TERMINATED, Entity\Server::STATUS_PENDING_TERMINATE, $this->getEnvironmentId()];
     if ($leaseStatus && $expirePeriod) {
         $dt = new DateTime();
         $dt->add(new DateInterval('P' . $expirePeriod . 'D'));
         $sql .= " AND EXISTS (\n                        SELECT 1 FROM farm_settings\n                        WHERE farm_settings.farmid = f.id\n                        AND farm_settings.name = ?\n                        AND farm_settings.value != ''\n                        AND farm_settings.value < ?\n                    ) AND f.status = ?";
         $args[] = Entity\FarmSetting::LEASE_TERMINATE_DATE;
         $args[] = $dt->format('Y-m-d H:i:s');
         $args[] = Entity\Farm::STATUS_RUNNING;
     }
     if ($farmId) {
         $sql .= ' AND f.id = ?';
         $args[] = $farmId;
     }
     if ($owner) {
         if ($owner == 'me') {
             $sql .= " AND {$f->columnOwnerId('f')} = ?";
             $args[] = $this->getUser()->id;
         } else {
             if ($owner == 'team') {
                 $sql .= " AND " . Entity\Farm::getUserTeamOwnershipSql($this->getUser()->id);
             }
         }
     }
     if ($chefServerId) {
         $sql .= " AND f.id IN (\n                SELECT fr.farmid\n                FROM farm_roles fr\n                INNER JOIN farm_role_settings frs1 ON fr.id = frs1.farm_roleid AND frs1.name = ? AND frs1.value = ?\n                INNER JOIN farm_role_settings frs2 ON fr.id = frs2.farm_roleid AND frs2.name = ? AND frs2.value = ?\n            )";
         $args[] = \Scalr_Role_Behavior_Chef::ROLE_CHEF_SERVER_ID;
         $args[] = $chefServerId;
         $args[] = \Scalr_Role_Behavior_Chef::ROLE_CHEF_BOOTSTRAP;
         $args[] = 1;
     }
     if ($this->getContainer()->analytics->enabled && $projectId) {
         $sql .= " AND EXISTS (\n                SELECT 1 FROM farm_settings\n                WHERE farm_settings.farmid = f.id\n                AND farm_settings.name = " . $this->db->qstr(Entity\FarmSetting::PROJECT_ID) . "\n                AND farm_settings.value = ?) ";
         $args[] = $projectId;
     }
     $sql .= " GROUP BY {$f->columnId('f')}";
     $response = $this->buildResponseFromSql2($sql, array('id', 'name', 'dtadded', 'ownerEmail', 'status'), array('f.name', 'f.id', 'f.comments'), $args);
     foreach ($response["data"] as &$r) {
         $farm = new Entity\Farm();
         $farm->load($r);
         $row = get_object_vars($farm);
         $row['ownerEmail'] = $r['ownerEmail'];
         $row['farmTeams'] = $r['farmTeams'];
         $row['behaviors'] = $r['behaviors'];
         $row['rolesCnt'] = $r['rolesCnt'];
         $row['zonesCnt'] = $r['zonesCnt'];
         $row['alertsCnt'] = $r['alertsCnt'];
         $row['runningServers'] = $r['runningServers'];
         $row['suspendedServers'] = $r['suspendedServers'];
         $row['nonRunningServers'] = $r['nonRunningServers'];
         $row['added'] = Scalr_Util_DateTime::convertTz($farm->added);
         $row['lock'] = $farm->settings[Entity\FarmSetting::LOCK];
         if ($row['lock']) {
             try {
                 $farm->checkLocked();
             } catch (\Scalr\Exception\LockedException $e) {
                 $row['lockComment'] = $e->getMessage();
             }
         }
         if ($leaseStatus && $farm->settings[Entity\FarmSetting::LEASE_STATUS]) {
             $row['lease'] = $farm->settings[Entity\FarmSetting::LEASE_NOTIFICATION_SEND] ? 'Expire' : $farm->settings[Entity\FarmSetting::LEASE_STATUS];
             if ($row['lease'] == 'Expire') {
                 $dt = new DateTime();
                 $td = new DateTime($farm->settings[Entity\FarmSetting::LEASE_TERMINATE_DATE]);
                 $days = 0;
                 $hours = 1;
                 $interval = $dt->diff($td);
                 if ($interval) {
                     $days = $interval->days;
                     $hours = $interval->h ? $interval->h : 1;
                 }
                 $row['leaseMessage'] = sprintf('Your farm lease is about to expire in %d %s, after which this farm will be terminated', $days ? $days : $hours, $days ? $days > 1 ? 'days' : 'day' : ($hours > 1 ? 'hours' : 'hour'));
             }
         }
         $behaviors = explode(',', $row['behaviors']);
         $row["havemysqlrole"] = in_array(ROLE_BEHAVIORS::MYSQL, $behaviors);
         $row["havemysql2role"] = in_array(ROLE_BEHAVIORS::MYSQL2, $behaviors);
         $row["havepgrole"] = in_array(ROLE_BEHAVIORS::POSTGRESQL, $behaviors);
         $row["haveredisrole"] = in_array(ROLE_BEHAVIORS::REDIS, $behaviors);
         $row["haverabbitmqrole"] = in_array(ROLE_BEHAVIORS::RABBITMQ, $behaviors);
         $row["havemongodbrole"] = in_array(ROLE_BEHAVIORS::MONGODB, $behaviors);
         $row["haveperconarole"] = in_array(ROLE_BEHAVIORS::PERCONA, $behaviors);
         $row["havemariadbrole"] = in_array(ROLE_BEHAVIORS::MARIADB, $behaviors);
         $row['statusTxt'] = Entity\Farm::getStatusName($farm->status);
         if ($row['status'] == Entity\Farm::STATUS_RUNNING) {
             $row['shortcuts'] = [];
             foreach (\Scalr\Model\Entity\ScriptShortcut::find([['farmId' => $farm->id], ['farmRoleId' => null]]) as $shortcut) {
                 /* @var $shortcut \Scalr\Model\Entity\ScriptShortcut */
                 $row['shortcuts'][] = array('id' => $shortcut->id, 'name' => $shortcut->getScriptName());
             }
         }
         $row['farmOwnerIdPerm'] = $farm->ownerId && $this->getUser()->id == $farm->ownerId;
         $row['farmTeamIdPerm'] = !!$r['farmTeamIdPerm'];
         $r = $row;
     }
     $this->response->data($response);
 }
Example #7
0
File: Farm.php Project: scalr/scalr
 /**
  * Generate SQL query like "EXISTS(SELECT 1 FROM farm_teams .... WHERE ...) to check FARM_TEAMS permission.
  * Table `farms` should have alias `f`.
  * If farmId is set, when JOIN table farms to get envId from it.
  *
  * @param   int     $userId             Identifier of User
  * @param   int     $farmId optional    Identifier of Farm
  * @return  string
  */
 public static function getUserTeamOwnershipSql($userId, $farmId = null)
 {
     $farm = new Farm();
     $farmTeam = new FarmTeam();
     $accountTeamUser = new Account\TeamUser();
     $accountTeamEnv = new Account\TeamEnvs();
     $sql = "EXISTS(" . "SELECT 1 FROM {$farmTeam->table()}" . "JOIN {$accountTeamUser->table()} ON {$accountTeamUser->columnTeamId} = {$farmTeam->columnTeamId} " . "JOIN {$accountTeamEnv->table()} ON {$accountTeamEnv->columnTeamId} = {$farmTeam->columnTeamId} " . ($farmId ? "JOIN {$farm->table('f')} ON {$farmTeam->columnFarmId} = {$farm->columnId('f')}" : "") . "WHERE {$accountTeamEnv->columnEnvId()} = {$farm->columnEnvId('f')} " . "AND " . ($farmId ? "{$farm->columnId('f')} = " . $farm->db()->qstr($farmId) : "{$farm->columnId('f')} = {$farmTeam->columnFarmId}") . " " . "AND {$accountTeamUser->columnUserId} = " . $farm->db()->qstr($userId) . ")";
     return $sql;
 }
Example #8
0
 /**
  * @param   string  $query
  * @throws  Scalr_Exception_Core
  */
 public function xSearchResourcesAction($query)
 {
     if (trim($query) == '') {
         $this->response->data(['data' => []]);
         return;
     }
     $environments = $this->request->getScope() == ScopeInterface::SCOPE_ACCOUNT ? array_map(function ($r) {
         return $r['id'];
     }, $this->user->getEnvironments()) : [$this->getEnvironmentId()];
     $f = new Entity\Farm();
     $s = new Entity\Server();
     $fr = new Entity\FarmRole();
     $e = new Entity\Account\Environment();
     $at = new Entity\Account\Team();
     $sp = new Entity\Server\Property();
     $farmSql = [];
     $serverSql = [];
     $queryEnc = "%{$query}%";
     foreach ($environments as $envId) {
         $acl = $this->user->getAclRolesByEnvironment($envId);
         $isTermporaryServerPerm = $acl->isAllowed(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_BUILD) || $acl->isAllowed(Acl::RESOURCE_IMAGES_ENVIRONMENT, Acl::PERM_IMAGES_ENVIRONMENT_IMPORT);
         if ($acl->isAllowed(Acl::RESOURCE_FARMS)) {
             $farmSql[] = "{$f->columnEnvId} = {$envId}";
             if ($isTermporaryServerPerm) {
                 $serverSql[] = "{$s->columnEnvId} = {$envId}";
             } else {
                 $serverSql[] = "{$s->columnEnvId} = {$envId} AND {$s->columnFarmId} IS NOT NULL";
             }
         } else {
             $q = [];
             if ($acl->isAllowed(Acl::RESOURCE_TEAM_FARMS)) {
                 $t = array_map(function ($t) {
                     return $t['id'];
                 }, $this->user->getTeams());
                 if (count($t)) {
                     $q[] = "{$f->columnTeamId} IN (" . join(',', $t) . ")";
                 }
             }
             if ($acl->isAllowed(Acl::RESOURCE_OWN_FARMS)) {
                 $q[] = "{$f->columnCreatedById} = {$this->user->getId()}";
             }
             if (count($q)) {
                 $farmSql[] = "{$f->columnEnvId} = {$envId} AND (" . join(" OR ", $q) . ")";
             }
             if ($isTermporaryServerPerm) {
                 $q[] = "{$s->columnStatus} IN ('" . Entity\Server::STATUS_IMPORTING . "', '" . Entity\Server::STATUS_TEMPORARY . "') AND {$s->columnFarmId} IS NULL";
             }
             if (count($q)) {
                 $serverSql[] = "{$s->columnEnvId} = {$envId} AND (" . join(" OR ", $q) . ")";
             }
         }
     }
     $farms = [];
     if (count($farmSql)) {
         $farmStmt = $this->db->Execute("\n                SELECT {$f->columnId} AS id, {$f->columnName} AS name, {$f->columnEnvId} AS envId, {$f->columnStatus} AS status,\n                {$f->columnAdded} AS added, {$f->columnCreatedByEmail} AS createdByEmail, {$at->columnName} AS teamName, {$e->columnName} AS `envName`\n                FROM {$f->table()}\n                LEFT JOIN {$at->table()} ON {$at->columnId} = {$f->columnTeamId}\n                LEFT JOIN {$e->table()} ON {$f->columnEnvId} = {$e->columnId}\n                WHERE ({$f->columnName} LIKE ?) AND (" . join(" OR ", $farmSql) . ")", [$queryEnc]);
         while ($farm = $farmStmt->FetchRow()) {
             $farm['status'] = Entity\Farm::getStatusName($farm['status']);
             $farm['added'] = Scalr_Util_DateTime::convertTz($farm['added'], 'M j, Y H:i');
             $farms[] = ['entityName' => 'farm', 'envId' => $farm['envId'], 'envName' => $farm['envName'], 'matchField' => 'Name', 'matchValue' => $farm['name'], 'data' => $farm];
         }
     }
     $servers = [];
     if (count($serverSql)) {
         $serverStmt = $this->db->Execute("\n                SELECT {$s->columnServerId} AS serverId, {$s->columnFarmId} AS farmId, {$s->columnFarmRoleId} AS farmRoleId,\n                {$s->columnEnvId} AS envId, {$s->columnPlatform} AS platform, {$s->columnInstanceTypeName} AS instanceTypeName,\n                {$s->columnStatus} AS status, {$s->columnCloudLocation} AS cloudLocation, {$s->columnRemoteIp} AS publicIp,\n                {$s->columnLocalIp} AS privateIp, {$s->columnAdded} AS added, {$f->columnName} AS farmName,\n                {$fr->columnAlias} AS farmRoleName, {$e->columnName} AS `envName`, {$fr->columnRoleId} AS roleId,\n                {$sp->columnValue('sp1', 'hostname')}\n                FROM {$s->table()}\n                LEFT JOIN {$f->table()} ON {$f->columnId} = {$s->columnFarmId}\n                LEFT JOIN {$fr->table()} ON {$fr->columnId} = {$s->columnFarmRoleId}\n                LEFT JOIN {$e->table()} ON {$e->columnId} = {$s->columnEnvId}\n                LEFT JOIN {$sp->table('sp1')} ON {$sp->columnServerId('sp1')} = {$s->columnServerId} AND {$sp->columnName('sp1')} = ?\n                WHERE ({$s->columnRemoteIp} LIKE ? OR {$s->columnLocalIp} LIKE ? OR {$sp->columnValue('sp1')} LIKE ?) AND (" . join(" OR ", $serverSql) . ")\n                GROUP BY {$s->columnServerId}", [Scalr_Role_Behavior::SERVER_BASE_HOSTNAME, $queryEnc, $queryEnc, $queryEnc]);
         $names = ['publicIp' => 'Public IP', 'privateIp' => 'Private IP', 'hostname' => 'Hostname'];
         while ($server = $serverStmt->FetchRow()) {
             $server['added'] = Scalr_Util_DateTime::convertTz($server['added'], 'M j, Y H:i');
             if (strstr($server['publicIp'], $query)) {
                 $m = 'publicIp';
             } else {
                 if (strstr($server['privateIp'], $query)) {
                     $m = 'privateIp';
                 } else {
                     $m = 'hostname';
                 }
             }
             $servers[] = ['entityName' => 'server', 'envId' => $server['envId'], 'envName' => $server['envName'], 'matchField' => $names[$m], 'matchValue' => $server[$m], 'data' => $server];
         }
     }
     $this->response->data(['data' => array_merge($farms, $servers)]);
 }