3 include_once("aur.inc.php");
6 * This class defines a remote interface for fetching data from the AUR using
7 * JSON formatted elements.
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(
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.');
90 if (isset($http_data['search_by']) && !isset($http_data['by'])) {
91 $http_data['by'] = $http_data['search_by'];
93 if (isset($http_data['by']) && !in_array($http_data['by'], self
::$exposed_fields)) {
94 return $this->json_error('Incorrect by field specified.');
97 $this->dbh
= DB
::connect();
99 $type = str_replace('-', '_', $http_data['type']);
100 if ($type == 'info' && $this->version
>= 5) {
103 $json = call_user_func(array(&$this, $type), $http_data);
106 header("Etag: \"$etag\"");
108 * Make sure to strip a few things off the
109 * if-none-match header. Stripping whitespace may not
110 * be required, but removing the quote on the incoming
111 * header is required to make the equality test.
113 $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ?
114 trim($_SERVER['HTTP_IF_NONE_MATCH'], "\t\n\r\" ") : false;
115 if ($if_none_match && $if_none_match == $etag) {
116 header('HTTP/1.1 304 Not Modified');
120 if (isset($http_data['callback'])) {
121 $callback = $http_data['callback'];
122 if (!preg_match('/^[a-zA-Z0-9()_.]{1,128}$/D', $callback)) {
123 return $this->json_error('Invalid callback name.');
125 header('content-type: text/javascript');
126 return '/**/' . $callback . '(' . $json . ')';
128 header('content-type: application/json');
134 * Returns a JSON formatted error string.
136 * @param $msg The error string to return
138 * @return mixed A json formatted error response.
140 private function json_error($msg) {
141 header('content-type: application/json');
142 if ($this->version
< 3) {
143 return $this->json_results('error', 0, $msg, NULL);
144 } elseif ($this->version
>= 3) {
145 return $this->json_results('error', 0, array(), $msg);
150 * Returns a JSON formatted result data.
152 * @param $type The response method type.
153 * @param $count The number of results to return
154 * @param $data The result data to return
155 * @param $error An error message to include in the response
157 * @return mixed A json formatted result response.
159 private function json_results($type, $count, $data, $error) {
161 'version' => $this->version
,
163 'resultcount' => $count,
168 $json_array['error'] = $error;
171 return json_encode($json_array);
175 * Get extended package details (for info and multiinfo queries).
177 * @param $pkgid The ID of the package to retrieve details for.
179 * @return array An array containing package details.
181 private function get_extended_fields($pkgid) {
182 $query = "SELECT DependencyTypes.Name AS Type, " .
183 "PackageDepends.DepName AS Name, " .
184 "PackageDepends.DepCondition AS Cond " .
185 "FROM PackageDepends " .
186 "LEFT JOIN DependencyTypes " .
187 "ON DependencyTypes.ID = PackageDepends.DepTypeID " .
188 "WHERE PackageDepends.PackageID = " . $pkgid . " " .
189 "UNION SELECT RelationTypes.Name AS Type, " .
190 "PackageRelations.RelName AS Name, " .
191 "PackageRelations.RelCondition AS Cond " .
192 "FROM PackageRelations " .
193 "LEFT JOIN RelationTypes " .
194 "ON RelationTypes.ID = PackageRelations.RelTypeID " .
195 "WHERE PackageRelations.PackageID = " . $pkgid . " " .
196 "UNION SELECT 'groups' AS Type, Groups.Name, '' AS Cond " .
197 "FROM Groups INNER JOIN PackageGroups " .
198 "ON PackageGroups.PackageID = " . $pkgid . " " .
199 "AND PackageGroups.GroupID = Groups.ID " .
200 "UNION SELECT 'license' AS Type, Licenses.Name, '' AS Cond " .
201 "FROM Licenses INNER JOIN PackageLicenses " .
202 "ON PackageLicenses.PackageID = " . $pkgid . " " .
203 "AND PackageLicenses.LicenseID = Licenses.ID";
204 $result = $this->dbh
->query($query);
211 'depends' => 'Depends',
212 'makedepends' => 'MakeDepends',
213 'checkdepends' => 'CheckDepends',
214 'optdepends' => 'OptDepends',
215 'conflicts' => 'Conflicts',
216 'provides' => 'Provides',
217 'replaces' => 'Replaces',
218 'groups' => 'Groups',
219 'license' => 'License',
222 while ($row = $result->fetch(PDO
::FETCH_ASSOC
)) {
223 $type = $type_map[$row['Type']];
224 $data[$type][] = $row['Name'] . $row['Cond'];
231 * Retrieve package information (used in info, multiinfo, search and
234 * @param $type The request type.
235 * @param $where_condition An SQL WHERE-condition to filter packages.
237 * @return mixed Returns an array of package matches.
239 private function process_query($type, $where_condition) {
240 $max_results = config_get_int('options', 'max_rpc_results');
242 if ($this->version
== 1) {
243 $fields = implode(',', self
::$fields_v1);
244 $query = "SELECT {$fields} " .
245 "FROM Packages LEFT JOIN PackageBases " .
246 "ON PackageBases.ID = Packages.PackageBaseID " .
248 "ON PackageBases.MaintainerUID = Users.ID " .
249 "LEFT JOIN PackageLicenses " .
250 "ON PackageLicenses.PackageID = Packages.ID " .
251 "LEFT JOIN Licenses " .
252 "ON Licenses.ID = PackageLicenses.LicenseID " .
253 "WHERE ${where_condition} " .
254 "AND PackageBases.PackagerUID IS NOT NULL " .
255 "GROUP BY Packages.ID " .
256 "LIMIT $max_results";
257 } elseif ($this->version
>= 2) {
258 if ($this->version
== 2 ||
$this->version
== 3) {
259 $fields = implode(',', self
::$fields_v2);
260 } else if ($this->version
== 4 ||
$this->version
== 5) {
261 $fields = implode(',', self
::$fields_v4);
263 $query = "SELECT {$fields} " .
264 "FROM Packages LEFT JOIN PackageBases " .
265 "ON PackageBases.ID = Packages.PackageBaseID " .
267 "ON PackageBases.MaintainerUID = Users.ID " .
268 "WHERE ${where_condition} " .
269 "AND PackageBases.PackagerUID IS NOT NULL " .
270 "LIMIT $max_results";
272 $result = $this->dbh
->query($query);
276 $search_data = array();
277 while ($row = $result->fetch(PDO
::FETCH_ASSOC
)) {
279 $row['URLPath'] = sprintf(config_get('options', 'snapshot_uri'), urlencode($row['PackageBase']));
280 if ($this->version
< 4) {
281 $row['CategoryID'] = 1;
285 * Unfortunately, mysql_fetch_assoc() returns
286 * all fields as strings. We need to coerce
287 * numeric values into integers to provide
288 * proper data types in the JSON response.
290 foreach (self
::$numeric_fields as $field) {
291 if (isset($row[$field])) {
292 $row[$field] = intval($row[$field]);
296 foreach (self
::$decimal_fields as $field) {
297 if (isset($row[$field])) {
298 $row[$field] = floatval($row[$field]);
302 if ($this->version
>= 2 && ($type == 'info' ||
$type == 'multiinfo')) {
303 $row = array_merge($row, $this->get_extended_fields($row['ID']));
306 if ($this->version
< 3) {
307 if ($type == 'info') {
311 array_push($search_data, $row);
313 } elseif ($this->version
>= 3) {
314 array_push($search_data, $row);
318 if ($resultcount === $max_results) {
319 return $this->json_error('Too many package results.');
322 return $this->json_results($type, $resultcount, $search_data, NULL);
324 return $this->json_results($type, 0, array(), NULL);
329 * Parse the args to the multiinfo function. We may have a string or an
330 * array, so do the appropriate thing. Within the elements, both * package
331 * IDs and package names are valid; sort them into the relevant arrays and
332 * escape/quote the names.
334 * @param array $args Query parameters.
336 * @return mixed An array containing 'ids' and 'names'.
338 private function parse_multiinfo_args($args) {
339 if (!is_array($args)) {
340 $args = array($args);
344 $name_args = array();
345 foreach ($args as $arg) {
349 if (is_numeric($arg)) {
350 $id_args[] = intval($arg);
352 $name_args[] = $this->dbh
->quote($arg);
356 return array('ids' => $id_args, 'names' => $name_args);
360 * Performs a fulltext mysql search of the package database.
362 * @param array $http_data Query parameters.
364 * @return mixed Returns an array of package matches.
366 private function search($http_data) {
367 $keyword_string = $http_data['arg'];
369 if (isset($http_data['by'])) {
370 $search_by = $http_data['by'];
372 $search_by = 'name-desc';
375 if ($search_by === 'name' ||
$search_by === 'name-desc') {
376 if (strlen($keyword_string) < 2) {
377 return $this->json_error('Query arg too small');
379 $keyword_string = $this->dbh
->quote("%" . addcslashes($keyword_string, '%_') . "%");
381 if ($search_by === 'name') {
382 $where_condition = "(Packages.Name LIKE $keyword_string)";
383 } else if ($search_by === 'name-desc') {
384 $where_condition = "(Packages.Name LIKE $keyword_string OR ";
385 $where_condition .= "Description LIKE $keyword_string)";
387 } else if ($search_by === 'maintainer') {
388 if (empty($keyword_string)) {
389 $where_condition = "Users.ID is NULL";
391 $keyword_string = $this->dbh
->quote($keyword_string);
392 $where_condition = "Users.Username = $keyword_string ";
396 return $this->process_query('search', $where_condition);
400 * Returns the info on a specific package.
402 * @param array $http_data Query parameters.
404 * @return mixed Returns an array of value data containing the package data
406 private function info($http_data) {
407 $pqdata = $http_data['arg'];
408 if (is_numeric($pqdata)) {
409 $where_condition = "Packages.ID = $pqdata";
411 $where_condition = "Packages.Name = " . $this->dbh
->quote($pqdata);
414 return $this->process_query('info', $where_condition);
418 * Returns the info on multiple packages.
420 * @param array $http_data Query parameters.
422 * @return mixed Returns an array of results containing the package data
424 private function multiinfo($http_data) {
425 $pqdata = $http_data['arg'];
426 $args = $this->parse_multiinfo_args($pqdata);
428 $names = $args['names'];
430 if (!$ids && !$names) {
431 return $this->json_error('Invalid query arguments');
434 $where_condition = "";
436 $ids_value = implode(',', $args['ids']);
437 $where_condition .= "Packages.ID IN ($ids_value) ";
439 if ($ids && $names) {
440 $where_condition .= "OR ";
444 * Individual names were quoted in
445 * parse_multiinfo_args().
447 $names_value = implode(',', $args['names']);
448 $where_condition .= "Packages.Name IN ($names_value) ";
451 return $this->process_query('multiinfo', $where_condition);
455 * Returns all the packages for a specific maintainer.
457 * @param array $http_data Query parameters.
459 * @return mixed Returns an array of value data containing the package data
461 private function msearch($http_data) {
462 $http_data['by'] = 'maintainer';
463 return $this->search($http_data);
467 * Get all package names that start with $search.
469 * @param array $http_data Query parameters.
471 * @return string The JSON formatted response data.
473 private function suggest($http_data) {
474 $search = $http_data['arg'];
475 $query = "SELECT Packages.Name FROM Packages ";
476 $query.= "LEFT JOIN PackageBases ";
477 $query.= "ON PackageBases.ID = Packages.PackageBaseID ";
478 $query.= "WHERE Packages.Name LIKE ";
479 $query.= $this->dbh
->quote(addcslashes($search, '%_') . '%');
480 $query.= " AND PackageBases.PackagerUID IS NOT NULL ";
481 $query.= "ORDER BY Name ASC LIMIT 20";
483 $result = $this->dbh
->query($query);
484 $result_array = array();
487 $result_array = $result->fetchAll(PDO
::FETCH_COLUMN
, 0);
490 return json_encode($result_array);
494 * Get all package base names that start with $search.
496 * @param array $http_data Query parameters.
498 * @return string The JSON formatted response data.
500 private function suggest_pkgbase($http_data) {
501 $search = $http_data['arg'];
502 $query = "SELECT Name FROM PackageBases WHERE Name LIKE ";
503 $query.= $this->dbh
->quote(addcslashes($search, '%_') . '%');
504 $query.= " AND PackageBases.PackagerUID IS NOT NULL ";
505 $query.= "ORDER BY Name ASC LIMIT 20";
507 $result = $this->dbh
->query($query);
508 $result_array = array();
511 $result_array = $result->fetchAll(PDO
::FETCH_COLUMN
, 0);
514 return json_encode($result_array);
518 * Get the HTML markup of the comment form.
520 * @param array $http_data Query parameters.
522 * @return string The JSON formatted response data.
524 private function get_comment_form($http_data) {
525 if (!isset($http_data['base_id']) ||
!isset($http_data['pkgbase_name'])) {
528 'error' => __('Package base ID or package base name missing.')
530 return json_encode($output);
533 $comment_id = intval($http_data['arg']);
534 $base_id = intval($http_data['base_id']);
535 $pkgbase_name = $http_data['pkgbase_name'];
537 list($user_id, $comment) = comment_by_id($comment_id);
539 if (!has_credential(CRED_COMMENT_EDIT
, array($user_id))) {
542 'error' => __('You are not allowed to edit this comment.')
544 return json_encode($output);
545 } elseif (is_null($comment)) {
548 'error' => __('Comment does not exist.')
550 return json_encode($output);
554 include('pkg_comment_form.php');
555 $html = ob_get_clean();
561 return json_encode($output);