Improved www.ttss.krakow.pl
Jacek Kowalski
2017-03-17 505a3b3b52794365cd5350c41a1d649a371b5210
commit | author | age
ced309 1 <?php
JK 2 include(__DIR__.'/stops/common.php');
3 include(__DIR__.'/stops/stops.php');
4
5 try {
6     // Reject invalid input
7     if(!isset($_GET['query'])) throw new UnexpectedValueException();
8     if(empty($_GET['query'])) throw new UnexpectedValueException();
9     if(strlen($_GET['query']) > 50) throw new UnexpectedValueException();
10     
11     // Initialize DB connection an query
12     $pdo = new PDO('sqlite:stops/stops.db', NULL, NULL, array(
13         PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
14     ));
15     $st = $pdo->prepare('SELECT DISTINCT id FROM stop_search WHERE word LIKE ?');
16     
17     // Split stop name into words
18     $words = split_stop_name($_GET['query']);
19     
20     // Find relevant stop IDs
21     $ids = NULL;
22     foreach($words as $word) {
23         if(empty($word)) continue;
24         
25         // Find stop IDs with names matching the word
26         $st->execute(array($word.'%'));
27         $results = $st->fetchAll(PDO::FETCH_COLUMN);
28         $st->closeCursor();
29         
30         // Merge results with previous searches
31         if(is_array($ids)) {
32             $ids = array_intersect($ids, $results);
33         } else {
34             $ids = $results;
35         }
36         
37         // No results will be found
38         if(count($ids) == 0) break;
39     }
40     
41     // Close DB connection
42     unset($st, $pdo);
43     
44     // No query was executed
45     if(!is_array($ids)) throw new UnexpectedValueException();
46     
47     // Build structure for UI
48     $stop_list = [];
505a3b 49     $query_lower = mb_strtolower($_GET['query'], 'UTF-8');
ced309 50     foreach($ids as $id) {
JK 51         $stop_list[] = [
52             'id' => $id,
53             'name' => $stops[$id],
54             'type' => 'stop',
505a3b 55             'relevance' => similar_text(
JK 56                 $query_lower,
57                 mb_strtolower($stops[$id], 'UTF-8')
58             )
ced309 59         ];
JK 60     }
61     
62     // Sort stops by relevence
63     usort($stop_list, function($a, $b) {
505a3b 64         $rel = $b['relevance'] - $a['relevance'];
JK 65         if($rel == 0) return strcasecmp($a['name'], $b['name']);
66         return $rel;
ced309 67     });
JK 68     
69     // Return JSON
70     echo json_encode($stop_list);
71 } catch(UnexpectedValueException $e) {
72     echo '[]';
73 } catch(Exception $e) {
74     header('HTTP/1.1 503 Service Unavailable');
75     echo $e->getMessage();
76 }