Android & Apple Push Notifcations - ios

I have an app set for push notification. The Android code works fine and I receive a push notification. For Apple, the phone just vibrates and makes sound for push notifications, but I don't get a badge or anything else.
Can someone please show me where I am going wrong?
<?php
// function to send Android push notification
function send_message($deviceToken, $message){
$messageArr['message'] = "";
if($message=="")
{
$messageArr['message'] = "Test data";
}
else
{
$messageArr['message'] = $message ;
}
$registatoin_ids = $deviceToken;
return mer_send_notification($registatoin_ids, $messageArr);
}
function mer_curlPost($url, $headers, $fields) {
$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_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
function mer_send_notification($registatoin_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$apiKey = 'mykeyishere';
echo 'Test if 4\n';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
$result = mer_curlPost($url, $headers, $fields);
return $result;
}
function sendNotification($dataArr, $device_token_array) {
$apns_url = NULL;
$apns_cert = NULL;
$apns_port = 2195;
$development = false;
if ($development) {
$apns_url = 'gateway.sandbox.push.apple.com';
$apns_cert = 'devcert.pem';
} else {
$apns_url = 'gateway.push.apple.com';
$apns_cert = 'prodcert.pem';
}
$stream_context = stream_context_create();
stream_context_set_option($stream_context, 'ssl', 'local_cert', $apns_cert);
stream_context_set_option($stream_context, 'ssl', 'passphrase', 'mypassphrase');
$payload = array();
$payload['aps'] = $dataArr;
$payloadJson = json_encode($payload);
$apns = #stream_socket_client('ssl://' . $apns_url . ':' . $apns_port, $error, $error_string, 2, STREAM_CLIENT_CONNECT, $stream_context);
foreach ($device_token_array as $key => $device_token) {
$apns_message = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_token)) . chr(0) . chr(strlen($payloadJson)) . $payloadJson;
$xxx[] = #fwrite($apns, $apns_message);
}
$yyy = #socket_close($apns);
$zzz = #fclose($apns);
$arr = array();
$arr[] = $stream_context;
$arr[] = $apns;
$arr[] = $xxx;
$arr[] = $yyy;
$arr[] = $zzz;
return $arr;
}

The notification format for iOS is different than for Android. See here for iOS format: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW1

Related

Google contacts API php code stopped working

I was using the following code to get gmail contacts and it suddenly stopped working. The same code works with another domain. The credentials are being correctly retrieved from a file. The domain has been verified for google.
Any help would be appreciated.
//setup new google client
$client = new Google_Client();
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');
$client -> setScopes('https://www.google.com/m8/feeds');
$googleImportUrl = $client -> createAuthUrl();
//echo 'google import url: '.$googleImportUrl.'<br>';
function curl($url, $post = "") {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
if ($post != "") {
curl_setopt($curl, CURLOPT_POST, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$contents = curl_exec($curl);
curl_close($curl);
if($contents === FALSE) {
die(curl_error($ch));
}
return $contents;
}
if (isset($_GET['code'])) {
$auth_code = $_GET["code"];
$_SESSION['google_code'] = $auth_code;
header('Location: ' . $google_redirect_uri);
}
if(isset($_SESSION['google_code'])) {
$auth_code = $_SESSION['google_code'];
$max_results = 10000;
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($google_client_id),
'client_secret'=> urlencode($google_client_secret),
'redirect_uri'=> urlencode($google_redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value)
{
$post .= $key.'='.$value.'&';
}
$post = rtrim($post,'&');
$result = curl('https://accounts.google.com/o/oauth2/token',$post);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl($url);
$contacts = json_decode($xmlresponse,true);
unset($_SESSION['google_code']);
}

Uploading videos by other people on your channel via site

I want users to send their videos on my YT channel via my site.
It worked last year but now Youtube requests users to be authenticated on Youtube.
If it even possible now?
Here is the code:
public function getPostParams()
{
$header = array(
"alg" => "RS256",
"typ" => "JWT"
);
$jwt = array(
"iss" => "gulliapp#appspot.gserviceaccount.com",
"scope" => "https://www.googleapis.com/auth/youtube",
"aud" => "https://accounts.google.com/o/oauth2/token",
"exp" => time() + 3600,
"iat" => time()
);
$jwt_string = JWT::encode($jwt, null, 'RS256', "52e47342c1d175e88a94e0076e7a87474013a798", $header);
$headers = array(
"Content-type: application/x-www-form-urlencoded",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 3000);
curl_setopt($ch, CURLOPT_POST, true);
$post = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" . $jwt_string ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$res = curl_exec($ch);
$url = curl_getinfo($ch);
$token = json_decode($res);
curl_close($ch);
return $token->access_token;
}
public function saveFile($file, $name, $description, $token)
{
$client = new Google_Client();
$client->setClientId(self::$OAUTH2_CLIENT_ID);
$client->setClientSecret(self::$OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://gulli.ru/videocontest/add/', FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$client->setAccessToken($token);
$client->setAccessType("offline");
$youtube = new Google_Service_YouTube($client);
if ($client->getAccessToken()) {
try{
$videoPath = $file['tmp_name'];
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle("web2016");
$snippet->setDescription("web2016");
$snippet->setTags(array("tag1", "tag2"));
$snippet->setCategoryId("22");
$status = new Google_Service_YouTube_VideoStatus();
$status->privacyStatus = "private";
// Associate the snippet and status objects with a new video resource.
$video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$insertRequest = $youtube->videos->insert("status,snippet", $video);
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
$client->setDefer(false);
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
}
return false;
}

How do I upload a file to sharepoint with the office365 rest api?

Im using following ruby code to upload files to office 365
uri = URI.parse("#{site_url}/_api/v1.0/me/files/#{folder}/children/#{temp_file.original_filename}/content")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Put.new(uri.path, initheader = {
'Content-Type' =>'application/octet-stream',
'Authorization' => 'Bearer ' + #current_user.o_auth_token,
'resource' => 'site_url'
})
req.set_form_data(
'file' => temp_file.read,
'Content-Type' => 'application/octet-stream'
)
JSON.parse(https.request(req).body)
The file uploaded to office 365 is corrupt. What's the issue in the code?
The following code in PHP works fine. Please note these are functions within a class and also requires creating a SharepointException class.
public function upload_file($folder_id, $filepath, $filename) {
//remove illegal characters form filename
try {
$filename = $this->clean_filename($filename);
} catch (SharepointException $e) {
throw new SharepointException($e->getMessage());
}
//build uri
if (is_null($folder_id)) {
$uri = $this->base_url . 'files/root/children/'.rawurlencode($filename).'/content?nameConflict=abort';
} else {
$uri = $this->base_url . 'files/'.$folder_id.'/children/'.rawurlencode($filename).'/content?nameConflict=abort';
}
$response = $this->upload($uri, $filepath);
if (array_key_exists('error', $response)) {
throw new SharepointException($response['error']);
}
return $response;
}
private function upload($uri, $filepath) {
$pointer = fopen($filepath, 'r+');
$stat = fstat($pointer);
$pointersize = $stat['size'];
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $pointer);
curl_setopt($ch, CURLOPT_INFILESIZE, (int)$pointersize);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
//Expect:
//HTTP response code 100 workaround
//see http://www.php.net/manual/en/function.curl-setopt.php#82418
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Expect:',
'Content-Type: application/json',
'Authorization: Bearer ' . $this->access_token,
));
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$accepted_codes = array(
'200',
'201',
);
if (!in_array($httpcode, $accepted_codes)) {
//generic error
$error = 'HTTP status code not expected - got '.$httpcode;
//more descriptive error
if ($httpcode == '400') {
$data = json_decode($response, true);
if (isset($data['error']['message'])) {
$error = $data['error']['message'];
}
}
return array('error' => $error);
}
return json_decode($response, true);
}
private function clean_filename($filename) {
$filename = preg_replace('/[*><|}{&#%~:"?\/\\\\]/', '', $filename);
if (strpos('.', $filename) === 0) {
$filename = substr($filename, 1);
}
if (empty($filename)) {
throw new SharepointException('File is empty after removing illegal characters.');
}
return $filename;
}

Twitter OAuth Showing Timeline Not Tweets

Anyone know how I can tweak the settings in the Wordpress theme used in this site (http://www.ethnecity.church.ly/) to make the Twitter section (near the bottom left of the page) show the tweets for the account instead of the timeline from the Twitter account? Note: the plugin is using OAuth...I just don't know how to tell it to display tweets instead of the timeline.
I believe this is the code that displays the twitter info:
<?php
$user_screen_name = 'ethnecity';
$user_full_name = '(removed)';
$settings = array(
'consumer_key' => '(removed)',
'consumer_secret' => '(removed)',
'access_token' => '(removed)',
'access_token_secret' => '(removed)');
$api_url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
$api_params = array(
'count' => 40,
'contributor_details' => 'false',
'include_entities' => 'false');
// OAuth:
function oauth_encode($data){
if(is_array($data)){
return array_map('oauth_encode', $data);
} else if(is_scalar($data)) {
return str_ireplace(array('+', '%7E'), array(' ', '~'), rawurlencode($data));
} else {
return '';
}}
// OAuth base settings
$oauth_params = array(
'oauth_consumer_key' => $settings['consumer_key'],
'oauth_nonce' => md5(microtime() . mt_rand()),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $settings['access_token'],
'oauth_version' => '1.0',
);
// Sign OAuth params
$sign_params = array_merge($oauth_params, $api_params);
uksort($sign_params, 'strcmp');
foreach ($sign_params as $k => $v) {
$sparam[] = oauth_encode($k) . '=' . oauth_encode($v);
}
$sparams = implode('&', $sparam);
$base_string = 'GET&' . oauth_encode($api_url) . '&' . oauth_encode($sparams);
$signing_key = oauth_encode($settings['consumer_secret']) . '&' . oauth_encode($settings['access_token_secret']);
$oauth_params['oauth_signature'] = oauth_encode(base64_encode(hash_hmac('sha1', $base_string, $signing_key, TRUE)));
// Set Authorization header:
uksort($oauth_params, 'strcmp');
foreach ($oauth_params as $k => $v) {
$hparam[] = $k . '="' . $v . '"';
}
$hparams = implode(', ', $hparam);
$headers = array();
$headers['Expect'] = '';
$headers['Authorization'] = 'OAuth ' . $hparams;
foreach ($headers as $k => $v) {
$curlheaders[] = trim($k . ': ' . $v);
}
// Format params:
foreach ($api_params as $k => $v) {
$rparam[] = $k . '=' . $v;
}
$rparams = implode('&', $rparam);
// echo "curl --get '" . $api_url . "' --data '" . $rparams . "' --header 'Authorization: OAuth " . $hparams . "' --verbose" . PHP_EOL;
// GET:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url . '?' . $rparams);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheaders);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$info = curl_getinfo($ch);
$error = curl_error($ch);
$errno = curl_errno($ch);
curl_close($ch);
function get_twitterfeeds(){
global $code; global $response;
if($code != 200){
//echo 'Error' . PHP_EOL;
//echo $code . PHP_EOL;
//print_r($response);
//print_r($info);
} else {
$all = json_decode($response, true);
//echo '<pre />';
// print_r($all);
//exit;
return $all;
}
}
?>
Your code should be modified so as to retrieve user's timeline. As per the current code it should return only tweets present on your timeline.
If you need only your's or a particular user's feed , your code should be modified in such a way that resource URL should be changed.
$api_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$api_params = array(
'screen_name' => 'ethnecity'
'count' => 40,
'contributor_details' => 'false',
'include_entities' => 'false'
);
Please verify the document https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline

Override CURLOPT_FOLLOWLOCATION for Credit Card

I have an issue with a website i'm hosting on a shared server where an 'open_basedir' is set... So therefore the credit system throws an error and won't charge the buyers credit card.
Error Message
Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in
Code
function http_post($method, $server, $port, $url, $vars) {
$postdata = "";
foreach($vars as $key => $value) {
$postdata .= urlencode($key) . "=" . urlencode($value) . "&";
}
$postdata = substr($postdata,0,-1);
$content_length = strlen($postdata);
$headers = "POST $url HTTP/1.1\r\n".
"Accept: */*\r\n".
"Accept-Language: en-nz\r\n".
"Content-Type: application/x-www-form-urlencoded\r\n".
"Host: $server\r\n".
"Connection: Keep-Alive\r\n".
"Cache-Control: no-cache\r\n".
"Content-Length: $content_length\r\n\r\n";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $method . '://' . $server .":". $port . $url);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
Is there anyway around this without having access to the root PHP.ini and having to switch hosts? Thank you.
There is no way to override the value of open_basedir in php.ini as this would somewhat defeat the purpose. An alternative is to write your own function perform the same functionality as CURLOPT_FOLLOWLOCATION would with open_basedir not set. I have used a variation of this code found from http://php.benscom.com/manual/en/function.curl-setopt.php#102121 which loops your request and does a regex match for Location: in the response headers, following as needed with a new request:
function curl_exec_follow(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
$mr = $maxredirect === null ? 5 : intval($maxredirect);
if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0);
curl_setopt($ch, CURLOPT_MAXREDIRS, $mr);
} else {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
if ($mr > 0) {
$newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$rch = curl_copy_handle($ch);
curl_setopt($rch, CURLOPT_HEADER, true);
curl_setopt($rch, CURLOPT_NOBODY, true);
curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
do {
curl_setopt($rch, CURLOPT_URL, $newurl);
$header = curl_exec($rch);
if (curl_errno($rch)) {
$code = 0;
} else {
$code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/Location:(.*?)\n/', $header, $matches);
$newurl = trim(array_pop($matches));
} else {
$code = 0;
}
}
} while ($code && --$mr);
curl_close($rch);
if (!$mr) {
if ($maxredirect === null) {
trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
} else {
$maxredirect = 0;
}
return false;
}
curl_setopt($ch, CURLOPT_URL, $newurl);
}
}
return curl_exec($ch);
}

Resources