IAM Role Name considred as Class in Yii 1 - php

I have attached the policy to EC2 IAM role to access AWS services. After that i have have used below code in Yii 1 controller file:
ExampleController.php
class ExampleController extends Controller
{
public function init()
{
require_once dirname(dirname(__FILE__)) . '/extensions/awsv3/vendor/autoload.php';
$config = array(
'version' => 'latest',
'region' => 'us-west-2',
);
$s3_instance = new \Aws\Ssm\SsmClient($config);
$result = $s3_instance->getParameters([
'Names' => array('host_name'),
'WithDecryption' => true
]);
//converting S3 private data to array to read
$keys = $result->toArray();
var_dump($keys);
exit("Exit");
}
}
Output
PHP warning
include(TestRole.php): failed to open stream: No such file or directory
Note: TestRole is IAM Role Name.
I have used same code in Single PHP file (Not ties with Yii1)
test.php
require_once 'protected/extensions/awsv3/vendor/autoload.php';
$config = array(
'version' => 'latest',
'region' => 'us-west-2',
);
$s3_instance = new \Aws\Ssm\SsmClient($config);
$result = $s3_instance->getParameters([
'Names' => array('host_name'),
'WithDecryption' => true
]);
//converting S3 private data to array to read
$keys = $result->toArray();
var_dump($keys);
exit("Exit");
array(3) { ["Parameters"]=> array(1) { [0]=> array(3) { ["Name"]=> string(12) "host_name" ["Type"]=> string(6) "String" ["Value"]=> string(9) "localhost" } } ["InvalidParameters"]=> array(0) { } ["#metadata"]=> array(4) { ["statusCode"]=> int(200) ["effectiveUri"]=> string(35) "https://ssm.us-west-2.amazonaws.com" ["headers"]=> array(4) { ["x-amzn-requestid"]=> string(36) "d3fb85bc-da4e-494b-be4f-b31fe3814100" ["content-type"]=> string(26) "application/x-amz-json-1.1" ["content-length"]=> string(3) "182" ["date"]=> string(29) "Tue, 19 Jun 2018 12:28:50 GMT" } ["transferStats"]=> array(1) { ["http"]=> array(1) { [0]=> array(0) { } } } } } Exit
its working with single php file.
So question is how to fix it in Yii 1 and why its considering IAM Role Name as Class file?
Stack Trace

I was able to fix this out, Thanks to #javierfdezg.
So basically, Yii's auto loader and AWS's auto loader was got conflicted and may be due to Yii's assumption that class names must match file names.
So first i have unregistered the Yii's auto load then after the api call is finished registered it again.
class ExampleController extends Controller
{
public function init()
{
/* Unregister YiiBase */
spl_autoload_unregister(array('YiiBase', 'autoload'));
require_once dirname(dirname(__FILE__)) . '/extensions/awsv3/vendor/autoload.php';
$config = array(
'version' => 'latest',
'region' => 'us-west-2',
);
$s3_instance = new \Aws\Ssm\SsmClient($config);
$result = $s3_instance->getParameters([
'Names' => array('host_name'),
'WithDecryption' => true
]);
/* Register YiiBase */
spl_autoload_register(array('YiiBase', 'autoload'));
$keys = $result->toArray();
var_dump($keys);
exit("Exit");
}
}

You may set Yii::$enableIncludePath to false - it should improve compatibility with other autoloaders.
Yii::$enableIncludePath = false;
After this Yii will stop blindly including class files assuming that they're in one of the directories specified in include_path. If class cannot be loaded by Yii autoloader, next autoloader will get his chance.

Related

facebook reactions request on posts return empty array

I am trying with the new facebook sdk (V 5.0) to get the number of reactions on posts from my facebook page
but when I execute the request it returns me an empty array for reactions key
But When I execute the same request on Graph facebook explorer It works, it return me the summary of reactions on each posts
This my code:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once('vendor/autoload.php');
use Facebook\Facebook;
use Facebook\FacebookApp;
use Facebook\FacebookRequest;
$fb = new Facebook([
'app_id' => '1795766XXX',
'app_secret' => 'e6b0d137adf110e089d9eeXXXX',
'default_graph_version' => 'v3.2',
'default_access_token' => 'EAACjUvPz1UUBAFMlFb5CQzsRx0jYUCZCIIYddqUtyXXX',
]);
$data = $fb->get('/252613XX/posts?fields=id,reactions.type(LOVE).limit(0).summary(total_count)');
$posts = $data->getGraphEdge();
echo '<pre>';
var_dump($posts->asArray());
echo '</pre>';
And the output:
array(25) {
[0]=>
array(2) {
["id"]=>
string(30) "252613xxxx_101568062385xxxx"
["reactions"]=>
array(0) {
}
}
[1]=>
array(2) {
["id"]=>
string(30) "25261330xxx_1015680576642xxxx"
["reactions"]=>
array(0) {
}
}
[2]=>
array(2) {
["id"]=>
string(30) "25261330xxx_1015680568030xxx"
["reactions"]=>
array(0) {
}
}
[3]=>
array(2) {
["id"]=>
string(30) "2526133xxx_1015680571755xxx"
["reactions"]=>
array(0) {
}
}
[4]=>
array(2) {
["id"]=>
string(30) "2526133xxx_101568058112xxx"
["reactions"]=>
array(0) {
}
}
And I don't know how to solve my problem
UPDATE code :
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require_once('vendor/autoload.php');
use Facebook\Facebook;
use Facebook\FacebookApp;
use Facebook\FacebookRequest;
$fb = new Facebook([
'app_id' => 'XXXX',
'app_secret' => 'XXXX',
'default_graph_version' => 'v3.2',
'default_access_token' => 'xxx',
]);
$data = $fb->get('/XXX/posts?fields=id,reactions.limit(0).summary(total_count)&since=1548603879&until=1553701479&limit=100');
$posts = $data->getGraphObject();
//$posts = $data->getDecodedBody();
$all_posts = array();
$all_post_info = array();
if($fb->next($posts)){
$posts_array = $posts->asArray();
$all_posts = array_merge($posts_array, $all_posts);
while($posts = $fb->next($posts)){
echo '<pre>';
var_dump($posts);
echo '</pre>';
die();
}
}

Request URI Too Long with POST REST

I have the following peice of PHP code, using to access a POST method REST web service :
$PJS = isset($_REQUEST['arrayFile']) ? $_REQUEST['arrayFile'] : array();
foreach ($PJS as $PJ) {
$ext = explode('/', $PJ['type'])[1];
$storeAttachmentResourceParams = array(
'encodedFile' => $PJ['content'],
'resId' => $resId,
'data' => json_encode(
array(
array('column' => 'title', 'value' => 'PJ', 'type' => 'string'),
array('column' => 'attachment_type', 'value' => 'simple_attachment', 'type' => 'string'),
array('column' => 'status', 'value' => 'A_TRA', 'type' => 'string'),
)
),
'collId' => 'letterbox_coll',
'collIdMaster' => 'letterbox_coll',
'table' => 'res_attachments',
'fileFormat' => $ext
);
$storeAttachmentResource = Requests::post($cfg['url'] . '/attachments', array(), $storeAttachmentResourceParams, $options);
This piece of PHP code is call under a wordpress PHP snippet like the following :
$url = 'https://XXXX.XXX.fr/interface/iface.php';
$options = array(
'http' => array(
'header' => "",
'proxy' => "tcp://192.168.X.X:3128",
'timeout' => 100,
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$return = file_get_contents($url, false, $context);
$returnIface = json_decode($return);
I modify my Apache2.conf like the following to add the LimitRequestLine:
AccessFileName .htaccess
LimitRequestLine 10000000
LimitRequestFieldSize 10000000
Restarted the Apache2 server but still have the following error in my browser :
Request-URI Too Long
The requested URL's length exceeds the capacity
limit for this server.
Apache/2.4.25 (Debian) Server at infosv47.sartrouville.lan Port 80
"
["headers"]=>
object(Requests_Response_Headers)#23 (1) {
["data":protected]=>
array(4) {
["date"]=>
array(1) {
[0]=>
string(29) "Fri, 06 Jul 2018 13:03:25 GMT"
}
["server"]=>
array(1) {
[0]=>
string(22) "Apache/2.4.25 (Debian)"
}
["content-length"]=>
array(1) {
[0]=>
string(3) "339"
}
["content-type"]=>
array(1) {
[0]=>
string(29) "text/html; charset=iso-8859-1"
}
}
}
["status_code"]=>
int(414)
["protocol_version"]=>
float(1.1)
["success"]=>
bool(false)
["redirects"]=>
int(0)
["url"]=>
string(46) "http://10.10.XX.XX/cs_maarch/rest/attachments"
["history"]=>
array(0) {
}
["cookies"]=>
object(Requests_Cookie_Jar)#20 (1) {
["cookies":protected]=>
array(0) {
}
}
}
It's under a Debian 9

PHPUnit - Guzzle: API calls not returning the desired response

I am using PHPUnit and Guzzle to test the REST api, which creates a new record in db, if the username(passed in request parameters) which is not already available in db and it sends response in JSON like below:
{
"success": true,
"id": "<unique_ID>"
}
And if the username is already available in db, then it sends response in JSON like below:
{
"success": false,
"error": "username is already available"
}
This is my PHPUnit testcase to test the above mentioned API along with Guzzle:
This is a setUp function is used to setup the Guzzle client
public function setUp()
{
$this->client = new GuzzleHttp\Client([
'base_uri' => 'http://localhost/test/'
]);
}
And this is the actual test function:
public function testActualResult()
{
$response = $this->client->post('service.php', [
'json' => [
'operation' => 'create_user',
'user_name' => 'testUser1'
]
]);
var_dump($response);
}
Whenever I test this, I get response like this:
class GuzzleHttp\Psr7\Response#99 (6) {
private $reasonPhrase =>
string(2) "OK"
private $statusCode =>
int(200)
private $headers =>
array(5) {
'Date' =>
array(1) {
[0] =>
string(29) "Tue, 21 Nov 2017 10:27:22 GMT"
}
'Server' =>
array(1) {
[0] =>
string(47) "Apache/2.4.26 (Win32) OpenSSL/1.0.2l PHP/5.6.31"
}
'X-Powered-By' =>
array(1) {
[0] =>
string(10) "PHP/5.6.31"
}
'Content-Length' =>
array(1) {
[0] =>
string(4) "1357"
}
'Content-Type' =>
array(1) {
[0] =>
string(16) "application/json"
}
}
private $headerNames =>
array(5) {
'date' =>
string(4) "Date"
'server' =>
string(6) "Server"
'x-powered-by' =>
string(12) "X-Powered-By"
'content-length' =>
string(14) "Content-Length"
'content-type' =>
string(12) "Content-Type"
}
private $protocol =>
string(3) "1.1"
private $stream =>
class GuzzleHttp\Psr7\Stream#86 (7) {
private $stream =>
resource(408) of type (stream)
private $size =>
NULL
private $seekable =>
bool(true)
private $readable =>
bool(true)
private $writable =>
bool(true)
private $uri =>
string(10) "php://temp"
private $customMetadata =>
array(0) {
}
}
}
But I am not getting the desired response sent back by an API call itself.
If I test my above mentioned API with POSTMAN, it works perfectly and gives back desired responses.
Have you read the GuzzlePHP documentation? Under 'Quickstart' -> 'Using Responses' it is described that when you want to get the body of the response you'll need to use the getBody() function on the $response.
What you are doing is just dumping the whole request variable, which contains way more information then you'll need for what you want to do.
See Using Responses for an example:
$response = $client->post('your parameters here');
$body = $response->getBody();
echo $body;

Yii2 AuthClient Facebook

I have a problem with FB login in my Yii application. When I try to get the user attributes, application returns internal server error. I checked all logs and found nothing.
This is my config
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'authUrl' => 'https://www.facebook.com/dialog/oauth?display=popup',
'clientId' => 'xxxxxxxx',
'clientSecret' => 'xxxxxxxxx',
],
],
],
Controller actions
public function actions()
{
return
[
'auth' =>
[
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'authSuccess'],
],
];
}
and the app crashes when it reaches this statement inside the callback
$attributes = $client->getUserAttributes();
this is the $client object
object(yii\authclient\clients\Facebook)#115 (20) {
["authUrl"]=>
string(51) "https://www.facebook.com/dialog/oauth?display=popup"
["tokenUrl"]=>
string(45) "https://graph.facebook.com/oauth/access_token"
["apiBaseUrl"]=>
string(26) "https://graph.facebook.com"
["scope"]=>
string(5) "email"
["attributeNames"]=>
array(2) {
[0]=>
string(4) "name"
[1]=>
string(5) "email"
}
["version"]=>
string(3) "2.0"
["clientId"]=>
string(15) "xxxxxxxxxx"
["clientSecret"]=>
string(32) "xxxxxxxxxx"
["_returnUrl":"yii\authclient\BaseOAuth":private]=>
string(49) "http://xxxxxx.xx/auth?authclient=facebook"
["_curlOptions":"yii\authclient\BaseOAuth":private]=>
array(0) {
}
["_accessToken":"yii\authclient\BaseOAuth":private]=>
object(yii\authclient\OAuthToken)#117 (5) {
["tokenParamKey"]=>
string(12) "access_token"
["tokenSecretParamKey"]=>
string(18) "oauth_token_secret"
["createTimestamp"]=>
int(1461360063)
["_expireDurationParamKey":"yii\authclient\OAuthToken":private]=>
NULL
["_params":"yii\authclient\OAuthToken":private]=>
array(2) {
["access_token"]=>
string(175) "EAACZCvJlBssYBAF1vwxq7PMgKAsEz5GueWEpBTf3OZAGEHPrONRKVXLGggRudgsNcpHiWD2IWDlEwnVmku9qmyYvUWh2VYVPShOK6VfsQ7TID1dEozVUMgYU01raFK3IBJ2mvi5PNztnqgQ12d0yBZBYnZCVloft4FmkkYyjvwZDZD"
["expires"]=>
string(7) "5181417"
}
}
["_signatureMethod":"yii\authclient\BaseOAuth":private]=>
array(0) {
}
["_id":"yii\authclient\BaseClient":private]=>
string(8) "facebook"
["_name":"yii\authclient\BaseClient":private]=>
NULL
["_title":"yii\authclient\BaseClient":private]=>
NULL
["_userAttributes":"yii\authclient\BaseClient":private]=>
NULL
["_normalizeUserAttributeMap":"yii\authclient\BaseClient":private]=>
NULL
["_viewOptions":"yii\authclient\BaseClient":private]=>
NULL
["_events":"yii\base\Component":private]=>
array(0) {
}
["_behaviors":"yii\base\Component":private]=>
NULL
}
EDIT: I just found out that it must be some problem with Yii's AuthClient (maybe FB changed response?), because I used this in another project, about a year ago and it worked just fine. Now i tried to login to that project and it does the same thing
sorry, I haven't qualification for comment...
please post your function content
function authSuccess($client) {
...
}
extra:
check your user model has implements IdentityInterface and yii\web\User it's set user attribute at login function.
you could set breakpoint on there.

PayPal Billing Plan Key Response Error

function testing(){
$headers_array_sub_new = array("X-PAYPAL-SECURITY-USERID" => 'testing',
"X-PAYPAL-SECURITY-PASSWORD" => '12345645',
"X-PAYPAL-SECURITY-SIGNATURE" => 'Ab2145sdfd-IhWqUntNLtS4AWDawDzjOUVWjw6nXIcMtyOrkmDu',
"X-PAYPAL-APPLICATION-ID" => 'APP-80W284485P519543T',
"X-PAYPAL-REQUEST-DATA-FORMAT" => "NV",
"X-PAYPAL-RESPONSE-DATA-FORMAT" => "JSON",
"Authorization" =>array('clientId'=>'testing','secret'=>'testing'),
"Accept" =>'application/json',
);
$url = "https://api.sandbox.paypal.com/v1/payments/billing-plans";
$subscriptionplan = array(
'name'=>'T shirt Plan',
'description'=> 'welcome plan',
'type'=> 'INFINITE' ,
'payment_definitions'=>array('name'=>'welcome','type'=>'REGULAR','frequency_interval'=>'2','frequency'=>'Month','cycles'=>'10','amount'=>'100'),
'merchant_preferences'=>''
);
$pay_result_trial = wp_remote_request($url, array('method' => 'POST', 'timeout' => 20, 'headers' => $headers_array_sub_new, 'body' => $subscriptionplan));
//$pay_result_trial2 = wp_remote_request($url2, array('method' => 'POST', 'timeout' => 20, 'headers' => $headers_array_sub1, 'body' =>$subscriptionplan));
var_dump($pay_result_trial);
here is the response error
array(5) { ["headers"]=> array(7) { ["server"]=> string(17) "Apache-Coyote/1.1" ["proxy_server_info"]=> string(57) "host=slcsbplatformapiserv3002.slc.paypal.com;threadId=322" ["paypal-debug-id"]=> string(13) "c764b1af30167" ["content-type"]=> string(16) "application/json" ["content-length"]=> string(1) "0" ["date"]=> string(29) "Fri, 20 Mar 2015 05:25:30 GMT" ["connection"]=> string(5) "close" } ["body"]=> string(0) "" ["response"]=> array(2) { ["code"]=> int(401) ["message"]=> string(12) "Unauthorized" } ["cookies"]=> array(0) { } ["filename"]=> NULL ?>
}
Can any one help me?
You are not using the right credentials for the call. You are using your API User/Pwd/Signature which are used for the Classic APIs. The Billing Plans you are attempting to use are part of the RESTful APIs which use standard oAuth credentials of Client ID and Client Secret. The REST API reference can be found here and contains information regarding Authentication/Headers as well as other useful information.

Categories