aurjson: Merge info and multiinfo commands
[aur.git] / web / lib / aurjson.class.php
blob2bf2e7a38c801e7ea82fdfb22f9d52f191ddfe52
1 <?php
3 include_once("aur.inc.php");
5 /*
6 * This class defines a remote interface for fetching data from the AUR using
7 * JSON formatted elements.
9 * @package rpc
10 * @subpackage classes
12 class AurJSON {
13 private $dbh = false;
14 private $version = 1;
15 private static $exposed_methods = array(
16 'search', 'info', 'multiinfo', 'msearch', 'suggest',
17 'suggest-pkgbase', 'get-comment-form'
19 private static $exposed_fields = array(
20 'name', 'name-desc', 'maintainer'
22 private static $fields_v1 = array(
23 'Packages.ID', 'Packages.Name',
24 'PackageBases.ID AS PackageBaseID',
25 'PackageBases.Name AS PackageBase', 'Version',
26 'Description', 'URL', 'NumVotes', 'OutOfDateTS AS OutOfDate',
27 'Users.UserName AS Maintainer',
28 'SubmittedTS AS FirstSubmitted', 'ModifiedTS AS LastModified',
29 'Licenses.Name AS License'
31 private static $fields_v2 = array(
32 'Packages.ID', 'Packages.Name',
33 'PackageBases.ID AS PackageBaseID',
34 'PackageBases.Name AS PackageBase', 'Version',
35 'Description', 'URL', 'NumVotes', 'OutOfDateTS AS OutOfDate',
36 'Users.UserName AS Maintainer',
37 'SubmittedTS AS FirstSubmitted', 'ModifiedTS AS LastModified'
39 private static $fields_v4 = array(
40 'Packages.ID', 'Packages.Name',
41 'PackageBases.ID AS PackageBaseID',
42 'PackageBases.Name AS PackageBase', 'Version',
43 'Description', 'URL', 'NumVotes', 'Popularity',
44 'OutOfDateTS AS OutOfDate', 'Users.UserName AS Maintainer',
45 'SubmittedTS AS FirstSubmitted', 'ModifiedTS AS LastModified'
47 private static $numeric_fields = array(
48 'ID', 'PackageBaseID', 'NumVotes', 'OutOfDate',
49 'FirstSubmitted', 'LastModified'
51 private static $decimal_fields = array(
52 'Popularity'
56 * Handles post data, and routes the request.
58 * @param string $post_data The post data to parse and handle.
60 * @return string The JSON formatted response data.
62 public function handle($http_data) {
64 * Unset global aur.inc.php Pragma header. We want to allow
65 * caching of data in proxies, but require validation of data
66 * (if-none-match) if possible.
68 header_remove('Pragma');
70 * Overwrite cache-control header set in aur.inc.php to allow
71 * caching, but require validation.
73 header('Cache-Control: public, must-revalidate, max-age=0');
74 header('Content-Type: application/json, charset=utf-8');
76 if (isset($http_data['v'])) {
77 $this->version = intval($http_data['v']);
79 if ($this->version < 1 || $this->version > 5) {
80 return $this->json_error('Invalid version specified.');
83 if (!isset($http_data['type']) || !isset($http_data['arg'])) {
84 return $this->json_error('No request type/data specified.');
86 if (!in_array($http_data['type'], self::$exposed_methods)) {
87 return $this->json_error('Incorrect request type specified.');
89 if (isset($http_data['search_by']) && !in_array($http_data['search_by'], self::$exposed_fields)) {
90 return $this->json_error('Incorrect search_by field specified.');
93 $this->dbh = DB::connect();
95 $type = str_replace('-', '_', $http_data['type']);
96 if ($type == 'info' && $this->version >= 5) {
97 $type = 'multiinfo';
99 $json = call_user_func(array(&$this, $type), $http_data);
101 $etag = md5($json);
102 header("Etag: \"$etag\"");
104 * Make sure to strip a few things off the
105 * if-none-match header. Stripping whitespace may not
106 * be required, but removing the quote on the incoming
107 * header is required to make the equality test.
109 $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ?
110 trim($_SERVER['HTTP_IF_NONE_MATCH'], "\t\n\r\" ") : false;
111 if ($if_none_match && $if_none_match == $etag) {
112 header('HTTP/1.1 304 Not Modified');
113 return;
116 if (isset($http_data['callback'])) {
117 $callback = $http_data['callback'];
118 if (!preg_match('/^[a-zA-Z0-9().]{1,128}$/D', $callback)) {
119 return $this->json_error('Invalid callback name.');
121 header('content-type: text/javascript');
122 return '/**/' . $callback . '(' . $json . ')';
123 } else {
124 header('content-type: application/json');
125 return $json;
130 * Returns a JSON formatted error string.
132 * @param $msg The error string to return
134 * @return mixed A json formatted error response.
136 private function json_error($msg) {
137 header('content-type: application/json');
138 if ($this->version < 3) {
139 return $this->json_results('error', 0, $msg, NULL);
140 } elseif ($this->version >= 3) {
141 return $this->json_results('error', 0, array(), $msg);
146 * Returns a JSON formatted result data.
148 * @param $type The response method type.
149 * @param $count The number of results to return
150 * @param $data The result data to return
151 * @param $error An error message to include in the response
153 * @return mixed A json formatted result response.
155 private function json_results($type, $count, $data, $error) {
156 $json_array = array(
157 'version' => $this->version,
158 'type' => $type,
159 'resultcount' => $count,
160 'results' => $data
163 if ($error) {
164 $json_array['error'] = $error;
167 return json_encode($json_array);
171 * Get extended package details (for info and multiinfo queries).
173 * @param $pkgid The ID of the package to retrieve details for.
175 * @return array An array containing package details.
177 private function get_extended_fields($pkgid) {
178 $query = "SELECT DependencyTypes.Name AS Type, " .
179 "PackageDepends.DepName AS Name, " .
180 "PackageDepends.DepCondition AS Cond " .
181 "FROM PackageDepends " .
182 "LEFT JOIN DependencyTypes " .
183 "ON DependencyTypes.ID = PackageDepends.DepTypeID " .
184 "WHERE PackageDepends.PackageID = " . $pkgid . " " .
185 "UNION SELECT RelationTypes.Name AS Type, " .
186 "PackageRelations.RelName AS Name, " .
187 "PackageRelations.RelCondition AS Cond " .
188 "FROM PackageRelations " .
189 "LEFT JOIN RelationTypes " .
190 "ON RelationTypes.ID = PackageRelations.RelTypeID " .
191 "WHERE PackageRelations.PackageID = " . $pkgid . " " .
192 "UNION SELECT 'groups' AS Type, Groups.Name, '' AS Cond " .
193 "FROM Groups INNER JOIN PackageGroups " .
194 "ON PackageGroups.PackageID = " . $pkgid . " " .
195 "AND PackageGroups.GroupID = Groups.ID " .
196 "UNION SELECT 'license' AS Type, Licenses.Name, '' AS Cond " .
197 "FROM Licenses INNER JOIN PackageLicenses " .
198 "ON PackageLicenses.PackageID = " . $pkgid . " " .
199 "AND PackageLicenses.LicenseID = Licenses.ID";
200 $result = $this->dbh->query($query);
202 if (!$result) {
203 return null;
206 $type_map = array(
207 'depends' => 'Depends',
208 'makedepends' => 'MakeDepends',
209 'checkdepends' => 'CheckDepends',
210 'optdepends' => 'OptDepends',
211 'conflicts' => 'Conflicts',
212 'provides' => 'Provides',
213 'replaces' => 'Replaces',
214 'groups' => 'Groups',
215 'license' => 'License',
217 $data = array();
218 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
219 $type = $type_map[$row['Type']];
220 $data[$type][] = $row['Name'] . $row['Cond'];
223 return $data;
227 * Retrieve package information (used in info, multiinfo, search and
228 * msearch requests).
230 * @param $type The request type.
231 * @param $where_condition An SQL WHERE-condition to filter packages.
233 * @return mixed Returns an array of package matches.
235 private function process_query($type, $where_condition) {
236 $max_results = config_get_int('options', 'max_rpc_results');
238 if ($this->version == 1) {
239 $fields = implode(',', self::$fields_v1);
240 $query = "SELECT {$fields} " .
241 "FROM Packages LEFT JOIN PackageBases " .
242 "ON PackageBases.ID = Packages.PackageBaseID " .
243 "LEFT JOIN Users " .
244 "ON PackageBases.MaintainerUID = Users.ID " .
245 "LEFT JOIN PackageLicenses " .
246 "ON PackageLicenses.PackageID = Packages.ID " .
247 "LEFT JOIN Licenses " .
248 "ON Licenses.ID = PackageLicenses.LicenseID " .
249 "WHERE ${where_condition} " .
250 "AND PackageBases.PackagerUID IS NOT NULL " .
251 "GROUP BY Packages.ID " .
252 "LIMIT $max_results";
253 } elseif ($this->version >= 2) {
254 if ($this->version == 2 || $this->version == 3) {
255 $fields = implode(',', self::$fields_v2);
256 } else if ($this->version == 4 || $this->version == 5) {
257 $fields = implode(',', self::$fields_v4);
259 $query = "SELECT {$fields} " .
260 "FROM Packages LEFT JOIN PackageBases " .
261 "ON PackageBases.ID = Packages.PackageBaseID " .
262 "LEFT JOIN Users " .
263 "ON PackageBases.MaintainerUID = Users.ID " .
264 "WHERE ${where_condition} " .
265 "AND PackageBases.PackagerUID IS NOT NULL " .
266 "LIMIT $max_results";
268 $result = $this->dbh->query($query);
270 if ($result) {
271 $resultcount = 0;
272 $search_data = array();
273 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
274 $resultcount++;
275 $row['URLPath'] = sprintf(config_get('options', 'snapshot_uri'), urlencode($row['PackageBase']));
276 if ($this->version < 4) {
277 $row['CategoryID'] = 1;
281 * Unfortunately, mysql_fetch_assoc() returns
282 * all fields as strings. We need to coerce
283 * numeric values into integers to provide
284 * proper data types in the JSON response.
286 foreach (self::$numeric_fields as $field) {
287 if (isset($row[$field])) {
288 $row[$field] = intval($row[$field]);
292 foreach (self::$decimal_fields as $field) {
293 if (isset($row[$field])) {
294 $row[$field] = floatval($row[$field]);
298 if ($this->version >= 2 && ($type == 'info' || $type == 'multiinfo')) {
299 $row = array_merge($row, $this->get_extended_fields($row['ID']));
302 if ($this->version < 3) {
303 if ($type == 'info') {
304 $search_data = $row;
305 break;
306 } else {
307 array_push($search_data, $row);
309 } elseif ($this->version >= 3) {
310 array_push($search_data, $row);
314 if ($resultcount === $max_results) {
315 return $this->json_error('Too many package results.');
318 return $this->json_results($type, $resultcount, $search_data, NULL);
319 } else {
320 return $this->json_results($type, 0, array(), NULL);
325 * Parse the args to the multiinfo function. We may have a string or an
326 * array, so do the appropriate thing. Within the elements, both * package
327 * IDs and package names are valid; sort them into the relevant arrays and
328 * escape/quote the names.
330 * @param array $args Query parameters.
332 * @return mixed An array containing 'ids' and 'names'.
334 private function parse_multiinfo_args($args) {
335 if (!is_array($args)) {
336 $args = array($args);
339 $id_args = array();
340 $name_args = array();
341 foreach ($args as $arg) {
342 if (!$arg) {
343 continue;
345 if (is_numeric($arg)) {
346 $id_args[] = intval($arg);
347 } else {
348 $name_args[] = $this->dbh->quote($arg);
352 return array('ids' => $id_args, 'names' => $name_args);
356 * Performs a fulltext mysql search of the package database.
358 * @param array $http_data Query parameters.
360 * @return mixed Returns an array of package matches.
362 private function search($http_data) {
363 $keyword_string = $http_data['arg'];
365 if (isset($http_data['search_by'])) {
366 $search_by = $http_data['search_by'];
367 } else {
368 $search_by = 'name-desc';
371 if ($search_by === 'name' || $search_by === 'name-desc') {
372 if (strlen($keyword_string) < 2) {
373 return $this->json_error('Query arg too small');
375 $keyword_string = $this->dbh->quote("%" . addcslashes($keyword_string, '%_') . "%");
377 if ($search_by === 'name') {
378 $where_condition = "(Packages.Name LIKE $keyword_string)";
379 } else if ($search_by === 'name-desc') {
380 $where_condition = "(Packages.Name LIKE $keyword_string OR ";
381 $where_condition .= "Description LIKE $keyword_string)";
383 } else if ($search_by === 'maintainer') {
384 if (empty($keyword_string)) {
385 $where_condition = "Users.ID is NULL";
386 } else {
387 $keyword_string = $this->dbh->quote($keyword_string);
388 $where_condition = "Users.Username = $keyword_string ";
392 return $this->process_query('search', $where_condition);
396 * Returns the info on a specific package.
398 * @param array $http_data Query parameters.
400 * @return mixed Returns an array of value data containing the package data
402 private function info($http_data) {
403 $pqdata = $http_data['arg'];
404 if (is_numeric($pqdata)) {
405 $where_condition = "Packages.ID = $pqdata";
406 } else {
407 $where_condition = "Packages.Name = " . $this->dbh->quote($pqdata);
410 return $this->process_query('info', $where_condition);
414 * Returns the info on multiple packages.
416 * @param array $http_data Query parameters.
418 * @return mixed Returns an array of results containing the package data
420 private function multiinfo($http_data) {
421 $pqdata = $http_data['arg'];
422 $args = $this->parse_multiinfo_args($pqdata);
423 $ids = $args['ids'];
424 $names = $args['names'];
426 if (!$ids && !$names) {
427 return $this->json_error('Invalid query arguments');
430 $where_condition = "";
431 if ($ids) {
432 $ids_value = implode(',', $args['ids']);
433 $where_condition .= "Packages.ID IN ($ids_value) ";
435 if ($ids && $names) {
436 $where_condition .= "OR ";
438 if ($names) {
440 * Individual names were quoted in
441 * parse_multiinfo_args().
443 $names_value = implode(',', $args['names']);
444 $where_condition .= "Packages.Name IN ($names_value) ";
447 return $this->process_query('multiinfo', $where_condition);
451 * Returns all the packages for a specific maintainer.
453 * @param array $http_data Query parameters.
455 * @return mixed Returns an array of value data containing the package data
457 private function msearch($http_data) {
458 $http_data['search_by'] = 'maintainer';
459 return $this->search($http_data);
463 * Get all package names that start with $search.
465 * @param array $http_data Query parameters.
467 * @return string The JSON formatted response data.
469 private function suggest($http_data) {
470 $search = $http_data['arg'];
471 $query = "SELECT Packages.Name FROM Packages ";
472 $query.= "LEFT JOIN PackageBases ";
473 $query.= "ON PackageBases.ID = Packages.PackageBaseID ";
474 $query.= "WHERE Packages.Name LIKE ";
475 $query.= $this->dbh->quote(addcslashes($search, '%_') . '%');
476 $query.= " AND PackageBases.PackagerUID IS NOT NULL ";
477 $query.= "ORDER BY Name ASC LIMIT 20";
479 $result = $this->dbh->query($query);
480 $result_array = array();
482 if ($result) {
483 $result_array = $result->fetchAll(PDO::FETCH_COLUMN, 0);
486 return json_encode($result_array);
490 * Get all package base names that start with $search.
492 * @param array $http_data Query parameters.
494 * @return string The JSON formatted response data.
496 private function suggest_pkgbase($http_data) {
497 $search = $http_data['arg'];
498 $query = "SELECT Name FROM PackageBases WHERE Name LIKE ";
499 $query.= $this->dbh->quote(addcslashes($search, '%_') . '%');
500 $query.= " AND PackageBases.PackagerUID IS NOT NULL ";
501 $query.= "ORDER BY Name ASC LIMIT 20";
503 $result = $this->dbh->query($query);
504 $result_array = array();
506 if ($result) {
507 $result_array = $result->fetchAll(PDO::FETCH_COLUMN, 0);
510 return json_encode($result_array);
514 * Get the HTML markup of the comment form.
516 * @param array $http_data Query parameters.
518 * @return string The JSON formatted response data.
520 private function get_comment_form($http_data) {
521 if (!isset($http_data['base_id']) || !isset($http_data['pkgbase_name'])) {
522 $output = array(
523 'success' => 0,
524 'error' => __('Package base ID or package base name missing.')
526 return json_encode($output);
529 $comment_id = intval($http_data['arg']);
530 $base_id = intval($http_data['base_id']);
531 $pkgbase_name = $http_data['pkgbase_name'];
533 list($user_id, $comment) = comment_by_id($comment_id);
535 if (!has_credential(CRED_COMMENT_EDIT, array($user_id))) {
536 $output = array(
537 'success' => 0,
538 'error' => __('You are not allowed to edit this comment.')
540 return json_encode($output);
541 } elseif (is_null($comment)) {
542 $output = array(
543 'success' => 0,
544 'error' => __('Comment does not exist.')
546 return json_encode($output);
549 ob_start();
550 include('pkg_comment_form.php');
551 $html = ob_get_clean();
552 $output = array(
553 'success' => 1,
554 'form' => $html
557 return json_encode($output);