Check for unread mail in php - php

I'm trying to implement a check new mail function to my page.
By this I mean a script that checks the mail, if there exists unread mails it will notify the user "You got one unread mail".
Is this possible?
Thanks in advance
I managed to get it to work as long as the users emails and passwords are stored as plain text in the database.
I'm using a query to retrieve email and password of a user from my database ($email) and ($password)
The code:
$mbox =
imap_open("{imap.domain.com:143/novalidate-cert}INBOX",
"$email", "$password");
The only problem is that the email passwords for my users are stored as md5 hash.
How can I handle this with imap_open?
Thanks

It is possible, if you implement an IMAP (or POP3) client in your PHP script. When you open your page, PHP would connect to the mail server and check for new messages. To achieve this, PHP would need your username/password and server address/port. Hence, this information will have to be stored on the server.
The example given at http://lv.php.net/imap_mailboxmsginfo will give you some more hints.

If you can't use imap_open (the extension is not installed, for example), you can use curl (example tested with gmail):
// https://support.google.com/mail/answer/7126229 [2017-10-22]
define('URL', 'imaps://imap.gmail.com');
define('PORT', 993);
define('USER', 'your.user#gmail.com');
define('PASS', 'your_Secret_Password');
if ($ch = curl_init()) {
curl_setopt($ch, CURLOPT_URL, URL);
curl_setopt($ch, CURLOPT_PORT, PORT);
curl_setopt($ch, CURLOPT_USE_SSL, CURLUSESSL_ALL);
curl_setopt($ch, CURLOPT_USERNAME, USER);
curl_setopt($ch, CURLOPT_PASSWORD, PASS);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// set IMAP command
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'STATUS INBOX (MESSAGES UNSEEN)');
$res = curl_exec($ch);
if (curl_errno($ch)) {
echo 'CURL ERROR: ' . curl_error($ch);
} else {
echo trim($res);
}
echo PHP_EOL;
curl_close($ch);
} else {
die('Curl initialization failed.');
}
The script will return something like:
* STATUS "INBOX" (MESSAGES 2 UNSEEN 1)
More about IMAP commands (https://www.google.com/search?q=imap+protocol+commands) [2017-10-22]:
https://www.rfc-editor.org/rfc/rfc3501
https://donsutherland.org/crib/imap
http://busylog.net/telnet-imap-commands-note/
https://www.skytale.net/blog/archives/23-Manual-IMAP.html

You can comfortably do that using the Zeta Mail component, even without any special extension being available.

$hostname='{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'mygmail#gmail.com';
$password = 'mypass';
$mbox = imap_open($hostname,$username,$password) or die('Cannot connect to Tiriyo: ' . imap_last_error());
$status=imap_status($mbox,$hostname,SA_ALL);
if ($status) {
echo "Messages: " . $status->messages . "<br />\n";
echo "Recent: " . $status->recent . "<br />\n";
echo "Unseen: " . $status->unseen . "<br />\n";
echo "UIDnext: " . $status->uidnext . "<br />\n";
echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";
}
else {
echo "imap_status failed: " . imap_last_error() . "\n";
}
$hostname='{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'mygmail#gmail.com';
$password = 'mypass';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Tiriyo: ' . imap_last_error());
$MB = imap_search($inbox,'UNSEEN');
$xcount($MB);
echo $x;

Related

403- request has insufficient authentication scopes

I want to link and view the analytics account linked with Google Adwords.
Procedure used:
Authenticating google account with scopes "Ananlytics and Adwords" with following url
https://www.googleapis.com/auth/adwords
https://www.googleapis.com/auth/analytics
After getting the authentication response creating Google analytics service object.
Google ads link API throwing error "Insufficient Premissions" screenshot attached
Script :
<?php
//function to authenticate google account and create analytics service object
function googleAuth(){
if (!empty($code)) {
$postFields = 'client_id=' . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . '&client_secret=' . Configure::read('GOOGLE_OAUTH_CLIENT_SECRET') . '&code=' . $code . '&grant_type=authorization_code&redirect_uri=' . Configure::read('GOOGLE_OAUTH_REDIRECT_URI');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$Rec_Data = curl_exec($ch);
if (curl_exec($ch) === false) {
return $Rec_Data;
}
$Rec_Data = json_decode($Rec_Data, true);
if (isset($Rec_Data['refresh_token'])) {
try {
$credentials = array('client_id' => Configure::read('GOOGLE_OAUTH_CLIENT_ID'), 'client_secret' => Configure::read('GOOGLE_OAUTH_CLIENT_SECRET'), 'redirect_uris' => array(Configure::read('GOOGLE_OAUTH_REDIRECT_URI')));
$client = new \Google_Client($credentials);
$client->addScope(\Google_Service_Analytics::ANALYTICS_READONLY);
$client->setAccessToken($Rec_Data['access_token']);
// Create an authorized analytics service object.
$analytics = new \Google_Service_Analytics($client);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
die();
}
}
} else {
if (!empty($id)) {
header("Location:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=" . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . "&redirect_uri=" . Configure::read('GOOGLE_OAUTH_REDIRECT_URI') . "&access_type=offline&approval_prompt=force&state=" . $id . "&scope=https://www.googleapis.com/auth/adwords https://www.googleapis.com/auth/analytics");
exit;
}
}
}
//function to fetch linked account list
function adwordsLinkAnalytics($analyticsAuth) {
$this->autoRender = false;
try {
$adWordsLinks = $analyticsAuth->management_webPropertyAdWordsLinks
->listManagementwebPropertyAdWordsLinks('123456', 'UA-123456-1');
} catch (apiServiceException $e) {
print 'There was an Analytics API service error '
. $e->getCode() . ':+' . $e->getMessage();
exit;
} catch (apiException $e) {
print 'There was a general API error '
. $e->getCode() . ':-' . $e->getMessage();
exit;
}
pr($adWordsLinks);
exit;
}
Required result: List of the analytics account linked with adwords account.
You are missing scope to management entities in Google Analytics, please look at this https://developers.google.com/identity/protocols/oauth2/scopes#analytics
Please update your scope with "https://www.googleapis.com/auth/analytics.edit"
My suggested Updates:
function googleAuth(){
if (!empty($code)) {
--------------
---- Your existing script ----
--------------
} else {
if (!empty($id)) {
header("Location:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=" . Configure::read('GOOGLE_OAUTH_CLIENT_ID') . "&redirect_uri=" . Configure::read('GOOGLE_OAUTH_REDIRECT_URI') . "&access_type=offline&approval_prompt=force&state=" . $id . "&scope=https://www.googleapis.com/auth/adwords%20https://www.googleapis.com/auth/analytics%20https://www.googleapis.com/auth/analytics.edit");
exit;
}
}
}
Reference Url: https://developers.google.com/identity/protocols/oauth2/scopes#analytics

Slack bot API no longer works

I have a slackbot that posts a message for a user and was working for a few months without any hiccups but is now not posting a message, after some digging I see that the error I'm getting back from slack is
{
"ok":false,
"error":"invalid_request_data"
}
Googling hasn't helped me find anything and I'm not sure what the problem is now knowing that it was working this whole time and no code has changed.
When the user types in a slash command, it hits a php file interactive.php this allows the user to fill out some information and that information then gets sent to deploy.php via slack as well
This is the deploy.php file
<?php
$receivedRequest = json_decode($_POST['payload'], true);
$type = $receivedRequest["type"];
if ($type != "dialog_submission") {
exit("No");
}
$response_url = $receivedRequest["response_url"];
$user_id = $receivedRequest["user"]["id"];
$service = $receivedRequest["submission"]["service"];
$rollback = $receivedRequest["submission"]["rollback"];
$target = $receivedRequest["submission"]["target"];
$featureList = $receivedRequest["submission"]["featureList"];
$diff = $receivedRequest["submission"]["diff"];
$environment = $receivedRequest["submission"]["environment"];
$canary = $receivedRequest["submission"]["canary"];
if ($canary == "yes"){
$environment = $environment . " _canary_ ";
}
$data = [
"response_type" => "in_channel",
"text" =>
"<#" . $user_id . ">" . " is deploying *" . $service . "* to *" . $environment . "*" .
"\n" .
"*rollback: " . $rollback . " target: " . $target . "*\n" .
$featureList . "\n" .
"Diff: " . $diff . "\n <!here>"
];
$payload = json_encode($data);
// Prepare new cURL resource
$ch = curl_init($response_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Set HTTP Header for POST request
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
"Content-Length: " . strlen($payload),
]);
// Submit the POST request
$result = curl_exec($ch);
// Close cURL session handle
curl_close($ch);
return json_encode(array(
'status' => 200,
'message' => ''
));
The issue I'm having is that the $result variable now holds the error I put above.
Does anyone happen to know what the issue could be?
Thanks!!
Welp, it started to work again.
Must have been something on Slack's end. Weird because their status page didn't indicate anything

sms api not working in local machine but working if placed in the hosting server

The below php code works well from a web server (i.e., where the sms server
is located) but not working well from a local machine with xampp or wamp.
The actual server is in godaddy
What am i missing out?
The code retrieves the connection details from a table which includes:
username, password, msisdn, and sender. When the message is eventually sent,
the message is flagged so that is is not sent again.
<?php
$id = 0;
$con=mysqli_connect("localhost","root","","afrcan_wp");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT id,message,username,password,MSISDN,sender,messagestatus FROM outgoingsms where messagestatus = 'not sent' LIMIT 1";
if ($result=mysqli_query($con,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
$id=$row[0];
$text1=$row[1];
$username=$row[2];
$password=$row[3];
$to=$row[4];
$sender=$row[5];
$messagestatus=$row[6];
//$conn1=mysqli_connect("localhost","afrcan_wp","Sirhenry888","afrcan_wp");
$conn1 = new mysqli("localhost","root","","african_wp");
// Check connection
if ($conn1->connect_error) {
die("Connection failed: " . $conn1->connect_error);
}
$sql = "UPDATE outgoingsms SET messagestatus='sent' WHERE id=$id";
if ($conn1->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn1->error;
}
$text = trim($text1);
$postUrl = "https://www.connectmedia.co.ke/user-board/?api";
$action="send";
$post = [
'action' => "$action",
'to' => array($to),
'username' => "$username",
'password' => "$password",
'sender' => "$sender",
'message' => urlencode("$text"),
];
$ch = curl_init($postUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
curl_close($ch);
echo "$response";
//send messages
}
// Free result set
mysqli_free_result($result);
$conn1->close();
}
mysqli_close($con);
?>
Is it an issue with the code? internet connection?
Any assistance will be highly appreciated
if this works on a web server but doesn't work on your localhost , it maybe that CURL is having firewall issues . By default CURL uses the port 1080 . Check to see that that port is opn on your localhost or try changing the port by doing
curl_setopt ($ch, CURLOPT_PORT , 8089);

PDO connection times out in try but works in catch

We have an autoscaling group in AWS where upon launch database connections timeout. This is a Zend Framework 1 app using PHP 7.0.22-0ubuntu0.16.04.1 on Ubuntu 16.04.3 LTS
The code is baked into the AMI but during launch a userdata script will pull from git and phing configure the app. The database domain hasn't changed in years, the configure is mostly to take care of which elasticache instance to use. In other words, the baked in code already has the database configured and just gets overwritten with same value during configure step.
Once the ec2 instance is in the ELB, it begins getting hit on /health-check to see if things are OK by the load balancer. Inside this controller is the following code:
public function healthCheckAction() {
try {
/* #var $DBConn Zend_Db_Adapter_Pdo_Mysql */
$DBConn = Zend_Registry::get('multidb')->getDb();
// test guide service (most likely will be from memcache, unlikely to hit db)
$guideService = $this->_apiGuideService();
$guideService->isLoaded();
// this line fails and throws an exception
// I put host in here just so an error would include it in throw during this phase instead of catch phase (where it works)
// test raw db connection
$dbh = new PDO("mysql:host={$DBConn->getConfig()['host']};dbname={$DBConn->getConfig()['dbname']}", $DBConn->getConfig()['username'], $DBConn->getConfig()['password']);
$data = $dbh->query("SELECT '{$DBConn->getConfig()['host']}' as host, now()")->fetchObject();
// test database connectivity
// I put host in here just so an error would include it in throw during this phase instead of catch phase (where it works)
$sql = "SELECT '{$DBConn->getConfig()['host']}' as host, now()";
$DBConn->fetchRow($sql);
// test cache
/* #var $cache Zend_Cache_Core */
$cache = Zend_Registry::get('cachemanager')->getCache('default');
if (!$cache->load('health_check')) {
$cache->save(true, 'health_check');
}
echo 'Instance is healthy';
}
catch (Exception $e) {
header('HTTP/1.1 500 Internal Server Error');
echo 'Instance is unhealthy';
// get instance id
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://169.254.169.254/latest/meta-data/public-ipv4');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get instance ip
$ip = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://169.254.169.254/latest/meta-data/instance-id');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$instance = curl_exec($ch);
// email us some info
$message = "Instance $instance failed health check. ssh ubuntu#$ip to investigate<br><br>" . $e->getLine() . " " . $e->getCode() . "<br>" . $e->getMessage() . "<br>" . $e->getTraceAsString(). "<br><br>";
ob_start();
// this works and returns access denied, not timeout
$this->runCommand('mysql -u examplecom_platform -h sg-rds-example.us-east-1.rds.amazonaws.com');
echo "testing DB with php<br>";
try {
echo "write host: " . $DBConn->getConfig()['host'] . "<br>";
echo "read host: " . $DBConn->getConfig()['host'] . "<br>";
$dbh = new PDO("mysql:host={$DBConn->getConfig()['host']};dbname={$DBConn->getConfig()['dbname']}", $DBConn->getConfig()['username'], $DBConn->getConfig()['password']);
$data = $dbh->query('select now()')->fetchObject();
echo "query database without zend:<br>";
print_r($data);
// this line works and prints out
// stdClass Object
// (
// [now()] => 2018-01-09 14:47:12
// )
$dbh = null;
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "<br/>";
}
// this all work/show correct IP
$this->runCommand('nc -vz sg-rds-example.us-east-1.rds.amazonaws.com 3306');
$this->runCommand('host sg-rds-example.us-east-1.rds.amazonaws.com');
$this->runCommand('dig sg-rds-example.us-east-1.rds.amazonaws.com');
$debug = ob_get_contents();
ob_end_clean();
$message .= "<br><br>" . str_replace("\n", "<br>", $debug);
$mail = new Zend_Mail();
$mail->setSubject('[examplecom] Instance Failed Healthcheck v2')
->setFrom('noreply#example.com')
->addTo('alerts#example.com')
->setBodyHtml($message)
->send();
}
}
As I kept debugging things I would add more and more stuff to test the connection
The try statement throws an error of SQLSTATE[HY000] [2002] Connection timed out
But this exact same connection works in the catch and is able to query now() from the database.
This is where I am stumped, how could the same process timeout on first connection but work during the error catching?
Also I will only get 1 or 2 of these emails saying it cant connect, but then eventually by the time I can login to test some things it is working and connecting fine. Health-check reports happy and instance is kept in ELB.
Any ideas or suggestions to add more debugging?

Docusign api Connect

I am experiencing connection problems to demo API
https://demo.docusign.net/restapi
To connect to API I am using the code provided below. It works well for my colleague from US, but when I try to connect from Lithuania there is zero response. Could it be there any location restrictions, or am I missing something?
Should it be some specifics in fire wall (I am under NAT)? Does my local php/http server needs some specific configuration?
$email = "some email # fsdfdsf";
$integratorKey = "TEST-xxxxxxxxxxx";
$password = "some password";
$url = "https://demo.docusign.net/restapi/v2/login_information?include_account_id_guid=true";
$header = "<DocuSignCredentials><Username>" . $email . "</Username><Password>" . $password . "</Password><IntegratorKey>" . $integratorKey . "</IntegratorKey></DocuSignCredentials>";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-DocuSign-Authentication: $header"));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($status==200){
$response = json_decode($json_response, true);
print_r(json_encode($response['loginAccounts'][0]));
}else{
print_r($json_response);
}
I found a what was stopping to work a source code above.
On my local server ssl was not signed.
So simple and only in test environment quick fix could be to turn off ssl checking on curl:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
or get a signed ssl sertificate.
This is how I solved it, I added $config->setSSLVerification(false); tu turn off ssl verification
$username = "marko#XXX.com";
$password = "XXX";
$integrator_key = "some_key";
// change to production before going live
//https://www.docusign.net/restapi
//https://www.docusign.com/p/RESTAPIGuide/Content/GettingStarted/REST%20API%20Version.htm
$host = "https://demo.docusign.net/restapi";
// create a new DocuSign configuration and assign host and header(s)
$config = new \DocuSign\eSign\Configuration();
$config->setHost($host);
$config->setSSLVerification(false);
$config->addDefaultHeader("X-DocuSign-Authentication", "{\"Username\":\"" . $username . "\",\"Password\":\"" . $password . "\",\"IntegratorKey\":\"" . $integrator_key . "\"}");
// instantiate a new docusign api client
$apiClient = new \DocuSign\eSign\ApiClient($config);
DocuSign does not implement any location restrictions for API clients.
You can check that your firewall is allowing connections to DocuSign by trying to use the service from your web browser. Try demo.docusign.net
You can also use your browser to directly access a method in the API server that provides information on the API service points.
If it works then you know the problem is in your API code.
If so, first try one of the API recipes.
If you can't access the web service then check your firewall settings.

Categories