how can i test php api in firebase.google.com - firebase

I am working in php project to send pushnotification. I have signup and get api key at https://console.firebase.google.com. I have also get following code from some reference site.
/*
Parameter Example
$data = array('post_id'=>'12345','post_title'=>'A Blog post');
$target = 'single tocken id or topic name';
or
$target = array('token1','token2','...'); // up to 1000 in one request
*/
function sendMessage($data,$target){
//FCM api URL
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = 'AIzaSyBY5ZTQiCrFY6Syq9oymtlJODcwvkGyxmI';
$fields = array();
$fields['data'] = $data;
if(is_array($target)){
$fields['registration_ids'] = $target;
}else{
$fields['to'] = $target;
}
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$server_key
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
But my query is that how can i use it ? i means how can i get target/token to test ? can i get this required token without android ? Is there any console where i can get test token for specific mobile. I want to test above code and so.

In the application you will have a class that extends FirebaseInstanceIdService
Overwrites the following method and run the code
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
//Getting registration token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//Displaying token on logcat
Log.d(TAG, "Refreshed token: " + refreshedToken);
}
it displays the token on the AndroidStudio console

Related

Telegram Bot join new user to kick and keep whitelist a member of private group?

I'm trying telegram bot of Webhook ex. new user join check database not my membership to kick user!
<?php
$API_KEY = 'token';
define('API_KEY', $API_KEY);
function bot($method,$datas=[]){
$url = "https://api.telegram.org/bot" . API_KEY . "/" . $method;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datas);
$res = curl_exec($ch);
if (curl_error($ch)) {
var_dump(curl_error($ch));
} else {
return json_decode($res);
}
}
$update = json_decode(file_get_contents('php://input'));
$message = $update->message;
$text = $message->text;
$chat_id = $message->chat->id;
$from_id = $message->from->id;
$new_member = $message->new_chat_member->id;
$memberid = file_get_contents('whitelist.txt'); //put userid in whitelist.txt
$whitelist = explode("\n", $memberid);
if ($new_member) {
if (!in_array($chat_id, $whitelist)) {
bot('kickChatMember',[
'chat_id'=>$chat_id,
'user_id'=>$message->new_chat_member->id]);
}
}
?>
I tried it gave me error results "Array" something wrong format json this code?
You could try $update["message"] instead of $update->message; and use the same syntax for remaining variables too. For me, it's working perfectly fine.

Image from url is a string not UploadFile instanceOf ¿why?

I'm looking for a solution to this issue for a long time.
This is an img => https://www.siweb.es/images/logo-light.png
I want to store this image as zip file usin OneupUploaderBundle.
So, when i get the image from Url usin file_get_contents or CURL it returns the image correctly but when i pass this file to $zip->addFile(); or an uoload service using Symfony\Component\HttpFoundation\File\UploadedFile both returns an error cause they are receiving a string as first Parameter.
I guess the problem is the file is not an instanceOf UploadeFile but i don't know how to convert it or use Filebag without a form.
public function testAction(Request $request){
$term = 'https://www.siweb.es/images/logo-light.png';
$image = $this->getimg($term);
if ($image instanceof UploadedFile){
$upload = $this->get('pablo.file_upload_service')->uploadZipFile($image,'test');
}
return $this->render('#pabloUser/Test/zip_test.html.twig',['upload' => $image]);
}
private function getimg($url) {
$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
$return = curl_exec($process);
curl_close($process);
return $return;
}
And the service:
public function uploadZipFile(UploadedFile $file,$folder){
// Check if the file's mime type is in the list of allowed mime types.
if (!in_array($file->getClientMimeType(), self::$allowedMimeTypes)) {
$this->pushbulletService->notification('Error en la subida de archivos',sprintf('Files of type %s are not allowed.', $file->getClientMimeType()));
throw new \InvalidArgumentException(sprintf('Files of type %s are not allowed.', $file->getClientMimeType()));
}
// Generate a unique filename based on the date and add file extension of the uploaded file
$filename = sprintf('%s/%s.%s', $folder, uniqid(), $file->getClientOriginalExtension());
$zipname = 'file.zip';
$zip = new \ZipArchive();
$zip->open($zipname,\ZipArchive::CREATE);
$zip->addFile($file);
$zip->close();
$adapter = $this->filesystem->getAdapter();
$adapter->write($filename, $zipname);
return $filename;
}
The problem is that your result from getimg is a (binary) string containing the image data. In order to pass it on as an UploadedFile you have to store the image in a (temporary) file first and then pass the path to it in the constructor.
It could look something like this:
$data = $this->getimg(...);
file_put_contents(sys_get_temp_dir() . '/filename.jpg', $data);
$image = new UploadedFile(
sys_get_temp_dir() . '/logo-light.png',
'logo-light.png'
);
$upload = $this->get('pablo.file_upload_service')->uploadZipFile($image,'test');

automate login / scrape files from a website

I need to figure out how to scrape a website and download files from an authenticated website.
A script needs to
login to this website using a username/password
navigate through the pages to get to the download page
set some fields in the form and hit download button
save the downloaded file
I have been looking at Jsoup (since Java is my preference), but can also try scrapy etc. But I need to understand if these are commonly done and if there is some other technology to enable this.
I could set this up using something like Selenium, but I dont want a tool that uses a browser as a UA because of the huge additional overhead.
I am getting somewhere but the whole cookie management is getting very confusing.
Thanks,
Vivek
If you require a lot of interaction with the webpage as you describe there is no way around using a real browser - at least from my experience. Selenium webdriver however works great with phantomjs, so the overhead is not too big.
As pointed out in then comment below you can use something like mechanize as well, however such solutions tend to be usesless when there is javascript that changes the DOM on the pages. (see http://wwwsearch.sourceforge.net/mechanize/faq.html#script)
I recommend you use Fiddler2 and navigate through the site as normal.
Once you have done it you should easily be able to replicate the page calls required and anything Javascript may have done with minimal fuss and code.
I tend to use the below to download pages in a number of forms at once and it saves cookies for login sites etc:
function Download($href)
{
curl_setopt($this->ch, CURLOPT_COOKIEJAR, COOKIE_FILE); // Cookie management.
curl_setopt($this->ch, CURLOPT_COOKIEFILE, COOKIE_FILE);
curl_setopt($this->ch, CURLOPT_TIMEOUT, CURL_TIMEOUT); // Timeout
curl_setopt($this->ch, CURLOPT_USERAGENT, WEBBOT_NAME); // Webbot name
curl_setopt($this->ch, CURLOPT_VERBOSE, FALSE); // Minimize logs
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE); // No certificate
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follow redirects
curl_setopt($this->ch, CURLOPT_MAXREDIRS, 4); // Limit redirections to four
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE); // Return in string
curl_setopt($this->ch, CURLOPT_URL, $href); // Target site
curl_setopt($this->ch, CURLOPT_REFERER, $href); // Referer value
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
# Create return arrays
$return_array['FILE'] = curl_exec($this->ch);
$return_array['STATUS'] = curl_getinfo($this->ch);
$return_array['ERRORS'] = curl_error($this->ch);
$dom_document = new DOMDocument();
#$dom_document->loadHTML($return_array['FILE']);
$return_array['DOM'] = new DOMXpath($dom_document);
return $return_array;
}
This is my HttpHelper Class. Easy to make use of and its just Html:
<?php
class HttpHelper {
function __construct() {
//setcookie("UserPostcode","2065",time() + 3600);
$this->ch = curl_init();
define("WEBBOT_NAME", "Test Webbot");
# Length of time cURL will wait for a response (seconds)
define("CURL_TIMEOUT", 25);
# Location of your cookie file. (Must be fully resolved local address)
define("COOKIE_FILE", "cookie.txt");
# DEFINE METHOD CONSTANTS
define("HEAD", "HEAD");
define("GET", "GET");
define("POST", "POST");
# DEFINE HEADER INCLUSION
define("EXCL_HEAD", FALSE);
define("INCL_HEAD", TRUE);
$header = array();
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$header[] = "Cache-Control: max-age=0";
$header[] = "Connection: keep-alive";
$header[] = "Keep-Alive: 300";
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Pragma: "; // browsers keep this blank.
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $header); // Set Header Information
}
// Collects the HTML, Status, Errors and a DOM.
function Download($href)
{
curl_setopt($this->ch, CURLOPT_COOKIEJAR, COOKIE_FILE); // Cookie management.
curl_setopt($this->ch, CURLOPT_COOKIEFILE, COOKIE_FILE);
curl_setopt($this->ch, CURLOPT_TIMEOUT, CURL_TIMEOUT); // Timeout
curl_setopt($this->ch, CURLOPT_USERAGENT, WEBBOT_NAME); // Webbot name
curl_setopt($this->ch, CURLOPT_VERBOSE, FALSE); // Minimize logs
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE); // No certificate
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follow redirects
curl_setopt($this->ch, CURLOPT_MAXREDIRS, 4); // Limit redirections to four
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE); // Return in string
curl_setopt($this->ch, CURLOPT_URL, $href); // Target site
curl_setopt($this->ch, CURLOPT_REFERER, $href); // Referer value
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
# Create return arrays
$return_array['FILE'] = curl_exec($this->ch);
$return_array['STATUS'] = curl_getinfo($this->ch);
$return_array['ERRORS'] = curl_error($this->ch);
$dom_document = new DOMDocument();
#$dom_document->loadHTML($return_array['FILE']);
$return_array['DOM'] = new DOMXpath($dom_document);
return $return_array;
}
function http_post_form($target, $ref, $data_array)
{
return $this->http($target, $ref, $method="POST", $data_array, EXCL_HEAD);
}
function http_post_withheader($target, $ref, $data_array)
{
return http($target, $ref, $method="POST", $data_array, INCL_HEAD);
}
function http($target, $ref, $method, $data_array, $incl_head)
{
# Initialize PHP/CURL handle
$ch = curl_init();
# Prcess data, if presented
if(is_array($data_array))
{
# Convert data array into a query string (ie animal=dog&sport=baseball)
foreach ($data_array as $key => $value)
{
if(strlen(trim($value))>0)
$temp_string[] = $key . "=" . urlencode($value);
else
$temp_string[] = $key;
}
$query_string = join('&', $temp_string);
}else{
$query_string =$data_array;
}
# HEAD method configuration
if($method == HEAD)
{
curl_setopt($ch, CURLOPT_HEADER, TRUE); // No http head
curl_setopt($ch, CURLOPT_NOBODY, TRUE); // Return body
}
else
{
# GET method configuration
if($method == GET)
{
if(isset($query_string))
$target = $target . "?" . $query_string;
curl_setopt ($ch, CURLOPT_HTTPGET, TRUE);
curl_setopt ($ch, CURLOPT_POST, FALSE);
}
# POST method configuration
if($method == POST)
{
if(isset($query_string))
curl_setopt ($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt ($ch, CURLOPT_POST, TRUE);
curl_setopt ($ch, CURLOPT_HTTPGET, FALSE);
}
curl_setopt($ch, CURLOPT_HEADER, $incl_head); // Include head as needed
curl_setopt($ch, CURLOPT_NOBODY, FALSE); // Return body
}
curl_setopt($ch, CURLOPT_COOKIEJAR, COOKIE_FILE); // Cookie management.
curl_setopt($ch, CURLOPT_COOKIEFILE, COOKIE_FILE);
curl_setopt($ch, CURLOPT_TIMEOUT, CURL_TIMEOUT); // Timeout
curl_setopt($ch, CURLOPT_USERAGENT, WEBBOT_NAME); // Webbot name
curl_setopt($ch, CURLOPT_URL, $target); // Target site
curl_setopt($ch, CURLOPT_REFERER, $ref); // Referer value
curl_setopt($ch, CURLOPT_VERBOSE, FALSE); // Minimize logs
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // No certificate
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follow redirects
curl_setopt($ch, CURLOPT_MAXREDIRS, 4); // Limit redirections to four
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Return in string
# Create return array
$return_array['FILE'] = curl_exec($ch);
$return_array['STATUS'] = curl_getinfo($ch);
$return_array['ERROR'] = curl_error($ch);
# Close PHP/CURL handle
curl_close($ch);
# Return results
return $return_array;
}
function InnerHtml($element)
{
$innerHTML = "";
if($element != NULL && $element->hasChildNodes())
{
$children = $element->childNodes;
foreach ($children as $child)
{
$tmp_dom = new DOMDocument();
$tmp_dom->appendChild($tmp_dom->importNode($child, true));
$innerHTML.=trim($tmp_dom->saveHTML());
}
}
return $innerHTML;
}
function Split($data, $split)
{
return explode($split, $data);
}
function correctImgUrls($html, $url)
{
$DOM = new DOMDocument;
$DOM->loadHTML($html);
$imgs = $DOM->getElementsByTagName('img');
foreach($imgs as $img){
$src = $img->getAttribute('src');
if(strpos($src, $url) !== 0){
$img->setAttribute('src', $url.$src);
}
}
$html = $DOM->saveHTML();
return $html;
}
function correctUrls($html, $url)
{
$DOM = new DOMDocument;
$DOM->loadHTML($html);
$imgs = $DOM->getElementsByTagName('a');
foreach($imgs as $img){
$src = $img->getAttribute('href');
if(strpos($src, $url) !== 0){
$img->setAttribute('a', $url.$src);
}
}
$html = $DOM->saveHTML();
return $html;
}
function removeHref($html)
{
$DOM = new DOMDocument;
$DOM->loadHTML($html);
$imgs = $DOM->getElementsByTagName('a');
foreach($imgs as $img){
$src = $img->getAttribute('href');
$img->setAttribute('href', "#");
}
$html = $DOM->saveHTML();
return $html;
}
function QuerySelector($dom, $xPath)
{
return $dom->query($xPath);
}
/*
function __destruct() {
# Close PHP/CURL handle
echo "Destruct Called..";
curl_close($ch);
}*/
}
?>
Simulate your login and do what you need to do: This is an example I use to login to my oDesk account and scrape job postings that I then email to myself :P
include("Business/Http/HttpHelper.php");
$bot = new HttpHelper;
//$download = $bot ->Download("https://www.odesk.com/login");
$data['username'] = "myusername";
$data['password'] = "myPassword";
$bot -> http_post_form("https://www.odesk.com/login", "https://www.odesk.com/login", $data);
You owe me!

Testing a download file with symfony2

Can you please help me on how to test a download file in symfony2?
There are my source code :
Controller.php
public function downloadAction($picture_id)
{
$fichier= $this->uploadDir.$picture_id;
if (($fichier != "") && (file_exists($fichier))) {
$content = file_get_contents($fichier);
$response = new Response();
$response->headers->set('Content-Type', 'application/octet-stream');
$response->headers->set('Content-Disposition', 'attachment;filename="'.$picture_id);
$response->setContent($content);
return $response;
}
else return new Response(json_encode(array("response_code" => "ko")));
}
ControllerTest.php
public function testdownload()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, "path/img.jpg");
$response = curl_exec($ch);
}
The issue is that how can I test that the download has been successful,or which assertion could I use to do my functionnal test?
Asked 5 years ago, but maybe someone will find this useful (functional test):
$client = static::createClient();
$client->request('GET', '/path/img.jpg');
$this->assertEquals(true, $client->getResponse()->isOk());
$binaryData = $client->getInternalResponse()->getContent()
The problem is that $client->getResponse()->getContent() returns empty string when there's binary data.
Tested with Symfony 4.2.

Curl PUT data is not received

I'm trying to parse a file sent through http CURL PUT method. I'm using generic handler for parsing the file. I have created a generic handler for getting posted file. Following is the ASP.Net Code:
I'm not able to receive any file or contents. Do I have any problem in my code? Also following is the CURL script that is being used for sending file:
public class Test : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string result = string.Empty;
try
{
context.Response.ContentType = "text/plain";
//VALIDATE FILES IN REQUEST
if (context.Request.Files.Count > 0)
{
try
{
//HANDLE EACH FILE IN THE REQUEST
foreach (HttpPostedFile item in context.Request.Files)
{
item.SaveAs(context.Server.MapPath("~/Temp/" + item.FileName));
context.Response.Write("FILE UPLOADED");
}
}
catch (Exception ex)
{
//NO FILES IN REQUEST TO HANDLE
context.Response.Write("ERROR: " + ex.Message);
}
}
else
{
//NO FILES IN REQUEST TO HANDLE
context.Response.Write("NO FILE(S) SENT");
}
context.Response.Write(result);
}
catch (Exception ex)
{
//result = "205";
context.Response.Write(ex.Message);
}
}
public bool IsReusable
{
get
{
return false;
}
}
function putRequest($url, $data)
{
$putData = tmpfile();
fwrite($putData, $data);
fseek($putData, 0);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_INFILE, $putData);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data));
curl_setopt($ch, CURLOPT_PUT, true);
curl_exec($ch);
$headers = curl_getinfo($ch);
fclose($putData);
curl_close($ch);
return $headers['http_code'];
}
$url= " http://api.domain.com/upload/ ";
$data = "21.2,1000,1,2,3,4,5,6,7,8,9";
echo "Starting the put request<br />";
$ret = putRequest($url,$data);
echo "Returned code: $ret<br />";

Resources