<?php
//ASSUME gcm_registration_table field
// id || registration_id || user_id || created_at || updated_at
// FIND CANONICAL IDS POSITION
function CanonicalIdPosition($gcm_response)
{
$c_ids = array();
foreach ($gcm_response['results'] as $k => $val) {
if (isset($val['registration_id'])) {
$c_ids[] = $k;
}
}
if ($c_ids) {
return $c_ids;
} else {
return false;
}
}
// Find Duplicate registration Ids from Server Matchind to index position
function DuplicateRegIdFromRegistrationTable($canonical_ids)
{
DB::query("SELECT registration_id FROM gcm_registration_table");
$results = DB::fetch_assoc_all();
$duplicate_reg_val = array();
// Match Position and Find Value
foreach ($results as $key => $val) {
if (in_array($key, $canonical_ids)) {
$duplicate_reg_val[] = $val['registration_id'];
}
}
return $duplicate_reg_val;
}
// update existing Duplicate registration id with New Canonical registration ids
function UpdateDuplicateRegIds($duplicateVal)
{
foreach ($duplicateVal as $val) {
$sql = "UPDATE gcm_registration_table SET registration_id = {$val} WHERE registration_id ={$val}";
// Some Yours Code...
}
}
// Method to send Notification to GCM Server
function SendGcmNotification($registatoin_ids_from_table, $message, $gcm_api_key, $dry_run = false)
{
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
'dry_run' => $dry_run
);
$headers = array(
'Authorization: key=' . $gcm_api_key,
'Content-Type: application/json'
);
//print_r($headers);
// Open connection
if (!class_exists('curl_init')) {
$ch = curl_init();
} else {
echo "Class Doesnot Exist";
exit();
}
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
return false;
} else {
return json_decode($result, true);
}
// Close connection
curl_close($ch);
}
//This Wont Send Notification to Device but gives you response to remove canonical ids
$gcm_response = SendGcmNotification($registatoin_ids_from_table, $message, $gcm_api_key, $dry_run = true);
$canonical_ids = CanonicalIdPosition($gcm_response);
if ($canonical_ids) {
$duplicate_ids = DuplicateRegIdFromRegistrationTable($canonical_ids);
UpdateDuplicateRegIds($duplicate_ids);
}
// Finally Get updated Registration Ids from table and send to GCM Server with
$gcm_response = SendGcmNotification($registatoin_ids_from_table, $message, $gcm_api_key, $dry_run = false);