Example #1
1
 function getRoutesFromDB()
 {
     $relations = array();
     $relations = $this->getRelations();
     $json_relations = JSONRouteRelation::getJSONRelations();
     if (count($json_relations) > 0) {
         foreach ($json_relations as $route => $relation) {
             if (isset($relations[$route])) {
                 $relations[$route] = array_merge($relations[$route], $relation);
             } else {
                 $relations[$route] = $relation;
             }
         }
     }
     $result = DBController::Query("SHOW TABLES");
     if ($result === false) {
         exit(ApiResponse::errorResponse(404));
     } else {
         if (empty($result) === true) {
             exit(ApiResponse::errorResponse(204));
         } else {
             foreach ($result as $k => $v) {
                 $route = reset($v);
                 $route = new Route();
                 $route->routeName = reset($v);
                 if (isset($relations[$route->routeName])) {
                     $route->routeFields = $this->getRouteFields($route, $relations[$route->routeName]);
                 } else {
                     $route->routeFields = $this->getRouteFields($route);
                 }
                 ResterUtils::Log("*** PRIMARY KEY: " . $route->routeName . " => " . $route->primaryKey->fieldName);
                 $routes[$route->routeName] = $route;
             }
         }
     }
     ApiCacheManager::saveValueToCache(ROUTE_CACHE_KEY, $routes);
     return $routes;
 }
 public function loginFbAction()
 {
     $response = new ApiResponse();
     if ($this->request->isPost()) {
         $fbId = $this->request->getPost('fbId');
         $username = $this->request->getPost('username');
         $email = $this->request->getPost('email');
         $avatar = $this->request->getPost('avatar');
         $user = Users::findFirstByFbId($fbId);
         if ($user == true) {
             $response->setResponseMessage('Login successfully!');
             return $response;
         } else {
             $user = new Users();
             $user->id = uniqid();
             $user->fbId = $fbId;
             $user->avatar = $avatar;
             $user->username = $username;
             $user->email = $email;
             try {
                 if ($user->save() == false) {
                     $response->setResponseError(implode(', ', $user->getMessages()));
                 } else {
                     $response->setResponseMessage('Register successfully!');
                 }
             } catch (PDOException $e) {
                 $response->setResponseError($e->getMessage());
             }
         }
     } else {
         $response->setResponseError('Wrong HTTP Method');
     }
     return $response;
 }
Example #3
0
 public function __construct(ApiResponse $response, $previous = null)
 {
     $this->response = $response;
     $rpcError = $response->getResult();
     $message = "{$rpcError->getRpcErrorMessage()} {$rpcError->getRpcErrorData()} ({$rpcError->getRpcErrorCode()})";
     parent::__construct($message, $response['code'], $previous);
 }
Example #4
0
 /**
  * testGeneral
  *
  * @return void
  */
 public function testGeneral()
 {
     $data = ['access_token' => 'TESTaccess_token', 'token_type' => 'TESTtoken_type', 'data' => ['some' => 'TESTdata']];
     $unit = new ApiResponse($data);
     $this->assertEquals($data['access_token'], $unit->getAccessToken());
     $this->assertEquals($data['token_type'], $unit->getTokenType());
     $this->assertEquals($data['data'], $unit->getData());
 }
 public function getApiResponse($data)
 {
     $data = json_decode($data, true);
     $apiResponse = new ApiResponse();
     $apiResponse->setStatus($data['status']);
     $apiResponse->setData($data['data']);
     return $apiResponse;
 }
 public function testCreateRatingErrorWrongIsMyWine()
 {
     $_params = $this->_params;
     $_params['is_my_wine'] = 'wrong_is_my_wine';
     $response = $this->_getAuth($_params);
     $this->assertEquals(json_encode(array("code" => ApiResponse::UNAVAILABLE_RATING, "data" => ApiResponse::getErrorContent(ApiResponse::UNAVAILABLE_RATING))), $response->getContent());
 }
Example #7
0
 public function run()
 {
     $uri = $this->getURI();
     foreach ($this->routes as $uriPattern => $path) {
         if (preg_match("~{$uriPattern}~", $uri)) {
             $internalRoute = preg_replace("~{$uriPattern}~", $path, $uri);
             $segments = explode('/', $internalRoute);
             $controllerName = ucfirst(array_shift($segments)) . 'Controller';
             $nameAction = lcfirst(array_shift($segments)) . 'Action';
             $result = null;
             $class = "\\app\\controllers\\" . $controllerName;
             $controllerObject = new $class();
             if (method_exists($controllerObject, $nameAction)) {
                 $result = $controllerObject->{$nameAction}();
                 if (!empty($_POST) || !empty($_GET)) {
                     ApiResponse::afterExecuteRoute($result);
                 }
             }
             if ($result != null) {
                 break;
             } else {
                 require_once ROOT . '/app/views/error/index.phtml';
             }
         }
     }
 }
 public function testRegisterDeviceExisted()
 {
     Device::create($this->_params);
     $response = $this->_getResponse();
     $this->assertTrue($this->client->getResponse()->isOk());
     $this->assertEquals(json_encode(array("code" => ApiResponse::EXISTED_DEVICE, "data" => ApiResponse::getErrorContent(ApiResponse::EXISTED_DEVICE))), $response->getContent());
 }
Example #9
0
 public static function errorResponse($errorCode)
 {
     $status = "Bad Request";
     switch ($errorCode) {
         case 204:
             $status = "No Content";
             break;
         case 400:
             $status = "Bad Request";
             break;
         case 403:
             $status = "Forbidden";
             break;
         case 404:
             $status = "Not found";
             break;
         case 405:
             $status = "Method not allowed";
             break;
         case 409:
             $status = "Conflict";
             break;
         case 503:
             $status = "Service Unavailable";
             break;
     }
     return ApiResponse::errorResponseWithMessage($errorCode, $status);
 }
Example #10
0
 public static function deleteLike($rating_id)
 {
     $error_code = ApiResponse::OK;
     $user_id = Session::get('user_id');
     if (Rating::where('id', $rating_id)->first()) {
         $like = Like::where('rating_id', $rating_id)->where('user_id', $user_id)->first();
         if ($like) {
             //update like_count on rating
             $like_rating = Rating::where('id', $like->rating_id)->first();
             if ($like_rating != null) {
                 $like_rating->like_count = $like_rating->like_count - 1;
                 $like_rating->save();
             }
             $like->delete();
             $data = 'Like deleted';
         } else {
             $error_code = ApiResponse::NOT_EXISTED_LIKE;
             $data = ApiResponse::getErrorContent(ApiResponse::NOT_EXISTED_LIKE);
         }
     } else {
         $error_code = ApiResponse::UNAVAILABLE_RATING;
         $data = ApiResponse::getErrorContent(ApiResponse::UNAVAILABLE_RATING);
     }
     return array("code" => $error_code, "data" => $data);
 }
Example #11
0
 public function testLogoutErrorInvalidSession()
 {
     $params = $this->_params;
     $params['session_id'] = "123456";
     $response = $this->_getResponse($params);
     $this->assertEquals(json_encode(array("code" => ApiResponse::SESSION_INVALID, "data" => ApiResponse::getErrorContent(ApiResponse::SESSION_INVALID))), $response->getContent());
 }
 public function testUpdateRatingErrorWrongIsMyWine()
 {
     $this->setUpRating();
     $_params = $this->_params;
     $_params['is_my_wine'] = 'wrong_is_my_wine';
     $response = $this->action('POST', 'RatingController@update', array('id' => 1), array('data' => json_encode($_params), '_method' => 'PUT'));
     $this->assertEquals(json_encode(array("code" => ApiResponse::UNAVAILABLE_RATING, "data" => ApiResponse::getErrorContent(ApiResponse::UNAVAILABLE_RATING))), $response->getContent());
 }
Example #13
0
 public function testLoginByEmailErrorWrongEmail()
 {
     $_params = $this->_params;
     $_params['email'] = '*****@*****.**';
     $response = $this->_getResponse($_params);
     $this->assertTrue($this->client->getResponse()->isOk());
     $this->assertEquals(json_encode(array("code" => ApiResponse::WRONG_AUTH, "data" => ApiResponse::getErrorContent(ApiResponse::WRONG_AUTH))), $response->getContent());
 }
 public function testRegisterErrorExistedEmail()
 {
     $user = new User();
     $user->email = $this->_params['email'];
     $user->password = $this->_params['password'];
     $user->device_id = $this->_params['device_id'];
     $user->save();
     $response = $this->_getResponse();
     $this->assertEquals(json_encode(array("code" => ApiResponse::EXISTED_EMAIL, "data" => ApiResponse::getErrorContent(ApiResponse::EXISTED_EMAIL))), $response->getContent());
 }
Example #15
0
 public function testGetTimelineSuccess()
 {
     $this->setUpRating();
     $this->setUpCountry();
     $this->setUpWineNote();
     $this->setUpProfile();
     $_params = $this->_params;
     $_params['user_id'] = "user_id";
     $response = $this->_getAuth($_params);
     $error_code = ApiResponse::OK;
     $user_timeline = array();
     $user_timeline[] = $this->_user_id;
     $user_follow = Follow::where('from_id', $this->_user_id)->orderBy('updated_at', 'asc')->get();
     if (isset($user_follow)) {
         foreach ($user_follow as $user) {
             $user_timeline[] = $user->to_id;
         }
     }
     $pagination = ApiResponse::pagination();
     $page = $pagination['page'];
     $limit = $pagination['limit'];
     $wine = Wine::with('winery')->forPage($page, $limit)->get();
     $ratings = Rating::whereIn('user_id', $user_timeline)->whereNotNull('wine_unique_id')->with('profile')->with('wine')->forPage($page, $limit)->get();
     foreach ($ratings as $rating) {
         $winery = Winery::where('id', $rating->wine->winery_id)->first();
         $rating->winery = $winery;
         $country = Country::where('id', $rating->winery->country_id)->first();
         $rating->winery->country_name = $country->country_name;
         $like = Like::where('user_id', $this->_user_id)->where('rating_id', $rating->id)->first();
         if ($like) {
             $rating->liked = true;
         } else {
             $rating->liked = false;
         }
         $wishlist = Wishlist::where('user_id', $this->_user_id)->where('wine_unique_id', $rating->wine_unique_id)->first();
         if ($wishlist) {
             $rating->wishlist = true;
         } else {
             $rating->wishlist = false;
         }
         if ($rating->wine->image_url != null) {
             $rating->wine->image_url = URL::asset($rating->wine->image_url);
         }
         if ($rating->wine->wine_flag != null) {
             $rating->wine->wine_flag = URL::asset($rating->wine->wine_flag);
         }
         if ($rating->profile->image != null) {
             $rating->profile->image = URL::asset($rating->profile->image);
         }
         $rating->winery = $rating->winery->toArray();
     }
     $data = $ratings;
     $this->assertEquals(array("code" => ApiResponse::OK, "data" => $ratings->toArray()), json_decode($response->getContent(), true));
 }
 public function newAction()
 {
     $response = new ApiResponse();
     if ($this->request->isPost()) {
         $question = new Questions();
         $question->id = uniqid();
         $question->tags = $this->request->getPost('tags');
         $question->title = $this->request->getPost('title');
         $question->content = $this->request->getPost('content');
         $question->users_id = $this->request->getPost('users_id');
         if ($this->request->hasFiles() == true) {
             $baseLocation = 'files/';
             foreach ($this->request->getUploadedFiles() as $file) {
                 $photos = new Photos();
                 $unique_filename = $question->id;
                 $photos->size = $file->getSize();
                 $photos->original_name = $file->getName();
                 $photos->file_name = $unique_filename;
                 $photos->extension = $file->getExtension();
                 $location = $baseLocation . $unique_filename . "." . $file->getExtension();
                 $photos->public_link = $location;
                 try {
                     if (!$photos->save()) {
                         $response->setResponseError($photos->getMessages());
                     } else {
                         //Move the file into the application
                         $file->moveTo($location);
                         $question->photo = $photos->public_link;
                     }
                 } catch (PDOException $e) {
                     $response->setResponseError($e->getMessage());
                 }
             }
         }
         try {
             if ($question->save() == false) {
                 $response->setResponseError($question->getMessages());
             } else {
                 $response->setResponseMessage($question->id);
             }
         } catch (PDOException $e) {
             $response->setResponseError($e->getMessage());
         }
     } else {
         $response->setResponseError('Wrong HTTP Method');
     }
     return $response;
 }
Example #17
0
 public static function deleteWishlist($wine_unique_id)
 {
     $user_id = Session::get('user_id');
     $error_code = ApiResponse::OK;
     $wishlist = Wishlist::where('user_id', $user_id)->where('wine_unique_id', $wine_unique_id)->first();
     if ($wishlist) {
         $wishlist->delete();
         $data = 'wine in wishlist is deleted';
     } else {
         $error_code = ApiResponse::NOT_EXISTED_WINE_WISHLIST;
         $data = ApiResponse::getErrorContent(ApiResponse::NOT_EXISTED_WINE_WISHLIST);
     }
     return array("code" => $error_code, "data" => $data);
 }
Example #18
0
 public function apiCall($action, array $params)
 {
     if (null === $this->requestStrategy) {
         $this->setRequestStrategy(new \SentioneApi\Net\RequestStrategy\Curl());
     }
     $metadata = array('host' => $this->apiUrl, 'authentication_username' => $this->username, 'authentication_password' => $this->password, 'authentication_strategy' => 'digest');
     /* @var $response \SentioneApi\Net\Response */
     $response = $this->requestStrategy->doApiRequest($action, $params, $metadata);
     if (200 == $response->getResponseCode()) {
         $metadata = array();
         return ApiResponse::build($action, $params, $response->getResponseBody(), $metadata);
     }
     switch ($response->getResponseCode()) {
         case 401:
             throw new ApiException("Bad credentials", 401);
         default:
             throw new ApiException("Unknown error", $response->getResponseCode());
     }
 }
Example #19
0
 public static function logout($input)
 {
     $error_code = ApiResponse::OK;
     //validate params
     if (!array_key_exists('session_id', $input)) {
         $error_code = ApiResponse::MISSING_PARAMS;
         $data = $input;
     } else {
         //check email existed
         $login_information = self::where('session_id', $input['session_id'])->first();
         if ($login_information == null) {
             $error_code = ApiResponse::SESSION_INVALID;
             $data = ApiResponse::getErrorContent(ApiResponse::SESSION_INVALID);
         } else {
             $login_information->delete();
             $data = "ok";
         }
     }
     return array("code" => $error_code, "data" => $data);
 }
Example #20
0
 public static function pagination()
 {
     if (Input::has('page')) {
         $getPage = Input::get('page');
         if (Input::get('per_page')) {
             $getLimit = Input::get('per_page');
         } else {
             $getLimit = 10;
         }
         $paginate = ApiResponse::checkPagination($getPage, $getLimit);
         if ($paginate !== false) {
             $page = $paginate['page'];
             $limit = $paginate['limit'];
         } else {
             return false;
         }
     } else {
         $page = 1;
         $limit = 10;
     }
     return array('page' => $page, 'limit' => $limit);
 }
Example #21
0
 public static function push_notification($input)
 {
     $error_code = ApiResponse::OK;
     $validator = Validator::make($input, array('auth_key' => 'required', 'device_id' => 'required', 'platform' => 'required'));
     //validate params
     if ($validator->fails()) {
         $error_code = ApiResponse::MISSING_PARAMS;
         $data = $input;
     } else {
         //check device existed
         if (Device::where('auth_key', $input['auth_key'])->first() != null) {
             $error_code = ApiResponse::EXISTED_DEVICE;
             $data = ApiResponse::getErrorContent(ApiResponse::EXISTED_DEVICE);
         } else {
             $device = Device::create($input);
             if ($device) {
                 $data = "ok";
             }
         }
     }
     return array("code" => $error_code, "data" => $data);
 }
Example #22
0
 public function testDeleteWishlistErrorNoWishlist()
 {
     $wishlist = Wishlist::destroy(1);
     $response = $this->action('delete', 'WishlistController@destroy', array('wine_unique_id' => "1_2009"));
     $this->assertEquals(array("code" => ApiResponse::NOT_EXISTED_WINE_WISHLIST, "data" => ApiResponse::getErrorContent(ApiResponse::NOT_EXISTED_WINE_WISHLIST)), json_decode($response->getContent(), true));
 }
 public function missingMethod($parameters = array())
 {
     return ApiResponse::errorNotFound('Sorry, no method found');
 }
Example #24
0
 public function testDeleteWineryErrorNoWinery()
 {
     $response = $this->action('delete', 'WineryController@destroy', array('id' => 2));
     //get created login information
     $this->assertEquals(array("code" => ApiResponse::UNAVAILABLE_WINERY, "data" => ApiResponse::getErrorContent(ApiResponse::UNAVAILABLE_WINERY)), json_decode($response->getContent(), true));
 }
Example #25
0
 public function testDeleteFollowErrorNoFollow()
 {
     $follow = Follow::destroy(1);
     $follow_id = User::where('email', '*****@*****.**')->first()->user_id;
     $response = $this->action('delete', 'FollowController@destroy', array('follow_id' => $follow_id));
     $this->assertEquals(array("code" => ApiResponse::NOT_EXISTED_FOLLOW, "data" => ApiResponse::getErrorContent(ApiResponse::NOT_EXISTED_FOLLOW)), json_decode($response->getContent(), true));
 }
Example #26
0
    }
    if ($config->get('config_error_display')) {
        echo '<b>' . $error . '</b>: ' . $message . ' in <b>' . $file . '</b> on line <b>' . $line . '</b>';
    }
    if ($config->get('config_error_log')) {
        $log->write('PHP ' . $error . ':  ' . $message . ' in ' . $file . ' on line ' . $line);
    }
    return true;
}
// Error Handler
set_error_handler('error_handler');
// Request
$request = new ApiRequest($registry);
$registry->set('request', $request);
// Response
$response = new ApiResponse($registry);
$response->addHeader('Content-Type: application/json');
$response->setCompression($config->get('config_compression'));
$registry->set('response', $response);
// Auth
$registry->set('oauth', new Authentication($registry));
// Cache
$cache = new Cache('file');
$registry->set('cache', $cache);
// Session
if (isset($request->get['token']) && isset($request->get['route']) && substr($request->get['route'], 0, 4) == 'api/') {
    $db->query("DELETE FROM `" . DB_PREFIX . "restapi_session` WHERE TIMESTAMPADD(HOUR, 1, date_modified) < NOW()");
    $query = $db->query("SELECT DISTINCT * FROM `" . DB_PREFIX . "api` `a` LEFT JOIN `" . DB_PREFIX . "restapi_session` `as` ON (a.api_id = as.api_id) LEFT JOIN " . DB_PREFIX . "api_ip `ai` ON (as.api_id = ai.api_id) WHERE a.status = '1' AND as.token = '" . $db->escape($request->get['token']) . "' AND ai.ip = '" . $db->escape($request->server['REMOTE_ADDR']) . "'");
    if ($query->num_rows) {
        // Does not seem PHP is able to handle sessions as objects properly so so wrote my own class
        $session = new Session($query->row['session_id'], $query->row['session_name']);
Example #27
0
 public static function getProfieLastRate($user_id)
 {
     $error_code = ApiResponse::OK;
     $pagination = ApiResponse::pagination();
     if ($pagination == false) {
         $error_code = ApiResponse::URL_NOT_EXIST;
         $data = ApiResponse::getErrorContent(ApiResponse::URL_NOT_EXIST);
     } else {
         $page = $pagination['page'];
         $limit = $pagination['limit'];
         if (User::where('user_id', $user_id)->first()) {
             $last_rates = Rating::where('user_id', $user_id)->orderBy('updated_at', 'desc')->with('wine')->forPage($page, $limit)->get();
             foreach ($last_rates as $last_rate) {
                 $last_rate->winery = Winery::where('id', $last_rate->wine->winery_id)->first();
                 if ($last_rate->wine->image_url != null) {
                     $last_rate->wine->image_url = URL::asset($last_rate->wine->image_url);
                 }
                 if ($last_rate->wine->wine_flag != null) {
                     $last_rate->wine->wine_flag = URL::asset($last_rate->wine->wine_flag);
                 }
             }
             $data = $last_rates->toArray();
         } else {
             $error_code = ApiResponse::UNAVAILABLE_USER;
             $data = ApiResponse::getErrorContent(ApiResponse::UNAVAILABLE_USER);
         }
     }
     return array("code" => $error_code, "data" => $data);
 }
Example #28
0
                $app->stop();
            }
            $stmt = $db->prepare('INSERT INTO teachers (name, website, addedby) VALUES (?, ?, ?)');
            $stmt->execute(array(utf8_encode($name), utf8_encode($website), $userid));
            ApiResponse::success(200, "success", "teacherid", $db->lastInsertId());
        } catch (PDOException $ex) {
            ApiResponse::error(500, "Internal server error");
        }
    })->via('GET', 'POST');
    //################# Teachers  ##################
    $app->map('/list', function () use($app, $db) {
        try {
            $stmt = $db->prepare('SELECT * FROM teachers LIMIT 50');
            $stmt->execute();
            ApiResponse::success(200, "success", "teachers", $stmt->fetchAll(PDO::FETCH_ASSOC));
        } catch (PDOException $ex) {
            ApiResponse::error(500, "Internal server error");
        }
    })->via('GET', 'POST');
    //################## Search Teachers  ##################
    $app->map('/search', function () use($app, $db) {
        $query = $app->request->get('q');
        try {
            $stmt = $db->prepare('SELECT * FROM teachers WHERE name LIKE ? LIMIT 10');
            $stmt->execute(array("%{$query}%"));
            ApiResponse::success(200, "success", "teachers", $stmt->fetchAll(PDO::FETCH_ASSOC));
        } catch (PDOException $ex) {
            ApiResponse::error(500, "Internal server error");
        }
    })->via('GET', 'POST');
});
Example #29
0
 public static function removeWineFromMyWine($id)
 {
     $rating = Rating::where('id', $id)->first();
     $error_code = ApiResponse::OK;
     if ($rating) {
         $rating->is_my_wine = 0;
         $rating->save();
         $data = 'Rating is removed from my wine';
     } else {
         $error_code = ApiResponse::UNAVAILABLE_RATING;
         $data = ApiResponse::getErrorContent(ApiResponse::UNAVAILABLE_RATING);
     }
     return array("code" => $error_code, "data" => $data);
 }
Example #30
0
 public static function uploadImageWineScan($wine_unique_id)
 {
     $error_code = ApiResponse::OK;
     $user_id = Session::get('user_id');
     $wine = Wine::where('wine_unique_id', $wine_unique_id)->first();
     if ($wine) {
         if (Input::hasFile('file')) {
             $file = Input::file('file');
             $destinationPath = public_path() . '/images/' . $user_id . '/wine/' . $wine->wine_unique_id;
             $filename = date('YmdHis') . '_' . $file->getClientOriginalName();
             $extension = $file->getClientOriginalExtension();
             if (!File::isDirectory($destinationPath)) {
                 File::makeDirectory($destinationPath, $mode = 0777, true, true);
             } else {
                 File::cleanDirectory($destinationPath);
             }
             $upload_success = $file->move($destinationPath, $filename);
             $data = URL::asset('images/' . $user_id . '/wine/' . $wine_unique_id . '/' . $filename);
         } else {
             $error_code = ApiResponse::MISSING_PARAMS;
             $data = null;
         }
     } else {
         $error_code = ApiResponse::UNAVAILABLE_WINE;
         $data = ApiResponse::getErrorContent(ApiResponse::UNAVAILABLE_WINE);
     }
     return array("code" => $error_code, "data" => $data);
 }