Git Product home page Git Product logo

codeigniter-restserver's People

Contributors

adg-wandu avatar boh1996 avatar c4xp avatar chernjie avatar chriskacerguis avatar ckacerguis avatar cnanney avatar davidnewhall avatar davidstanley01 avatar dfreerksen avatar franksierra avatar grawerpl avatar ivantcholakov avatar jamieburchell avatar jamierumbelow avatar jcbuck avatar jerel avatar juanatgmo avatar natanfelles avatar onema avatar repox avatar ruthlessfish avatar sekati avatar smizdev avatar softwarespot avatar sskylar avatar teabrg avatar tjoosten avatar tpojka avatar zaherg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

codeigniter-restserver's Issues

Sending array to RESTserver

Hello,

I want to be able to send an array of for example email addresses to the RESTserver how is this done?

array("email" => "[email protected]","email" => "[email protected]") does not work.

I cannot send many of one type. What is the correct way of doing this. Does RESTserver support it?

Question about API KEYS

If i have KEYS enabled on the rest server and if i add a class and a method to the auth_override_class_method , will the api key still be needed?
Another question is how can i generate new API KEYS , or is there any way to connect the auth method to a database?

AJAX request only

This is just a very minor improvement. In the rest.php config file I created

$config['rest_ajax_only'] = TRUE;

In REST_Controller.php at the very end of the __construct() method I added

// only allow ajax requests
if( ! $this->input->is_ajax_request() && $this->config->item('rest_ajax_only') )
{
$this->response( array('error' => 'Only AJAX requests are accepted.'), 505 );
}

This basically returns an error message if the request is not coming from AJAX.

Upload images.

How to upload images using the RestServer?
Is there support for this?

requesting api keys

According to the code, the only way I can request an api key is if I already have a key. Is there something I'm missing or any way to circumvent the _detect_api_key() when requesting one? I realize that I can create a separate controller that does not extend the REST_Controller to insert the needed record into the database, but I'm trying to use the key controller that you provide as an example with the REST Server.

Thanks

JSON and CSV formats auto download

I'm not sure if there is a setting somewhere that I am missing, as I'm just starting to play with the RESTserver but it appears the following are bugs:

1.) When I go to

http://localhost:8888/social-igniter/api/users/format/json

it automatically downloads a file called "json" that has the correct data in it

Then the url redirects to:

http://localhost:8888/social-igniter/api/users/format/csv

Which has the following error:

Severity: Warning
Message: array_keys() [function.array-keys]: The first argument should be an array
Filename: libraries/REST_Controller.php
Line Number: 531

My data is coming out of a database now, but it the same thing happened even when the data was coming out of your demo arrays. Is this a setting or a feature I am not understanding somewhere?

Notice undefined index

Using CodeIgniter 2
This code:
$this->get('email')

generates:
Severity: Notice
Message: Undefined index: email
Filename: libraries/REST_Controller.php
Line Number: 450

Changing that line from:
return $this->_xss_clean($this->_get_args[$key], $xss_clean);
to:
return $this->input->_fetch_from_array($this->_get_args, $key, $xss_clean);

solves problem in codeigniter 2.
or perhas you should solve the notice the same (array_key_exists) way you solved it for put and delete?

PUT/POST errors

Not sure whats going on but PUT and POST are both being acting up recently. Take a look in cURL library too to see what might be going on.

Using special characters is not working.

Hello!

First of all, thank you for a fantastic library!

I am having problems posting special characters.

I am using this format for the request:

application/x-www-form-urlencoded

The string I am sending along with the POST request is:

street=Södergatan

This parameter is not "picked up" by codeigniter.

RESTcontroller.php failure

Hello!

I got an issue with the RESTcontroller.php file. It works perfectly fine on my local computer (mac lion)
but not on the server (Ubuntu 10.04, PHP 5.3). I get the below error. How can I fix it?

Severity: Notice

Message: Use of undefined constant CURLOPT_FAILONERROR - assumed 'CURLOPT_FAILONERROR'

Filename: libraries/REST_Controller.php

Line Number: 717

Thankful for all help!

Delete is not acting normal

Hello,

I am struggling with delete requests.
As I understand a delete request is normally sent in the URL (the ID) but now I am forced to
send it as an "attachment", like a POST request and that does not work with my RestClient (appcelerator).

Is this a bug? How can I fix it?

No PHP format support

Support for the php format is not supported.

Just need to add

// Encode as Php Text array
public function to_php()
{
    return print_r($this->_data, TRUE);
}

to Format.php

Connection Keep-alive not close

Perhaps this was done on purpose but in my case it was causing a 3 second "retrieving data" state when calling the api. To fix this in the Rest_Controller.php I explicitly set the header to -> header('Connection: close').

I also had to add some access control headers for POST GET PUT DELETE so that this would work cross domain.

If there is a better way to implement this, let me know.

PHP fatal error

I am getting this error but not sure how to fix it. can you please help?

PHP Fatal error: Cannot access protected property Example::$rest in system/core/Loader.php on line 947

when i tried to access the url as:
url/index.php/api/example/user/id/1/format/json

Using Codeigniters memcached driver seems to break output

I was trying today to use your codeigniter-restserver for the first time and i managed to get everything working fine, until i brought in the memcached driver and tried to use it to cache database results.

Somehow, reading or writing to the cache seems to "break" the REST server output.

However enabling zlib.output_compression in php.ini fixed it.

It seems that on windows machines such as mine, zlib is built in, so the extension__loaded test is allways true.
Also php returns string values for ini_get('zlib.output_compression') when its turned of in php.ini.

Casting the return value of ini_get('zlib.output_compression') as bool seems to be more trustworthy.

in REST_Codeigniter.php (line 247)

// all the compression settings must be done before sending any headers
            // if php is not handling the compression by itself
      if (@(bool)ini_get('zlib.output_compression') == FALSE) {
          // ob_gzhandler depends on zlib
          if (extension_loaded('zlib')) {
              // if the client supports GZIP compression
              if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE) {
                  ob_start('ob_gzhandler');
              }
          }
      }

Cannot auth with restclient library

I'm trying to play around with the Restserver and Client that you've so wonderfully offered, but can't seem to understand why this isn't working.

My API controller is at base_url()/api and the following is trying to access the api.

        $this->load->helper('url');

        // REST Client
        $this->load->spark('restclient/2.0.0');             
        $this->load->library('rest', array(
            'server' => base_url('api'),
            'http_user' => 'admin',
            'http_pass' => '1234',
            'http_auth' => 'digest' // or 'digest'
        ));

        $user = $this->rest->get('api/user', array('id' => 1), 'json');

        $this->rest->debug();

The problem I have is that I'm passing the right credentials, but it doesn't auth. When I hit base_url('api'), the auth prompt shows up and I can log in just fine; it's just when I'm doing it through the REST client that I can't access the api.

I'm sure it's a simple issue, but one that I'd appreciate some help with. Thank you!

XML Parsing Error

If I pass an array into $this->response() and any of the array keys happen to be prefixed with a numeric value, an 'XML Parsing Error: not well-formed' error is thrown.

Eg. Fail

$props['3gpp'] = 1;
$this->response($props, 200);

Eg. Okay

$props['x3gpp'] = 1;
$this->response($props, 200);

Not following RFC 2617 standard in Digest authentication

After lots and lots of hours debugging why Digest authentication between REST_Controller and spring rest client doesn't work, I noticed you are not following the RFC 2617 standard in sending the digest authentication header response.

All parameters in the header response should be seperated by commas. Please refer to the RFC 2617 document, section 3.5, at http://tools.ietf.org/html/rfc2617#section-3.5.

Not using comma separated parameters in the response causes clients to not be able to interpretate the response correctly.

I have tested the v2.2 of the REST_Controller for this problem, but I can see that the problem persists in the latest 2.5 build as well.

Please adjust line 629 (v2.2), 772 (v2.5)
From:
header('WWW-Authenticate: Digest realm="' . $this->config->item('rest_realm') . '" qop="auth" nonce="' . $nonce . '" opaque="' . md5($this->config->item('rest_realm')) . '"');

To:
header('WWW-Authenticate: Digest realm="'.$this->config->item('rest_realm'). '", qop="auth", nonce="'.$nonce.'", opaque="'.md5($this->config->item('rest_realm')).'"');

Best regards
//Fredrik

Format Serialize error

Hi Phil!

First, thanks for developing this "module"! =)
I'm having trouble when requesting the format in serialized format.

Using clean install, try to access:
domain.com/example/users/format/serialize

Returns the following error:

A PHP Error was encountered

Severity: Warning

Message: strlen() expects parameter 1 to be string, array given

Filename: libraries/REST_Controller.php

Line Number: 255
Array

Error in code

Fatal error: Call to undefined method CI_Output::set_status_header() in /var/www/system/application/libraries/REST_Controller.php on line 97

Adding option to return 400 and error on input missing

I would like to add a feature so that when you call

$this->get('id');

and your code requires id to be passed, it would automatically return 400 (bad input).

For that we can change put, get, delete, post functions to take second parameter, i.e.

function get($key,$error_on_missing=false)
{
....
....
// if not key exists and $error_on_missing true
$this->response(array('error'=>'Missing '.$key.' in input'),400);
}

I have created it, should I fork and send pull request?

Resetting URL parameters

I have two small patches for the rest.php config file and REST_Controller.php file. Thought I'd pass along in case you wanted to implement. I didn't think it was worth forking but forgive me if I don't quite get git yet. I've only used it for about 6 months now.

REST_Controller:
147c147
< public function _remap($object_called)
---
> public function _remap($object_called,$arguments)
207c207,213
< $this->$controller_method();
---
> if(config_item('parameter_no_override'))
> {
> call_user_func_array(array($this,$controller_method),$arguments);
> } else {
> $this->$controller_method();
> }
>
774c780
< }
\ No newline at end of file
---
> }

rest.php (in config)

259a260,261
> $config['parameter_no_override'] = TRUE;
> 
261c263
< /* Location: ./system/application/config/rest.php */
\ No newline at end of file

---
> /* Location: ./system/application/config/rest.php */

Digest auth couldn't work with IE8

GET Request:
WWW-Authenticate: Digest realm="REST API" qop="auth" nonce="4eba4f8591de5" opaque="aba3d4b49c454e1974970e7b5514b001" algorithm="MD5"

Response:
Authorization: Digest username="admin",realm="REST API" qop="auth" nonce="4eba4f8591de5" opaque="aba3d4b49c454e1974970e7b5514b001",nonce="4eba4f8591de5",uri="/auction/result",cnonce="a9cf78826c1a441a367627549e03cfc1",nc=00000001,response="c1d351b4c87729bbc94447f61551d376",qop="auth",opaque="aba3d4b49c454e1974970e7b5514b001"

Key code:
$A1 = md5($digest['username'] . ':' . $this->config->item('rest_realm') . ':' . $valid_pass);
$A2 = md5(strtoupper($this->request->method) . ':' . $digest['uri']);
EXPECTED RESPONSE = $A1 . ':' . $digest['nonce'] . ':' . $digest['nc'] . ':' . $digest['cnonce'] . ':' . $digest['qop'] . ':' . $A2;

EXPECTED RESPONSE value is "4495f0bb3634d4b629b89a72009d514a". But under my IE8 (8.0.6001.18702), response is "c1d351b4c87729bbc94447f61551d376". Why? Digest auth could work with my Firefox8.

BTW: Can anyone tell me why Chrome does not popup authorization dialogue box? (http://www.google.com/support/forum/p/Chrome/thread?tid=79d3a183e70ede42&hl=en)

Paging

Is there an easy way to bring in paging to this? I'd love to have a /list/ endpoint, but only let it find X values at a time unless they add a GET string. Thoughts anyone?

Disabled security library is generating error

I am not sure why security library is disabled i.e. //$this->load->library('security'); on line 50 REST_Controller.php,
when I try to make a GET request, the instance of REST Controller which I have created has no access to
$this->security->xss_clean($val) and the request fails. I uncommented that line and the controller works fine. Not sure why it has been disabled.

CSV & HTML error out if passed an object instead of an array

So either this is a bug or a suggestion for an improvement. My app currently passes objects from DB via active record. As i've been going through making Modules have api's the XML, JSON, and everything except CSV & HTML.

The error at the top of the page loading it is:

Severity: Warning
Message: array_keys() [function.array-keys]: The first argument should be an array
Filename: libraries/REST_Controller.php
Line Number: 788

This isn't a huge worry for me as I almost never use those formats... but figured I would submit a bug ticket.

Parameters are not being passed ahead

When using the REST_Controller the parameters are note passed ahead to the methods, it diffucults backwards compatibility and easy to handle parameters way.

Considering the way REST_Controller maps the parameters as key-value pairs, I'd like to suggest at least an associative array being passed as a the parameters. Or, in other approach, ignore the paramters name and send just the values down, keeping backwards compatibility.

What are your toughts?

Cheers,
CaioToOn!

improve serialize function by adding base64_encode

I was using the serialize function (DO not ask me why) and i had the following error: Message: unserialize(): Error at offset 0 of 7116 bytes

I changed the function and added a base64_encode
// Encode as Serialized array
private function _format_serialize($data = array())
{
return base64_encode(serialize($data));
}

to decode it use:
unserialize(base64_decode($what_ever_var_you_got));

Probable improvements in _format_xml()

Around line 673 inside _format_xml() :

// replace anything not alpha numeric
$key = preg_replace('/[^a-z_]/i', '', $key);

should probably be :

// replace anything not alpha numeric
$key = preg_replace('/[^a-z0-9_-]/i', '', $key);

That said i'm not sure it wouldn't validate a node like <1address>. I was seeking for the ability to have <address1>, <address2> and so on...

Finally, instead of having numeric keys called item, I think an improvement can be made by loading the inflector helper and using the singular function. Modified code goes like this :

    // Format XML for output
    private function _format_xml($data = array(), $structure = NULL, $basenode = 'xml')
    {
        $this->load->helper('inflector');
    
        // turn off compatibility mode as simple xml throws a wobbly if you don't.
        if (ini_get('zend.ze1_compatibility_mode') == 1)
        {
            ini_set ('zend.ze1_compatibility_mode', 0);
        }

        if ($structure == NULL)
        {
            $structure = simplexml_load_string("<$basenode />");
        }

        // loop through the data passed in.
        $data = $this->_force_loopable($data);
        foreach($data as $key => $value)
        {
            // no numeric keys in our xml please!
            if (is_numeric($key))
            {
                // make string key...
                //$key = "item_". (string) $key;
                //$key = 'item';                
                $key = (singular($basenode) != $basenode) ? singular($basenode) : 'item';
            }

            // replace anything not alpha numeric
            $key = preg_replace('/[^a-z0-9_-]/i', '', $key);

            // if there is another array found recrusively call this function
            if (is_array($value) || is_object($value))
            {
                $node = $structure->addChild($key);
                // recrusive call.
                $this->_format_xml($value, $node, $key);
            }

            else
            {
                // add single node.

                $value = htmlentities($value, ENT_NOQUOTES, "UTF-8");

                $UsedKeys[] = $key;

                $structure->addChild($key, $value);
            }
        }

        // pass back as string. or simple xml object if you want!
        return $structure->asXML();
    }

(changed is_numeric key check and recursive call $basenode to $key)

With this I can have an array "lines" containing lines output like this :

<lines>
  <line>
  ...
  </line>
  <line>
  ...
  </line>
</lines>

What do you think?

can't handle requests encoded as application/json

I am using Backbone.js along with the REST_Controller. It seems either the REST_Controller or Codeigniter cant handle requests encoded as application/json, so I had to use a property in Backbone.js to make the request as application/x-www-form-urlencoded. This is not so much a issue, but it would be nice if requests could be encoded as application/json.

For those of you using Backbone.js with the REST_Controller, just set:

Backbone.emulateJSON = true;

Backbone.js doc: http://documentcloud.github.com/backbone/#Sync-emulateJSON

Conflict when using together with Rest-Client library

I installed rest-client library using sparks command line. When i try to load the rest-client library in a Rest Controller, i have the following error

PHP Fatal error:  Cannot access protected property Example::$rest in /home/tran/public_html/peacemoon/system/core/Loader.php on line 1095

This is the code in my Rest Controller

public function test_get() {
    $this->load->spark('restclient/2.0.0');

    // Load the library
    $this->load->library('rest');

    $this->response('hello', 200);
}

PUT var issues

I'm using backbone.js to construct a frontend client using rest. The put method is causing me troubles. In my controller (server side) I can only access the variables using something like $this->request->body['varname']; If I add this to line 94 though, things seem to allow me to use $this->put('varname');:


I'm not sure so far if this is a problem with the way backbone.js constructs the request (how else can it send put vars except through the body?) or if it's just a small issue with the rest server.

Is it possible to have one controller not auth?

It seems that the current $config is global to all instances of REST_Controller, though we are building a public lite version of our API thus we want to just turn off authentication for one controller.

$this->put() doesn't work with backbone.js

Been pulling my hairs for last two hours because of this bug.

When I call model.save() from backbone the function where the put request is routed doesn't gets any PUT data.

Firebug shows right PUT parameters being sent. However $this->put('keyname') never returns data always false.

simplexml_load_string() in Format library.

Everything was working fine fine days ago, and the following issue started happening all MAMP and LAMP stacks. I am not sure how I can fix this. For this reason POST values (parameters) are not work any more.

Please fix the format library according to it.

BTW: This error is coming in your latest code (from this repo).

A PHP Error was encountered

Severity: Warning

Message: simplexml_load_string() [function.simplexml-load-string]: Entity: line 1: parser error : Start tag expected, '<' not found

Filename: libraries/Format.php

Line Number: 223

A PHP Error was encountered

Severity: Warning

Message: simplexml_load_string() [function.simplexml-load-string]: email=support%40fortsolution.com&id=1&name=Yahoo

Filename: libraries/Format.php

Line Number: 223

A PHP Error was encountered

Severity: Warning

Message: simplexml_load_string() [function.simplexml-load-string]: ^

Filename: libraries/Format.php

Line Number: 223

A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at /Users/Arfeen/Sites/test/system/core/Exceptions.php:170)

Filename: libraries/REST_Controller.php

Line Number: 241

A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at /Users/Arfeen/Sites/test/system/core/Exceptions.php:170)

Filename: libraries/REST_Controller.php

Line Number: 253

A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at /Users/Arfeen/Sites/test/system/core/Exceptions.php:170)

Filename: libraries/REST_Controller.php

Line Number: 254

A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at /Users/Arfeen/Sites/test/system/core/Exceptions.php:170)

Filename: libraries/REST_Controller.php

Line Number: 255

{"id":false,"name":false,"email":false,"message":"ADDED!"}

Empty results returning 404 status even on explicit status code

The response method checks for empty results and return a 404 in case of true. The problem is that not always we have a empty result we have a 404. Even when we passes a 200 code to the response it ignores the status and sets to 404.

I made a slightly change to the beginning of the method so that we can foce the status code. I'm sending a suggestion so the class will only set a 404 error if no status code is sent at all:

The current method seems like:
public function response($data = array(), $http_code = 200)
{
if (empty($data))
{
$http_code = 404;
}

    else
    {

    ...

And here the suggestion:

public function response($data = array(), $http_code = 0)
{

    if (empty($data) && $http_code == 0 )
    {
        $http_code = 404;

    }

    else
    {

        // Check if the status has been setted, if not sets the default.
        $http_code = $http_code || 200;
        ...

Cheers,
CaioToOn!

P.S.: great work, friend.

cross-origin resource sharing

To avoid denied requests from the rest API,
I've included in the REST_Controller.php ~line 253:

        header('Access-Control-Allow-Origin: *');

defining format in the url doesn't work

Hello,

I am having an issue with defining the format in the url, as in "/api/user/1/format/json". This gets ignored and the rest controller returns the value in the default format or whatever it is asked in the http header. Are you guys having the same issue?

Thanks,
msawired

Output gets cut off

I'm currently using REST_controller V 2.5.x and found this problem:

When the content-length gets longer then 8000 bytes (the content-length set as http header by the library) the whole JSON output always misses the last two characters, making it invalid and unusable. After some debugging I found out the whole problem went away when I removed the line where the 'content-length' header is being set in the response() function. Apparently setting the http header causes the whole JSON output to be two characters shorter than it's supposed to, only in JSON btw..

Get array variables throwing array to string conv.

Eg: /api/myservice/read?id[]=1&id[]=2&id[]=3

Results in:

A PHP Error was encountered

Severity: Warning

Message: preg_match() expects parameter 2 to be string, array given

Filename: core/REST_Controller.php

Line Number: 303

The fix appears to be a quick check on line 303 of REST_Controller.php

        // Check if a file extension is used
        elseif ($this->_get_args AND preg_match($pattern, end($this->_get_args), $matches))
        {

to

        // Check if a file extension is used
        elseif ($this->_get_args AND !is_array(end($this->_get_args)) AND preg_match($pattern, end($this->_get_args), $matches))
        {

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.