3 * Name: WindowsPhonePush
4 * Description: Enable push notification to send information to Friendica Mobile app on Windows phone (count of unread timeline entries, text of last posting - if wished by user)
6 * Author: Gerhard Seeber <http://friendica.seeber.at/profile/admin>
9 * Pre-requisite: Windows Phone mobile device (at least WP 7.0)
10 * Friendica mobile app on Windows Phone
12 * When plugin is installed, the system calls the plugin
13 * name_install() function, located in 'addon/name/name.php',
14 * where 'name' is the name of the addon.
15 * If the addon is removed from the configuration list, the
16 * system will call the name_uninstall() function.
19 * 1.1 : addon crashed on php versions >= 5.4 as of removed deprecated call-time
20 * pass-by-reference used in function calls within function windowsphonepush_content
21 * 2.0 : adaption for supporting emphasizing new entries in app (count on tile cannot be read out,
22 * so we need to retrieve counter through show_settings secondly). Provide new function for
23 * calling from app to set the counter back after start (if user starts again before cronjob
24 * sets the counter back
25 * count only unseen elements which are not type=activity (likes and dislikes not seen as new elements)
29 function windowsphonepush_install() {
33 * Our plugin will attach in three places.
34 * The first is within cron - so the push notifications will be
35 * sent every 10 minutes (or whatever is set in crontab).
39 register_hook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
43 * Then we'll attach into the plugin settings page, and also the
44 * settings post hook so that we can create and update
45 * user preferences. User shall be able to activate the plugin and
46 * define whether he allows pushing first characters of item text
50 register_hook('plugin_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
51 register_hook('plugin_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
53 logger("installed windowsphonepush");
57 function windowsphonepush_uninstall() {
61 * uninstall unregisters any hooks created with register_hook
62 * during install. Don't delete data in table `pconfig`.
66 unregister_hook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
67 unregister_hook('plugin_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
68 unregister_hook('plugin_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
70 logger("removed windowsphonepush");
74 /* declare the windowsphonepush function so that /windowsphonepush url requests will land here */
75 function windowsphonepush_module() {}
80 * Callback from the settings post function.
81 * $post contains the $_POST array.
82 * We will make sure we've got a valid user account
83 * and if so set our configuration setting for this person.
86 function windowsphonepush_settings_post($a,$post) {
87 if(! local_user() || (! x($_POST,'windowsphonepush-submit')))
89 $enable = intval($_POST['windowsphonepush']);
90 set_pconfig(local_user(),'windowsphonepush','enable',$enable);
93 set_pconfig(local_user(),'windowsphonepush','counterunseen', 0);
96 set_pconfig(local_user(),'windowsphonepush','senditemtext',intval($_POST['windowsphonepush-senditemtext']));
98 info( t('WindowsPhonePush settings updated.') . EOL);
104 * Called from the Plugin Setting form.
105 * Add our own settings info to the page.
108 function windowsphonepush_settings(&$a,&$s) {
113 /* Add our stylesheet to the page so we can make our settings look nice */
114 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/windowsphonepush/windowsphonepush.css' . '" media="all" />' . "\r\n";
116 /* Get the current state of our config variables */
117 $enabled = get_pconfig(local_user(),'windowsphonepush','enable');
118 $checked_enabled = (($enabled) ? ' checked="checked" ' : '');
120 $senditemtext = get_pconfig(local_user(), 'windowsphonepush', 'senditemtext');
121 $checked_senditemtext = (($senditemtext) ? ' checked="checked" ' : '');
123 $device_url = get_pconfig(local_user(), 'windowsphonepush', 'device_url');
125 /* Add some HTML to the existing form */
126 $s .= '<div class="settings-block">';
127 $s .= '<h3>' . t('WindowsPhonePush Settings') . '</h3>';
129 $s .= '<div id="windowsphonepush-enable-wrapper">';
130 $s .= '<label id="windowsphonepush-enable-label" for="windowsphonepush-enable-chk">' . t('Enable WindowsPhonePush Plugin') . '</label>';
131 $s .= '<input id="windowsphonepush-enable-chk" type="checkbox" name="windowsphonepush" value="1" ' . $checked_enabled . '/>';
132 $s .= '</div><div class="clear"></div>';
134 $s .= '<div id="windowsphonepush-senditemtext-wrapper">';
135 $s .= '<label id="windowsphonepush-senditemtext-label" for="windowsphonepush-senditemtext-chk">' . t('Push text of new item') . '</label>';
136 $s .= '<input id="windowsphonepush-senditemtext-chk" type="checkbox" name="windowsphonepush-senditemtext" value="1" ' . $checked_senditemtext . '/>';
137 $s .= '</div><div class="clear"></div>';
139 /* provide a submit button - enable und senditemtext can be changed by the user*/
140 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="windowsphonepush-submit" name="windowsphonepush-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div><div class="clear"></div>';
142 /* provide further read-only information concerning the addon (useful for */
143 $s .= '<div id="windowsphonepush-device_url-wrapper">';
144 $s .= '<label id="windowsphonepush-device_url-label" for="windowsphonepush-device_url-text">Device-URL</label>';
145 $s .= '<input id="windowsphonepush-device_url-text" type="text" readonly value=' . $device_url . '/>';
146 $s .= '</div><div class="clear"></div></div>';
155 * Cron function used to regularly check all users on the server with active windowsphonepushplugin and send
156 * notifications to the Microsoft servers and consequently to the Windows Phone device
160 function windowsphonepush_cron() {
161 // retrieve all UID's for which the plugin windowsphonepush is enabled and loop through every user
162 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'windowsphonepush' AND `k` = 'enable' AND `v` = 1");
165 // load stored information for the user-id of the current loop
166 $device_url = get_pconfig($rr['uid'], 'windowsphonepush', 'device_url');
167 $lastpushid = get_pconfig($rr['uid'], 'windowsphonepush', 'lastpushid');
169 // pushing only possible if device_url (the URI on Microsoft server) is available or not "NA" (which will be sent
170 // by app if user has switched the server setting in app - sending blank not possible as this would return an update error)
171 if ( ( $device_url == "" ) || ( $device_url == "NA" ) ) {
172 // no Device-URL for the user availabe, but plugin is enabled --> write info to Logger
173 logger("WARN: windowsphonepush is enable for user " . $rr['uid'] . ", but no Device-URL is specified for the user.");
175 // retrieve the number of unseen items and the id of the latest one (if there are more than
176 // one new entries since last poller run, only the latest one will be pushed)
177 $count = q("SELECT count(`id`) as count, max(`id`) as max FROM `item` WHERE `unseen` = 1 AND `type` <> 'activity' AND `uid` = %d",
181 // send number of unseen items to the device (the number will be displayed on Start screen until
182 // App will be started by user) - this update will be sent every 10 minutes to update the number to 0 if
183 // user has loaded the timeline through app or website
184 $res_tile = send_tile_update($device_url, "", $count[0]['count'], "");
185 switch (trim($res_tile)) {
187 // ok, count has been pushed, let's save it in personal settings
188 set_pconfig($rr['uid'], 'windowsphonepush', 'counterunseen', $count[0]['count']);
191 // maximum of 30 messages reached, server rejects any further push notification until device reconnects
192 logger("INFO: Device-URL '" . $device_url . "' returns a QueueFull.");
195 // notification received and dropped as something in app was not enabled
196 logger("WARN. Device-URL '" . $device_url . "' returns a Suppressed. Unexpected error in Mobile App?");
199 // mostly combines with Expired, in that case Device-URL will be deleted from pconfig (function send_push)
202 // error, mostly called by "" which means that the url (not "" which has been checked)
203 // didn't not received Microsoft Notification Server -> wrong url
204 logger("ERROR: specified Device-URL '" . $device_url . "' didn't produced any response.");
207 // additionally user receives the text of the newest item (function checks against last successfully pushed item)
208 if (intval($count[0]['max']) > intval($lastpushid)) {
209 // user can define if he wants to see the text of the item in the push notification
210 // this has been implemented as the device_url is not a https uri (not so secure)
211 $senditemtext = get_pconfig($rr['uid'], 'windowsphonepush', 'senditemtext');
212 if ($senditemtext == 1) {
213 // load item with the max id
214 $item = q("SELECT `author-name` as author, `body` as body FROM `item` where `id` = %d",
215 intval($count[0]['max'])
218 // as user allows to send the item, we want to show the sender of the item in the toast
219 // toasts are limited to one line, therefore place is limited - author shall be in
220 // max. 15 chars (incl. dots); author is displayed in bold font
221 $author = $item[0]['author'];
222 $author = ((strlen($author) > 12) ? substr($author, 0, 12) . "..." : $author);
224 // normally we show the body of the item, however if it is an url or an image we cannot
225 // show this in the toast (only test), therefore changing to an alternate text
226 // Otherwise BBcode-Tags will be eliminated and plain text cutted to 140 chars (incl. dots)
227 // BTW: information only possible in English
228 $body = $item[0]['body'];
229 if (substr($body, 0, 4) == "[url")
230 $body = "URL/Image ...";
232 require_once('include/bbcode.php');
233 require_once("include/html2plain.php");
234 $body = bbcode($body, false, false, 2, true);
235 $body = html2plain($body, 0);
236 $body = ((strlen($body) > 137) ? substr($body, 0, 137) . "..." : $body);
239 // if user wishes higher privacy, we only display "Friendica - New timeline entry arrived"
240 $author = "Friendica";
241 $body = "New timeline entry arrived ...";
243 // only if toast push notification returns the Notification status "Received" we will update th settings with the
244 // new indicator max-id is checked against (QueueFull, Suppressed, N/A, Dropped shall qualify to resend
245 // the push notification some minutes later (BTW: if resulting in Expired for subscription status the
246 // device_url will be deleted (no further try on this url, see send_push)
247 // further log information done on count pushing with send_tile (see above)
248 $res_toast = send_toast($device_url, $author, $body);
249 if (trim($res_toast) === 'Received') {
250 set_pconfig($rr['uid'], 'windowsphonepush', 'lastpushid', $count[0]['max']);
261 * Tile push notification change the number in the icon of the App in Start Screen of
262 * a Windows Phone Device, Image could be changed, not used for App "Friendica Mobile"
265 function send_tile_update($device_url, $image_url, $count, $title, $priority = 1) {
266 $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
267 "<wp:Notification xmlns:wp=\"WPNotification\">" .
269 "<wp:BackgroundImage>" . $image_url . "</wp:BackgroundImage>" .
270 "<wp:Count>" . $count . "</wp:Count>" .
271 "<wp:Title>" . $title . "</wp:Title>" .
273 "</wp:Notification>";
275 $result = send_push($device_url, array(
276 'X-WindowsPhone-Target: token',
277 'X-NotificationClass: ' . $priority,
284 * Toast push notification send information to the top of the display
285 * if the user is not currently using the Friendica Mobile App, however
286 * there is only one line for displaying the information
289 function send_toast($device_url, $title, $message, $priority = 2) {
290 $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
291 "<wp:Notification xmlns:wp=\"WPNotification\">" .
293 "<wp:Text1>" . $title . "</wp:Text1>" .
294 "<wp:Text2>" . $message . "</wp:Text2>" .
295 "<wp:Param></wp:Param>" .
297 "</wp:Notification>";
299 $result = send_push($device_url, array(
300 'X-WindowsPhone-Target: toast',
301 'X-NotificationClass: ' . $priority,
308 * General function to send the push notification via cURL
311 function send_push($device_url, $headers, $msg) {
313 curl_setopt($ch, CURLOPT_URL, $device_url);
314 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
315 curl_setopt($ch, CURLOPT_POST, true);
316 curl_setopt($ch, CURLOPT_HEADER, true);
317 curl_setopt($ch, CURLOPT_HTTPHEADER,
319 'Content-Type: text/xml',
321 'Accept: application/*',
324 curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
326 $output = curl_exec($ch);
329 // if we received "Expired" from Microsoft server we will delete the obsolete device-URL
331 $subscriptionStatus = get_header_value($output, 'X-SubscriptionStatus');
332 if ($subscriptionStatus == "Expired") {
333 set_pconfig(local_user(),'windowsphonepush','device_url', "");
334 logger("ERROR: the stored Device-URL " . $device_url . "returned an 'Expired' error, it has been deleted now.");
337 // the notification status shall be returned to windowsphonepush_cron (will
338 // update settings if 'Received' otherwise keep old value in settings (on QueuedFull. Suppressed, N/A, Dropped)
339 $notificationStatus = get_header_value($output, 'X-NotificationStatus');
340 return $notificationStatus;
344 * helper function to receive statuses from webresponse of Microsoft server
346 function get_header_value($content, $header) {
347 return preg_match_all("/$header: (.*)/i", $content, $match) ? $match[1][0] : "";
353 * reading information from url and deciding which function to start
354 * show_settings = delivering settings to check
355 * update_settings = set the device_url
356 * update_counterunseen = set counter for unseen elements to zero
359 function windowsphonepush_content(&$a) {
360 // Login with the specified Network credentials (like in api.php)
361 windowsphonepush_login();
364 $path2 = $a->argv[1];
365 if ($path == "windowsphonepush") {
367 case "show_settings":
368 windowsphonepush_showsettings($a);
371 case "update_settings":
372 $ret = windowsphonepush_updatesettings($a);
373 header("Content-Type: application/json; charset=utf-8");
374 echo json_encode(array('status' => $ret));
377 case "update_counterunseen":
378 $ret = windowsphonepush_updatecounterunseen();
379 header("Content-Type: application/json; charset=utf-8");
380 echo json_encode(array('status' => $ret));
390 * return settings for windowsphonepush addon to be able to check them in WP app
392 function windowsphonepush_showsettings(&$a) {
396 $enable = get_pconfig(local_user(), 'windowsphonepush', 'enable');
397 $device_url = get_pconfig(local_user(), 'windowsphonepush', 'device_url');
398 $senditemtext = get_pconfig(local_user(), 'windowsphonepush', 'senditemtext');
399 $lastpushid = get_pconfig(local_user(), 'windowsphonepush', 'lastpushid');
400 $counterunseen = get_pconfig(local_user(), 'windowsphonepush', 'counterunseen');
401 $addonversion = "2.0";
409 header ("Content-Type: application/json");
410 echo json_encode(array('uid' => local_user(),
412 'device_url' => $device_url,
413 'senditemtext' => $senditemtext,
414 'lastpushid' => $lastpushid,
415 'counterunseen' => $counterunseen,
416 'addonversion' => $addonversion));
420 * update_settings is used to transfer the device_url from WP device to the Friendica server
421 * return the status of the operation to the server
423 function windowsphonepush_updatesettings(&$a) {
425 return "Not Authenticated";
428 // no updating if user hasn't enabled the plugin
429 $enable = get_pconfig(local_user(), 'windowsphonepush', 'enable');
431 return "Plug-in not enabled";
434 // check if sent url is empty - don't save and send return code to app
435 $device_url = $_POST['deviceurl'];
436 if ($device_url == "") {
437 logger("ERROR: no valid Device-URL specified - client transferred '" . $device_url . "'");
438 return "No valid Device-URL specified";
441 // check if sent url is already stored in database for another user, we assume that there was a change of
442 // the user on the Windows Phone device and that device url is no longer true for the other user, so we
443 // et the device_url for the OTHER user blank (should normally not occur as App should include User/server
444 // in url request to Microsoft Push Notification server)
445 $r = q("SELECT * FROM `pconfig` WHERE `uid` <> " . local_user() . " AND
446 `cat` = 'windowsphonepush' AND
447 `k` = 'device_url' AND
448 `v` = '" . $device_url . "'");
451 set_pconfig($rr['uid'], 'windowsphonepush', 'device_url', '');
452 logger("WARN: the sent URL was already registered with user '" . $rr['uid'] . "'. Deleted for this user as we expect to be correct now for user '" . local_user() . "'.");
456 set_pconfig(local_user(),'windowsphonepush','device_url', $device_url);
457 // output the successfull update of the device URL to the logger for error analysis if necessary
458 logger("INFO: Device-URL for user '" . local_user() . "' has been updated with '" . $device_url . "'");
459 return "Device-URL updated successfully!";
463 * update_counterunseen is used to reset the counter to zero from Windows Phone app
465 function windowsphonepush_updatecounterunseen() {
467 return "Not Authenticated";
470 // no updating if user hasn't enabled the plugin
471 $enable = get_pconfig(local_user(), 'windowsphonepush', 'enable');
473 return "Plug-in not enabled";
476 set_pconfig(local_user(),'windowsphonepush','counterunseen', 0);
477 return "Counter set to zero";
481 * helper function to login to the server with the specified Network credentials
482 * (mainly copied from api.php)
484 function windowsphonepush_login() {
485 if (!isset($_SERVER['PHP_AUTH_USER'])) {
486 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
487 header('WWW-Authenticate: Basic realm="Friendica"');
488 header('HTTP/1.0 401 Unauthorized');
489 die('This api requires login');
492 $user = $_SERVER['PHP_AUTH_USER'];
493 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
495 // check if user specified by app is available in the user table
496 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
497 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
506 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
507 header('WWW-Authenticate: Basic realm="Friendica"');
508 header('HTTP/1.0 401 Unauthorized');
509 die('This api requires login');
512 require_once('include/security.php');
513 authenticate_success($record); $_SESSION["allow_api"] = true;
514 call_hooks('logged_in', $a->user);