Replace Contents of Request Object in Slim Middleware - slim

I'm encrypting a header value and params of the request object. In the middleware.. I decrypt the values and would I like replace the values.
Tried the below. Doesnt seem to be working.
new \Slim\Http\Request($method, $uri, $headers, $cookies, $serverParams, $body)
For - $response = $next($request, $response); I tried the below
$response = $next(new \Slim\Http\Request($request->getMethod(),$request->getUri(), $arr, $request->getCookieParams(), $request->getServerParams(), $request->getBody()), $response);
Any help would be very much appreciated.

Try this to replace the header value:
$value = $response->getHeaderLine('MyHeader');
// ...
$response = $response->withHeader('MyHeader', $value);

Related

Newbie on Fb messenger Sender_action function

I am under a learning process in chatbot, and kinda new to coding overall ( learning by doing right? )
Trying to execute a messenger function so our chatbot gets the little "writing" bubble for x amount of time before it sends a template. = sender_action_typing_on.
I have tried sleep, await, wait, and so on but the code doesn´t seem to be executed, but the template still shows after the time I chose.
The json is also correct by the documentation from Facebook, and if it get´s executed alone it runs for 20 sek before a timeout.
Code:
if ( $response == "")
{
$jsonData = '{"recipient":{"id":"' . $sender . '"},"message":{"text":"' . $message_to_reply.'"}}';
$jsonDataEncoded = $jsonData;
}
else
if ( $response == "123456")
{
$sender_action_typing_on = '{
"recipient":{
"id":"<PSID>"
},
"sender_action":"Typing_on"
}';
$sender_action_typing_on = str_replace("<PSID>", $sender, $sender_action_typing_on);
$jsonDataEncoded = $sender_action_typing_on;
$velkommenTemplateJSON = str_replace("<PSID>", $sender, $velkommenTemplateJSON);
$jsonDataEncoded = $velkommenTemplateJSON;
}
I have now fixed this issue, this may be very self-explaining for many but for the "lost soul" looking for answers u can see the way i dealed with the problem here:
First i created a new function:
function sendToMessenger($access_token, $sender, $sender_actiontemplateJSON)
{
$content = str_replace("<PSID>", $sender, $sender_actiontemplateJSON);
$opts = array(
'http'=>array(
'method'=>"POST",
'header' => "Content-Type: application/json",
'content' => $content
)
);
$context = stream_context_create($opts);
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=' . $access_token;
// Open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
return $file;
Then i rearranged the way i´m sending template since the template got sent at det end of my code "Sender_action" would always be overwritten, Now with the "SendToMessenger" Function it gets sent right away.
else
if ( $response == "123456")
{
sendToMessenger($access_token, $sender, $sender_actiontemplateJSON);
sleep(1);
sendToMessenger($access_token, $sender, $velkommenTemplateJSON);
}
Now it works like a charm!

Zend_Config_Xml

So i will list my problems here, please help
First of all, i use Zend_Http_Client to call to an url:
$client = new Zend_Http_Client('http://mydomain.com/Statistics.aspx?activity=top');
$response = $client->request('POST');
$response = $response->getRawBody();
Then i get an Xml document structure for $response when i print it out:
[?xml version='1.0' encoding='UTF-8'?]
[root]
[member]
[username>gh_MXH[/username]
[money]129300[/money]
[/member]
[member]
[username]sonhothiet_MXH[/username]
[money]107400[/money]
[/member]
[/root]
After that, i use Zend_Config_Xml:
$xmlReader = new Zend_Config_Xml($response);
$xml = $xmlReader->toArray();
But all i get is just only the first element of the array when i print out $xml:
Array
(
[member] => Array
(
[username] => gh_MXH
[money] => 129300
)
)
Please show me how to get all the elements so that i can do the looping like:
foreach($xml as $key => $value){
echo $value['username'] . 'has' . $value['money'];
}
And one more question, when i wrote:
$xml = new Zend_Config_Xml($response, 'root');
It appears an error saying: Section 'root' cannot be found in. Really need your help. Thank you and sorry for bad English.
Don't use Zend_Config_Xml to parse standard XML docments, it is for config files. PHP can easily do this natively:
$xml = simplexml_load_string($response);
foreach($xml->member as $member){
echo $member->username . 'has' . $member->money;
}

PEAR Mail, Mail_Mime and headers() overwrite

I'm currently working on a reminder PHP Script which will be called via Cronjob once a day in order to inform customers about smth.
Therefore I'm using the PEAR Mail function, combined with Mail_Mime. Firstly the script searches for users in a mysql database. If $num_rows > 0, it's creating a new Mail object and a new Mail_mime object (the code encluded in this posts starts at this point). The problem now appears in the while-loop.
To be exact: The problem is
$mime->headers($headers, true);
As the doc. states, the second argument should overwrite the old headers. However all outgoing mails are sent with the header ($header['To']) from the first user.
I'm really going crazy about this thing... any suggestions?
(Note: However it's sending the correct headers when calling $mime = new Mail_mime() for each user - but it should work with calling it only once and then overwriting the old headers)
Code:
// sql query and if num_rows > 0 ....
require_once('/usr/local/lib/php/Mail.php');
require_once('/usr/local/lib/php/Mail/mime.php');
ob_start();
require_once($inclPath.'/email/head.php');
$head = ob_get_clean();
ob_start();
require_once($inclPath.'/email/foot.php');
$foot = ob_get_clean();
$XY['mail']['params']['driver'] = 'smtp';
$XY['mail']['params']['host'] = 'smtp.XY.at';
$XY['mail']['params']['port'] = 25;
$mail =& Mail::factory('smtp', $XY['mail']['params']);
$headers = array();
$headers['From'] = 'XY <service#XY.at>';
$headers['Subject'] = '=?UTF-8?B?'.base64_encode('Subject').'?=';
$headers['Reply-To'] = 'XY <service#XY.at>';
ob_start();
require_once($inclPath.'/email/templates/files.mail.require-review.php');
$template = ob_get_clean();
$crfl = "\n";
$mime = new Mail_mime($crfl);
while($row = $r->fetch_assoc()){
$html = $head . $template . $foot;
$mime->setHTMLBody($html);
#$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <'.$row['email'].'>'; // for testing purpose i'm sending all mails to webmaster#XY.at
$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <webmaster#XY.at>';
$headers['To'] = $to; // Sets to in headers to a new
$body = $mime->get(array('head_charset' => 'UTF-8', 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8'));
$hdrs = $mime->headers($headers, true); // although the second parameters says true, the second, thrid, ... mail still includes the To-header form the first user
$sent = $mail->send($to, $hdrs, $body);
if (PEAR::isError($sent)) {
errlog('error while sending to user_id: '.$row['id']); // personal error function
} else {
// Write log file
}
}
There is no reason to keep the old object and not creating a new one.
Use OOP properly and create new objects - you do not know how they work internally.

How can I change the hostname in a URL using Perl?

I have some URLs like http://anytext.a.abs.com
In these, 'anytext' is the data that is dynamic. Rest of the URL will remain same in every case.
I'm using the following code:
$url = "http://anytext.a.abs.com";
my $request = new HTTP::Request 'GET', $url;
my $response = $ua->request($request);
if ($response->is_success)
{
function......;
}
Now, how can I parse a URL that has dynamic data in it?
Not sure but is this close to what you're after?:
for my $host qw(anytext someothertext andanother) {
my $url = "http://$host.a.abs.com";
my $request = new HTTP::Request 'GET', $url;
my $response = $ua->request($request);
if ($response->is_success)
{
function......;
}
}
Something like this maybe?
Otherwise, you can use the URI class to do url manipulation.
my $protocol = 'http://'
my $url_end = '.a.abs.com';
$url = $protocol . "anytext" . $url_end;
my $request = new HTTP::Request 'GET', $url;
my $response = $ua->request($request);
if ($response->is_success)
{
function......;
}
I think this is probably enough:
# The regex specifies a string preceded by two slashes and all non-dots
my ( $host_name ) = $url =~ m{//([^.]+)};
And if you want to change it:
$url =~ s|^http://\K([^.]+)|$host_name_I_want|;
Or even:
substr( $url, index( $url, $host_name ), length( $host_name ), $host_name_I_want );
This will expand the segment sufficiently to accommodate $host_name_I_want.
Well, like you would parse any other data: Use the information you have about the structure.
You have a protocol part, followed by "colon slash slash", then the host followed by optional "colon port number" and an optional path on the host.
So ... build a little parser that extracts the information you are after.
And frankly, if you are only hunting for "what exactely is 'anytext' here?", a RegEx of this form should help (untested; use as guidance):
$url =~ m/http\:\/\/(.*).a.abs.com/;
$subdomain = $1;
$do_something('with', $subdomain);
Sorry if I grossly misunderstood the problem at hand. Please explain what you mean with 'how can I parse a URL that has dynamic data in it?' in that case :)

Set Zend response into a variable

I have an action that returns a JSON. I need to call it from another controller and I need to get this response into a variable to parse the JSON.
I've tried:
private function makeListFromUrl($menu)
{
$req = new Zend_Controller_Request_Http();
$req->setRequestUri('/module/controller/get.json/');
$res = new Zend_Controller_Response_Http();
$dis = $this->getFrontController()->dispatch($req, $res);
$dis->dispatch($req, $res);
$json = $res->getBody();
return Zend_Json::decode($json);
}
But this code causes the front controller to render the action, overriding the actual action. I just want to make a request, get the response into a variable, while leaving the actual request untouched.
Thanks.
i have a simple solution to this, not sure if it's the best, but worked very well.
$actionHelper = new Zend_View_Helper_Action();
$var = $actionHelper->action('action', 'controller', 'module', $params);
same way you'd do inside the view, but in the controller.
i hope this can help somebody.
You have to set returnResponse(true) for the FrontController to send the response back.
private function makeListFromUrl($menu)
{
$req = new Zend_Controller_Request_Http();
$req->setRequestUri('/module/controller/get.json/');
$front = Zend_Controller_Front::getInstance();
$front->returnResponse(true);
$response = $front->dispatch($requestObj);
$json = $res->getBody();
return Zend_Json::decode($json);
}