Upload image/video to facebook asynchronously using php sdk 4 - asynchronous

I am trying to upload video/image to facebook albumb using php sdk 4 asynchronously.I googled and found that php asynchronous call be sent using fsockopen. However, it is not working for facebook request. I have two files, one for checking login and getting token. Then second file is called for uploading the file to facebook. Below is the code for first file:
// start session
session_start();
Yii::import('application.vendor.*');
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// init app with app id and secret
FacebookSession::setDefaultApplication('xxxxx', 'yyyy');
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://website.com/user/login/page/view/fb-share-php1' );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
}catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb'] = $session;
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
//$session = new FacebookSession( $session->getToken() );
// graph api request for user data
//$request = new FacebookRequest( $session, 'GET', '/me' );
//$response = $request->execute();
backgroundPost('http://website.com/user/login/page/view/fb-share-php');
// get response
//$graphObject = $response->getGraphObject()->asArray();
// print profile data
//echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
}else {
// show login url
echo 'Login';
}
function backgroundPost($url){
$parts=parse_url($url);
//print_r($parts);exit;
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
echo "test";
return false;
} else {
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ". 0 ."\r\n";
$out .= "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n";
$out .= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
// print_r($out);exit;
fwrite($fp, $out);
fclose($fp);
return true;
}
}
And second file is:
// start session
session_start();
Yii::import('application.vendor.*');
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
$session = $_SESSION['fb'] ;
file_put_contents('file.txt', serialize($session));
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/photos', array(
'source' => '#/var/www/website-root/images/add_more.png',
'message' => 'User provided message'
)
))->execute()->getGraphObject();
file_put_contents('files.txt', serialize($session));
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}

Finally, I figured out the way to achieve it. Now, I am using facebook javascript sdk with php sdk. Following is the process:
1)Get access token from javascript sdk(first file) and pass it to background along with the url of image/video. Code may be modified, if image/video is being uploaded through source.
2) php file(2nd file) containing function for executing backend-process(which is in third file) receives the posted data and and call the third file(in the form of url) and pass the data to it as well.
3) File(s) are uploaded to facebook through php sdk 4(third file)
Below is the code for first file containing javascript sdk code:
<script>
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.fbAsyncInit = function() {
FB.init({
appId : 'your app id',
xfbml : true,
version : 'v2.0'
});
FB.login(function(response){
console.log(response);
if (response.status === 'connected') {
var data = new Array();
alert('Logged into your app and Facebook.');
//type: 0 for photo and type:1 for video. Create data array dynamically for real word applications
data[0]= {url: 'http://url-of-video-file.mov',privacy : 'SELF', message: "title of video", type:1};
data[1]= {url: 'http://url-to-image-file.png',privacy : 'SELF', message: "photo caption", type:0};
$.ajax({
url: 'http://url-of-second-file/containing-code-for/backend-process',
data: {data: data, accessToken:response.authResponse.accessToken},
type: 'POST',
success:function(){
alert("photo uploaded");
}
});
},{scope:'email'});
}
</script>
Now code of second file which receives data and execute back-end process:
<?php
//session_start();
ignore_user_abort(true);
set_time_limit(0);
function backgroundPost($url){
$parts=parse_url($url);
//print_r($parts);exit;
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
if (!$fp) {
echo "test";
return false;
} else {
$vars = $_POST;
$content = http_build_query($vars);
//file_put_contents('url.txt',$content);exit;
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ". strlen($content) ."\r\n";
//$out .= "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n";
$out .= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
// print_r($out);exit;
fwrite($fp, $out);
fwrite($fp,$content);
fclose($fp);
return true;
}
}
backgroundPost('http://link-to-third-file/containing-code-for-facebook-upload');
Now code of third file, which will actually upload the files. Please note, video files need to be downloaded before it can be uploaded.
<?php
// start session
//session_start();
error_reporting(1);
ignore_user_abort(true);
set_time_limit(0);
#ini_set('display_errors', 1);
//include facebook library through autoload
require_once('facebook-4/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// init app with app id and secret
FacebookSession::setDefaultApplication('app_id','secret_key' );
$session = new FacebookSession( $_POST['accessToken'] );
foreach($_POST['data'] as $key => $data){
if($data['type'] == 1){
$ext = substr($data['url'],strrpos($data['url'],'.'));
$file = '/path/to/temp/location/for/saving/video/'.time().$ext;
if(file_put_contents($file,file_get_contents($data['url']))){
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/videos', array(
'source' => '#'.$file,
'title' => $data['message'],
'privacy' => json_encode(array('value' => $data['privacy'])),
'published' => true
)
))->execute()->getGraphObject()->asArray();
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}else{
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$response = (new FacebookRequest(
$session, 'POST', '/me/photos', array(
'url' => $data['url'],
'message' => $data['message'],
'privacy' => json_encode(array('value' => $data['privacy'])),
'published' => true
)
))->execute()->getGraphObject()->asArray();
// If you're not using PHP 5.5 or later, change the file reference to:
// 'source' => '#/path/to/file.name'
//echo "Posted with id: " . $response->getProperty('id');
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}
?>

Related

dynamically populated cascading dropdown error

I found very useful article on the web
for contact form 7
<?php
function ajax_cf7_populate_values() {
// read the CSV file in the $makes_models_years array
$makes_models_years = array();
$uploads_folder = wp_upload_dir()['basedir'];
$file = fopen($uploads_folder.'\make_model_year.csv', 'r');
$firstline = true;
while (($line = fgetcsv($file)) !== FALSE) {
if ($firstline) {
$firstline = false;
continue;
}
$makes_models_years[$line[0]][$line[1]][] = $line[2];
}
fclose($file);
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'makes' => array_keys($makes_models_years),
'models' => array(),
'years' => array(),
'current_make' => false,
'current_model' => false
);
// collect the posted values from the submitted form
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
$year = key_exists('year', $_POST) ? $_POST['year'] : false;
// populate the $return_array with the necessary values
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = array_keys($makes_models_years[$make]);
if ($model) {
$return_array['current_model'] = $model;
$return_array['years'] = $makes_models_years[$make][$model];
if ($year) {
$return_array['current_year'] = $year;
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
}
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
and some java
<script>
(function($) {
// create references to the 3 dropdown fields for later use.
var $makes_dd = $('[name="makes"]');
var $models_dd = $('[name="models"]');
var $years_dd = $('[name="years"]');
// run the populate_fields function, and additionally run it every time a value changes
populate_fields();
$('select').change(function() {
populate_fields();
});
function populate_fields() {
var data = {
// action needs to match the action hook part after wp_ajax_nopriv_ and wp_ajax_ in the server side script.
'action' : 'cf7_populate_values',
// pass all the currently selected values to the server side script.
'make' : $makes_dd.val(),
'model' : $models_dd.val(),
'year' : $years_dd.val()
};
// call the server side script, and on completion, update all dropdown lists with the received values.
$.post('/wp-admin/admin-ajax.php', data, function(response) {
all_values = response;
$makes_dd.html('').append($('<option>').text(' -- choose make -- '));
$models_dd.html('').append($('<option>').text(' -- choose model -- '));
$years_dd.html('').append($('<option>').text(' -- choose year -- '));
$.each(all_values.makes, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_make == this) {
$option.attr('selected','selected');
}
$makes_dd.append($option);
});
$.each(all_values.models, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_model == this) {
$option.attr('selected','selected');
}
$models_dd.append($option);
});
$.each(all_values.years, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_year == this) {
$option.attr('selected','selected');
}
$years_dd.append($option);
});
},'json');
}
})( jQuery );
</script>
but when i add it to me website nothing appear in the dropdowns. They are empty.
I tried to contact the blogger but there is no answer yet. Give me some advice
I copied the csv almost as the one in the post. So I think the function is mistaken... somewhere
I found the solution: in the article the file name is mistaken. It has to be "make_model_year.csv" !!!

Get new acess_token after 3600 seconds

I'm trying to use google analytics api. I've already added the service account email that was created to the user list for the Google Analytics account in question.
I got the access_token and the refresh_token. But I do not know how to get the new access_token after 3600 seconds without the client having to re-authorize.
oauth2callback.php
<?php
require_once __DIR__.'/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
index.php
<?php
require_once __DIR__.'/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setAccessType("offline");
$client->setIncludeGrantedScopes(true);
$client->setApprovalPrompt('force');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
print_r($_SESSION['access_token']);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
After allowing access, the tokens generate normally. But I would like to get the new access_token automatically after 3600 seconds without the client having to give permission again.
Is this possible?
print_r($_SESSION['access_token']);
Array
(
[access_token] => ya29.GltpBl_Dkmt-uT9Z6t5aTSzKLmzsWP3xZCcVtRt8kLIOJj5M_TpLg-0x4Sm0eNxOLpdCahFy6Ec41nHnF-vhh-m3tbj7ecR-QHaR8vkP3ImYjuo_WPBLXBKMXCna
[expires_in] => 3600
[scope] => https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/analytics.readonly https://www.googleapis.com/auth/plus.me
[token_type] => Bearer
[id_token] => eyJhbGciOiJSUzI1NiIsImtpZCI6IjQ2M2ZlNDgwYzNjNTgzOWJiYjE1ODYxZTA4YzMyZDE4N2ZhZjlhNTYiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiI5NzI5NDE4MzY0MzctZ2o2ZmtxNHZ1NjU3dDkyMzhucDVyajY5NjRqZ3NyMWouYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiI5NzI5NDE4MzY0MzctZ2o2ZmtxNHZ1NjU3dDkyMzhucDVyajY5NjRqZ3NyMWouYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDM3NzMzMDA1MzYwNTk3MzI0OTAiLCJlbWFpbCI6ImZhYnJpY2lvdmllaXJhLnN0ckBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXRfaGFzaCI6IndQcVUxc1I4c3Z6bFBBSWRUSjZoNGciLCJpYXQiOjE1NDQwMjg2MjEsImV4cCI6MTU0NDAzMjIyMX0.g_3w66FxAGViuXxFDGR2oErlo1yIMk376iDdOpgv8EfVz764hBywc-DuNXPE2y5p4nTd_y6oWbH7mK2DvFIGd7b_BLsNJJaZjJBFBHNk9Q1Z5VrpeZ9T1-0gQiXu0xS0pBdRnEtDwZN7qlL4_op6ojfHT02HbmyrlpdCbnp57LN5zJkufnL4VhQYp3Rqsui4ttL1VT0KBaHjzIzL6zWMuuMBdXKk9Ug6J1KuR0xCuWGytjb2y-YpsHVrgqvOfMEeAnxcpv6-ilUEpc-Mo4ZL4NGsDjK2BGFVCwfxZctzgERwSzYyH9P6g_raIJpqyXGvASOvkPJ7xHGI1wWO4QGsxA
[created] => 1544028621
[refresh_token] => 1/ifyxSjTnwv5kFMPcPEENx8kRWNSFmTYZUjMxcHJl8spoQqWdmaNh1ZjV3W2qR16W
)
1
The code you are using is not the code for a service account. If you are using the Code for a service account you dont need to worry about refreshing anything becouse it doesnt have a refresh token it just always has access.
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
* Initializes a client object.
* #return A google client object.
*/
function getGoogleClient() {
return getServiceAccountClient();
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Scopes will need to be changed depending upon the API's being accessed.
* array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* #return A google client object.
*/
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope([YOUR SCOPES HERE]);
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
ServiceAccount.php
Sorted out:
<?php
require_once __DIR__ . '/vendor/autoload.php';
$KEY_FILE_LOCATION = __DIR__ . '/service-account.json';
$client = new Google_Client();
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setAccessType('offline');
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$client->refreshTokenWithAssertion();
$analytics = new Google_Service_Analytics($client);
$token = $client->getAccessToken();
?>
<!DOCTYPE html>
<html>
<head>
<title>Embed API Demo</title>
<style>
body{
overflow: hidden;
}
</style>
</head>
<body>
<!-- Step 1: Create the containing elements. -->
<div id="chart-1-container"></div>
<div id="chart-2-container"></div>
<!-- Step 2: Load the library. -->
<script>
(function(w,d,s,g,js,fs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
</script>
<script>
gapi.analytics.ready(function() {
/**
* Authorize the user with an access token obtained server side.
*/
gapi.analytics.auth.authorize({
'serverAuth': {
'access_token': '<?php echo $token['access_token']; ?>'
}
});
/**
* Creates a new DataChart instance showing sessions over the past 30 days.
* It will be rendered inside an element with the id "chart-1-container".
*/
var dataChart1 = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': 'ga:171325437', // <-- Replace with the ids value for your view.
'start-date': '30daysAgo',
'end-date': 'yesterday',
'metrics': 'ga:sessions,ga:users',
'dimensions': 'ga:date'
},
chart: {
'container': 'chart-1-container',
'type': 'LINE',
'options': {
'width': '100%'
}
}
});
dataChart1.execute();
/**
* Creates a new DataChart instance showing top 5 most popular demos/tools
* amongst returning users only.
* It will be rendered inside an element with the id "chart-3-container".
*/
var dataChart2 = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': 'ga:171325437', // <-- Replace with the ids value for your view.
'start-date': '30daysAgo',
'end-date': 'yesterday',
'metrics': 'ga:pageviews',
'dimensions': 'ga:pagePathLevel1',
'sort': '-ga:pageviews',
'filters': 'ga:pagePathLevel1!=/',
'max-results': 7
},
chart: {
'container': 'chart-2-container',
'type': 'PIE',
'options': {
'width': '100%',
'pieHole': 4/9,
}
}
});
dataChart2.execute();
});
</script>
</body>
</html>

ReplyMarkup in php telegram bot

I have problem with my telegram bot.I want to make Keybaord for my bot. When I run my telegram api url from my browser it works:
https://api.telegram.org/mybottoken/sendmessage?chat_id=93119306&text=something&reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]], "one_time_keyboard":true};
but
When I want run to this url($sendto Variable) in my php file this not work.
my php code is:
<?php
define('BOT_TOKEN', '183690241:AAHgluc7D9g0DF_InurfBj2YdBgPE7fmymo');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
$array = array();
// read incoming info and grab the chatID
$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatID = $update["message"]["chat"]["id"];
$chatText = $update["message"]["text"];
// compose reply
$reply = sendMessage();
// send reply
$sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".$reply."&reply_markup={"keyboard":[["Yes","No"],["Maybe"],["1","2","3"]], "one_time_keyboard":true};
file_get_contents($sendto);
function sendMessage(){
global $chatID;
global $chatText;
if ($chatText =="/start") {
$message = "Salam - Roboate Megat Hastam";
}
elseif ($chatText =="Khoobi?") {
$message = "Merc - Shomaa khobi?";
}
elseif ($chatText =="Chand salete?") {
$message = "Be Tu Che!";
}
else
{
$message = "No Command";
}
return rawurlencode($message);
}
?>
please help where i made mistake.
thanks all guys.
Try this code:
var_dump($keyboard = json_encode($keyboard = [
'keyboard' => [
['Yes'],['No'],['Maybe'],
['1'],['2'],['3'],
] ,
'resize_keyboard' => true,
'one_time_keyboard' => true,
'selective' => true
]),true);
function sendKeyboard($chat_id, $keyboard) {
$text = "Merc - Shomaa khobi?";
file_get_contents(API_URL ."sendMessage?chat_id=".$chat_id."&reply_markup=".$keyboard."&text=".urlencode($text));
}
if($message == "/start"){
sendKeyboard($chat_id, $keyboard);
}

can I stop all email sending from a wordpress site ?where to do this wp-includes/class-phpmailer.php?

howto close all email sending option in that word press config. should i use
wp-includes/class-phpmailer.php ? or where ?
if ($this->SingleTo === true && count($toArr) > 1) {
foreach ($toArr as $key => $val) {
$rt = #mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
// implement call back function if it exists
$isSent = ($rt == 1) ? 1 : 0;
$this->doCallback($isSent,$val,$this->cc,$this->bcc,$this->Subject,$body);
}
}
will this do ?
Add the following code to wp-config.php, it will stop sending of all emails
function wp_mail()
{
//silence is golden!!
}

I can push notification to one device but fail to push in a loop

I code my push notification service as shown below. It will gain token stored in test_db and then send it. The problem is that I don't receive notification from all my device. But, if I send notification to one specific device and I uncomment **//if( $row['pushtoken']=='bfd53a383e0f65bc96b43f3547548ec13d4c46d61526d7b6be5d7ed581563e77')**, the device will receive a notification. It is very weird. Here is my code:
$link = mysql_connect('localhost', 'root', '111111');
if (!$link) {
error_log( "mysql_connect fail\n");
die('could not connect: ' . mysql_error());
}
else
{
$is_db_selected = mysql_select_db('test_db',$link);
if($is_db_selected)
{
$sql = "select * from pushtoken;";
error_log($sql);
$result = mysql_query($sql, $link);
if ($result)
{
echo "ready to push notification\n";
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'aps_dev.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 10, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT , $streamContext);
if (!$apns)
exit("Failed to connect: $error $errorString" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
ob_flush();
flush();
$payload['aps'] = array('alert' => 'xman give mortal 7 messages!!!', 'badge' => 1, 'sound' => 'default');
$payload = json_encode($payload);
while ($row = mysql_fetch_assoc($result))
{
***//if( $row['pushtoken']=='bfd53a383e0f65bc96b43f3547548ec13d4c46d61526d7b6be5d7ed581563e77')***
{
echo "push notification one by one\n";
$deviceToken = $row['pushtoken'];
$apnsMessage = chr(0) . pack("n", 32) . pack('H*', $deviceToken) .pack("n", strlen($payload)). $payload;
if(fwrite($apns, $apnsMessage,strlen($apnsMessage))==FALSE)
{
echo "can't write to socket!<br />";
}
ob_flush();
flush();
//fclose($apns);
echo "token is ".$deviceToken ."\n";
//break;
}
}
//socket_close($apns);
fclose($apns);
} else {
error_log ('error select pushtoken: ' . mysql_error() . "\n");
}
}
}
You may want to check that all of the tokens are valid. In the past I had an issue where if I had a dev token in my DB and tried to use the production push server all the messages that were sent after the message using the dev token would fail to be delivered.

Resources