Example #1
0
 /**
  * Render the selected script
  * @param RestServer $rest 
  * @return RestServer
  */
 function show(RestServer $rest)
 {
     ob_start();
     $params = $this->props;
     include $this->file;
     $content = ob_get_clean();
     $rest->getResponse()->setResponse($content);
     return $rest;
 }
 function testNamed()
 {
     $rs = new RestServer();
     $rs->setMatch(array("", "user", ":me"));
     $r = $rs->getRequest();
     $r->setURI("/user/diogo");
     $this->assertEquals($r->getURI("me"), "diogo");
     $this->assertEquals($r->getURI("user"), null);
 }
Example #3
0
 public function __construct()
 {
     $data = RestServer::process_request();
     $this->method = $data->get_method();
     $this->params = $data->get_params();
     $this->request_vars = $data->get_request_vars();
 }
Example #4
0
 /**
  * Parse the incoming request and store the request params and meta data into
  * the class variables.
  * 
  * @return RestServer
  */
 public static function process_request()
 {
     $request_method = strtolower($_SERVER['REQUEST_METHOD']);
     $request_params = $_SERVER['REQUEST_URI'];
     $request_params = strstr($request_params, WS_API_BASE_DIR);
     $request_params = explode(DIRECTORY_SEPARATOR, $request_params);
     array_shift($request_params);
     $return_obj = new RestServer();
     $data = array();
     switch ($request_method) {
         case 'get':
             $data = $_GET;
             break;
         case 'post':
             $data = $_POST;
             break;
         case 'put':
             parse_str(file_get_contents('php://input'), $put_vars);
             $data = $put_vars;
             break;
     }
     $return_obj->set_method($request_method);
     $return_obj->set_params($request_params);
     $data = Validate::sanitize($data);
     $return_obj->set_request_vars($data);
     if (isset($data['data'])) {
         $return_obj->set_data(json_decode($data['data']));
     }
     return $return_obj;
 }
Example #5
0
 public function show(RestServer $rest)
 {
     $r = "Method=" . $rest->getRequest()->getMethod() . "\n";
     $r .= "URI=" . $rest->getRequest()->getRequestURI() . "\n";
     foreach ($rest->getRequest()->getGET() as $key => $value) {
         $r .= "GET[" . $key . "]=" . $value . "\n";
     }
     foreach ($rest->getRequest()->getPOST() as $key => $value) {
         $r .= "POST[" . $key . "]=" . $value . "\n";
     }
     $rest->getResponse()->setResponse(nl2br($r));
     return $rest;
 }
Example #6
0
 /**
  * The main execution
  *
  * It will verify the URL and
  * call the module and action
  *
  * When the call is not Ajax, then
  * there's no place like home
  */
 public function execute()
 {
     $uri = self::getUri();
     /**
      * When server is running as a RESTful server
      */
     if (RESTFUL == '1') {
         RestServer::runRestMethod($uri);
         $this->terminate();
     }
     /**
      * When it's required to be a logged user to access
      */
     if (REQUIRE_LOGIN == '1') {
         $this->checkAuthenticated($uri);
     }
     /**
      * When the request is not running over ajax,
      * then call the home for full page rendering
      * before calling the requested method
      */
     if (!$this->isAjax()) {
         $this->controller = $this->requireHome();
         if (self::isLoggedIn()) {
             $this->controller->newModel('uid');
         }
         $this->controller->itStarts($uri);
         $this->terminate();
     }
     /**
      * Normal Ajax Request, call the method only
      */
     $this->runMethod($uri);
     $this->terminate();
 }
Example #7
0
<?php

//spl_autoload_register();
set_include_path(get_include_path() . PATH_SEPARATOR . 'src');
require_once 'src/bootstrap.php';
require_once 'src/controller_mwp.php';
require_once 'vendor/jacwright/restserver/RestServer.php';
$doapi = true;
if ($doapi) {
    $mode = 'debug';
    $server = new RestServer($mode);
    $server->addClass('MWP_Controller');
    $server->addClass('WP_Sites', '/sites');
    $server->handle();
} else {
    include 'html/home.html';
}
<?php

ob_start();
require_once "RestServer.php";
$rest = new RestServer('Hello');
$rest->handle();
header('Content-type: application/json');
function php_rlike($str)
{
    $a1 = array('/[aабдегжвAАБДЕГВ]/', '/[eийклEИЙКЛ]/', '/[iмнопIМНОП]/', '/[oцфхртушOЦФХТУШ]/', '/[uьыщъЬЫЩЪ]/', '/[yяэЭ]/', '/[nNсС]/', '/[зЗ]/');
    $a2 = array('[aабдегжвAАБДЕГВ]', '[eийклEИЙКЛ]', '[iмнопIМНОП]', '[oцфхртушOЦФХТУШ]', '[uьыщъЬЫЩЪ]', '[yяэЭ]', '[nNсС]', '[зЗ]');
    return preg_replace($a1, $a2, $str);
}
function utf8_encode_deep(&$input)
{
    if (is_string($input)) {
        $input = utf8_encode($input);
    } else {
        if (is_array($input)) {
            foreach ($input as &$value) {
                utf8_encode_deep($value);
            }
            unset($value);
        } else {
            if (is_object($input)) {
                $vars = array_keys(get_object_vars($input));
                foreach ($vars as $var) {
                    utf8_encode_deep($input->{$var});
                }
            }
        }
Example #9
0
    {
        try {
            // get connession
            $conn = new PDO("mysql:host=" . $GLOBALS['$dbhost'] . ";dbname=" . $GLOBALS['$dbname'] . "", $GLOBALS['$dbuser'], $GLOBALS['$dbpass']);
            // set the PDO error mode to exception
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            // select query
            $sql = "SELECT    country_code,\n                          GROUP_CONCAT(CONCAT( release_tag,'#',num )) AS installations,\n                          country_name\n\n                FROM      ( SELECT  country_code,\n                                    release_tag,\n                                    country_name,\n                                    reg_date,\n                                    COUNT(release_tag) AS num\n                            FROM phone_home_tb\n                            WHERE reg_date >= DATE_SUB(CURDATE(), INTERVAL 10 DAY)\n                            GROUP BY release_tag, country_code\n                          ) AS t\n\n                GROUP BY  country_code;";
            // prepare statement
            $stmt = $conn->prepare($sql);
            // execute query
            $stmt->execute();
            // create new empty array
            $infos = array();
            // set the resulting array to associative
            for ($i = 0; $row = $stmt->fetch(); $i++) {
                array_push($infos, array('installations' => $row['installations'], 'country_code' => $row['country_code'], 'country_name' => $row['country_name']));
            }
            // close connession
            $conn = null;
            // return info inserted
            return '{"nethservers":' . json_encode($infos) . '}';
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }
}
$rest = new RestServer();
$rest->addServiceClass(AddInfo);
$rest->addServiceClass(GetInfo);
$rest->handle();
Example #10
0
<?php

//define('ABS_PATH', str_replace('\\', '/', dirname(dirname(dirname($_SERVER['SCRIPT_FILENAME'])) . '/')));
//require_once ABS_PATH . 'oc-load.php';
require_once '../../oc-load.php';
require_once '../RestServer.php';
require_once '../RestDAO.php';
require_once 'apiServer.php';
$server = new RestServer('debug');
//$server->refreshCache();
$server->addClass('apiServer');
$server->handle();
<?php

require_once './autoload.php';
try {
    // Rest Server Class New Instance
    $restServer = new RestServer();
    //Rest Server starts with a 200 message
    $restServer->setStatus(200);
    //Rest Server Variables
    $resource = $restServer->getResource();
    //Get the Resources
    $verb = $restServer->getVerb();
    //Get the Verb
    $getData = $restServer->getServerData();
    //Get Data
    $id = $restServer->getId();
    //Get ID
    //Get, Put, Post, Delete
    if ($resource === 'corps') {
        $resourceCorps = new Corporations();
        //Corporations New Instance
        $dataResults = null;
        if ($verb === 'GET') {
            if ($id === NULL) {
                $dataResults = $resourceCorps->getAll();
            } else {
                $dataResults = $resourceCorps->get($id);
            }
        }
        if ($verb === 'PUT') {
            if ($id === NULL) {
Example #12
0
<?php

include_once './bootstrap.php';
$restServer = new RestServer();
try {
    $restServer->setStatus(200);
    $resource = $restServer->getResource();
    $verb = $restServer->getVerb();
    $id = $restServer->getId();
    $serverData = $restServer->getServerData();
    $config = array('DB_DNS' => 'mysql:host=localhost;dbname=PHPAdvClassFall2015', 'DB_USER' => 'root', 'DB_PASSWORD' => '');
    $db = new PDO($config['DB_DNS'], $config['DB_USER'], $config['DB_PASSWORD']);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    if ('corp' === $resource) {
        $resourceData = new CorpResource();
        if ('GET' === $verb) {
            if (NULL === $id) {
                $restServer->setData($resourceData->getAll());
            } else {
                $restServer->setData($resourceData->get($id));
            }
        }
        if ('POST' === $verb) {
            if ($resourceData->post($serverData)) {
                $restServer->setMessage('Corp Added');
                $restServer->setStatus(201);
            } else {
                throw new Exception('Corp could not be added');
            }
        }
        if ('PUT' === $verb) {
Example #13
0
<?php

function __autoload($class_name)
{
    include $class_name . '.php';
}
//spl_autoload_register(); // don't load our classes unless we use them
$mode = 'debug';
// 'debug' or 'production'
$server = new RestServer($mode);
//$server->refreshCache(); // uncomment momentarily to clear the cache if classes change in production mode
$server->addClass('NowController', '/kt/now.js');
$server->addClass('KtController', '/kt/kt.js');
$server->addClass('UserController', '/kt/user.js');
$server->addClass('TupleController', '/kt/tuple.js');
$server->addClass('LocController', '/kt/loc.js');
$server->addClass('BrowseController', '/kt/browse.js');
$server->addClass('NewController', '/kt/new.js');
$server->handle();
Example #14
0
 * domus.Link :: PHP Web-based frontend for Heyu (X10 Home Automation)
 * Copyright (c) 2007, Istvan Hubay Cebrian (istvan.cebrian@domus.link.co.pt)
 * Project's homepage: http://domus.link.co.pt
 * Project's dev. homepage: http://domuslink.googlecode.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope's that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details. You should have 
 * received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, 
 * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
require_once "./apiinclude.php";
$dirname = dirname(__FILE__);
require_once $dirname . DIRECTORY_SEPARATOR . 'lib/classes/restserver.php';
require_once $dirname . DIRECTORY_SEPARATOR . 'api/domuscontroller.php';
spl_autoload_register();
// don't load our classes unless we use them
$mode = 'production';
// 'debug' or 'production'
$server = new RestServer($mode, "domus.Link", "db/");
# $server->refreshCache(); // uncomment momentarily to clear the cache if classes change in production mode
$config = $_SESSION['frontObj']->getConfig();
$server->addClass('DomusController', $config['url_path'] . "/api.php/");
$server->handle();
Example #15
0
 /**
  * Returns the error JSON when server
  * is running RESTful requests
  *
  * @param array $error
  * @return string
  */
 private function throwRestException(array $error)
 {
     echo json_encode($error, JSON_UNESCAPED_UNICODE);
     RestServer::terminate();
 }
Example #16
0
<?php

//error_reporting(E_ALL);
//ini_set('display_errors', 1);
include 'Core.php';
require 'RestServer.php';
$rest = new RestServer('production');
$rest->cacheDir = '/var/www/rest/cache';
// File-based REST APIs
const BEHAVIOR = 'FILE';
const DIRECTORY = '/var/www/rest/provision/';
// REST API proxy pass-thru -- using this will allow for generation of configs and validation, but all config changes
// are proxied to a third party service
// const BEHAVIOR = 'REST';
// const URL = 'http://apps001-sdflkjsflksdjfkls-ord.2600hz.com:8000/v1/accounts/bb361ffd5a373ac463ac9/';
if (BEHAVIOR == 'REST') {
    $handler = new Pest(URL);
} else {
    $handler = new FileRest(DIRECTORY, $rest);
}
// A simple router, to invoke the proper class
// Parse URL here
$uri = $rest->getPath();
$verb = $rest->getMethod();
header('Access-Control-Allow-Headers:Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, X-Auth-Token');
//header('Access-Control-Allow-Methods:'.$verb);
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Max-Age:86400');
// Adjust per your expectations from the software you're using
$regex = preg_match('/\\/(.*)\\/accounts\\/(.*)\\/(.*)\\/(.*)/', $uri) ? '/\\/(.*)\\/accounts\\/(.*)\\/(.*)\\/(.*)/' : '/\\/(.*)\\/accounts\\/(.*)\\/(.*)/';
<?php

include_once './models/RestServer.php';
$restServer = new RestServer();
try {
    $restServer->setStatus(200);
    $restServer->getResource();
    $restServer->getId();
} catch (Exception $ex) {
    $restServer->setErrors($ex->getMessage());
}
$restServer->outputResponse();
?>
;
Example #18
0
 /**
  * @return mixed|string data of request body
  */
 public function getRequestBody()
 {
     $restServer = new RestServer('debug');
     $restServer->format = 'json';
     return $restServer->getData();
 }
Example #19
0
        if (isset($_GET['callback'])) {
            return $_GET['callback'] . '(' . json_encode($data) . ');';
        } else {
            return json_encode($data);
        }
    }
    public function isPost()
    {
        return isset($_POST) && count($_POST) > 0 || isset($_FILES) && count($_FILES) > 0;
    }
    public function getPostInput($field)
    {
        if (!$this->isPost()) {
            return;
        }
        // It's a file input
        if (isset($_FILES[$field])) {
            // Reorder the data
            $result = array();
            foreach ($_FILES[$field]['name'] as $k => $d) {
                $result[] = array('name' => $d, 'size' => $_FILES[$field]['size'][$k], 'tmpfile' => $_FILES[$field]['tmp_name'][$k], 'error' => $_FILES[$field]['error'][$k]);
            }
            return $result;
        }
        if (isset($_POST[$field])) {
            return $_POST[$field];
        }
    }
}
$server = new RestServer();
$server->response();
Example #20
0
<?php

include_once './bootstrap.php';
$restServer = new RestServer();
try {
    $restServer->setStatus(200);
    $resource = $restServer->getResource();
    $verb = $restServer->getVerb();
    $id = $restServer->getId();
    $serverData = $restServer->getServerData();
    $config = array('DB_DNS' => 'mysql:host=localhost;port=3306;dbname=PHPAdvClassFall2015', 'DB_USER' => 'root', 'DB_PASSWORD' => '');
    $db = new PDO($config['DB_DNS'], $config['DB_USER'], $config['DB_PASSWORD']);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    if ('address' === $resource) {
        $resourceData = new AddressResoruce();
        if ('GET' === $verb) {
            if (NULL === $id) {
                $restServer->setData($resourceData->getAll());
            } else {
                $restServer->setData($resourceData->get($id));
            }
        }
        if ('POST' === $verb) {
            if ($resourceData->post($serverData)) {
                $restServer->setMessage('Address Added');
                $restServer->setStatus(201);
            } else {
                throw new Exception('Address could not be added');
            }
        }
        if ('PUT' === $verb) {
Example #21
0
<?php

include_once './autoload.php';
try {
    $RestServer = new RestServer();
    $RestServer->setStatus(200);
    $id = $RestServer->getId();
    $resource = $RestServer->getResource();
    $verb = $RestServer->getVerb();
    $data = $RestServer->getServerData();
    if ('corps' === $resource) {
        $corps = new Corps();
        $results = null;
        if ($verb === 'GET') {
            if ($id === NULL) {
                $results = $corps->getAll();
            } else {
                $results = $corps->get($id);
            }
        }
        if ($verb === 'PUT') {
            if ($id === NULL) {
                throw new InvalidArgumentException('Corporation ID ' . $id . ' was not found');
            } else {
                $results = $corps->put($data, $id);
                $RestServer->setMessage($id . ' updated');
            }
        }
        if ($verb === 'POST') {
            if ($corps->post($data)) {
                $RestServer->setMessage('Corporation  Added');
 /**
  * Update survey
  * 
  * @param int $id survey id
  * 
  * Request body must be an object with properties to update
  * 
  * @return array
  * 
  * @throws RestBadParameterException
  * @throws RestMissingParameterException
  * @throws RestSurveyNotFoundException
  * @throws RestNotAllowedException
  */
 public static function put($id)
 {
     if (!$id) {
         throw new RestMissingParameterException('id');
     }
     // Get survey and update data
     $survey = Survey::fromId($id);
     $data = RestServer::getRequest()->input;
     // Check permissions
     if (!Auth::isAdmin() || !$survey->owner->is(Auth::user())) {
         throw new RestNotAllowedException('update survey ' . $survey->id);
     }
     if (property_exists($data, 'title')) {
         if (!$data->title) {
             throw new RestMissingParameterException('survey.title');
         }
         $survey->title = $data->title;
     }
     if (property_exists($data, 'description')) {
         $survey->description = $data->description;
     }
     $survey->save();
     return self::cast($survey);
 }
 /**
  * Constructor
  * 
  * @param string $message message id to return to the interface
  * @param int $code http error code
  * @param mixed $details details about what happened (for logging)
  */
 public function __construct($message, $code = 0, $details = '')
 {
     $request = RestServer::getRequest();
     parent::__construct($message, $details, $request ? $request->context : null);
     $this->code = $code;
 }
Example #24
0
<?php

/**
 * This file is part of the BaseProject project.
 * 2015 
 * Copyright (c) RENATER
 */
require_once '../includes/core/init.php';
Logger::setProcess(ProcessTypes::REST);
RestServer::process();
Example #25
0
<?php

require 'RestServer.php';
class HelloWorld
{
    function hello($name)
    {
        return "Hello from " . $name;
    }
}
$server = new RestServer();
$server->setClass("HelloWorld");
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    $server->handle();
} else {
    echo "Ce serveur REST peut gérer les fonctions suivantes : ";
    $functions = $server->getFunctions();
    foreach ($functions as $func) {
        echo $func . "\r";
    }
}
Example #26
0
<?php

// bootstrap wp
require_once "../../../../wp-load.php";
require_once "../includes/mm-constants.php";
require_once "../includes/init.php";
require_once "classes/class.response.php";
require_once "classes/class.utils.php";
require_once "include/loadLibrary.php";
require_once 'controllers/class.webcontroller.php';
require_once 'controllers/class.membercontroller.php';
require_once 'controllers/class.releasecontroller.php';
require_once 'include/constants.php';
$_GET["q"] = isset($_GET["q"]) && $_GET["q"] != null ? $_GET["q"] : "";
$rest = new RestServer($_GET["q"]);
$ref = isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "";
$ip = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : "";
$rest->addMap("GET", "/?", "WebController");
if (MM_Utils::isMemberMouseActive() && MM_MemberMouseService::hasPermission(MM_MemberMouseService::$FEATURE_API)) {
    $rest->addMap("GET", "/createMember", "MemberController::createMember");
    $rest->addMap("POST", "/createMember", "MemberController::createMember");
    $rest->addMap("GET", "/purchaseBundle", "MemberController::purchaseBundle");
    $rest->addMap("POST", "/purchaseBundle", "MemberController::purchaseBundle");
    $rest->addMap("GET", "/updateMember", "MemberController::updateMember");
    $rest->addMap("POST", "/updateMember", "MemberController::updateMember");
    $rest->addMap("GET", "/getMember", "MemberController::getMember");
    $rest->addMap("POST", "/getMember", "MemberController::getMember");
    // added as temporary end point for SamCart to use until our new API is released
    $rest->addMap("GET", "/addMember", "MemberController::addMember");
    $rest->addMap("POST", "/addMember", "MemberController::addMember");
    $rest->addMap("GET", "/addBundle", "MemberController::addBundle");
Example #27
0
<?php

require 'RestServer.php';
require 'TestController.php';
$server = new RestServer('debug');
$server->addClass('TestController');
$server->handle();
 /**
  * Get user(s)
  * 
  * Call examples :
  *  /user : get all users (admin)
  *  /user/@me : get current user (null if no session)
  *  /user/<uid> : get user (admin or current)
  * 
  * @param int $id user id to get info about
  * 
  * @return mixed
  * 
  * @throws RestAuthenticationRequiredException
  * @throws RestAdminRequiredException
  * @throws RestBadParameterException
  */
 public static function get($id = null)
 {
     // "Session getter"
     if ($id == '@me') {
         return Auth::isAuthenticated() ? static::cast(Auth::user()) : null;
     }
     // Need to be authenticated ...
     if (!Auth::isAuthenticated()) {
         throw new RestAuthenticationRequiredException();
     }
     $request = RestServer::getRequest();
     if ($id) {
         $user = User::fromId($id);
         // Check ownership
         if (!$user->is(Auth::user()) && !Auth::isAdmin()) {
             throw new RestOwnershipRequiredException(Auth::user()->id, 'user = ' . $user->id);
         }
         return self::cast($user);
     }
     if (!Auth::isAdmin()) {
         throw new RestAdminRequiredException();
     }
     $users = User::all();
     if ($request->filterOp) {
         $users = static::filter($users, $request->filterOp);
     }
     if ($request->updatedSince) {
         $time = $request->updatedSince;
         $users = array_filter($users, function ($user) use($time) {
             return $user->last_activity >= $time;
         });
     }
     $data = array();
     foreach ($users as $user) {
         $data[] = static::cast($user);
     }
     return $data;
 }
Example #29
0
 function testMapping()
 {
     $r = new RestServer();
     $r->addMap("GET", "/user", "Foo");
     $r->addMap("GET", "/user/diogo", "Bar");
     $r->addMap("GET", "/user/[0-9]+", "Hal");
     $r->addMap("GET", "/user/[a-z]+", "Hal2");
     $r->addMap("GET", "/user/[a-z]+/profile", "Hal2::profile");
     $r->addMap("GET", "/user2/:name", "Named");
     $r->addMap("GET", "/user2/:name/:id", "Named2");
     $r->setQuery("/user");
     $this->assertEquals($r->getMap("GET", "/user"), "Foo");
     $this->assertEquals($r->getMap("GET", "/user/diogo"), "Bar");
     $this->assertEquals($r->getMap("GET", "/user/123"), "Hal");
     $this->assertEquals($r->getMap("GET", "/user/abc"), "Hal2");
     $this->assertEquals($r->getMap("GET", "/user/abc/profile"), "Hal2::profile");
     $this->assertEquals($r->getMap("GET", "/user/123abc"), null);
     $this->assertEquals($r->getMap("GET", "/user2/abc"), "Named");
     $this->assertEquals($r->getMap("GET", "/user2/abc/123"), "Named2");
 }
Example #30
0
<?php

/**
 * This is the gatekeeper of the API
 */
require_once 'base.inc.php';
if (AUTH_OPTION === true) {
    $auth = new Auth(AUTH_TYPE);
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $client_ip = $_SERVER['REMOTE_ADDR'];
}
$server = new RestServer();
$server->start_server();