1 <?php defined('SYSPATH') OR die('No direct access allowed.');
3 * API controller for communicating with mobile clients
5 * @author Artem Daniliants <artem@daniliants.com>
6 * @copyright (c) 2010 Speed Freak team
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
10 class Api_Controller extends Controller{
13 * Default action when no parameters are given to controller
15 public function index(){
16 url::redirect(Kohana::config('api.default_redirect'),301);
20 * New user registration
22 public function register(){
23 $xml = $this->get_xml();
25 $user = new User_Model($xml->login, $xml->password, $xml->email);
28 catch (Exception $e) {
29 echo $e->getMessage() . "\n";
35 * Returns XML file supplied by client
37 private function get_xml(){
38 if (isset($_POST['xml'])){
39 $xml = simplexml_load_string($_POST['xml']);
41 elseif (isset($_FILES['xml'])){
42 $xml = simplexml_load_file($_FILES['xml']['tmp_name']);
45 header("HTTP/1.1 400 Bad Request");
46 echo "Please supply required parameters";
53 * Check that supplied credentials are valid using basic authentication
56 public function login(){
57 if ($this->is_authorized()){
62 $this->not_authorized();
66 * Validate supplied credentials
68 public function is_authorized(){
69 if (isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])){
70 $user = new User_Model();
71 if ($user->login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']))
82 * Display "You're not authorized error to client
84 * @todo Need to create function for generally displaying errors
86 public function not_authorized(){
87 header('HTTP/1.0 401 Unauthorized');
88 print "Invalid credentials or not registered";
93 * Get categories list and output it as XML
96 public function categories(){
97 if ($this->is_authorized()){
98 $view = new View('api/categories');
99 $cat = new Category_Model();
100 $view->categories=$cat->get_all();
104 $this->not_authorized();
111 public function results($category, $limit){
112 $results = New Result_Model();
113 $cat = New Category_Model();
114 if ($cat->category_exists($category) AND $this->is_authorized() AND isset($limit)){
115 $view = new View('api/results');
116 $view->results = $results->get_results($category, $limit);
120 $this->not_authorized();
124 * Submit results to selected category
126 * @param string $category Category to which results are submitted
128 public function update($category){
129 $cat = New Category_Model();
130 if ($cat->category_exists($category) AND $this->is_authorized()){
131 $xml = $this->get_xml();
132 $result = New Result_Model();
133 if ($result->insert($category,$_SERVER['PHP_AUTH_USER'], $xml['value'])){
138 header("HTTP/1.1 400 Bad Request");
139 echo "Invalid request";
144 header("HTTP/1.0 404 Not Found");
145 die('Category not found or not authorized');