You are here

function push_notifications_apns_feedback_service in Push Notifications 7

Connect to Apple's feedback server to remove unused device tokens. Connection modeled after daddyhunt_apns_send_notifications function.

See also

http://stackoverflow.com/questions/4774681/php-script-for-apple-push-not...

http://stackoverflow.com/questions/1278834/php-technique-to-query-the-ap...

1 call to push_notifications_apns_feedback_service()
push_notifications_cron in ./push_notifications.module
Implements of hook_cron().

File

./push_notifications.module, line 1303
Push Notifications functionality.

Code

function push_notifications_apns_feedback_service() {

  // Create a Stream context and open an Internet socket connection.
  $stream_context = stream_context_create();
  $apns_cert = _push_notifications_get_apns_certificate();
  stream_context_set_option($stream_context, 'ssl', 'local_cert', $apns_cert);

  // If the user has a passphrase stored, we use it.
  $passphrase = variable_get('push_notifications_apns_passphrase', '');
  if (strlen($passphrase)) {
    stream_context_set_option($stream_context, 'ssl', 'passphrase', $passphrase);
  }
  if (variable_get('push_notifications_set_entrust_certificate', FALSE)) {
    stream_context_set_option($stream_context, 'ssl', 'CAfile', drupal_get_path('module', 'push_notifications') . '/certificates/entrust_2048_ca.cer');
  }
  $apns = stream_socket_client('ssl://' . PUSH_NOTIFICATIONS_APNS_FEEDBACK_HOST . ':' . PUSH_NOTIFICATIONS_APNS_FEEDBACK_PORT, $error, $error_string, 2, STREAM_CLIENT_CONNECT, $stream_context);
  if (!$apns) {
    return;
  }

  // Gather expired tokens in an array
  $tokens = array();
  while (!feof($apns)) {
    $data = fread($apns, 38);
    if (strlen($data)) {
      $tokens[] = unpack("N1timestamp/n1length/H*devtoken", $data);
    }
  }

  // Close connection.
  fclose($apns);
  if (empty($tokens)) {
    watchdog('push_notifications', 'Apple\'s feedback service returned no tokens to be removed.');
    return;
  }

  // Remove all tokens that are not valid anymore.
  $counter = 0;
  foreach ($tokens as $token) {
    push_notifications_purge_token($token['devtoken'], PUSH_NOTIFICATIONS_TYPE_ID_IOS);
    $counter++;
  }

  // Invoke rules.
  if (module_exists('rules')) {
    rules_invoke_event_by_args('push_notifications_after_apns_feedback', array(
      'counter' => $counter,
    ));
  }

  // Give some feedback after the process finished.
  watchdog('push_notifications', '!count were removed after pulling the Apple feedback service.', array(
    '!count' => $counter,
  ));
}