apns-php
 All Data Structures Files Functions Variables Groups Pages
Message.php
Go to the documentation of this file.
1 <?php
2 /**
3  * @file
4  * ApnsPHP_Message class definition.
5  *
6  * LICENSE
7  *
8  * This source file is subject to the new BSD license that is bundled
9  * with this package in the file LICENSE.txt.
10  * It is also available through the world-wide-web at this URL:
11  * http://code.google.com/p/apns-php/wiki/License
12  * If you did not receive a copy of the license and are unable to
13  * obtain it through the world-wide-web, please send an email
14  * to aldo.armiento@gmail.com so we can send you a copy immediately.
15  *
16  * @author (C) 2010 Aldo Armiento (aldo.armiento@gmail.com)
17  * @version $Id$
18  */
19 
20 /**
21  * @defgroup ApnsPHP_Message Message
22  * @ingroup ApplePushNotificationService
23  */
24 
25 /**
26  * The Push Notification Message.
27  *
28  * The class represents a message to be delivered to an end user device.
29  * Notification Service.
30  *
31  * @ingroup ApnsPHP_Message
32  * @see http://tinyurl.com/ApplePushNotificationPayload
33  */
35 {
36  const PAYLOAD_MAXIMUM_SIZE = 2048; /**< @type integer The maximum size allowed for a notification payload. */
37  const APPLE_RESERVED_NAMESPACE = 'aps'; /**< @type string The Apple-reserved aps namespace. */
38 
39  protected $_bAutoAdjustLongPayload = true; /**< @type boolean If the JSON payload is longer than maximum allowed size, shorts message text. */
40 
41  protected $_aDeviceTokens = array(); /**< @type array Recipients device tokens. */
42 
43  protected $_sText; /**< @type string Alert message to display to the user. */
44  protected $_nBadge; /**< @type integer Number to badge the application icon with. */
45  protected $_sSound; /**< @type string Sound to play. */
46  protected $_sCategory; /**< @type string notification category. */
47  protected $_bContentAvailable; /**< @type boolean True to initiates the Newsstand background download. @see http://tinyurl.com/ApplePushNotificationNewsstand */
48 
49  protected $_aCustomProperties; /**< @type mixed Custom properties container. */
50 
51  protected $_nExpiryValue = 604800; /**< @type integer That message will expire in 604800 seconds (86400 * 7, 7 days) if not successful delivered. */
52 
53  protected $_mCustomIdentifier; /**< @type mixed Custom message identifier. */
54 
55  /**
56  * Constructor.
57  *
58  * @param $sDeviceToken @type string @optional Recipients device token.
59  */
60  public function __construct($sDeviceToken = null)
61  {
62  if (isset($sDeviceToken)) {
63  $this->addRecipient($sDeviceToken);
64  }
65  }
66 
67  /**
68  * Add a recipient device token.
69  *
70  * @param $sDeviceToken @type string Recipients device token.
71  * @throws ApnsPHP_Message_Exception if the device token
72  * is not well formed.
73  */
74  public function addRecipient($sDeviceToken)
75  {
76  if (!preg_match('~^[a-f0-9]{64}$~i', $sDeviceToken)) {
77  throw new ApnsPHP_Message_Exception(
78  "Invalid device token '{$sDeviceToken}'"
79  );
80  }
81  $this->_aDeviceTokens[] = $sDeviceToken;
82  }
83 
84  /**
85  * Get a recipient.
86  *
87  * @param $nRecipient @type integer @optional Recipient number to return.
88  * @throws ApnsPHP_Message_Exception if no recipient number
89  * exists.
90  * @return @type string The recipient token at index $nRecipient.
91  */
92  public function getRecipient($nRecipient = 0)
93  {
94  if (!isset($this->_aDeviceTokens[$nRecipient])) {
95  throw new ApnsPHP_Message_Exception(
96  "No recipient at index '{$nRecipient}'"
97  );
98  }
99  return $this->_aDeviceTokens[$nRecipient];
100  }
101 
102  /**
103  * Get the number of recipients.
104  *
105  * @return @type integer Recipient's number.
106  */
107  public function getRecipientsNumber()
108  {
109  return count($this->_aDeviceTokens);
110  }
111 
112  /**
113  * Get all recipients.
114  *
115  * @return @type array Array of all recipients device token.
116  */
117  public function getRecipients()
118  {
119  return $this->_aDeviceTokens;
120  }
121 
122  /**
123  * Set the alert message to display to the user.
124  *
125  * @param $sText @type string An alert message to display to the user.
126  */
127  public function setText($sText)
128  {
129  $this->_sText = $sText;
130  }
131 
132  /**
133  * Get the alert message to display to the user.
134  *
135  * @return @type string The alert message to display to the user.
136  */
137  public function getText()
138  {
139  return $this->_sText;
140  }
141 
142  /**
143  * Set the number to badge the application icon with.
144  *
145  * @param $nBadge @type integer A number to badge the application icon with.
146  * @throws ApnsPHP_Message_Exception if badge is not an
147  * integer.
148  */
149  public function setBadge($nBadge)
150  {
151  if (!is_int($nBadge)) {
152  throw new ApnsPHP_Message_Exception(
153  "Invalid badge number '{$nBadge}'"
154  );
155  }
156  $this->_nBadge = $nBadge;
157  }
158 
159  /**
160  * Get the number to badge the application icon with.
161  *
162  * @return @type integer The number to badge the application icon with.
163  */
164  public function getBadge()
165  {
166  return $this->_nBadge;
167  }
168 
169  /**
170  * Set the sound to play.
171  *
172  * @param $sSound @type string @optional A sound to play ('default sound' is
173  * the default sound).
174  */
175  public function setSound($sSound = 'default')
176  {
177  $this->_sSound = $sSound;
178  }
179 
180  /**
181  * Get the sound to play.
182  *
183  * @return @type string The sound to play.
184  */
185  public function getSound()
186  {
187  return $this->_sSound;
188  }
189 
190  /**
191  * Set the category of notification
192  *
193  * @param $sCategory @type string @optional A category for ios8 notification actions.
194  */
195  public function setCategory($sCategory = '')
196  {
197  $this->_sCategory = $sCategory;
198  }
199 
200  /**
201  * Get the category of notification
202  *
203  * @return @type string The notification category
204  */
205  public function getCategory()
206  {
207  return $this->_sCategory;
208  }
209 
210  /**
211  * Initiates the Newsstand background download.
212  * @see http://tinyurl.com/ApplePushNotificationNewsstand
213  *
214  * @param $bContentAvailable @type boolean True to initiates the Newsstand background download.
215  * @throws ApnsPHP_Message_Exception if ContentAvailable is not a
216  * boolean.
217  */
218  public function setContentAvailable($bContentAvailable = true)
219  {
220  if (!is_bool($bContentAvailable)) {
221  throw new ApnsPHP_Message_Exception(
222  "Invalid content-available value '{$bContentAvailable}'"
223  );
224  }
225  $this->_bContentAvailable = $bContentAvailable ? true : null;
226  }
227 
228  /**
229  * Get if should initiates the Newsstand background download.
230  *
231  * @return @type boolean Initiates the Newsstand background download property.
232  */
233  public function getContentAvailable()
234  {
236  }
237 
238  /**
239  * Set a custom property.
240  *
241  * @param $sName @type string Custom property name.
242  * @param $mValue @type mixed Custom property value.
243  * @throws ApnsPHP_Message_Exception if custom property name is not outside
244  * the Apple-reserved 'aps' namespace.
245  */
246  public function setCustomProperty($sName, $mValue)
247  {
248  if (trim($sName) == self::APPLE_RESERVED_NAMESPACE) {
249  throw new ApnsPHP_Message_Exception(
250  "Property name '" . self::APPLE_RESERVED_NAMESPACE . "' can not be used for custom property."
251  );
252  }
253  $this->_aCustomProperties[trim($sName)] = $mValue;
254  }
255 
256  /**
257  * Get the first custom property name.
258  *
259  * @deprecated Use getCustomPropertyNames() instead.
260  *
261  * @return @type string The first custom property name.
262  */
263  public function getCustomPropertyName()
264  {
265  if (!is_array($this->_aCustomProperties)) {
266  return;
267  }
268  $aKeys = array_keys($this->_aCustomProperties);
269  return $aKeys[0];
270  }
271 
272  /**
273  * Get the first custom property value.
274  *
275  * @deprecated Use getCustomProperty() instead.
276  *
277  * @return @type mixed The first custom property value.
278  */
279  public function getCustomPropertyValue()
280  {
281  if (!is_array($this->_aCustomProperties)) {
282  return;
283  }
284  $aKeys = array_keys($this->_aCustomProperties);
285  return $this->_aCustomProperties[$aKeys[0]];
286  }
287 
288  /**
289  * Get all custom properties names.
290  *
291  * @return @type array All properties names.
292  */
293  public function getCustomPropertyNames()
294  {
295  if (!is_array($this->_aCustomProperties)) {
296  return array();
297  }
298  return array_keys($this->_aCustomProperties);
299  }
300 
301  /**
302  * Get the custom property value.
303  *
304  * @param $sName @type string Custom property name.
305  * @throws ApnsPHP_Message_Exception if no property exists with the specified
306  * name.
307  * @return @type string The custom property value.
308  */
309  public function getCustomProperty($sName)
310  {
311  if (!array_key_exists($sName, $this->_aCustomProperties)) {
312  throw new ApnsPHP_Message_Exception(
313  "No property exists with the specified name '{$sName}'."
314  );
315  }
316  return $this->_aCustomProperties[$sName];
317  }
318 
319  /**
320  * Set the auto-adjust long payload value.
321  *
322  * @param $bAutoAdjust @type boolean If true a long payload is shorted cutting
323  * long text value.
324  */
325  public function setAutoAdjustLongPayload($bAutoAdjust)
326  {
327  $this->_bAutoAdjustLongPayload = (boolean)$bAutoAdjust;
328  }
329 
330  /**
331  * Get the auto-adjust long payload value.
332  *
333  * @return @type boolean The auto-adjust long payload value.
334  */
335  public function getAutoAdjustLongPayload()
336  {
338  }
339 
340  /**
341  * PHP Magic Method. When an object is "converted" to a string, JSON-encoded
342  * payload is returned.
343  *
344  * @return @type string JSON-encoded payload.
345  */
346  public function __toString()
347  {
348  try {
349  $sJSONPayload = $this->getPayload();
350  } catch (ApnsPHP_Message_Exception $e) {
351  $sJSONPayload = '';
352  }
353  return $sJSONPayload;
354  }
355 
356  /**
357  * Get the payload dictionary.
358  *
359  * @return @type array The payload dictionary.
360  */
361  protected function _getPayload()
362  {
363  $aPayload[self::APPLE_RESERVED_NAMESPACE] = array();
364 
365  if (isset($this->_sText)) {
366  $aPayload[self::APPLE_RESERVED_NAMESPACE]['alert'] = (string)$this->_sText;
367  }
368  if (isset($this->_nBadge) && $this->_nBadge >= 0) {
369  $aPayload[self::APPLE_RESERVED_NAMESPACE]['badge'] = (int)$this->_nBadge;
370  }
371  if (isset($this->_sSound)) {
372  $aPayload[self::APPLE_RESERVED_NAMESPACE]['sound'] = (string)$this->_sSound;
373  }
374  if (isset($this->_bContentAvailable)) {
375  $aPayload[self::APPLE_RESERVED_NAMESPACE]['content-available'] = (int)$this->_bContentAvailable;
376  }
377  if (isset($this->_sCategory)) {
378  $aPayload[self::APPLE_RESERVED_NAMESPACE]['category'] = (string)$this->_sCategory;
379  }
380 
381  if (is_array($this->_aCustomProperties)) {
382  foreach($this->_aCustomProperties as $sPropertyName => $mPropertyValue) {
383  $aPayload[$sPropertyName] = $mPropertyValue;
384  }
385  }
386 
387  return $aPayload;
388  }
389 
390  /**
391  * Convert the message in a JSON-encoded payload.
392  *
393  * @throws ApnsPHP_Message_Exception if payload is longer than maximum allowed
394  * size and AutoAdjustLongPayload is disabled.
395  * @return @type string JSON-encoded payload.
396  */
397  public function getPayload()
398  {
399  $sJSON = json_encode($this->_getPayload(), defined('JSON_UNESCAPED_UNICODE') ? JSON_UNESCAPED_UNICODE : 0);
400  if (!defined('JSON_UNESCAPED_UNICODE') && function_exists('mb_convert_encoding')) {
401  $sJSON = preg_replace_callback(
402  '~\\\\u([0-9a-f]{4})~i',
403  create_function('$aMatches', 'return mb_convert_encoding(pack("H*", $aMatches[1]), "UTF-8", "UTF-16");'),
404  $sJSON);
405  }
406 
407  $sJSONPayload = str_replace(
408  '"' . self::APPLE_RESERVED_NAMESPACE . '":[]',
409  '"' . self::APPLE_RESERVED_NAMESPACE . '":{}',
410  $sJSON
411  );
412  $nJSONPayloadLen = strlen($sJSONPayload);
413 
414  if ($nJSONPayloadLen > self::PAYLOAD_MAXIMUM_SIZE) {
415  if ($this->_bAutoAdjustLongPayload) {
416  $nMaxTextLen = $nTextLen = strlen($this->_sText) - ($nJSONPayloadLen - self::PAYLOAD_MAXIMUM_SIZE);
417  if ($nMaxTextLen > 0) {
418  while (strlen($this->_sText = mb_substr($this->_sText, 0, --$nTextLen, 'UTF-8')) > $nMaxTextLen);
419  return $this->getPayload();
420  } else {
421  throw new ApnsPHP_Message_Exception(
422  "JSON Payload is too long: {$nJSONPayloadLen} bytes. Maximum size is " .
423  self::PAYLOAD_MAXIMUM_SIZE . " bytes. The message text can not be auto-adjusted."
424  );
425  }
426  } else {
427  throw new ApnsPHP_Message_Exception(
428  "JSON Payload is too long: {$nJSONPayloadLen} bytes. Maximum size is " .
429  self::PAYLOAD_MAXIMUM_SIZE . " bytes"
430  );
431  }
432  }
433 
434  return $sJSONPayload;
435  }
436 
437  /**
438  * Set the expiry value.
439  *
440  * @param $nExpiryValue @type integer This message will expire in N seconds
441  * if not successful delivered.
442  */
443  public function setExpiry($nExpiryValue)
444  {
445  if (!is_int($nExpiryValue)) {
446  throw new ApnsPHP_Message_Exception(
447  "Invalid seconds number '{$nExpiryValue}'"
448  );
449  }
450  $this->_nExpiryValue = $nExpiryValue;
451  }
452 
453  /**
454  * Get the expiry value.
455  *
456  * @return @type integer The expire message value (in seconds).
457  */
458  public function getExpiry()
459  {
460  return $this->_nExpiryValue;
461  }
462 
463  /**
464  * Set the custom message identifier.
465  *
466  * The custom message identifier is useful to associate a push notification
467  * to a DB record or an User entry for example. The custom message identifier
468  * can be retrieved in case of error using the getCustomIdentifier()
469  * method of an entry retrieved by the getErrors() method.
470  * This custom identifier, if present, is also used in all status message by
471  * the ApnsPHP_Push class.
472  *
473  * @param $mCustomIdentifier @type mixed The custom message identifier.
474  */
475  public function setCustomIdentifier($mCustomIdentifier)
476  {
477  $this->_mCustomIdentifier = $mCustomIdentifier;
478  }
479 
480  /**
481  * Get the custom message identifier.
482  *
483  * @return @type mixed The custom message identifier.
484  */
485  public function getCustomIdentifier()
486  {
488  }
489 }
mixed $_mCustomIdentifier
Custom message identifier.
Definition: Message.php:53
mixed $_aCustomProperties
Custom properties container.
Definition: Message.php:49
void setExpiry(integer $nExpiryValue)
Set the expiry value.
Definition: Message.php:443
const PAYLOAD_MAXIMUM_SIZE
integer The maximum size allowed for a notification payload.
Definition: Message.php:36
string $_sText
Alert message to display to the user.
Definition: Message.php:43
integer getBadge()
Get the number to badge the application icon with.
Definition: Message.php:164
string getCustomPropertyName()
Get the first custom property name.
Definition: Message.php:263
string $_sCategory
notification category.
Definition: Message.php:46
void setText(string $sText)
Set the alert message to display to the user.
Definition: Message.php:127
integer getRecipientsNumber()
Get the number of recipients.
Definition: Message.php:107
void setCustomProperty(string $sName, mixed $mValue)
Set a custom property.
Definition: Message.php:246
array getRecipients()
Get all recipients.
Definition: Message.php:117
string getPayload()
Convert the message in a JSON-encoded payload.
Definition: Message.php:397
string getCustomProperty(string $sName)
Get the custom property value.
Definition: Message.php:309
void setBadge(integer $nBadge)
Set the number to badge the application icon with.
Definition: Message.php:149
void __construct(string $sDeviceToken=null)
Constructor.
Definition: Message.php:60
const APPLE_RESERVED_NAMESPACE
string The Apple-reserved aps namespace.
Definition: Message.php:37
string getSound()
Get the sound to play.
Definition: Message.php:185
mixed getCustomPropertyValue()
Get the first custom property value.
Definition: Message.php:279
string getRecipient(integer $nRecipient=0)
Get a recipient.
Definition: Message.php:92
integer $_nBadge
Number to badge the application icon with.
Definition: Message.php:44
array $_aDeviceTokens
Recipients device tokens.
Definition: Message.php:41
void setCustomIdentifier(mixed $mCustomIdentifier)
Set the custom message identifier.
Definition: Message.php:475
void addRecipient(string $sDeviceToken)
Add a recipient device token.
Definition: Message.php:74
string $_sSound
Sound to play.
Definition: Message.php:45
void setSound(string $sSound= 'default')
Set the sound to play.
Definition: Message.php:175
integer getExpiry()
Get the expiry value.
Definition: Message.php:458
string getText()
Get the alert message to display to the user.
Definition: Message.php:137
array getCustomPropertyNames()
Get all custom properties names.
Definition: Message.php:293
boolean $_bContentAvailable
True to initiates the Newsstand background download.
Definition: Message.php:47
array _getPayload()
Get the payload dictionary.
Definition: Message.php:361
void setAutoAdjustLongPayload(boolean $bAutoAdjust)
Set the auto-adjust long payload value.
Definition: Message.php:325
void setContentAvailable(boolean $bContentAvailable=true)
Initiates the Newsstand background download.
Definition: Message.php:218
string __toString()
PHP Magic Method.
Definition: Message.php:346
boolean getAutoAdjustLongPayload()
Get the auto-adjust long payload value.
Definition: Message.php:335
integer $_nExpiryValue
That message will expire in 604800 seconds (86400 * 7, 7 days) if not successful delivered.
Definition: Message.php:51
The Push Notification Message.
Definition: Message.php:34
boolean getContentAvailable()
Get if should initiates the Newsstand background download.
Definition: Message.php:233
boolean $_bAutoAdjustLongPayload
If the JSON payload is longer than maximum allowed size, shorts message text.
Definition: Message.php:39
mixed getCustomIdentifier()
Get the custom message identifier.
Definition: Message.php:485
void setCategory(string $sCategory= '')
Set the category of notification.
Definition: Message.php:195
string getCategory()
Get the category of notification.
Definition: Message.php:205