Sending Image via Telegram-Bot API with PHP - php

I have this function
function suspendido($chat_id,$foo)
{
$TOKEN = "blablalbal";
$TELEGRAM = "https://api.telegram.org:443/bot$TOKEN";
$url. = "https://zrabogados-pruebas.xyz/bot/404.png";
$query = http_build_query(array(
'chat_id'=> $chat_id,
'photo'=> $url,
'text'=> $foo,
'parse_mode'=> "HTML", // Optional: Markdown | HTML
));
$response = file_get_contents("$TELEGRAM/sendMessage?$query");
return $response;
}
I try to sending an Image without using curl, tried to use file_get_contents but nothing works. Is something missing?.

Apparently, there is some problem with telegram servers.
If you put some image attributes into url it works.
function suspendido($chat_id,$foo)
{
$TOKEN = "blablalbla";
$TELEGRAM = "https://api.telegram.org:443/bot$TOKEN";
$url = "https://zrabogados-pruebas.xyz/bot/404.png?center=140.50,36.15&width=1024&height=576";
$query = http_build_query(array(
'chat_id'=> $chat_id,
'photo'=> $url,
'text'=> $foo,
'parse_mode'=> "HTML", // Optional: Markdown | HTML
));
$response = file_get_contents("$TELEGRAM/sendMessage?$query");
return $response;
}
I know its just silly but it works that way if you send the image url without this then you will receive a 400 error.

You used sendMessage method, And this method isn't accept photo parameter.
And $url shouldn't be concatenated with another link.
To send photo use sendPhoto method like this:
<?php
function suspendido($chat_id, $url, $foo)
{
$TOKEN = "<bot_token>";
$TELEGRAM = "https://api.telegram.org:443/bot$TOKEN";
$url = "https://zrabogados-pruebas.xyz/bot/404.png";
$query = http_build_query(array(
'chat_id'=> $chat_id,
'photo'=> $url,
'text'=> $foo,
'parse_mode'=> 'HTML' // Optional: Markdown | HTML
));
# Use sendPhoto here, Not sendMessage
$response = file_get_contents("$TELEGRAM/sendPhoto?$query");
return $response;
}

Related

Streaming a response in CakePHP

I want CakePHP to stream a download to the browser. The content of the stream is served via an API.
So, CakePHP makes a request to that API, gets a response with a file and must stream this response to the browser.
This is what I got so far:
public function getDownload() {
// do other things
$http = new Client([
'headers' => [
'accept' =>'application/octet-stream'
]
]);
$response = $http->get($this->url,[]);
// first try
// $stream = new CallbackStream(function () use ($response) {
// return $response;
// });
// $response = $response->withBody($stream);
// second try
// $stream = new CallbackStream($http->get($this->url,[])->getData());
// $response = $response->withBody($stream);
return $response;
}
With this setup I can download small files. The reason I need a stream is, because the API could send files up to 10GB. My guess is, that with $http->get CakePHP stores the whole response in memory. Thats why I'm getting a memory exhausted error.
I know I'm lacking a bit of understanding here. Any help is appreciated :)
Finally I found a solution:
public function getDownload($url) {
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"accept: application/octet-stream\r\n"
)
);
$context = stream_context_create($opts);
$response = new Response();
$file = fopen($url, 'r',false, $context);
$stream = new CallbackStream(function () use ($file) {
rewind($file);
fpassthru($file);
fclose($file);
});
$response = $response->withBody($stream);
return $response;
}

get content of search result with file_get_content php

is there a possible way to get content of search result by file_get_content. I am trying to do this site's search results.
http://brillia.com/search/?attribute=1&area=13900,13100,13200,14999,12999,11999
but it's not giving me the content of this part ?attribute=1&area=13900,13100,13200,14999,12999,11999 is it something missing in my function. Or file_get_content is not enough for this?
function pageContent(String $url): \DOMDocument
{
$html = cache()->rememberForever($url, function () use ($url) {
$opts = [
"http" => [
"method" => "GET",
"header" => "Accept: text/html\r\n"
]
];
$context = stream_context_create($opts);
$file = file_get_contents($url, false, $context);
return $file;
});
$parser = new \DOMDocument();
libxml_use_internal_errors(true);
$parser->loadHTML($html = mb_convert_encoding($html,'HTML-ENTITIES', 'ASCII, JIS, UTF-8, EUC-JP, SJIS'));
return $parser;
}
The URL you're using is making another Ajax call, which is:
http://brillia.com/api/search/?area=13900,13100,13200,14999,12999,11999&key=2CsR0Bzv&mode=1&attribute=1&area=13900%2C13100%2C13200%2C14999%2C12999%2C11999&_=1552729056711
This will give you the desired result.
<?php
function pageContent( $url ) {
header('Content-type: text/html; charset=EUC-JP');
echo '<base href="http://brillia.com">';
echo file_get_contents($url);
}
echo pageContent('http://brillia.com/search/?attribute=1&area=13900,13100,13200,14999,12999,11999');

how to include google analytics in php web service

I have a webservice writen in php and it is called from an desktop application installed on PC's.
I want to have a register of the users who calls the functions on the web service and for this I only want to send hits to Google Analytics.
webservice in php:
<?php
require_once('lib/nusoap.php'); // basic include.. must go at the top
$SERVICE_NAMESPACE = "urn:Service"; // create a namespace to run under.
$server = new soap_server(); // the soap object from the include above.
// this has many input parameters but we only need two: the service name and the namespace
$server->configureWSDL('Service', $SERVICE_NAMESPACE);
$server->register('test',// method name
array('name' => 'xsd:string', 'name99' => 'xsd:string'),// input parameter called name.. and it's a string.
array('return' => 'xsd:string'),// output - one string is returned called "return"
$SERVICE_NAMESPACE,// namespace
$SERVICE_NAMESPACE . '#hello1',// soapaction
'rpc',// style.. remote procedure call
'encoded',// use of the call
'Nada interesante'// documentation for people who hook into your service.
);
function test($sName,$sName99)
{
return 'TEST ';
}
//This processes the request and returns a result.
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
I want to have google analytics info and for that i want to integrate the following script:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-89356985-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments)};
gtag('js', new Date());
gtag('config', 'UA-89356985-1');
</script>
I don't know how to integrate in the test function. I want to know when the users calls the test function.
Thanks in advance very much.
You cannot use the Javascript tracker unless your PHP script produces HTML and Javascript that is executed in a browser.
You can however use the Measurement Protocol to make server side calls to Google Analytics. That's basically an endpoint where you send predefined parameters with your custom values (via any method that can make http calls) and they will register in Google Analytics.
This can be used as en example of what you need. use http_build_queryto build you hit as you want to Google Analytics. Change Google_Analytics_UA_Stringto match your Google Analytics ID
<?php
//some of the functions we need to make it work
function generate_serial($n) {
$c = "abcdefghijklmnopqrstuvwyxz0123456789";
$s = '';
for($i=0;$i<$n;$i++) {
$s .= substr($c,rand(0,37),1);
}
return $s;
}
function generate_uuid() {
return generate_serial(8).'-'.generate_serial(4).'-4'.generate_serial(3).'-a'.generate_serial(3).'-'.generate_serial(12);
}
function ip() {
$ip = false;
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
$ip = trim(array_shift($ip));
}
elseif(isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
//define necessary variables
define('Google_Analytics_UA_String','UA-XXXXXXXX-X');
//create a UUID string for the user sending the request and store in the the session
if(isset($_COOKIE['Google_Analytics_UUID']) and !empty($_COOKIE['Google_Analytics_UUID'])) {
define('Google_Analytics_UUID',$_COOKIE['Google_Analytics_UUID']);
}
else {
define('Google_Analytics_UUID',generate_uuid());
setcookie('Google_Analytics_UUID',Google_Analytics_UUID,time()+63072000);
}
//compile the data we want to send to the API
$data = http_build_query(array(
'v' => 1, // version
'ds' => 'app', // data source
'tid' => Google_Analytics_UA_String, // Tracking ID / Web Property ID
'cid' => Google_Analytics_UUID, // Client ID
'uip' => ip(), // IP Override
't' => 'event', // Hit type
'ec' => 'site clicks', // event category
'ea' => 'click', // event action
'el' => 'button', // event label
'ev' => 'Click here!' // event value
));
//send using PHP's cURL extension
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://www.google-analytics.com/collect');
curl_setopt($ch,CURLOPT_HEADER,true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$response = curl_exec($ch);
//parse the response and send back to the browser
header('Content-Type: application/json');
$status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($status == 200) {
echo json_encode([
'success' => true
]);
}
else {
echo json_encode([
'error' => true
]);
}
?>
The exact running sample is:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://www.google-analytics.com/collect?v=1&tid=UA-XXXXXXX-1&cid=35009a79-1a05-49d7-b876-2b884d0f825b&uid=myserid&uip=179.52.60.197&t=event&ec=Service&ea=SER&el=999999&z=54564653213',
CURLOPT_USERAGENT => 'Vanity-URL-Tracker',
));
$resp = curl_exec($curl);
curl_close($curl);
?>
I have an example for Page Tracking:
public function send($trackingId, $host, $page, $title)
{
$google_analytics_url = 'https://www.google-analytics.com/collect';
$google_analytics_params = http_build_query(array(
'v' => 1,
'tid' => $trackingId, // UA-xxxxxxx-x
'cid' => uniqid(),
't' => 'pageview',
'dh' => $host,
'dp' => '/'.$page,
'dt' => urlencode($title),
));
$url = $google_analytics_url.'?'.$google_analytics_params;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Vanity-URL-Tracker',
));
$resp = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($status!= 200) {
log_message('error', json_encode(array('status' => $status, 'response' => $resp)) );
}
if (curl_errno($curl)) {
log_message('error', curl_error($curl));
}
curl_close($curl);
return $resp;
}

# value of POST variable in PHP CURL

I'm creating a function to untilize NameCheap's API for registering domain names. The registration process worked out smoothly, now I'm looking to set the proper DNS Hosts.
When I create a pure POST request with something like POSTMAN this works fine and returns the expected XML response. However when I try to pass the data through PHP's CURL functions it breaks. I've narrowed the problem the the '#' symbol that needs to be passed to the DNS Host. If i put anything else there the request goes through. I've tried to url_encode the symbol but the API does not accept that.
Any suggestions?
public function setDNSHost($name, $server){
list($domain,$tld) = explode('.',$name,2);
$request = $this->request_URL;
$curl = curl_init();
$args['ApiUser'] = $this->API_User;
$args['ApiKey'] = $this->API_Key;
$args['UserName'] = $this->API_User;
$args['Command'] = 'namecheap.domains.dns.setHosts';
$args['ClientIP'] = $this->Client_IP;
$args['SLD'] = $domain;
$args['TLD'] = $tld;
$args['HostName1'] = utf8_encode('#');
$args['RecordType1'] = 'A';
$args['Address1'] = $server;
$args['HostName2'] = 'www';
$args['RecordType2'] = 'CNAME';
$args['Address2'] = $name;
$args['HostName3'] = '*';
$args['RecordType3'] = 'CNAME';
$args['Address3'] = $name;
curl_setopt_array($curl, array(
CURLOPT_URL => $request,
CURLOPT_USERAGENT => 'API',
// CURLOPT_FAILONERROR => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $args,
CURLOPT_TIMEOUT => 15
));
$response = curl_exec($curl);
curl_close($curl);
// $oXML = new SimpleXMLElement($response);
return $response;
}
Some caracters are not allowed to be in the string. To avoid such problems you could use http_build_query on your data before you use the curl function.

Restful API for CakePHP 2

I am creating a Restful WebService with CakePHP 2 however, i am getting 500 Internal Server Error since i am not able to capture Post Data. The Rest Server is as below:
App::import ( 'Vendor', 'ExchangeFunctions', array ('file'=> 'exchange/exchangefunctions.php'));
class ExchangeController extends AppController
{
public $components = array('RequestHandler');
public
function index()
{
$exchange = new ExchangeFunctions();
$data = $this->request->data('json_decode');
$exchange->username = $_POST['username'];
$exchange->password = $_POST['password'];
$emailList = $exchange->listEmails();
$response = new stdClass();
$response->emailList = $emailList;
foreach($emailList->messages as $listid => $email)
{
$tempEmail = $exchange->getEmailContent(
$email->Id,
$email->ChangeKey,
TRUE,
$_POST['attachmentPath']
);
$response->emails[$tempEmail['attachmentCode']] = $tempEmail;
}
$this->set('response', $response);
$this->set('_serialize','response');
}
}
and the client goes as:
class ApitestController extends AppController
{
Public function index()
{
$this->layout = 'ajax';
$jRequestURLPrefix = 'http://localhost/EWSApi/';
$postUrl = $jRequestURLPrefix."exchange/index.json";
$postData = array(
'username' => 'username',
'password' => 'password',
'attachmentPath'=> $_SERVER['DOCUMENT_ROOT'] . $this->base . DIRECTORY_SEPARATOR . 'emailDownloads' . DIRECTORY_SEPARATOR . 'attachments'
);
$postData = json_encode($postData);
pr($postData);
$ch = curl_init( $postUrl );
$options = array(
CURLOPT_RETURNTRANSFER=> true,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData)
),
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_POSTFIELDS => $postData,
);
curl_setopt_array( $ch, $options );
$jsonString = curl_exec($ch);
curl_close($ch);
$data = json_decode($jsonString, FALSE);
echo $jsonString;
}
}
Not sure where i am messing up! Please help!
Ok, after a second look there are some more suspicious things. As already mentioned, your CURL request uses GET instead of POST.
$options = array(
...
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $postData,
);
Another thing is that you are encoding the POST data for your CURL call to JSON, but then you are trying to access it on the other side using $_POST, however there won't be anything, POST data would have to be key/value query string formatted in order to appear in $_POST. You have to read php://input instead, which may be what you were trying to do with
$data = $this->request->data('json_decode');
However you must use CakeRequest::input() for that purpose, and of course you must then use the $data variable instead of $_POST
$data = $this->request->input('json_decode');
$exchange->username = $data['username'];
$exchange->password = $data['password'];
....
$tempEmail = $exchange->getEmailContent(
$email->Id,
$email->ChangeKey,
TRUE,
$data['attachmentPath']
);
Also make double sure that your CURL request looks like expected:
$options = array(
...
CURLOPT_POSTFIELDS => $postData,
CURLINFO_HEADER_OUT => true // supported as of PHP 5.1.3
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo '<pre>';
print_r($info);
echo '</pre>';

Categories