-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathBugzillaQuery.class.php
461 lines (382 loc) · 12.9 KB
/
BugzillaQuery.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
<?php
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
// Factory class
class BugzillaQuery
{
public static function create($type, $options, $title)
{
global $wgBugzillaMethod;
switch (strtolower($wgBugzillaMethod)) {
case 'xml-rpc':
return new BugzillaXMLRPCQuery ($type, $options, $title);
case 'json-rpc':
return new BugzillaJSONRPCQuery($type, $options, $title);
default:
return new BugzillaRESTQuery ($type, $options, $title);
}
}
}
// Base class
abstract class BugzillaBaseQuery
{
public function __construct($type, $options, $title)
{
global $wgBugzillaDefaultFields;
$this->type = $type;
$this->title = $title;
$this->url = FALSE;
$this->id = FALSE;
$this->error = FALSE;
$this->data = array();
$this->synthetic_fields = array();
$this->cached = FALSE;
$this->options = $this->prepare_options($options, $wgBugzillaDefaultFields);
}
public function id()
{
if (!$this->id) {
$this->id = $this->_generate_id($this->options);
}
return $this->id;
}
protected function _build_querystring_pair($key, $val)
{
return urlencode($key) . "=" . urlencode($val);
}
protected function _build_querystring($params)
{
$buffer = array();
foreach ($params as $param_key => $param_val) {
if (is_array($param_val)) {
foreach ($param_val as $i => $v) {
if (!is_int($i)) {
# error handling here would be nice, but I'm not sure what mediawiki expects.
continue;
}
$buffer [] = $this->_build_querystring_pair($param_key, $v);
}
} else {
$buffer [] = $this->_build_querystring_pair($param_key, $param_val);
}
}
return join("&", $buffer);
}
/**
*
* @param Array $options
* @return String|false
*
* FIXME: Should we strtolower() the keys?
*/
protected function _generate_id($options)
{
// No need to generate if there are errors
if (!empty($this->error)) {
return false;
}
ksort($options);
$options['include_fields'] = $this->rebase_fields(
$options['include_fields'],
$this->synthetic_fields
);
return sha1(serialize($options));
}
/**
* A query to the remote API will always contain at least,
* $synthetic_fields.
* So, whatever fields are requested, we just make sure:
* - all synthetic fields are included,
* - there's no duplicate,
* - fields are ordered,
* so that we reduce unnecessary queries to API.
*
* For instance, for synthetic (A, B) fields, actual queries on
* (A), (A,B), (B) will anyway lead to a query for (A, B).
*
* See BugzillaQueryTest::testRebaseFields().
*
* @param Array $requested_fields
* @param $synthetic_fields
* @return Array
*/
public function rebase_fields(array $requested_fields, $synthetic_fields): array
{
$fields = array_unique(array_merge($synthetic_fields, $requested_fields));
sort($fields);
return $fields;
}
public function rebased_options(): array
{
$options = $this->options;
$options['include_fields'] = $this->rebase_fields(
$options['include_fields'],
$this->synthetic_fields
);
return $options;
}
/**
* Wrap around sub-classes actual fetch action, with caching.
* Uses MediaWiki main cache strategy.
*
* @return string
*/
public function fetch()
{
global $wgMainCacheType;
global $wgBugzillaCacheTimeOut;
if ($this->error) {
return;
}
$key = implode(':', ['mediawiki', 'bugzilla', 'bugs', sha1(serialize($this->id()))]);
// TODO: since 1.43; use ObjectCacheFactory::getInstance instead.
$cache = ObjectCache::getInstance($wgMainCacheType);
$row = $cache->get($key);
if ($row === false) {
$this->cached = false;
$this->_fetch_by_options();
$cache->set($key, base64_encode(serialize($this->data)), $wgBugzillaCacheTimeOut * 60);
return $this->data;
} else {
$this->cached = true;
return $this->data = unserialize(base64_decode($row));
}
}
/**
* Parse/prepare query options
* and set appropriate, working defaults.
*
* See BugzillaQueryTest::testPrepareOptions().
*
* @param String $query_options_raw
* @param array $default_fields
* @return array prepared options array
*/
public function prepare_options(string $query_options_raw, array $default_fields = array())
{
$options = array();
$query_options_raw = trim($query_options_raw);
// if no query is provided, at least set a working default
// so that first experience is nicer than an error message.
if (!$query_options_raw) {
$options['include_fields'] = $default_fields;
} else {
$options = json_decode($query_options_raw, true);
if ($options === null) {
$this->error = 'Query options must be valid JSON.';
return $options;
}
if (empty($options['include_fields'])) {
$options['include_fields'] = $default_fields;
}
}
// It happens that some define it as:
// - either {"include_fields": "A,B,C"}
// - either {"include_fields": ["A", "B", "C"]}
// so we accept both.
if (!is_array($options['include_fields'])) {
$options['include_fields'] = preg_split("/\\s*,\\s*/", $options['include_fields']);
}
return $options;
}
abstract public function _fetch_by_options();
protected function _update_cache()
{
$cache = $this->_getCache();
$cache->set($this->id(), base64_encode(serialize($this->data)));
}
public function full_query_url(): string
{
global $wgBugzillaURL;
return $wgBugzillaURL . '/buglist.cgi?' . $this->_build_querystring($this->options);
}
}
class BugzillaRESTQuery extends BugzillaBaseQuery
{
function __construct($type, $options, $title = '')
{
global $wgBugzillaRESTURL;
global $wgBugzillaDefaultFields;
parent::__construct($type, $options, $title);
// See what sort of REST query we are going to
switch ($type) {
// Whitelist
case 'count':
$this->url = $wgBugzillaRESTURL . '/' . urlencode($type);
// Note there are no synthetic fields for count
break;
// Default to a bug query
case 'bug':
default:
$this->url = $wgBugzillaRESTURL . '/bug';
// Even if the user didn't specify, we need these
$this->synthetic_fields = $wgBugzillaDefaultFields;
}
}
public function user_agent()
{
global $wgBugzillaExtVersion;
global $wgVersion;
return 'MediawikiBugzilla/' . $wgBugzillaExtVersion
. ' MediaWiki/' . $wgVersion
. ' PHP/' . PHP_VERSION;
}
// Load data from the Bugzilla REST API
public function _fetch_by_options()
{
// Add the requested query options to the request
$ua = MWHttpRequest::factory($this->url . '?'
. $this->_build_querystring($this->options),
[
'method' => 'GET',
'follow_redirects' => true,
// TODO: Not sure if I should do this
'ssl_verify_peer' => false
], __METHOD__);
// The REST API requires these
$ua->setHeader('Accept', 'application/json');
$ua->setHeader('Content-Type', 'application/json');
try {
$response = $ua->execute();
if (200 == $ua->getStatus()) {
$this->data = json_decode($ua->getContent(), TRUE);
} else {
$errors = $response->getStatusValue()->getErrors();
$this->error = $errors[0];
return;
}
} catch (MWException $e) {
$this->error = $e->getMessage();
return;
}
// Check for REST API errors
if (isset($this->data['error']) && !empty($this->data['error'])) {
$this->error = "Bugzilla API returned an error: " .
$this->data['message'];
}
}
}
/**
*/
class BugzillaJSONRPCQuery extends BugzillaBaseQuery
{
function __construct($type, $options, $title = '')
{
global $wgBugzillaURL;
global $wgBugzillaDefaultFields;
// add include_fields
parent::__construct($type, $options, $title);
$this->url = $wgBugzillaURL . '/jsonrpc.cgi';
// See what sort of REST query we are going to
switch ($type) {
// Whitelist
case 'count':
$this->error = "Type count is not supported yet";
break;
// Default to a bug query
case 'bug':
default:
$this->synthetic_fields = $wgBugzillaDefaultFields;
break;
}
}
// Load data from the Bugzilla JSONRPC API
public function _fetch_by_options()
{
$this->getJsonData('Bug.search', $this->rebased_options());
}
protected function getJsonData($method, $params): bool
{
$query = json_encode($params, true);
$url = $this->url . "?method=$method¶ms=[" . urlencode($query) . "]";
$req = MWHttpRequest::factory($url, array(
'sslVerifyHost' => false,
'sslVerifyCert' => false
)
);
$status = $req->execute();
if (!$status->isOK()) {
$this->error = $req->getMessage();
return false;
} else {
$this->rawData = $req->getContent();
$params = json_decode($this->rawData, true);
$this->data = $params['result'];
return true;
}
}
}
/**
*/
class BugzillaXMLRPCQuery extends BugzillaBaseQuery
{
function __construct($type, $options, $title = '')
{
global $wgBugzillaURL;
global $wgBugzillaDefaultFields;
parent::__construct($type, $options, $title);
$this->url = $wgBugzillaURL . '/xmlrpc.cgi';
}
// Load data from the Bugzilla XMLRPC API
public function _fetch_by_options()
{
$method = 'Bug.search';
$struct = '';
foreach ($this->options as $k => $v)
$struct .= sprintf('<member><name>%s</name><value><%s>%s</%s></value></member>' . "\n",
$k, 'string', $v, 'string');
$xml = <<<X
<?xml version="1.0" encoding="utf-8"?>
<methodCall>
<methodName>{$method}</methodName>
<params>
<param>
<struct>
{$struct}
</struct>
</param>
</params>
</methodCall>
X;
$ua = MWHttpRequest::factory($this->url, [
'method' => 'POST',
'follow_redirects' => true,
// TODO: Not sure if I should do this
'ssl_verify_peer' => false
], __METHOD__);
$ua->setHeader('Accept', 'text/xml');
$ua->setHeader('Content-Type', 'text/xml;charset=utf-8');
$ua->setBody($xml);
try {
$response = $ua->execute();
if (200 == $ua->getStatus()) {
$x = simplexml_load_string($ua->getContent());
$this->data['bugs'] = array();
// FIXME there must be a better way
foreach ($x->params->param->value->struct->member->value->array->data->value as $b) {
$bug = array();
foreach ($b->struct->member as $m) {
if ($m->name == 'internals') {
continue;
}
$value = (array)$m->value;
$bug[(string)$m->name] = (string)array_shift($value);
}
$this->data['bugs'][] = $bug;
}
} else {
$errors = $response->getStatusValue()->getErrors();
$this->error = $errors[0];
return;
}
} catch (MWException $e) {
$this->error = $e->getMessage();
return;
}
if (isset($this->data['error']) && !empty($this->data['error'])) {
$this->error = "Bugzilla API returned an error: " .
$this->data['message'];
}
}
}