aurjson.class.php: Add method get_comment_form()
[aur.git] / web / lib / aurjson.class.php
blob4e4d5dc880b405b4a44ba40a7b24071144b5da8f
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 header('content-type: text/javascript');
115 return $http_data['callback'] . "({$json})";
116 } else {
117 header('content-type: application/json');
118 return $json;
123 * Returns a JSON formatted error string.
125 * @param $msg The error string to return
127 * @return mixed A json formatted error response.
129 private function json_error($msg) {
130 header('content-type: application/json');
131 if ($this->version < 3) {
132 return $this->json_results('error', 0, $msg, NULL);
133 } elseif ($this->version >= 3) {
134 return $this->json_results('error', 0, array(), $msg);
139 * Returns a JSON formatted result data.
141 * @param $type The response method type.
142 * @param $data The result data to return
143 * @param $error An error message to include in the response
145 * @return mixed A json formatted result response.
147 private function json_results($type, $count, $data, $error) {
148 $json_array = array(
149 'version' => $this->version,
150 'type' => $type,
151 'resultcount' => $count,
152 'results' => $data
155 if ($error) {
156 $json_array['error'] = $error;
159 return json_encode($json_array);
162 private function get_extended_fields($pkgid) {
163 $query = "SELECT DependencyTypes.Name AS Type, " .
164 "PackageDepends.DepName AS Name, " .
165 "PackageDepends.DepCondition AS Cond " .
166 "FROM PackageDepends " .
167 "LEFT JOIN DependencyTypes " .
168 "ON DependencyTypes.ID = PackageDepends.DepTypeID " .
169 "WHERE PackageDepends.PackageID = " . $pkgid . " " .
170 "UNION SELECT RelationTypes.Name AS Type, " .
171 "PackageRelations.RelName AS Name, " .
172 "PackageRelations.RelCondition AS Cond " .
173 "FROM PackageRelations " .
174 "LEFT JOIN RelationTypes " .
175 "ON RelationTypes.ID = PackageRelations.RelTypeID " .
176 "WHERE PackageRelations.PackageID = " . $pkgid . " " .
177 "UNION SELECT 'groups' AS Type, Groups.Name, '' AS Cond " .
178 "FROM Groups INNER JOIN PackageGroups " .
179 "ON PackageGroups.PackageID = " . $pkgid . " " .
180 "AND PackageGroups.GroupID = Groups.ID " .
181 "UNION SELECT 'license' AS Type, Licenses.Name, '' AS Cond " .
182 "FROM Licenses INNER JOIN PackageLicenses " .
183 "ON PackageLicenses.PackageID = " . $pkgid . " " .
184 "AND PackageLicenses.LicenseID = Licenses.ID";
185 $result = $this->dbh->query($query);
187 if (!$result) {
188 return null;
191 $type_map = array(
192 'depends' => 'Depends',
193 'makedepends' => 'MakeDepends',
194 'checkdepends' => 'CheckDepends',
195 'optdepends' => 'OptDepends',
196 'conflicts' => 'Conflicts',
197 'provides' => 'Provides',
198 'replaces' => 'Replaces',
199 'groups' => 'Groups',
200 'license' => 'License',
202 $data = array();
203 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
204 $type = $type_map[$row['Type']];
205 $data[$type][] = $row['Name'] . $row['Cond'];
208 return $data;
211 private function process_query($type, $where_condition) {
212 $max_results = config_get_int('options', 'max_rpc_results');
214 if ($this->version == 1) {
215 $fields = implode(',', self::$fields_v1);
216 $query = "SELECT {$fields} " .
217 "FROM Packages LEFT JOIN PackageBases " .
218 "ON PackageBases.ID = Packages.PackageBaseID " .
219 "LEFT JOIN Users " .
220 "ON PackageBases.MaintainerUID = Users.ID " .
221 "LEFT JOIN PackageLicenses " .
222 "ON PackageLicenses.PackageID = Packages.ID " .
223 "LEFT JOIN Licenses " .
224 "ON Licenses.ID = PackageLicenses.LicenseID " .
225 "WHERE ${where_condition} " .
226 "AND PackageBases.PackagerUID IS NOT NULL " .
227 "GROUP BY Packages.ID " .
228 "LIMIT $max_results";
229 } elseif ($this->version >= 2) {
230 if ($this->version == 2 || $this->version == 3) {
231 $fields = implode(',', self::$fields_v2);
232 } else if ($this->version == 4) {
233 $fields = implode(',', self::$fields_v4);
235 $query = "SELECT {$fields} " .
236 "FROM Packages LEFT JOIN PackageBases " .
237 "ON PackageBases.ID = Packages.PackageBaseID " .
238 "LEFT JOIN Users " .
239 "ON PackageBases.MaintainerUID = Users.ID " .
240 "WHERE ${where_condition} " .
241 "AND PackageBases.PackagerUID IS NOT NULL " .
242 "LIMIT $max_results";
244 $result = $this->dbh->query($query);
246 if ($result) {
247 $resultcount = 0;
248 $search_data = array();
249 while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
250 $resultcount++;
251 $row['URLPath'] = sprintf(config_get('options', 'snapshot_uri'), urlencode($row['PackageBase']));
252 if ($this->version < 4) {
253 $row['CategoryID'] = 1;
257 * Unfortunately, mysql_fetch_assoc() returns
258 * all fields as strings. We need to coerce
259 * numeric values into integers to provide
260 * proper data types in the JSON response.
262 foreach (self::$numeric_fields as $field) {
263 $row[$field] = intval($row[$field]);
266 foreach (self::$decimal_fields as $field) {
267 $row[$field] = floatval($row[$field]);
270 if ($this->version >= 2 && ($type == 'info' || $type == 'multiinfo')) {
271 $row = array_merge($row, $this->get_extended_fields($row['ID']));
274 if ($this->version < 3) {
275 if ($type == 'info') {
276 $search_data = $row;
277 break;
278 } else {
279 array_push($search_data, $row);
281 } elseif ($this->version >= 3) {
282 array_push($search_data, $row);
286 if ($resultcount === $max_results) {
287 return $this->json_error('Too many package results.');
290 return $this->json_results($type, $resultcount, $search_data, NULL);
291 } else {
292 return $this->json_results($type, 0, array(), NULL);
297 * Parse the args to the multiinfo function. We may have a string or an
298 * array, so do the appropriate thing. Within the elements, both * package
299 * IDs and package names are valid; sort them into the relevant arrays and
300 * escape/quote the names.
302 * @param array $http_data Query parameters.
304 * @return mixed An array containing 'ids' and 'names'.
306 private function parse_multiinfo_args($http_data) {
307 $args = $http_data['arg'];
308 if (!is_array($args)) {
309 $args = array($args);
312 $id_args = array();
313 $name_args = array();
314 foreach ($args as $arg) {
315 if (!$arg) {
316 continue;
318 if (is_numeric($arg)) {
319 $id_args[] = intval($arg);
320 } else {
321 $name_args[] = $this->dbh->quote($arg);
325 return array('ids' => $id_args, 'names' => $name_args);
329 * Performs a fulltext mysql search of the package database.
331 * @param array $http_data Query parameters.
333 * @return mixed Returns an array of package matches.
335 private function search($http_data) {
336 $keyword_string = $http_data['arg'];
337 if (isset($http_data['search_by'])) {
338 $search_by = $http_data['search_by'];
339 } else {
340 $search_by = 'name-desc';
343 if (strlen($keyword_string) < 2) {
344 return $this->json_error('Query arg too small');
347 $keyword_string = $this->dbh->quote("%" . addcslashes($keyword_string, '%_') . "%");
349 if ($search_by === 'name') {
350 $where_condition = "(Packages.Name LIKE $keyword_string)";
351 } else if ($search_by === 'name-desc') {
352 $where_condition = "(Packages.Name LIKE $keyword_string OR ";
353 $where_condition .= "Description LIKE $keyword_string)";
356 return $this->process_query('search', $where_condition);
360 * Returns the info on a specific package.
362 * @param array $http_data Query parameters.
364 * @return mixed Returns an array of value data containing the package data
366 private function info($http_data) {
367 $pqdata = $http_data['arg'];
368 if (is_numeric($pqdata)) {
369 $where_condition = "Packages.ID = $pqdata";
370 } else {
371 $where_condition = "Packages.Name = " . $this->dbh->quote($pqdata);
374 return $this->process_query('info', $where_condition);
378 * Returns the info on multiple packages.
380 * @param array $http_data Query parameters.
382 * @return mixed Returns an array of results containing the package data
384 private function multiinfo($http_data) {
385 $pqdata = $http_data['arg'];
386 $args = $this->parse_multiinfo_args($pqdata);
387 $ids = $args['ids'];
388 $names = $args['names'];
390 if (!$ids && !$names) {
391 return $this->json_error('Invalid query arguments');
394 $where_condition = "";
395 if ($ids) {
396 $ids_value = implode(',', $args['ids']);
397 $where_condition .= "Packages.ID IN ($ids_value) ";
399 if ($ids && $names) {
400 $where_condition .= "OR ";
402 if ($names) {
404 * Individual names were quoted in
405 * parse_multiinfo_args().
407 $names_value = implode(',', $args['names']);
408 $where_condition .= "Packages.Name IN ($names_value) ";
411 return $this->process_query('multiinfo', $where_condition);
415 * Returns all the packages for a specific maintainer.
417 * @param array $http_data Query parameters.
419 * @return mixed Returns an array of value data containing the package data
421 private function msearch($http_data) {
422 $maintainer = $http_data['arg'];
423 $maintainer = $this->dbh->quote($maintainer);
425 $where_condition = "Users.Username = $maintainer ";
427 return $this->process_query('msearch', $where_condition);
431 * Get all package names that start with $search.
433 * @param array $http_data Query parameters.
435 * @return string The JSON formatted response data.
437 private function suggest($http_data) {
438 $search = $http_data['arg'];
439 $query = "SELECT Packages.Name FROM Packages ";
440 $query.= "LEFT JOIN PackageBases ";
441 $query.= "ON PackageBases.ID = Packages.PackageBaseID ";
442 $query.= "WHERE Packages.Name LIKE ";
443 $query.= $this->dbh->quote(addcslashes($search, '%_') . '%');
444 $query.= " AND PackageBases.PackagerUID IS NOT NULL ";
445 $query.= "ORDER BY Name ASC LIMIT 20";
447 $result = $this->dbh->query($query);
448 $result_array = array();
450 if ($result) {
451 $result_array = $result->fetchAll(PDO::FETCH_COLUMN, 0);
454 return json_encode($result_array);
458 * Get all package base names that start with $search.
460 * @param array $http_data Query parameters.
462 * @return string The JSON formatted response data.
464 private function suggest_pkgbase($http_data) {
465 $search = $http_data['arg'];
466 $query = "SELECT Name FROM PackageBases WHERE Name LIKE ";
467 $query.= $this->dbh->quote(addcslashes($search, '%_') . '%');
468 $query.= " AND PackageBases.PackagerUID IS NOT NULL ";
469 $query.= "ORDER BY Name ASC LIMIT 20";
471 $result = $this->dbh->query($query);
472 $result_array = array();
474 if ($result) {
475 $result_array = $result->fetchAll(PDO::FETCH_COLUMN, 0);
478 return json_encode($result_array);
482 * Get the HTML markup of the comment form.
484 * @param array $http_data Query parameters.
486 * @return string The JSON formatted response data.
488 private function get_comment_form($http_data) {
489 if (!isset($http_data['base_id']) || !isset($http_data['pkgbase_name'])) {
490 $output = array(
491 'success' => 0,
492 'error' => __('Package base ID or package base name missing.')
494 return json_encode($output);
497 $comment_id = intval($http_data['arg']);
498 $base_id = intval($http_data['base_id']);
499 $pkgbase_name = $http_data['pkgbase_name'];
501 list($user_id, $comment) = comment_by_id($comment_id);
503 if (!has_credential(CRED_COMMENT_EDIT, array($user_id))) {
504 $output = array(
505 'success' => 0,
506 'error' => __('You do not have the right to edit this comment.')
508 return json_encode($output);
509 } elseif (is_null($comment)) {
510 $output = array(
511 'success' => 0,
512 'error' => __('Comment does not exist.')
514 return json_encode($output);
517 ob_start();
518 include('pkg_comment_form.php');
519 $html = ob_get_clean();
520 $output = array(
521 'success' => 1,
522 'form' => $html
525 return json_encode($output);