Firstly, How would you get Google Alerts information into a database other than to parse the text of the email message that Google sends you?
It seems that there is no Google Alerts API.
If you must parse text, how would you go about parsing out the relevant pieces of the email message?
When you create the alert, set the "Deliver To" to "Feed" and then you can consume the feed XML as you would any other feed. This is much easier to parse and digest into a database.
class googleAlerts{
public function createAlert($alert){
$USERNAME = 'XXXXXX#gmail.com';
$PASSWORD = 'YYYYYY';
$COOKIEFILE = 'cookies.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $COOKIEFILE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $COOKIEFILE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_URL,
'https://accounts.google.com/ServiceLogin?hl=en&service=alerts&continue=http://www.google.com/alerts/manage');
$data = curl_exec($ch);
$formFields = $this->getFormFields($data);
$formFields['Email'] = $USERNAME;
$formFields['Passwd'] = $PASSWORD;
unset($formFields['PersistentCookie']);
$post_string = '';
foreach($formFields as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/ServiceLoginAuth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
if (strpos($result, '<title>') === false) {
return false;
} else {
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts');
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/create');
curl_setopt($ch, CURLOPT_POST, 0);
$result = curl_exec($ch);
//var_dump($result);
$result = $this->getFormFieldsCreate($result);
$result['q'] = $alert;
$result['t'] = '7';
$result['f'] = '1';
$result['l'] = '0';
$result['e'] = 'feed';
unset($result['PersistentCookie']);
$post_string = '';
foreach($result as $key => $value) {
$post_string .= $key . '=' . urlencode($value) . '&';
}
$post_string = substr($post_string, 0, -1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/alerts/manage');
$result = curl_exec($ch);
if (preg_match_all('%'.$alert.'(?=</a>).*?<a href=[\'"]http://www.google.com/alerts/feeds/([^\'"]+)%i', $result, $matches)) {
return ('http://www.google.com/alerts/feeds/'.$matches[1][0]);
} else {
return false;
}
}
}
private function getFormFields($data)
{
if (preg_match('/(<form.*?id=.?gaia_loginform.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form');
}
}
private function getFormFieldsCreate($data)
{
if (preg_match('/(<form.*?name=.?.*?<\/form>)/is', $data, $matches)) {
$inputs = $this->getInputs($matches[1]);
return $inputs;
} else {
die('didnt find login form1');
}
}
private function getInputs($form)
{
$inputs = array();
$elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);
if ($elements > 0) {
for($i = 0; $i < $elements; $i++) {
$el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];
$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}
$inputs[$name] = $value;
}
}
}
return $inputs;
}
}
$alert = new googleAlerts;
echo $alert->createAlert('YOUR ALERT');
It will return link to rss feed of your newly created alert
I found a Google Alerts API here. It's pretty minimal and I haven't tested it.
Related
we select checbox & onclick button "Show Status" , I am calling external webservice api url & updating the "status" column [4th in below image] values in Database.....
once we got success response we are displaying alert message....
Requirement :
but now i want to display Progress like "1% completed , 2 % completed" , so on.... :
status page
<button type= "button" id="show_status" >Show Status</button>
script
$('#show_status').click(function()
{
var selected = [];
$('.assigneeid-order:checked').each(function()
{
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var jsonString = JSON.stringify(selected);
$.ajax
({
type: "POST",
url: "api.php",
data: {data : jsonString},
success: function(response)
{
response = $.parseJSON(response);
alert("completed");
$.each(response, function(index, val)
{
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
}
});
});
api.php
<?php
$data = json_decode(stripslashes($_POST['data']));
$response = array();
foreach($data as $id){
$post_data['username']='a';
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
//print_r($orderResults); die;
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
echo json_encode($response);
?>
Please try this script and code
$('#show_status').click(function()
{
var selected = [];
$('.assigneeid-order:checked').each(function(){
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var count = selected.length
var perPlush = 100/count;
var per = 0;
for (var i = 0; i <= count; i++) {
$.ajax
({
type: "POST",
url: "api.php",
data: {id : selected[i]},
success: function(response)
{
response = $.parseJSON(response);
$.each(response, function(index, val)
{
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
per = per + perPlush;
console.log(Math.round(per) + " % Complated");
$("#progress").html(Math.round(per) + " % Complated");
}
});
}
});
Your api.php file
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX);
require_once("dbcontroller.php");
$db_handle = new DBController();
$id = $_POST['id']; //960856092
$response = array();
$orderid = $id;
$hide = '';
$post_data['awb']=$orderid;
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "http://plapi.ecomexpress.in/track_me/api/mawbd/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec ($ch);
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
if($orderResults){
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
else{
$response[$orderid] = ['status' => 'Order already placed'];
}
echo json_encode($response);
?>
$scope.formatfilename = response.fileformat[0].FileName;
// it contains filename = abcd
$filename1 ='{{formatfilename}}'; // now I have taken into phpvariable
$siteaddr = "http://localhost:8080/demoproject/document/".$filename1.".html";
echo file_get_contents($siteaddressAPI);
it gives me Failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
if I assign full url static to $siteaddressAPI then it gives the result.
how to solve in codeigniter ??
Option 1:
change in php.ini
allow_url_fopen = On
Option 2: use cURL
You might want to try using curl to retrieve the data instead of file_get_contents. curl has better support for error handling:
$filename1 ='{{formatfilename}}'; // now I have taken into phpvariable
$siteaddr = "http://localhost:8080/demoproject/document/".$filename1.".html";
// make request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $siteaddr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
// convert response
$output = json_decode($output);
// handle error; error output
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
var_dump($output);
}
curl_close($ch);
Working Example
<?php
$siteaddr = "https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY";
// make request
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $siteaddr);
// Execute
$output = curl_exec($ch);
// convert response
$output = json_decode($output);
// handle error; error output
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
var_dump($output);
}
curl_close($ch);
echo "<pre>", print_r($output), "</pre>";
die();
?>
Output
stdClass Object
(
[error_message] => The provided API key is invalid.
[results] => Array
(
)
[status] => REQUEST_DENIED
)
I'm trying send push notifications with CakePHP. The notifications are send but the problem is that all notifications are repeating. I cant understand why this problem.
I have a table to add devices of GCM (Google Cloud Messaging). After save the Model I do a SELECT in this table to get all devide_id of GCM saved and send the push notifications. The field device_id is unique in table. After to select I do a foreach to get devices and send the notifications, but this always repeating and send a lot of push to the same device_id.
How could I solve it ?
Push Notification Class
<?php
class Pusher{
const GOOGLE_GCM_URL = 'https://android.googleapis.com/gcm/send';
private $apiKey;
private $proxy;
private $output;
public function __construct($apiKey, $proxy = null)
{
$this->apiKey = $apiKey;
$this->proxy = $proxy;
}
/**
* #param string|array $regIds
* #param string $data
* #throws \Exception
*/
public function notify($regIds, $data)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::GOOGLE_GCM_URL);
if (!is_null($this->proxy)) {
curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->getPostFields($regIds, $data));
$result = curl_exec($ch);
if ($result === false) {
throw new \Exception(curl_error($ch));
}
curl_close($ch);
$this->output = $result;
}
/**
* #return array
*/
public function getOutputAsArray()
{
return json_decode($this->output, true);
}
/**
* #return object
*/
public function getOutputAsObject()
{
return json_decode($this->output);
}
private function getHeaders(){
return [
'Authorization: key=' . $this->apiKey,
'Content-Type: application/json'
];
}
private function getPostFields($regIds, $data){
$fields = [
'registration_ids' => is_string($regIds) ? [$regIds] : $regIds,
'data' => is_string($data) ? ['message' => $data] : $data,
];
return json_encode($fields, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
}
}
Controller
<?php
App::uses('AppController', 'Controller');
App::uses('Pusher', 'Plugin/Push');
class NoticiasController extends AppController {
public function add() {
if ($this->request->is('post')) {
$this->Noticia->create();
if($this->Noticia->save($this->request->data)){
$this->Session->setFlash(__("Save ok!"));
$this->sendPush();
return $this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash(__("Not save :("));
}
}
}
/***************** push notifications ****************/
private function sendPush(){
$apiKey = "AIzaSyCMZ6roIEpHsj5P8cgErgceerljerhaljh";
//msg de push
$message = array("title"=>"Title",
"message"=>"Post a news",
"tickerText"=>"Post a news",
"url"=>"News");
$this->loadModel('Device');
$devices = $this->Device->query("SELECT device_id, status FROM devices Device WHERE status = 1");
$pusher = new Pusher($apiKey);
foreach ($devices as $device){
$pusher->notify($device["Device"]["device_id"], $message);
}
}
}
my urls array contains like 100 urls, and is getting the information from an API designed for something like that.
Anyway, like 50% of the urls returns
400 Bad Request
Your browser sent a request that this server could not understand.
GET /player/euw/Wolves Deficio/ingame HTTP/1.1
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1
Host: api.captainteemo.com
Accept: */*
the urls are 100% correct, cause when I copy them to my browser, I DO get the info.
Here is my code:
function get_data($urls) {
// spoofing FireFox 2.0
$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
$ch = curl_init();
// set user agent
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
if(is_array($urls)) {
$output = array();
foreach($urls as $url) {
// set the rest of your cURL options here
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
array_push($output, curl_exec($ch));
}
}
else {
// set the rest of your cURL options here
curl_setopt($ch, CURLOPT_URL, $urls);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
}
// close curl resource to free up system resources
curl_close($ch);
return $output;
}
I added CURLOPT_FOLLOWLOCATION in a case of redirect
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
Try this:
<?php
function get_data($urls)
{
if ( !is_array( $urls ) )
$urls = array( '0' => $urls );
$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output = array();
foreach($urls as $url)
{
curl_setopt($ch, CURLOPT_URL, $url);
$output[$url] = curl_exec($ch);
}
curl_close($ch);
return $output;
}
$urls = array(
'http://www.wikipedia.org/',
'http://www.stackoverflow.com'
);
//or single url
//$urls = 'http://www.stackoverflow.com';
print_r ( get_data($urls) );
The problem was that I spoofed the user agent instead of using a real one, also didnt repalced " " by "+".
UPDATED: I've simplified the code (tried to)
I'm trying to download a series of images as set in an array, but something is clearly not right:
function savePhoto($remoteImage,$fname) {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_NOBODY, true);
curl_setopt ($ch, CURLOPT_URL, $remoteImage);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
$fileContents = curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($retcode==200) {
$newImg = imagecreatefromstring($fileContents);
imagejpeg($newImg, ".{$fname}.jpg",100);
}
return $retcode;
}
$filesToGet = array('009');
$filesToPrint = array();
foreach ($filesToGet as $file) {
if(savePhoto('http://pimpin.dk/jpeg/'.$file.'.jpg',$file)==200) {
$size = getimagesize(".".$file.".jpg");
echo $size[0] . " * " . $size[1] . "<br />";
}
}
I get the following errors:
Warning: imagecreatefromstring()
[function.imagecreatefromstring]:
Empty string or invalid image in
C:\inetpub\vhosts\dehold.net\httpdocs\ripdw\index.php
on line 15
Warning: imagejpeg(): supplied
argument is not a valid Image resource
in
C:\inetpub\vhosts\dehold.net\httpdocs\ripdw\index.php
on line 16
Warning: getimagesize(.009.jpg)
[function.getimagesize]: failed to
open stream: No such file or directory
in
C:\inetpub\vhosts\dehold.net\httpdocs\ripdw\index.php
on line 26
*
try this instead:
function get_file1($file, $local_path, $newfilename)
{
$err_msg = '';
echo "<br>Attempting message download for $file<br>";
$out = fopen($newfilename, 'wb');
if ($out == FALSE){
print "File not opened<br>";
exit;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_FILE, $out);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $file);
curl_exec($ch);
echo "<br>Error is : ".curl_error ( $ch);
curl_close($ch);
//fclose($handle);
}//end function
// taken from: http://www.weberdev.com/get_example-4009.html
or file_get_contents
You should try file_get_contents in replacement of CURL (simpler but it does the job):
function savePhoto($remoteImage,$fname) {
$fileContents = file_get_contents($remoteImage);
try {
$newImg = imagecreatefromstring($fileContents);
imagejpeg($newImg, ".{$fname}.jpg",100);
} catch (Exception $e) {
//what to do if the url is invalid
}
}
I finally got it to work, with help from you all and a bit of snooping around :-)
I ended up using CURL:
function savePhoto($remoteImage,$fname) {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $remoteImage);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
$fileContents = curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($retcode == 200) {
$newImg = imagecreatefromstring($fileContents);
imagejpeg($newImg, $fname.".jpg",100);
}
return $retcode;
}
$website = "http://www.pimpin.dk/jpeg";
$filesToGet = array('009');
$filesToPrint = array();
foreach ($filesToGet as $file) {
if(savePhoto("$website/$file.jpg",$file)==200) {
$size = getimagesize($file.".jpg");
echo $size[0] . " * " . $size[1] . "<br />";
} else {
echo "File wasn't found";
}
}