Passed
Push — v3 ( 962004...bdfc5f )
by Austin
06:52
created

Teamspeak2::processResponse()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 46
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 46
ccs 20
cts 20
cp 1
rs 9.0444
cc 6
nc 6
nop 0
crap 6
1
<?php
2
/**
3
 * This file is part of GameQ.
4
 *
5
 * GameQ is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU Lesser General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * GameQ is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public License
16
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace GameQ\Protocols;
20
21
use GameQ\Protocol;
22
use GameQ\Buffer;
23
use GameQ\Result;
24
use GameQ\Server;
25
use GameQ\Exception\Protocol as Exception;
26
27
/**
28
 * Teamspeak 2 Protocol Class
29
 *
30
 * All values are utf8 encoded upon processing
31
 *
32
 * This code ported from GameQ v1/v2. Credit to original author(s) as I just updated it to
33
 * work within this new system.
34
 *
35
 * @author Austin Bischoff <[email protected]>
36
 */
37
class Teamspeak2 extends Protocol
38
{
39
40
    /**
41
     * Array of packets we want to look up.
42
     * Each key should correspond to a defined method in this or a parent class
43
     *
44
     * @type array
45
     */
46
    protected $packets = [
47
        self::PACKET_DETAILS  => "sel %d\x0asi\x0a",
48
        self::PACKET_CHANNELS => "sel %d\x0acl\x0a",
49
        self::PACKET_PLAYERS  => "sel %d\x0apl\x0a",
50
    ];
51
52
    /**
53
     * The transport mode for this protocol is TCP
54
     *
55
     * @type string
56
     */
57
    protected $transport = self::TRANSPORT_TCP;
58
59
    /**
60
     * The query protocol used to make the call
61
     *
62
     * @type string
63
     */
64
    protected $protocol = 'teamspeak2';
65
66
    /**
67
     * String name of this protocol class
68
     *
69
     * @type string
70
     */
71
    protected $name = 'teamspeak2';
72
73
    /**
74
     * Longer string name of this protocol class
75
     *
76
     * @type string
77
     */
78
    protected $name_long = "Teamspeak 2";
79
80
    /**
81
     * The client join link
82
     *
83
     * @type string
84
     */
85
    protected $join_link = "teamspeak://%s:%d/";
86
87
    /**
88
     * Normalize settings for this protocol
89
     *
90
     * @type array
91
     */
92
    protected $normalize = [
93
        // General
94
        'general' => [
95
            'dedicated'  => 'dedicated',
96
            'hostname'   => 'server_name',
97
            'password'   => 'server_password',
98
            'numplayers' => 'server_currentusers',
99
            'maxplayers' => 'server_maxusers',
100
        ],
101
        // Player
102
        'player'  => [
103
            'id'   => 'p_id',
104
            'team' => 'c_id',
105
            'name' => 'nick',
106
        ],
107
        // Team
108
        'team'    => [
109
            'id'   => 'id',
110
            'name' => 'name',
111
        ],
112
    ];
113
114
    /**
115
     * Before we send off the queries we need to update the packets
116
     *
117
     * @param \GameQ\Server $server
118
     *
119
     * @throws \GameQ\Exception\Protocol
120
     */
121 4
    public function beforeSend(Server $server)
122
    {
123
124
        // Check to make sure we have a query_port because it is required
125 4
        if (!isset($this->options[Server::SERVER_OPTIONS_QUERY_PORT])
126 4
            || empty($this->options[Server::SERVER_OPTIONS_QUERY_PORT])
127
        ) {
128 1
            throw new Exception(__METHOD__ . " Missing required setting '" . Server::SERVER_OPTIONS_QUERY_PORT . "'.");
129
        }
130
131
        // Let's loop the packets and set the proper pieces
132 3
        foreach ($this->packets as $packet_type => $packet) {
133
            // Update with the client port for the server
134 3
            $this->packets[$packet_type] = sprintf($packet, $server->portClient());
135
        }
136 3
    }
137
138
    /**
139
     * Process the response
140
     *
141
     * @return array
142
     * @throws \GameQ\Exception\Protocol
143
     */
144 2
    public function processResponse()
145
    {
146
147
        // Make a new buffer out of all of the packets
148 2
        $buffer = new Buffer(implode('', $this->packets_response));
149
150
        // Check the header [TS]
151 2
        if (($header = trim($buffer->readString("\n"))) !== '[TS]') {
152 1
            throw new Exception(__METHOD__ . " Expected header '{$header}' does not match expected '[TS]'.");
153
        }
154
155
        // Split this buffer as the data blocks are bound by "OK" and drop any empty values
156 1
        $sections = array_filter(explode("OK", $buffer->getBuffer()), function ($value) {
157
158 1
            $value = trim($value);
159
160 1
            return !empty($value);
161 1
        });
162
163
        // Trim up the values to remove extra whitespace
164 1
        $sections = array_map('trim', $sections);
165
166
        // Set the result to a new result instance
167 1
        $result = new Result();
168
169
        // Now we need to iterate over the sections and off load the processing
170 1
        foreach ($sections as $section) {
171
            // Grab a snip of the data so we can figure out what it is
172 1
            $check = substr($section, 0, 7);
173
174
            // Offload to the proper method
175 1
            if ($check == 'server_') {
176
                // Server settings and info
177 1
                $this->processDetails($section, $result);
178 1
            } elseif ($check == "id\tcode") {
179
                // Channel info
180 1
                $this->processChannels($section, $result);
181 1
            } elseif ($check == "p_id\tc_") {
182
                // Player info
183 1
                $this->processPlayers($section, $result);
184
            }
185
        }
186
187 1
        unset($buffer, $sections, $section, $check);
188
189 1
        return $result->fetch();
190
    }
191
192
    /*
193
     * Internal methods
194
     */
195
196
197
    /**
198
     * Handles processing the details data into a usable format
199
     *
200
     * @param string        $data
201
     * @param \GameQ\Result $result
202
     */
203 1
    protected function processDetails($data, Result &$result)
204
    {
205
206
        // Create a buffer
207 1
        $buffer = new Buffer($data);
208
209
        // Always dedicated
210 1
        $result->add('dedicated', 1);
211
212
        // Let's loop until we run out of data
213 1
        while ($buffer->getLength()) {
214
            // Grab the row, which is an item
215 1
            $row = trim($buffer->readString("\n"));
216
217
            // Split out the information
218 1
            list($key, $value) = explode('=', $row, 2);
219
220
            // Add this to the result
221 1
            $result->add($key, utf8_encode($value));
222
        }
223
224 1
        unset($data, $buffer, $row, $key, $value);
225 1
    }
226
227
    /**
228
     * Process the channel listing
229
     *
230
     * @param string        $data
231
     * @param \GameQ\Result $result
232
     */
233 1
    protected function processChannels($data, Result &$result)
234
    {
235
236
        // Create a buffer
237 1
        $buffer = new Buffer($data);
238
239
        // The first line holds the column names, data returned is in column/row format
240 1
        $columns = explode("\t", trim($buffer->readString("\n")), 9);
241
242
        // Loop through the rows until we run out of information
243 1
        while ($buffer->getLength()) {
244
            // Grab the row, which is a tabbed list of items
245 1
            $row = trim($buffer->readString("\n"));
246
247
            // Explode and merge the data with the columns, then parse
248 1
            $data = array_combine($columns, explode("\t", $row, 9));
249
250 1
            foreach ($data as $key => $value) {
251
                // Now add the data to the result
252 1
                $result->addTeam($key, utf8_encode($value));
253
            }
254
        }
255
256 1
        unset($data, $buffer, $row, $columns, $key, $value);
257 1
    }
258
259
    /**
260
     * Process the user listing
261
     *
262
     * @param string        $data
263
     * @param \GameQ\Result $result
264
     */
265 1
    protected function processPlayers($data, Result &$result)
266
    {
267
268
        // Create a buffer
269 1
        $buffer = new Buffer($data);
270
271
        // The first line holds the column names, data returned is in column/row format
272 1
        $columns = explode("\t", trim($buffer->readString("\n")), 16);
273
274
        // Loop through the rows until we run out of information
275 1
        while ($buffer->getLength()) {
276
            // Grab the row, which is a tabbed list of items
277 1
            $row = trim($buffer->readString("\n"));
278
279
            // Explode and merge the data with the columns, then parse
280 1
            $data = array_combine($columns, explode("\t", $row, 16));
281
282 1
            foreach ($data as $key => $value) {
283
                // Now add the data to the result
284 1
                $result->addPlayer($key, utf8_encode($value));
285
            }
286
        }
287
288 1
        unset($data, $buffer, $row, $columns, $key, $value);
289 1
    }
290
}
291