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)
28 use Friendica\Core\PConfig;
30 function windowsphonepush_install() {
34 * Our plugin will attach in three places.
35 * The first is within cron - so the push notifications will be
36 * sent every 10 minutes (or whatever is set in crontab).
40 register_hook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
44 * Then we'll attach into the plugin settings page, and also the
45 * settings post hook so that we can create and update
46 * user preferences. User shall be able to activate the plugin and
47 * define whether he allows pushing first characters of item text
51 register_hook('plugin_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
52 register_hook('plugin_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
54 logger("installed windowsphonepush");
58 function windowsphonepush_uninstall() {
62 * uninstall unregisters any hooks created with register_hook
63 * during install. Don't delete data in table `pconfig`.
67 unregister_hook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
68 unregister_hook('plugin_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
69 unregister_hook('plugin_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
71 logger("removed windowsphonepush");
75 /* declare the windowsphonepush function so that /windowsphonepush url requests will land here */
76 function windowsphonepush_module() {}
81 * Callback from the settings post function.
82 * $post contains the $_POST array.
83 * We will make sure we've got a valid user account
84 * and if so set our configuration setting for this person.
87 function windowsphonepush_settings_post($a,$post) {
88 if(! local_user() || (! x($_POST,'windowsphonepush-submit')))
90 $enable = intval($_POST['windowsphonepush']);
91 PConfig::set(local_user(),'windowsphonepush','enable',$enable);
94 PConfig::set(local_user(),'windowsphonepush','counterunseen', 0);
97 PConfig::set(local_user(),'windowsphonepush','senditemtext',intval($_POST['windowsphonepush-senditemtext']));
99 info( t('WindowsPhonePush settings updated.') . EOL);
105 * Called from the Plugin Setting form.
106 * Add our own settings info to the page.
109 function windowsphonepush_settings(&$a,&$s) {
114 /* Add our stylesheet to the page so we can make our settings look nice */
115 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/windowsphonepush/windowsphonepush.css' . '" media="all" />' . "\r\n";
117 /* Get the current state of our config variables */
118 $enabled = PConfig::get(local_user(),'windowsphonepush','enable');
119 $checked_enabled = (($enabled) ? ' checked="checked" ' : '');
121 $senditemtext = PConfig::get(local_user(), 'windowsphonepush', 'senditemtext');
122 $checked_senditemtext = (($senditemtext) ? ' checked="checked" ' : '');
124 $device_url = PConfig::get(local_user(), 'windowsphonepush', 'device_url');
126 /* Add some HTML to the existing form */
127 $s .= '<div class="settings-block">';
128 $s .= '<h3>' . t('WindowsPhonePush Settings') . '</h3>';
130 $s .= '<div id="windowsphonepush-enable-wrapper">';
131 $s .= '<label id="windowsphonepush-enable-label" for="windowsphonepush-enable-chk">' . t('Enable WindowsPhonePush Plugin') . '</label>';
132 $s .= '<input id="windowsphonepush-enable-chk" type="checkbox" name="windowsphonepush" value="1" ' . $checked_enabled . '/>';
133 $s .= '</div><div class="clear"></div>';
135 $s .= '<div id="windowsphonepush-senditemtext-wrapper">';
136 $s .= '<label id="windowsphonepush-senditemtext-label" for="windowsphonepush-senditemtext-chk">' . t('Push text of new item') . '</label>';
137 $s .= '<input id="windowsphonepush-senditemtext-chk" type="checkbox" name="windowsphonepush-senditemtext" value="1" ' . $checked_senditemtext . '/>';
138 $s .= '</div><div class="clear"></div>';
140 /* provide a submit button - enable und senditemtext can be changed by the user*/
141 $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>';
143 /* provide further read-only information concerning the addon (useful for */
144 $s .= '<div id="windowsphonepush-device_url-wrapper">';
145 $s .= '<label id="windowsphonepush-device_url-label" for="windowsphonepush-device_url-text">Device-URL</label>';
146 $s .= '<input id="windowsphonepush-device_url-text" type="text" readonly value=' . $device_url . '/>';
147 $s .= '</div><div class="clear"></div></div>';
156 * Cron function used to regularly check all users on the server with active windowsphonepushplugin and send
157 * notifications to the Microsoft servers and consequently to the Windows Phone device
161 function windowsphonepush_cron() {
162 // retrieve all UID's for which the plugin windowsphonepush is enabled and loop through every user
163 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'windowsphonepush' AND `k` = 'enable' AND `v` = 1");
166 // load stored information for the user-id of the current loop
167 $device_url = PConfig::get($rr['uid'], 'windowsphonepush', 'device_url');
168 $lastpushid = PConfig::get($rr['uid'], 'windowsphonepush', 'lastpushid');
170 // pushing only possible if device_url (the URI on Microsoft server) is available or not "NA" (which will be sent
171 // by app if user has switched the server setting in app - sending blank not possible as this would return an update error)
172 if ( ( $device_url == "" ) || ( $device_url == "NA" ) ) {
173 // no Device-URL for the user availabe, but plugin is enabled --> write info to Logger
174 logger("WARN: windowsphonepush is enable for user " . $rr['uid'] . ", but no Device-URL is specified for the user.");
176 // retrieve the number of unseen items and the id of the latest one (if there are more than
177 // one new entries since last poller run, only the latest one will be pushed)
178 $count = q("SELECT count(`id`) as count, max(`id`) as max FROM `item` WHERE `unseen` = 1 AND `type` <> 'activity' AND `uid` = %d",
182 // send number of unseen items to the device (the number will be displayed on Start screen until
183 // App will be started by user) - this update will be sent every 10 minutes to update the number to 0 if
184 // user has loaded the timeline through app or website
185 $res_tile = send_tile_update($device_url, "", $count[0]['count'], "");
186 switch (trim($res_tile)) {
188 // ok, count has been pushed, let's save it in personal settings
189 PConfig::set($rr['uid'], 'windowsphonepush', 'counterunseen', $count[0]['count']);
192 // maximum of 30 messages reached, server rejects any further push notification until device reconnects
193 logger("INFO: Device-URL '" . $device_url . "' returns a QueueFull.");
196 // notification received and dropped as something in app was not enabled
197 logger("WARN. Device-URL '" . $device_url . "' returns a Suppressed. Unexpected error in Mobile App?");
200 // mostly combines with Expired, in that case Device-URL will be deleted from pconfig (function send_push)
203 // error, mostly called by "" which means that the url (not "" which has been checked)
204 // didn't not received Microsoft Notification Server -> wrong url
205 logger("ERROR: specified Device-URL '" . $device_url . "' didn't produced any response.");
208 // additionally user receives the text of the newest item (function checks against last successfully pushed item)
209 if (intval($count[0]['max']) > intval($lastpushid)) {
210 // user can define if he wants to see the text of the item in the push notification
211 // this has been implemented as the device_url is not a https uri (not so secure)
212 $senditemtext = PConfig::get($rr['uid'], 'windowsphonepush', 'senditemtext');
213 if ($senditemtext == 1) {
214 // load item with the max id
215 $item = q("SELECT `author-name` as author, `body` as body FROM `item` where `id` = %d",
216 intval($count[0]['max'])
219 // as user allows to send the item, we want to show the sender of the item in the toast
220 // toasts are limited to one line, therefore place is limited - author shall be in
221 // max. 15 chars (incl. dots); author is displayed in bold font
222 $author = $item[0]['author'];
223 $author = ((strlen($author) > 12) ? substr($author, 0, 12) . "..." : $author);
225 // normally we show the body of the item, however if it is an url or an image we cannot
226 // show this in the toast (only test), therefore changing to an alternate text
227 // Otherwise BBcode-Tags will be eliminated and plain text cutted to 140 chars (incl. dots)
228 // BTW: information only possible in English
229 $body = $item[0]['body'];
230 if (substr($body, 0, 4) == "[url")
231 $body = "URL/Image ...";
233 require_once('include/bbcode.php');
234 require_once("include/html2plain.php");
235 $body = bbcode($body, false, false, 2, true);
236 $body = html2plain($body, 0);
237 $body = ((strlen($body) > 137) ? substr($body, 0, 137) . "..." : $body);
240 // if user wishes higher privacy, we only display "Friendica - New timeline entry arrived"
241 $author = "Friendica";
242 $body = "New timeline entry arrived ...";
244 // only if toast push notification returns the Notification status "Received" we will update th settings with the
245 // new indicator max-id is checked against (QueueFull, Suppressed, N/A, Dropped shall qualify to resend
246 // the push notification some minutes later (BTW: if resulting in Expired for subscription status the
247 // device_url will be deleted (no further try on this url, see send_push)
248 // further log information done on count pushing with send_tile (see above)
249 $res_toast = send_toast($device_url, $author, $body);
250 if (trim($res_toast) === 'Received') {
251 PConfig::set($rr['uid'], 'windowsphonepush', 'lastpushid', $count[0]['max']);
262 * Tile push notification change the number in the icon of the App in Start Screen of
263 * a Windows Phone Device, Image could be changed, not used for App "Friendica Mobile"
266 function send_tile_update($device_url, $image_url, $count, $title, $priority = 1) {
267 $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
268 "<wp:Notification xmlns:wp=\"WPNotification\">" .
270 "<wp:BackgroundImage>" . $image_url . "</wp:BackgroundImage>" .
271 "<wp:Count>" . $count . "</wp:Count>" .
272 "<wp:Title>" . $title . "</wp:Title>" .
274 "</wp:Notification>";
276 $result = send_push($device_url, array(
277 'X-WindowsPhone-Target: token',
278 'X-NotificationClass: ' . $priority,
285 * Toast push notification send information to the top of the display
286 * if the user is not currently using the Friendica Mobile App, however
287 * there is only one line for displaying the information
290 function send_toast($device_url, $title, $message, $priority = 2) {
291 $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
292 "<wp:Notification xmlns:wp=\"WPNotification\">" .
294 "<wp:Text1>" . $title . "</wp:Text1>" .
295 "<wp:Text2>" . $message . "</wp:Text2>" .
296 "<wp:Param></wp:Param>" .
298 "</wp:Notification>";
300 $result = send_push($device_url, array(
301 'X-WindowsPhone-Target: toast',
302 'X-NotificationClass: ' . $priority,
309 * General function to send the push notification via cURL
312 function send_push($device_url, $headers, $msg) {
314 curl_setopt($ch, CURLOPT_URL, $device_url);
315 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
316 curl_setopt($ch, CURLOPT_POST, true);
317 curl_setopt($ch, CURLOPT_HEADER, true);
318 curl_setopt($ch, CURLOPT_HTTPHEADER,
320 'Content-Type: text/xml',
322 'Accept: application/*',
325 curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
327 $output = curl_exec($ch);
330 // if we received "Expired" from Microsoft server we will delete the obsolete device-URL
332 $subscriptionStatus = get_header_value($output, 'X-SubscriptionStatus');
333 if ($subscriptionStatus == "Expired") {
334 PConfig::set(local_user(),'windowsphonepush','device_url', "");
335 logger("ERROR: the stored Device-URL " . $device_url . "returned an 'Expired' error, it has been deleted now.");
338 // the notification status shall be returned to windowsphonepush_cron (will
339 // update settings if 'Received' otherwise keep old value in settings (on QueuedFull. Suppressed, N/A, Dropped)
340 $notificationStatus = get_header_value($output, 'X-NotificationStatus');
341 return $notificationStatus;
345 * helper function to receive statuses from webresponse of Microsoft server
347 function get_header_value($content, $header) {
348 return preg_match_all("/$header: (.*)/i", $content, $match) ? $match[1][0] : "";
354 * reading information from url and deciding which function to start
355 * show_settings = delivering settings to check
356 * update_settings = set the device_url
357 * update_counterunseen = set counter for unseen elements to zero
360 function windowsphonepush_content(&$a) {
361 // Login with the specified Network credentials (like in api.php)
362 windowsphonepush_login();
365 $path2 = $a->argv[1];
366 if ($path == "windowsphonepush") {
368 case "show_settings":
369 windowsphonepush_showsettings($a);
372 case "update_settings":
373 $ret = windowsphonepush_updatesettings($a);
374 header("Content-Type: application/json; charset=utf-8");
375 echo json_encode(array('status' => $ret));
378 case "update_counterunseen":
379 $ret = windowsphonepush_updatecounterunseen();
380 header("Content-Type: application/json; charset=utf-8");
381 echo json_encode(array('status' => $ret));
391 * return settings for windowsphonepush addon to be able to check them in WP app
393 function windowsphonepush_showsettings(&$a) {
397 $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
398 $device_url = PConfig::get(local_user(), 'windowsphonepush', 'device_url');
399 $senditemtext = PConfig::get(local_user(), 'windowsphonepush', 'senditemtext');
400 $lastpushid = PConfig::get(local_user(), 'windowsphonepush', 'lastpushid');
401 $counterunseen = PConfig::get(local_user(), 'windowsphonepush', 'counterunseen');
402 $addonversion = "2.0";
410 header ("Content-Type: application/json");
411 echo json_encode(array('uid' => local_user(),
413 'device_url' => $device_url,
414 'senditemtext' => $senditemtext,
415 'lastpushid' => $lastpushid,
416 'counterunseen' => $counterunseen,
417 'addonversion' => $addonversion));
421 * update_settings is used to transfer the device_url from WP device to the Friendica server
422 * return the status of the operation to the server
424 function windowsphonepush_updatesettings(&$a) {
426 return "Not Authenticated";
429 // no updating if user hasn't enabled the plugin
430 $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
432 return "Plug-in not enabled";
435 // check if sent url is empty - don't save and send return code to app
436 $device_url = $_POST['deviceurl'];
437 if ($device_url == "") {
438 logger("ERROR: no valid Device-URL specified - client transferred '" . $device_url . "'");
439 return "No valid Device-URL specified";
442 // check if sent url is already stored in database for another user, we assume that there was a change of
443 // the user on the Windows Phone device and that device url is no longer true for the other user, so we
444 // et the device_url for the OTHER user blank (should normally not occur as App should include User/server
445 // in url request to Microsoft Push Notification server)
446 $r = q("SELECT * FROM `pconfig` WHERE `uid` <> " . local_user() . " AND
447 `cat` = 'windowsphonepush' AND
448 `k` = 'device_url' AND
449 `v` = '" . $device_url . "'");
452 PConfig::set($rr['uid'], 'windowsphonepush', 'device_url', '');
453 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() . "'.");
457 PConfig::set(local_user(),'windowsphonepush','device_url', $device_url);
458 // output the successfull update of the device URL to the logger for error analysis if necessary
459 logger("INFO: Device-URL for user '" . local_user() . "' has been updated with '" . $device_url . "'");
460 return "Device-URL updated successfully!";
464 * update_counterunseen is used to reset the counter to zero from Windows Phone app
466 function windowsphonepush_updatecounterunseen() {
468 return "Not Authenticated";
471 // no updating if user hasn't enabled the plugin
472 $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
474 return "Plug-in not enabled";
477 PConfig::set(local_user(),'windowsphonepush','counterunseen', 0);
478 return "Counter set to zero";
482 * helper function to login to the server with the specified Network credentials
483 * (mainly copied from api.php)
485 function windowsphonepush_login() {
486 if (!isset($_SERVER['PHP_AUTH_USER'])) {
487 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
488 header('WWW-Authenticate: Basic realm="Friendica"');
489 header('HTTP/1.0 401 Unauthorized');
490 die('This api requires login');
493 $user = $_SERVER['PHP_AUTH_USER'];
494 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
496 // check if user specified by app is available in the user table
497 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
498 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
507 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
508 header('WWW-Authenticate: Basic realm="Friendica"');
509 header('HTTP/1.0 401 Unauthorized');
510 die('This api requires login');
513 require_once('include/security.php');
514 authenticate_success($record); $_SESSION["allow_api"] = true;
515 call_hooks('logged_in', $a->user);