aurjson.class.php: Sync error message with front-end
[aur.git] / web / lib / aurjson.class.php
blobdb9cc5471b506792a5be210959fcc8eed25d9e9b
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'
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 > 4) {
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 $json = call_user_func(array(&$this, $type), $http_data);
98 $etag = md5($json);
99 header("Etag: \"$etag\"");
101 * Make sure to strip a few things off the
102 * if-none-match header. Stripping whitespace may not
103 * be required, but removing the quote on the incoming
104 * header is required to make the equality test.
106 $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ?
107 trim($_SERVER['HTTP_IF_NONE_MATCH'], "\t\n\r\" ") : false;
108 if ($if_none_match && $if_none_match == $etag) {
109 header('HTTP/1.1 304 Not Modified');
110 return;
113 if (isset($http_data['callback'])) {
114 $callback = $http_data['callback'];
115 if (!preg_match('/^[a-zA-Z0-9().]{1,128}$/D', $callback)) {
116 return $this->json_error('Invalid callback name.');
118 header('content-type: text/javascript');
119 return '/**/' . $callback . '(' . $json . ')';
120 } else {
121 header('content-type: application/json');
122 return $json;
127 * Returns a JSON formatted error string.
129 * @param $msg The error string to return
131 * @return mixed A json formatted error response.
133 private function json_error($msg) {
134 header('content-type: application/json');
135 if ($this->version < 3) {
136 return $this->json_results('error', 0, $msg, NULL);
137 } elseif ($this->version >= 3) {
138 return $this->json_results('error', 0, array(), $msg);
143 * Returns a JSON formatted result data.
145 * @param $type The response method type.
146 * @param $count The number of results to return
147 * @param $data The result data to return
148 * @param $error An error message to include in the response
150 * @return mixed A json formatted result response.
152 private function json_results($type, $count, $data, $error) {
153 $json_array = array(
154 'version' => $this->version,
155 'type' => $type,
156 'resultcount' => $count,
157 'results' => $data
160 if ($error) {
161 $json_array['error'] = $error;
164 return json_encode($json_array);
168 * Get extended package details (for info and multiinfo queries).
170 * @param $pkgid The ID of the package to retrieve details for.
172 * @return array An array containing package details.
174 private function get_extended_fields($pkgid) {
175 $query = "SELECT DependencyTypes.Name AS Type, " .
176 "PackageDepends.DepName AS Name, " .
177 "PackageDepends.DepCondition AS Cond " .
178 "FROM PackageDepends " .
179 "LEFT JOIN DependencyTypes " .
180 "ON DependencyTypes.ID = PackageDepends.DepTypeID " .
181 "WHERE PackageDepends.PackageID = " . $pkgid . " " .
182 "UNION SELECT RelationTypes.Name AS Type, " .
183 "PackageRelations.RelName AS Name, " .
184 "PackageRelations.RelCondition AS Cond " .
185 "FROM PackageRelations " .
186 "LEFT JOIN RelationTypes " .
187 "ON RelationTypes.ID = PackageRelations.RelTypeID " .
188 "WHERE PackageRelations.PackageID = " . $pkgid . " " .
189 "UNION SELECT 'groups' AS Type, Groups.Name, '' AS Cond " .
190 "FROM Groups INNER JOIN PackageGroups " .
191 "ON PackageGroups.PackageID = " . $pkgid . " " .
192 "AND PackageGroups.GroupID = Groups.ID " .
193 "UNION SELECT 'license' AS Type, Licenses.Name, '' AS Cond " .
194 "FROM Licenses INNER JOIN PackageLicenses " .
195 "ON PackageLicenses.PackageID = " . $pkgid . " " .
196 "AND PackageLicenses.LicenseID = Licenses.ID";
197 $result = $this->dbh->query($query);
199 if (!$result) {
200 return null;
203 $type_map = array(
204 'depends' => 'Depends',
205 'makedepends' => 'MakeDepends',
206 'checkdepends' => 'CheckDepends',
207 'optdepends' => 'OptDepends',
208 'conflicts' => 'Conflicts',
209 'provides' => 'Provides',
210 'replaces' => 'Replaces',
211 'groups' => 'Groups',
212 'license' => 'License',
214 $data = array();
215 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
216 $type = $type_map[$row['Type']];
217 $data[$type][] = $row['Name'] . $row['Cond'];
220 return $data;
224 * Retrieve package information (used in info, multiinfo, search and
225 * msearch requests).
227 * @param $type The request type.
228 * @param $where_condition An SQL WHERE-condition to filter packages.
230 * @return mixed Returns an array of package matches.
232 private function process_query($type, $where_condition) {
233 $max_results = config_get_int('options', 'max_rpc_results');
235 if ($this->version == 1) {
236 $fields = implode(',', self::$fields_v1);
237 $query = "SELECT {$fields} " .
238 "FROM Packages LEFT JOIN PackageBases " .
239 "ON PackageBases.ID = Packages.PackageBaseID " .
240 "LEFT JOIN Users " .
241 "ON PackageBases.MaintainerUID = Users.ID " .
242 "LEFT JOIN PackageLicenses " .
243 "ON PackageLicenses.PackageID = Packages.ID " .
244 "LEFT JOIN Licenses " .
245 "ON Licenses.ID = PackageLicenses.LicenseID " .
246 "WHERE ${where_condition} " .
247 "AND PackageBases.PackagerUID IS NOT NULL " .
248 "GROUP BY Packages.ID " .
249 "LIMIT $max_results";
250 } elseif ($this->version >= 2) {
251 if ($this->version == 2 || $this->version == 3) {
252 $fields = implode(',', self::$fields_v2);
253 } else if ($this->version == 4) {
254 $fields = implode(',', self::$fields_v4);
256 $query = "SELECT {$fields} " .
257 "FROM Packages LEFT JOIN PackageBases " .
258 "ON PackageBases.ID = Packages.PackageBaseID " .
259 "LEFT JOIN Users " .
260 "ON PackageBases.MaintainerUID = Users.ID " .
261 "WHERE ${where_condition} " .
262 "AND PackageBases.PackagerUID IS NOT NULL " .
263 "LIMIT $max_results";
265 $result = $this->dbh->query($query);
267 if ($result) {
268 $resultcount = 0;
269 $search_data = array();
270 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
271 $resultcount++;
272 $row['URLPath'] = sprintf(config_get('options', 'snapshot_uri'), urlencode($row['PackageBase']));
273 if ($this->version < 4) {
274 $row['CategoryID'] = 1;
278 * Unfortunately, mysql_fetch_assoc() returns
279 * all fields as strings. We need to coerce
280 * numeric values into integers to provide
281 * proper data types in the JSON response.
283 foreach (self::$numeric_fields as $field) {
284 if (isset($row[$field])) {
285 $row[$field] = intval($row[$field]);
289 foreach (self::$decimal_fields as $field) {
290 if (isset($row[$field])) {
291 $row[$field] = floatval($row[$field]);
295 if ($this->version >= 2 && ($type == 'info' || $type == 'multiinfo')) {
296 $row = array_merge($row, $this->get_extended_fields($row['ID']));
299 if ($this->version < 3) {
300 if ($type == 'info') {
301 $search_data = $row;
302 break;
303 } else {
304 array_push($search_data, $row);
306 } elseif ($this->version >= 3) {
307 array_push($search_data, $row);
311 if ($resultcount === $max_results) {
312 return $this->json_error('Too many package results.');
315 return $this->json_results($type, $resultcount, $search_data, NULL);
316 } else {
317 return $this->json_results($type, 0, array(), NULL);
322 * Parse the args to the multiinfo function. We may have a string or an
323 * array, so do the appropriate thing. Within the elements, both * package
324 * IDs and package names are valid; sort them into the relevant arrays and
325 * escape/quote the names.
327 * @param array $http_data Query parameters.
329 * @return mixed An array containing 'ids' and 'names'.
331 private function parse_multiinfo_args($http_data) {
332 $args = $http_data['arg'];
333 if (!is_array($args)) {
334 $args = array($args);
337 $id_args = array();
338 $name_args = array();
339 foreach ($args as $arg) {
340 if (!$arg) {
341 continue;
343 if (is_numeric($arg)) {
344 $id_args[] = intval($arg);
345 } else {
346 $name_args[] = $this->dbh->quote($arg);
350 return array('ids' => $id_args, 'names' => $name_args);
354 * Performs a fulltext mysql search of the package database.
356 * @param array $http_data Query parameters.
358 * @return mixed Returns an array of package matches.
360 private function search($http_data) {
361 $keyword_string = $http_data['arg'];
362 if (isset($http_data['search_by'])) {
363 $search_by = $http_data['search_by'];
364 } else {
365 $search_by = 'name-desc';
368 if (strlen($keyword_string) < 2) {
369 return $this->json_error('Query arg too small');
372 $keyword_string = $this->dbh->quote("%" . addcslashes($keyword_string, '%_') . "%");
374 if ($search_by === 'name') {
375 $where_condition = "(Packages.Name LIKE $keyword_string)";
376 } else if ($search_by === 'name-desc') {
377 $where_condition = "(Packages.Name LIKE $keyword_string OR ";
378 $where_condition .= "Description LIKE $keyword_string)";
381 return $this->process_query('search', $where_condition);
385 * Returns the info on a specific package.
387 * @param array $http_data Query parameters.
389 * @return mixed Returns an array of value data containing the package data
391 private function info($http_data) {
392 $pqdata = $http_data['arg'];
393 if (is_numeric($pqdata)) {
394 $where_condition = "Packages.ID = $pqdata";
395 } else {
396 $where_condition = "Packages.Name = " . $this->dbh->quote($pqdata);
399 return $this->process_query('info', $where_condition);
403 * Returns the info on multiple packages.
405 * @param array $http_data Query parameters.
407 * @return mixed Returns an array of results containing the package data
409 private function multiinfo($http_data) {
410 $pqdata = $http_data['arg'];
411 $args = $this->parse_multiinfo_args($pqdata);
412 $ids = $args['ids'];
413 $names = $args['names'];
415 if (!$ids && !$names) {
416 return $this->json_error('Invalid query arguments');
419 $where_condition = "";
420 if ($ids) {
421 $ids_value = implode(',', $args['ids']);
422 $where_condition .= "Packages.ID IN ($ids_value) ";
424 if ($ids && $names) {
425 $where_condition .= "OR ";
427 if ($names) {
429 * Individual names were quoted in
430 * parse_multiinfo_args().
432 $names_value = implode(',', $args['names']);
433 $where_condition .= "Packages.Name IN ($names_value) ";
436 return $this->process_query('multiinfo', $where_condition);
440 * Returns all the packages for a specific maintainer.
442 * @param array $http_data Query parameters.
444 * @return mixed Returns an array of value data containing the package data
446 private function msearch($http_data) {
447 $maintainer = $http_data['arg'];
449 if (empty($maintainer)) {
450 $where_condition = "Users.ID is NULL";
451 } else {
452 $maintainer = $this->dbh->quote($maintainer);
453 $where_condition = "Users.Username = $maintainer ";
456 return $this->process_query('msearch', $where_condition);
460 * Get all package names that start with $search.
462 * @param array $http_data Query parameters.
464 * @return string The JSON formatted response data.
466 private function suggest($http_data) {
467 $search = $http_data['arg'];
468 $query = "SELECT Packages.Name FROM Packages ";
469 $query.= "LEFT JOIN PackageBases ";
470 $query.= "ON PackageBases.ID = Packages.PackageBaseID ";
471 $query.= "WHERE Packages.Name LIKE ";
472 $query.= $this->dbh->quote(addcslashes($search, '%_') . '%');
473 $query.= " AND PackageBases.PackagerUID IS NOT NULL ";
474 $query.= "ORDER BY Name ASC LIMIT 20";
476 $result = $this->dbh->query($query);
477 $result_array = array();
479 if ($result) {
480 $result_array = $result->fetchAll(PDO::FETCH_COLUMN, 0);
483 return json_encode($result_array);
487 * Get all package base names that start with $search.
489 * @param array $http_data Query parameters.
491 * @return string The JSON formatted response data.
493 private function suggest_pkgbase($http_data) {
494 $search = $http_data['arg'];
495 $query = "SELECT Name FROM PackageBases WHERE Name LIKE ";
496 $query.= $this->dbh->quote(addcslashes($search, '%_') . '%');
497 $query.= " AND PackageBases.PackagerUID IS NOT NULL ";
498 $query.= "ORDER BY Name ASC LIMIT 20";
500 $result = $this->dbh->query($query);
501 $result_array = array();
503 if ($result) {
504 $result_array = $result->fetchAll(PDO::FETCH_COLUMN, 0);
507 return json_encode($result_array);
511 * Get the HTML markup of the comment form.
513 * @param array $http_data Query parameters.
515 * @return string The JSON formatted response data.
517 private function get_comment_form($http_data) {
518 if (!isset($http_data['base_id']) || !isset($http_data['pkgbase_name'])) {
519 $output = array(
520 'success' => 0,
521 'error' => __('Package base ID or package base name missing.')
523 return json_encode($output);
526 $comment_id = intval($http_data['arg']);
527 $base_id = intval($http_data['base_id']);
528 $pkgbase_name = $http_data['pkgbase_name'];
530 list($user_id, $comment) = comment_by_id($comment_id);
532 if (!has_credential(CRED_COMMENT_EDIT, array($user_id))) {
533 $output = array(
534 'success' => 0,
535 'error' => __('You are not allowed to edit this comment.')
537 return json_encode($output);
538 } elseif (is_null($comment)) {
539 $output = array(
540 'success' => 0,
541 'error' => __('Comment does not exist.')
543 return json_encode($output);
546 ob_start();
547 include('pkg_comment_form.php');
548 $html = ob_get_clean();
549 $output = array(
550 'success' => 1,
551 'form' => $html
554 return json_encode($output);