PHP IMAP parsing body text - imap

I working with php imap and I'm having trouble. I need to fetch the body text and the body html but it doesn't look like it have to be , my code is:
$this->email['bodyHTML'] = quoted_printable_decode(imap_fetchbody($imap, $i, 2.2,FT_PEEK ));
if(trim($this->email['bodyHTML']) == ''){
$this->email['bodyHTML'] = imap_fetchbody($imap, $i, 1.2,FT_PEEK );
}
$this->email['bodyText'] = quoted_printable_decode(imap_fetchbody($imap,$i,1.1,FT_PEEK ));
if(trim($this->email['bodyText']) == ''){
$this->email['bodyText'] = quoted_printable_decode(imap_fetchbody($imap,$i,1,FT_PEEK ));
}
The output when doing var_dump is the text below. but it isn't what email text is:
[bodyHTML] =>
[bodyText] => UGVyIGNvbXBldGVuemEuIEdyYXppZQ0KDQogDQoNCkRhOiBFbWFudWVsZSBQZXJzaWNvIFttYWls dG86ZS5wZXJzaWNvQGJsdXNlcnZpY2UuaXRdIA0KSW52aWF0bzogZ2lvdmVkw6wgMTAgbHVnbGlv IDIwMTQgMTc6NDQNCkE6IENyaW5pdGkgU29uaWENCkNjOiBOYXN0YSBFbWlsaWENCk9nZ2V0dG86 IEZ3ZDogSTogUml2aXN0YSBkaSBkaXJpdHRvIHByb2Nlc3N1YWxlIC0gY29kaWNlIGNsaWVudGUg MDAwMTY1NDc3Mw0KDQogDQoNCkNpYW8gU29uaWEsDQoNCmNvbiBsYSBwcmVzZW50ZSByZXN0aXR1 aWFtbyBsYSBwcmF0aWNhIGluZXJlbnRlIGlsIGNsaWVudGUgYy8xNjU0NzczIGRpIGNvbXBldGVu emEgSXBzb2EuDQoNCkdyYXppZSBFbWFudWVsZQ0KDQoNCg0KLS0tLS0tLS0gTWVzc2FnZ2lvIG9y aWdpbmFsZSAtLS0tLS0tLSANCg0KT2dnZXR0bzogDQoNCkk6IFJpdmlzdGEgZGkgZGlyaXR0byBw cm9jZXNzdWFsZSAtIGNvZGljZSBjbGllbnRlIDAwMDE2NTQ3NzMNCg0KRGF0YTogDQoNCk1vbiwg MTYgSnVuIDIwMTQgMTE6NTQ6MDEgKzAyMDANCg0KTWl0dGVudGU6IA0KDQpDcmluaXRpIFNvbmlh IDxTb25pYS5DcmluaXRpQHdraS5pdD4gPG1haWx0bzpTb25pYS5DcmluaXRpQHdraS5pdD4gDQoN CkE6IA0KDQo8Y2xpZW50aWdpdXJpZGljYUB3a2ltYWlsLml0PiA8bWFpbHRvOmNsaWVudGlnaXVy aWRpY2FAd2tpbWFpbC5pdD4gDQoNCg0KDQoNCg0KDQogIA0KDQogIA0KDQpEYTogTGlhIENhcm9s aW5hIEJhdGlzdGEgQ2ludHJhIFttYWlsdG86bGlhLmJhdGlzdGFAZ21haWwuY29tXSANCkludmlh dG86IG1lcmNvbGVkw6wgMTEgZ2l1Z25vIDIwMTQgMTQ6MjANCkE6IFNob3BXS0k7IEluZm8gQ29t bWVyY2lhbGkgV29sdGVyc0tsdXdlciBJdGFsaWE7IFNlcnZpemlvIENsaWVudGkgVXRldCBHaXVy aWRpY2ENCk9nZ2V0dG86IFJlOiBSaXZpc3RhIGRpIGRpcml0dG8gcHJvY2Vzc3VhbGUgLSBjb2Rp Y2UgY2xpZW50ZSAwMDAxNjU0NzczIA0KDQogIA0KDQpOb24gcmllc2NvIGEgY2FwaXJlIHBlc

That data is base64-encoded. You need to check the Content-Transfer-Encoding header: if it's quoted-printable, decode the data as quoted-printable, as you do in the code above, but if it says base64, decode the data as base64 instead.

Related

Telegram Bots: Encoding Plus Character / Plus Sign

I am working on a telegram bot which sends telephone numbers to my telegram account. The problem is, that a '+' is converted to a ' ' blank. So every telephone number is wrong.
E.g. '+4915733000000' turns into '4915733000000'. I've tried to use the HTML code &#43 the unicode version \u002B and the url encoding caracter %2B and none of them work.
https://api.telegram.org/botTOKEN/sendMessage?chat_id=MYID&text=Test:\u2031 Unicode:\u002B HTML:+ URL:%2B
Result: Test:‱ Unicode: HTML:
Do you know any possiblility to send a plus sign?
Thanks!
In case someone is using VBA to send Telegram messages with + in them you can replace your string like that:
Dim URL as String
Dim reURL as String
URL = "https://www.webpage.com/product+name/specifics+number" 'etc....
reURL = replace(URL, "+, "%2B")
'send message to telegram code here
For more Encoding info you can visit: https://www.w3schools.com/tags/ref_urlencode.ASP
It is possible to send the plus sign using POST method.
Here's the sample Google App Script code (can be easily adapted to JavaScript).
var options = {
method : "post",
payload: {
method: "sendMessage",
chat_id: "<chat_id_here>",
text: "+something",
parse_mode: "HTML"
}
};
var response = UrlFetchApp.fetch("https://api.telegram.org/bot<YOUR_TOKEN>/", options);
Plus sign can also be easily sent with parse_mode="Markdown".
Just checked (this time on Python using telebot library) that both options work:
bot.send_message(CHAT_ID, "Phone number: +1234567890", parse_mode='Markdown')
bot.send_message(CHAT_ID, "Phone number: +1234567890", parse_mode='HTML')
I had the same problem. I was using Java and Spring's WebClient. The only way to make it work is building WebClient using DefaultUriBuilderFactory and set encoding mode to NONE.
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(url);
factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
WebClient webClient = WebClient.builder().uriBuilderFactory(factory).filter(logRequest()).build();
Default is EncodingMode.TEMPLATE_AND_VALUES so if you replace + with %2B the resulting URL is %252B. Setting the encoding mode to NONE doesn't replace any especial characters so I had to replace them manually.
private String replaceUrlSpecialCharacters(String message) {
return message.replace("%", "%25").replace("+", "%2B").replace(" ", "%20").replace("|", "%7C").replace(System.lineSeparator(), "%0A");
}
And now the + sign is shown in my messages.
I'am using PHP and this case was solved with rawurlencode. Below is the code:
public function send_message($tg_msg)
{
$tg_token = ''; // Bot Token
$chat_id = ''; // Chat ID
$url = 'https://api.telegram.org/bot' . $tg_token . '/sendMessage?parse_mode=markdown&chat_id=' . $chat_id;
$curlopt_url = $url . '&text=' . rawurlencode($tg_msg);
$ch = curl_init();
$optArray = array(
CURLOPT_URL => $curlopt_url,
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $optArray);
curl_exec($ch);
curl_close($ch);
}
$msg = 'The message';
send_message($msg);
And now the + sign is shown in my messages.
I got that solved by just using this php function:
utf8_encode(text_to_send)

TCPDF and database: conflicts in PHP

Hi this my php code :
<?php require_once('tcpdf/config/lang/eng.php'); ?>
<?php require_once('tcpdf/tcpdf.php'); ?>
<?php include_once("class/class_productos.php"); ?>
<?php include_once("class/class_clientes.php"); ?>
<?php include_once("class/class_img_gen.php"); ?>
<?php include_once("class/class_acros.php"); ?> // here is MY DB CONNECTION
<?php
class MYPDF extends TCPDF {
//Page header
public function Header() {
$auto_page_break = $this->AutoPageBreak;
$this->SetAutoPageBreak(false, 0);
$img_file = 'img/pdf_fondo.jpg';
$this->Image($img_file, $x=0, $y=0, $w=210, $h=297, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0);
$this->SetAutoPageBreak($auto_page_break);
}
}
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator('ACROS');
$pdf->SetAuthor('ACROS');
$pdf->SetTitle('Lista de producto');
$pdf->SetSubject('Lista de producto');
$pdf->SetKeywords('ACROS, acros, mayorista, informática');
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(false);
$pdf->SetMargins(0, 0, 0);
$pdf->SetAutoPageBreak(FALSE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->setLanguageArray($l);
$pdf->AddPage();
$category = $_GET['c'];
$getCategory = "SELECT * FROM prod_detalle WHERE fk_marca = '$category'";
$getCategory = mysql_query($getCategory);
$count = mysql_num_rows($getCategory);
$txt = "result ".$count;
// output the HTML content
$pdf->writeHTML($txt, true, 0, true, 0);
$pdf->SetY(-30);
$pdf->SetX(0.65);
$pdf->MultiCell(20, 0, $txtB, $border = 0,$align = 'L',$fill = 0,$ln = 1,$x = '',$y = '',$reseth = false, $stretch = 0, $ishtml = true, $autopadding = false, $maxh = 0);
$pdf->Output('lista.pdf', 'I');
?>
and i'm getting this two warnings :
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean
given in /mnt/futurehome/netlogiq/public_html/acros/lista_pdf.php on
line 64
Warning: Cannot modify header information - headers already sent by
(output started at
/mnt/futurehome/netlogiq/public_html/acros/lista_pdf.php:64) in
/mnt/futurehome/netlogiq/public_html/acros/tcpdf/tcpdf.php on line
5405 TCPDF ERROR: Some data has already been output to browser, can't
send PDF file
Can anyone help me with this ?? If run the query in phpmyadmin, it returns the wanted data. So the query works fine !
The reason you are getting the error from mysql_num_rows() is because you haven't initialized the connection to the database. You are also using the old (and deprecated as og PHP 5.5) MySQL interface - you should look into using mysqli or PDO instead.
A full explanation of how to initialize the connection to the database and communicate with it using the correct resource handle is, IMO, beyond the scope of an SO answer. Maybe start here instead:
http://www.php.net/manual/en/mysqli.quickstart.connections.php
The reason you're getting the second error is simply because the first error message is being sent to the browser before your call to $pdf->Output(). Once you get your database connection working and remove the error messages that problem will go away.
Just remove the line
require_once('tcpdf/config/lang/eng.php');
and
edit the tcpdf.php file from the tcpdf folder:
add the line ob_end_clean(); as below (3rd last line):
public function Output($name='doc.pdf', $dest='I') {
//LOTS OF CODE HERE....}
switch($dest) {
case 'I': {
// Send PDF to the standard output
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');}
//some code here....}
case 'D': { // download PDF as file
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');}
break;}
case 'F':
case 'FI':
case 'FD': {
// save PDF to a local file
//LOTS OF CODE HERE..... break;}
case 'E': {
// return PDF as base64 mime email attachment)
case 'S': {
// returns PDF as a string
return $this->getBuffer();
}
default: {
$this->Error('Incorrect output destination: '.$dest);
}
}
ob_end_clean(); //add this line here
return '';
}

Youtube api Where will write this code

Too bad my php knowledge.I'm using YouTube-api.Where will write this code: Retrieve Youtube Channel info for "Vanity" channel
If you are talking about this line :
GET https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=UC6ltI41W4P14NShIBHU8z1Q&key={YOUR_API_KEY}
You are simply making a get request, you can use file_get_contents to get the response for you :
$response = file_get_contents("https://www.googleapis.com/youtube/v3/channels?part=snippet%2CcontentDetails%2Cstatistics&id=UC6ltI41W4P14NShIBHU8z1Q&key={YOUR_API_KEY}");
Two notes :
You have to replace {YOUR_API_KEY} with the developer key. You can easily request one from youtube: http://code.google.com/apis/youtube/dashboard/
This is just an example in one line of code, I suggest you use a better approach for making this request like the following :
// Encode the parameters of the link
function encode_param($params) {
foreach ($params as $field => $value){
$encoded_params[] = $field . '=' . urlencode($value);
}
return $encoded_params;
}
// Get the response
function get_response($url) {
$response = file_get_contents($url);
// If error, send message back to the client
if ($response === false) {
exit("Couldn't get response from the api");
}
return $response;
}
$params = array(
"part" => "snippet,contentDetails,statistics",
"id" => "UC6ltI41W4P14NShIBHU8",
"key" => "-----------", // Your API key
);
$encoded_params = encode_param($params);
$request_url = "https://www.googleapis.com/youtube/v3/channels?".implode('&', $encoded_params);
$response = get_response($request_url);
//............

Why i don't see my #replies in conversation view in twitter?

I need to reply to one particular twitter status. I'm using following functions. And I've used Abraham's twitteroauth library in php.
public function replyToTwitterStatus($user_id,$status_id,$twitt_reply,$account_name)
{
$connection= $this->getTwitterConnection($user_id,$account_name);
try{
$responce = $this->postApiData('statuses/update', array('status' => $twitt_reply,'in_reply_to_status_id '=> $status_id),$connection);
}
catch(Exception $e){
echo $message = $e->getMessage();
exit;
}
}
// this function will handle all post requests
// To post/update twitter data
// To post/update twitter data
public function postApiData($request,$params = array(),$connection)
{
if($params == null)
{
$data = $connection->post($request);
}
else
{
$data = $connection->post($request,$params);
}
// Need to check the error code for post method
if($data->errors['0']->code == '88' || $data->errors['0']->message == 'Rate limit exceeded')
{
throw new Exception( 'Sorry for the inconvenience,Please wait for minimum 15 mins. You exceeded the rate limit');
}
else
{
return $data;
}
}
But the issue is that it is not maintaining the conversation view and it is update like normal status for e.g #abraham hello how are you. but that "View conversation" is not coming. Like expanding menu is not coming.
Please do needful
Thanks
You've got an unwanted space in your in_reply_to_status_id key which causes that parameter to be ignored.
This call:
$responce = $this->postApiData('statuses/update', array(
'status' => $twitt_reply,
'in_reply_to_status_id ' => $status_id
), $connection);
should look like this:
$responce = $this->postApiData('statuses/update', array(
'status' => $twitt_reply,
'in_reply_to_status_id' => $status_id
), $connection);
Also, make sure that the $status_id variable is being handled as a string. Although they look like numbers, most ids will be too big to be represented as integers in php, so they'll end up being converted to floating point which isn't going to work.
Lastly, make sure you have include the username of the person you are replying to in the status text. Quoting from the documentation for the in_reply_to_status_id parameter:
Note:: This parameter will be ignored unless the author of the tweet this parameter references is mentioned within the status text. Therefore, you must include #username, where username is the author of the referenced tweet, within the update.

How do you POST to a page using the PHP header() function?

I found the following code on here that I think does what I want, but it doesn't work:
$host = "www.example.com";
$path = "/path/to/script.php";
$data = "data1=value1&data2=value2";
$data = urlencode($data);
header("POST $path HTTP/1.1\r\n");
header("Host: $host\r\n");
header("Content-type: application/x-www-form-urlencoded\r\n");
header("Content-length: " . strlen($data) . "\r\n");
header("Connection: close\r\n\r\n");
header($data);
I'm looking to post form data without sending users to a middle page and then using JavaScript to redirect them. I also don't want to use GET so it isn't as easy to use the back button.
Is there something wrong with this code? Or is there a better method?
Edit I was thinking of what the header function would do. I was thinking I could get the browser to post back to the server with the data, but this isn't what it's meant to do. Instead, I found a way in my code to avoid the need for a post at all (not breaking and just continuing onto the next case within the switch).
The header function is used to send HTTP response headers back to the user (i.e. you cannot use it to create request headers.
May I ask why are you doing this? Why simulate a POST request when you can just right there and then act on the data someway? I'm assuming of course script.php resides on your server.
To create a POST request, open a up a TCP connection to the host using fsockopen(), then use fwrite() on the handler returned from fsockopen() with the same values you used in the header functions in the OP. Alternatively, you can use cURL.
The answer to this is very needed today because not everyone wants to use cURL to consume web services. Also PHP does allow for this using the following code
function get_info()
{
$post_data = array(
'test' => 'foobar',
'okay' => 'yes',
'number' => 2
);
// Send a request to example.com
$result = $this->post_request('http://www.example.com/', $post_data);
if ($result['status'] == 'ok'){
// Print headers
echo $result['header'];
echo '<hr />';
// print the result of the whole request:
echo $result['content'];
}
else {
echo 'A error occured: ' . $result['error'];
}
}
function post_request($url, $data, $referer='') {
// Convert the data array into URL Parameters like a=b&foo=bar etc.
$data = http_build_query($data);
// parse the given URL
$url = parse_url($url);
if ($url['scheme'] != 'http') {
die('Error: Only HTTP request are supported !');
}
// extract host and path:
$host = $url['host'];
$path = $url['path'];
// open a socket connection on port 80 - timeout: 30 sec
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if ($fp){
// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
if ($referer != '')
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);
$result = '';
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
}
else {
return array(
'status' => 'err',
'error' => "$errstr ($errno)"
);
}
// close the socket connection:
fclose($fp);
// split the result header from the content
$result = explode("\r\n\r\n", $result, 2);
$header = isset($result[0]) ? $result[0] : '';
$content = isset($result[1]) ? $result[1] : '';
// return as structured array:
return array(
'status' => 'ok',
'header' => $header,
'content' => $content);
}
In addition to what Salaryman said, take a look at the classes in PEAR, there are HTTP request classes there that you can use even if you do not have the cURL extension installed in your PHP distribution.
There is a good class that does what you want. It can be downloaded at: http://sourceforge.net/projects/snoopy/
private function sendHttpRequest($host, $path, $query, $port=80){
header("POST $path HTTP/1.1\r\n" );
header("Host: $host\r\n" );
header("Content-type: application/x-www-form-urlencoded\r\n" );
header("Content-length: " . strlen($query) . "\r\n" );
header("Connection: close\r\n\r\n" );
header($query);
}
This will get you right away

Resources