How do I change the timeout for PHP ApaiIO Amazon library? - php

How do I change the timeout for the Amazon product library PHP client? I searched the code for timeout, but it's not obvious how to pass a different timeout value.
https://github.com/Exeu/apai-io/search?utf8=%E2%9C%93&q=timeout

Based on the link you provided, there is no way to pass in a parameter for the timeout. You can see it's hardcoded right there in the constructor. However you can easily extend the class and re-write the constructor like this. Just call eRequest instead of Request.
You can see that $options is private, so you know it's not being edited elsewhere and a simple ctrl-f can tell you that it's not being changed anywhere else in that class, so these are your only options for changing it.
class eRequest extends Request{
__construct(array $options = array(), $timeout=10){
$this->options = array(
self::USERAGENT => "ApaiIO [" . ApaiIO::VERSION . "]",
self::CONNECTION_TIMEOUT => $timeout,
self::TIMEOUT => $timeout,
self::FOLLOW_LOCATION => 1
);
$this->setOptions($options);
}
}
..Or if there are other parts of the library that use this, you will have to alter the actual source of the library.

Related

PHP prints out a buffer string into web-page on certain circuntances?

I don't know how to explain it but, I'm gonna give it a try.
This problem concerns 2 servers, a local and a hosting server. Both servers are running the same PHP version which is 7.0 [with almost same configurations]. And 2 controller actions. And the problem comes from $app->run($input, $out); from the codes below.
I have in my controller that action:
/**
* #Route("/testJson")
*/
public function testJsonAction() {
$app = new \Symfony\Bundle\FrameworkBundle\Console\Application($this->get("kernel"));
$app->setAutoExit(false);
$opt = array("command" =>
"doctrine:generate:entity",
"--entity" => "GuervylEditorBundle:TestOnline",
"--fields" => "kl:string");
$input = new \Symfony\Component\Console\Input\ArrayInput($opt);
$out = new \Symfony\Component\Console\Output\BufferedOutput();
$app->run($input, $out);
$out->fetch();
return new JsonResponse(\json_encode(["a" => "b", "c" => "d"]));
}
Calling this action from the local and hosting server returns "{\u0022a\u0022:\u0022b\u0022,\u0022c\u0022:\u0022d\u0022}" and with Content-Type
application/json which is great, it's the expected result.
Now, here comes the problem:
That almost same code above, I set it inside another class, I call it from another controller action, which passes through 4 methods from different classes to call the method that has the code above [callCommand]
This is the method that implement the code:
public function callCommand($cmd, $opt, &$mykernel = null) {
if ($mykernel == NULL) {
$mykernel = new myKernel("dev", false, __DIR__ . "/../Resources/template_2.8/app");
}
$app = new \Symfony\Bundle\FrameworkBundle\Console\Application($mykernel);
$app->setAutoExit(false);
$opt = array("command" => $cmd) + $opt;
$input = new \Symfony\Component\Console\Input\ArrayInput($opt);
$out = new \Symfony\Component\Console\Output\BufferedOutput();
$app->run($input, $out);
}
From that other controller action, I also return a json content at the end. I can't show the code because it's too big.
When I call that controller action from my localhost, I get the JSON content and Content-Type: application/json which is fine.
But calling it from the hosting server I get extra texts like:
Entity generation
created ./src/Guervyl/EditorBundle/Entity/TestCase.php
> Generating entity class src/Guervyl/EditorBundle/Entity/TestCase.php: OK!
> Generating repository class src/Guervyl/EditorBundle/Repository/TestCaseRepository.php: OK!
Everything is OK! Now get to work :).
Which is the output texts from the console when calling $app->run($input, $out);. After that I get the HTTP header that I set then the json content. And also the content-type is application/x-httpd-php5.
That error only happens on a specific hosting server. I tested other hosting server the code works like on my local server.
My question is why am I getting the error on that specific hosting? Is there something I can change from the PHP.ini to fix it? Because I really need to host my website on that hosting because it offers me great features that I need but the others don't or they are too expensive.
Well, After I debugged the code I noticed that error happened because I did not set the --no-interaction option. So without that option, Symfony was waiting for input when no fields are specified for an Entity.

Making simple operations in Cloudant using PHP

I have a simple SPA built with AngularJS.
I'm attempting now to do 2 simple operations in a CouchDB hosted in Cloudant using a PHP file: save a document, and get all documents.
All premade examples of CRUD operations using PHP are extremely complex, using multiple dependencies and I didn't get far with them, as PHP is not really my thing.
The last one I tried is this one, it gives me a Cannot redeclare class Cloudant in /.../comanda/incoming/test/Cloudant.php on line 10 error and I didn't manage to fix it.
What I see in the code though, is how they make the server log in, and some get/put.
It looks like this:
class Cloudant {
function __construct($server,$db,$username,$password){
$username = 'user';
$password = 'pass';
$server = 'cloudant.com';
$db = 'dbname';
$this->server = "https://".$username.":".$password.'#'.$username.$server;
$this->db = $db;
$this->header_short = "Content-Type: application/json";
$this->header = $this->header_short."\r\nContent-Length: ";
}
//curl -X PUT {USERNAME}:{PASSWORD}#{USERNAME}.cloudant.com/{DB}{/ID} -d ....
function upsert_doc( $id, $data ){ // to update - include _rev in document body
return $this->call($id, array(
'method' => 'POST',
'header' => $this->header . strlen($data) . "\r\n",
'content' => $data));
}
//curl -X GET {USERNAME}:{PASSWORD}#{USERNAME}.cloudant.com/{DB}/{ID}
function get( $id ){
return $this->call($id, array(
'method' => 'GET',
'header' => $this->header_short
));
}
Any tips on how to simplify this? I'm looking into having one PHP file to make the authentication + saving JSON array, and another to authenticate + getting all documents.
The error is literally that you can't redeclare the class "Cloudant" because there's another one in your project somewhere - renaming this class should help with that.
For talking to Cloudant from PHP, it's an HTTP interface so while there are libraries, you don't necessarily need one for some simple queries as you mentioned. I usually use Guzzle but you could use the curl extension or the built-in stream handlers. Some examples of PHP code that uses Guzzle to talk to Cloudant are here in a sample app I built, this might help give you some pointers: https://github.com/ibm-cds-labs/guestbook/blob/master/src/web/classes/Guestbook/CommentService.php

how to fix CConsoleApplication.user undefined in a command class in yii framework?

I am having that error , whenever I ran my simple cron script in shell ,
any idea how to fix that thing ?, from the error itself, it says the .user is undefiend,
when I placed the
'user' => array(
// enable cookie-based authentication
'allowAutoLogin' => true,
'loginUrl' => array('myaccount/blah/login'),
in the console config, it is looking for a "Class" ,, what class am i supposed to include in that array? , this user login url is using an LDAP stuff in loggin in and authentication, what should I do ?
A CConsoleApplication is for handling offline tasks. For example, the application starts a cronjob within a linux system. The application checks each day if a registered user of your website should change his password, because it must be changed every 3 month. If the password expired send an email.
To preselecting the users you have set a scope condition to check the status of a user, as well as a scope to restricted signed in users on her own data:
public function scopes(){
return array(...,
'user' => array(
'condition'=>'id='.Yii::app()->user->id,
),
'active' => array(
'condition'=>'status='.self::STATUS_ACTIVE,
), ...
);
}
Now, in your CCA-Code you use the active scope to get all users:
$usersArray = User::model()->active()->findAll(); ...foreach.... The Problem here is in the use of the extended class, the CActiveRecord-class. Mostly used as a class extension in models, which are stored in a database. In this CActiveRecord-class the CActiveRecord->__call function is used to get all stored scopes of a model. After that the class merged the actually requested scopes with the rest of the database criteria. The fact that all scopes are loaded first occures the error in loading the user-scope, include Yii::app()->user->id. The WebUser is called and throws the exception 'CException' with message 'attribute "CConsoleApplication.user is not defined'. You wouldn't call the WebUser, but the automatism arrange this for you :-)
So, do it like schmunk says. Generate in your scope code an exception part where ensures that Yii::app()->user is not called:
public function scopes(){
if (Yii::app() instanceof CConsoleApplication) {
$user = array(''); //no condition
}else{
$user = array(
'condition'=>'id='.Yii::app()->user->id,
);
}
return array(
'user' => $user,
'active' => array(
'condition'=>'status='.self::STATUS_ACTIVE,
), ...
);
}
I hope the explanation helps and perhaps also for other problems.
Short answer: You can't use CWebUser in console application. Don't include it in your config/console.php
Long(er) answer: If you rely on a component, which needs CWebUser, you'll have to detect this in the component and create some kind of workaround for this case. Have a look at this code piece for an example how to detect, if you're running a console app.
Try this
public static $console_user_id;
public function init() {
if (Yii::app() instanceof CConsoleApplication) {
if (self::$console_user_id) $this->id = self::$console_user_id;
return false;
}
parent::init();
}
solved my problem by using update, instead of save in the script...no need to use user array and CWebUser class
I had the same problem. Screened all answers given here and found some good point, but solved my problem my way, although it may not be the best.
First off all I had to figure out that my Cron Jon threw the aforementioned Exception because inside the Cron job I was running a script which had this part of code in it
if(Yii::app()->user->isAdmin()) {...} else {...}
So the console threw the error since the user was not defined. I changed my code in such a way that I tested if the console was running it. The changed code is as follows:
$console = false;
try {
$test = Yii::app()->user->isAdmin();
}
catch (CException $e) {
$console = true;
}
if($console || (!$console && Yii::app()->user->isAdmin()) {...} else {...}
As said, not perfect, but maybe a solution for someone.

Seemingly random SoapFault: not a valid method

I'm experiencing a problem with my SOAP solution. Sometimes I get an error saying the following:
Function (functionA) is not a valid method for this service
Edit 8 months later
Although I could not find the cause of the problem I was able to work around it. Whenever I recieve an response from the API I check for the SoapFault and just send another identical request and use the answer that comes back the second time.(posted as an answer)
This occurs in calls from PHP like:
functionA() - expected response
functionA() - expected response
functionA() - SoapFault
functionA() - expected response
Same result is to be expected in all the above calls and the same parameters are used(if any). Since it's working fine for almost all calls I know that the function and the corresponding WSDL is there.
What I thougt were the problem was caching an old version which would not have that function. I tried disabling the caching with:
ini_set("soap.wsdl_cache_enabled", "0");
And makeing every call with added with a random dummy parameter as well as disabling it when I use Zend_SoapClient.
'cache_wsdl' = false
I hope someone could point me in any direction or have any direct suggestion on what could be the cause.
My code looks like:
public function __construct()
{
$wsdl = "http://catlovers.nl/index.php?wsdl&dummy=".rand(1000,9999);
$this->_client = new Zend_Soap_Client($wsdl, array(
'soapVersion' => SOAP_1_1,
'cache_wsdl' => false
));
$this->_client->setWsdlCache(false);
}
function __call($name, $arguments) // Calls are made this way
{
array_unshift($arguments, $this->_apiKey, $this->_user, $this->_password);
return call_user_func_array(array($this->_client, $name), $arguments);
}
public function getCat()
{
return ($this->__call('getCat',array()));
}
On "the other side" I have:
$server = new nusoap_server();
$server->wsdl->addComplexType('Cat', ....
$server->register( 'getCat', return Cat ...
function getCat($apikey, $email, $password)
{
$cat = $db->get("redCat");
return $cat;
}
First of all, try to call function using built-in SoapClient class and printing debug information:
$wsdl = "http://abcd.com/index.php?wsdl&dummy=".rand(1000,9999);
$soap = new SoapClient($wsdl, array(
'cache_wsdl' => WSDL_CACHE_NONE,
'trace' => true,
));
try {
var_dump($soap->functionA());
} catch ( Exception $ex ) {
var_dump($ex);
}
var_dump($soap->__getLastRequest());
var_dump($soap->__getLastRequestHeaders());
var_dump($soap->__getLastResponse());
var_dump($soap->__getLastResponseHeaders());
This way you'll know where is the problem. If everything is ok all the time, the problem is in Zend's class. If not, look what service responds. May be there is some server-side error or dummy generation with such id fails
I guess your problem is related to nusoap, because for many years I'm using PHP soap server/client and I never faced this problem. (but I always had strange problems with nusoap lib)
currently I'm using jool.nl web service helper which is very powerfull yet neat and object oriented library not only makes coding easier and cleaner but also provides you object oriented approach to web service designing. It also provides a nice web interface for your web service with documentation.
As this library uses internal PHP SOAP server I'm pretty sure you're problem will be disappear then.
I suggest you to give it a try and I'm sure if you make your first web service with this library you will never try something else.
I hope this helps you.
So the problem was still there after trying other solutions so I was never able to find underlying cause of the problem. On the other hand I found a way to work around the problem that has been working since I wrote it. This is how my call to the API looks like with user,password and key for authentication.
function __call($name, $arguments)
{
/* Using the stored data to ensure that the user is allowed to access */
/* ............... */
array_unshift($arguments, $this->_apiKey, $this->_user, $this->_password);
$call = call_user_func_array(array($this->_client, $name), $arguments);
if(isset($call->faultstring) && substr(trim($call->faultstring),0,7) == "Function")
{
$recall = call_user_func_array(array($this->_client, $name), $arguments);
return $recall;
}
else
return $call;
}
This is basicly: if it doesn't work the first time just try again.

Zend Cache Backend Static Remove/Clean

I'm trying to implement a cache using Zend Cache. I use the following code to initialize the caches.
$tagCache = Zend_Cache::factory('Core',
'File',
array('automatic_serialization' => true),
array('cache_dir' => $cfg['instdir']. 'Cache_dir'));
$cache = Zend_Cache::factory('Capture',
'Static',
array(),
array('index_filename' => 'index',
'public_dir' => $cfg['instdir'] . 'Cached',
'tag_cache' => $tagCache));
I use the following code to start caching:
$id = bin2hex($_SERVER["REQUEST_URI"]);
$cache->start($id, array());
The cache files are generated but I can't delete them using the remove() method (the cache doesn't refresh):
$cache->remove($id); // id generated like above from the REQUEST_URI of the page I want to refresh
What am I doing wrong ?
Thanks.
$cache->remove() is a proxy to the backend's remove() method. In this case you are using the Static backend and so we look in there to find out what's happening.
My reading of that method leads me to believe that the $id parameter to remove has to be a filename, so:
$cache->remove('index');
will work.
The more usual way to clear a cache is to use the clean() method though. See the manual.

Categories