4 * Name: WindowsPhonePush
5 * 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)
7 * Author: Gerhard Seeber <http://friendica.seeber.at/profile/admin>
10 * Pre-requisite: Windows Phone mobile device (at least WP 7.0)
11 * Friendica mobile app on Windows Phone
13 * When addon is installed, the system calls the addon
14 * name_install() function, located in 'addon/name/name.php',
15 * where 'name' is the name of the addon.
16 * If the addon is removed from the configuration list, the
17 * system will call the name_uninstall() function.
20 * 1.1 : addon crashed on php versions >= 5.4 as of removed deprecated call-time
21 * pass-by-reference used in function calls within function windowsphonepush_content
22 * 2.0 : adaption for supporting emphasizing new entries in app (count on tile cannot be read out,
23 * so we need to retrieve counter through show_settings secondly). Provide new function for
24 * calling from app to set the counter back after start (if user starts again before cronjob
25 * sets the counter back
26 * count only unseen elements which are not type=activity (likes and dislikes not seen as new elements)
30 use Friendica\Content\Text\BBCode;
31 use Friendica\Content\Text\HTML;
32 use Friendica\Core\Addon;
33 use Friendica\Core\L10n;
34 use Friendica\Core\PConfig;
35 use Friendica\Model\User;
36 use Friendica\Model\Item;
38 function windowsphonepush_install()
40 /* Our addon will attach in three places.
41 * The first is within cron - so the push notifications will be
42 * sent every 10 minutes (or whatever is set in crontab).
44 Addon::registerHook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
46 /* Then we'll attach into the addon settings page, and also the
47 * settings post hook so that we can create and update
48 * user preferences. User shall be able to activate the addon and
49 * define whether he allows pushing first characters of item text
51 Addon::registerHook('addon_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
52 Addon::registerHook('addon_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
54 logger("installed windowsphonepush");
57 function windowsphonepush_uninstall()
59 /* uninstall unregisters any hooks created with register_hook
60 * during install. Don't delete data in table `pconfig`.
62 Addon::unregisterHook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
63 Addon::unregisterHook('addon_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
64 Addon::unregisterHook('addon_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
66 logger("removed windowsphonepush");
69 /* declare the windowsphonepush function so that /windowsphonepush url requests will land here */
70 function windowsphonepush_module()
75 /* Callback from the settings post function.
76 * $post contains the $_POST array.
77 * We will make sure we've got a valid user account
78 * and if so set our configuration setting for this person.
80 function windowsphonepush_settings_post($a, $post)
82 if (!local_user() || (!x($_POST, 'windowsphonepush-submit'))) {
85 $enable = intval($_POST['windowsphonepush']);
86 PConfig::set(local_user(), 'windowsphonepush', 'enable', $enable);
89 PConfig::set(local_user(), 'windowsphonepush', 'counterunseen', 0);
92 PConfig::set(local_user(), 'windowsphonepush', 'senditemtext', intval($_POST['windowsphonepush-senditemtext']));
94 info(L10n::t('WindowsPhonePush settings updated.') . EOL);
97 /* Called from the Addon Setting form.
98 * Add our own settings info to the page.
100 function windowsphonepush_settings(&$a, &$s)
106 /* Add our stylesheet to the page so we can make our settings look nice */
107 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/windowsphonepush/windowsphonepush.css' . '" media="all" />' . "\r\n";
109 /* Get the current state of our config variables */
110 $enabled = PConfig::get(local_user(), 'windowsphonepush', 'enable');
111 $checked_enabled = (($enabled) ? ' checked="checked" ' : '');
113 $senditemtext = PConfig::get(local_user(), 'windowsphonepush', 'senditemtext');
114 $checked_senditemtext = (($senditemtext) ? ' checked="checked" ' : '');
116 $device_url = PConfig::get(local_user(), 'windowsphonepush', 'device_url');
118 /* Add some HTML to the existing form */
119 $s .= '<div class="settings-block">';
120 $s .= '<h3>' . L10n::t('WindowsPhonePush Settings') . '</h3>';
122 $s .= '<div id="windowsphonepush-enable-wrapper">';
123 $s .= '<label id="windowsphonepush-enable-label" for="windowsphonepush-enable-chk">' . L10n::t('Enable WindowsPhonePush Addon') . '</label>';
124 $s .= '<input id="windowsphonepush-enable-chk" type="checkbox" name="windowsphonepush" value="1" ' . $checked_enabled . '/>';
125 $s .= '</div><div class="clear"></div>';
127 $s .= '<div id="windowsphonepush-senditemtext-wrapper">';
128 $s .= '<label id="windowsphonepush-senditemtext-label" for="windowsphonepush-senditemtext-chk">' . L10n::t('Push text of new item') . '</label>';
129 $s .= '<input id="windowsphonepush-senditemtext-chk" type="checkbox" name="windowsphonepush-senditemtext" value="1" ' . $checked_senditemtext . '/>';
130 $s .= '</div><div class="clear"></div>';
132 /* provide a submit button - enable und senditemtext can be changed by the user */
133 $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="windowsphonepush-submit" name="windowsphonepush-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div><div class="clear"></div>';
135 /* provide further read-only information concerning the addon (useful for */
136 $s .= '<div id="windowsphonepush-device_url-wrapper">';
137 $s .= '<label id="windowsphonepush-device_url-label" for="windowsphonepush-device_url-text">Device-URL</label>';
138 $s .= '<input id="windowsphonepush-device_url-text" type="text" readonly value=' . $device_url . '/>';
139 $s .= '</div><div class="clear"></div></div>';
144 /* Cron function used to regularly check all users on the server with active windowsphonepushaddon and send
145 * notifications to the Microsoft servers and consequently to the Windows Phone device
147 function windowsphonepush_cron()
149 // retrieve all UID's for which the addon windowsphonepush is enabled and loop through every user
150 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'windowsphonepush' AND `k` = 'enable' AND `v` = 1");
152 foreach ($r as $rr) {
153 // load stored information for the user-id of the current loop
154 $device_url = PConfig::get($rr['uid'], 'windowsphonepush', 'device_url');
155 $lastpushid = PConfig::get($rr['uid'], 'windowsphonepush', 'lastpushid');
157 // pushing only possible if device_url (the URI on Microsoft server) is available or not "NA" (which will be sent
158 // by app if user has switched the server setting in app - sending blank not possible as this would return an update error)
159 if (( $device_url == "" ) || ( $device_url == "NA" )) {
160 // no Device-URL for the user availabe, but addon is enabled --> write info to Logger
161 logger("WARN: windowsphonepush is enable for user " . $rr['uid'] . ", but no Device-URL is specified for the user.");
163 // retrieve the number of unseen items and the id of the latest one (if there are more than
164 // one new entries since last poller run, only the latest one will be pushed)
165 $count = q("SELECT count(`id`) as count, max(`id`) as max FROM `item` WHERE `unseen` = 1 AND `type` <> 'activity' AND `uid` = %d", intval($rr['uid']));
167 // send number of unseen items to the device (the number will be displayed on Start screen until
168 // App will be started by user) - this update will be sent every 10 minutes to update the number to 0 if
169 // user has loaded the timeline through app or website
170 $res_tile = send_tile_update($device_url, "", $count[0]['count'], "");
171 switch (trim($res_tile)) {
173 // ok, count has been pushed, let's save it in personal settings
174 PConfig::set($rr['uid'], 'windowsphonepush', 'counterunseen', $count[0]['count']);
177 // maximum of 30 messages reached, server rejects any further push notification until device reconnects
178 logger("INFO: Device-URL '" . $device_url . "' returns a QueueFull.");
181 // notification received and dropped as something in app was not enabled
182 logger("WARN. Device-URL '" . $device_url . "' returns a Suppressed. Unexpected error in Mobile App?");
185 // mostly combines with Expired, in that case Device-URL will be deleted from pconfig (function send_push)
188 // error, mostly called by "" which means that the url (not "" which has been checked)
189 // didn't not received Microsoft Notification Server -> wrong url
190 logger("ERROR: specified Device-URL '" . $device_url . "' didn't produced any response.");
193 // additionally user receives the text of the newest item (function checks against last successfully pushed item)
194 if (intval($count[0]['max']) > intval($lastpushid)) {
195 // user can define if he wants to see the text of the item in the push notification
196 // this has been implemented as the device_url is not a https uri (not so secure)
197 $senditemtext = PConfig::get($rr['uid'], 'windowsphonepush', 'senditemtext');
198 if ($senditemtext == 1) {
199 // load item with the max id
200 $item = Item::selectFirst(['author-name', 'body'], ['id' => $count[0]['max']]);
202 // as user allows to send the item, we want to show the sender of the item in the toast
203 // toasts are limited to one line, therefore place is limited - author shall be in
204 // max. 15 chars (incl. dots); author is displayed in bold font
205 $author = $item['author-name'];
206 $author = ((strlen($author) > 12) ? substr($author, 0, 12) . "..." : $author);
208 // normally we show the body of the item, however if it is an url or an image we cannot
209 // show this in the toast (only test), therefore changing to an alternate text
210 // Otherwise BBcode-Tags will be eliminated and plain text cutted to 140 chars (incl. dots)
211 // BTW: information only possible in English
212 $body = $item['body'];
213 if (substr($body, 0, 4) == "[url") {
214 $body = "URL/Image ...";
216 $body = BBCode::convert($body, false, 2, true);
217 $body = HTML::toPlaintext($body, 0);
218 $body = ((strlen($body) > 137) ? substr($body, 0, 137) . "..." : $body);
221 // if user wishes higher privacy, we only display "Friendica - New timeline entry arrived"
222 $author = "Friendica";
223 $body = "New timeline entry arrived ...";
225 // only if toast push notification returns the Notification status "Received" we will update th settings with the
226 // new indicator max-id is checked against (QueueFull, Suppressed, N/A, Dropped shall qualify to resend
227 // the push notification some minutes later (BTW: if resulting in Expired for subscription status the
228 // device_url will be deleted (no further try on this url, see send_push)
229 // further log information done on count pushing with send_tile (see above)
230 $res_toast = send_toast($device_url, $author, $body);
231 if (trim($res_toast) === 'Received') {
232 PConfig::set($rr['uid'], 'windowsphonepush', 'lastpushid', $count[0]['max']);
240 /* Tile push notification change the number in the icon of the App in Start Screen of
241 * a Windows Phone Device, Image could be changed, not used for App "Friendica Mobile"
243 function send_tile_update($device_url, $image_url, $count, $title, $priority = 1)
245 $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
246 "<wp:Notification xmlns:wp=\"WPNotification\">" .
248 "<wp:BackgroundImage>" . $image_url . "</wp:BackgroundImage>" .
249 "<wp:Count>" . $count . "</wp:Count>" .
250 "<wp:Title>" . $title . "</wp:Title>" .
252 "</wp:Notification>";
254 $result = send_push($device_url, [
255 'X-WindowsPhone-Target: token',
256 'X-NotificationClass: ' . $priority,
261 /* Toast push notification send information to the top of the display
262 * if the user is not currently using the Friendica Mobile App, however
263 * there is only one line for displaying the information
265 function send_toast($device_url, $title, $message, $priority = 2)
267 $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
268 "<wp:Notification xmlns:wp=\"WPNotification\">" .
270 "<wp:Text1>" . $title . "</wp:Text1>" .
271 "<wp:Text2>" . $message . "</wp:Text2>" .
272 "<wp:Param></wp:Param>" .
274 "</wp:Notification>";
276 $result = send_push($device_url, [
277 'X-WindowsPhone-Target: toast',
278 'X-NotificationClass: ' . $priority,
283 // General function to send the push notification via cURL
284 function send_push($device_url, $headers, $msg)
287 curl_setopt($ch, CURLOPT_URL, $device_url);
288 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
289 curl_setopt($ch, CURLOPT_POST, true);
290 curl_setopt($ch, CURLOPT_HEADER, true);
291 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers + [
292 'Content-Type: text/xml',
294 'Accept: application/*',
297 curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
299 $output = curl_exec($ch);
302 // if we received "Expired" from Microsoft server we will delete the obsolete device-URL
304 $subscriptionStatus = get_header_value($output, 'X-SubscriptionStatus');
305 if ($subscriptionStatus == "Expired") {
306 PConfig::set(local_user(), 'windowsphonepush', 'device_url', "");
307 logger("ERROR: the stored Device-URL " . $device_url . "returned an 'Expired' error, it has been deleted now.");
310 // the notification status shall be returned to windowsphonepush_cron (will
311 // update settings if 'Received' otherwise keep old value in settings (on QueuedFull. Suppressed, N/A, Dropped)
312 $notificationStatus = get_header_value($output, 'X-NotificationStatus');
313 return $notificationStatus;
316 // helper function to receive statuses from webresponse of Microsoft server
317 function get_header_value($content, $header)
319 return preg_match_all("/$header: (.*)/i", $content, $match) ? $match[1][0] : "";
322 /* reading information from url and deciding which function to start
323 * show_settings = delivering settings to check
324 * update_settings = set the device_url
325 * update_counterunseen = set counter for unseen elements to zero
327 function windowsphonepush_content(App $a)
329 // Login with the specified Network credentials (like in api.php)
330 windowsphonepush_login($a);
333 $path2 = $a->argv[1];
334 if ($path == "windowsphonepush") {
336 case "show_settings":
337 windowsphonepush_showsettings($a);
340 case "update_settings":
341 $ret = windowsphonepush_updatesettings($a);
342 header("Content-Type: application/json; charset=utf-8");
343 echo json_encode(['status' => $ret]);
346 case "update_counterunseen":
347 $ret = windowsphonepush_updatecounterunseen();
348 header("Content-Type: application/json; charset=utf-8");
349 echo json_encode(['status' => $ret]);
358 // return settings for windowsphonepush addon to be able to check them in WP app
359 function windowsphonepush_showsettings()
365 $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
366 $device_url = PConfig::get(local_user(), 'windowsphonepush', 'device_url');
367 $senditemtext = PConfig::get(local_user(), 'windowsphonepush', 'senditemtext');
368 $lastpushid = PConfig::get(local_user(), 'windowsphonepush', 'lastpushid');
369 $counterunseen = PConfig::get(local_user(), 'windowsphonepush', 'counterunseen');
370 $addonversion = "2.0";
380 header("Content-Type: application/json");
381 echo json_encode(['uid' => local_user(),
383 'device_url' => $device_url,
384 'senditemtext' => $senditemtext,
385 'lastpushid' => $lastpushid,
386 'counterunseen' => $counterunseen,
387 'addonversion' => $addonversion]);
390 /* update_settings is used to transfer the device_url from WP device to the Friendica server
391 * return the status of the operation to the server
393 function windowsphonepush_updatesettings()
396 return "Not Authenticated";
399 // no updating if user hasn't enabled the addon
400 $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
402 return "Plug-in not enabled";
405 // check if sent url is empty - don't save and send return code to app
406 $device_url = $_POST['deviceurl'];
407 if ($device_url == "") {
408 logger("ERROR: no valid Device-URL specified - client transferred '" . $device_url . "'");
409 return "No valid Device-URL specified";
412 // check if sent url is already stored in database for another user, we assume that there was a change of
413 // the user on the Windows Phone device and that device url is no longer true for the other user, so we
414 // et the device_url for the OTHER user blank (should normally not occur as App should include User/server
415 // in url request to Microsoft Push Notification server)
416 $r = q("SELECT * FROM `pconfig` WHERE `uid` <> " . local_user() . " AND
417 `cat` = 'windowsphonepush' AND
418 `k` = 'device_url' AND
419 `v` = '" . $device_url . "'");
421 foreach ($r as $rr) {
422 PConfig::set($rr['uid'], 'windowsphonepush', 'device_url', '');
423 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() . "'.");
427 PConfig::set(local_user(), 'windowsphonepush', 'device_url', $device_url);
428 // output the successfull update of the device URL to the logger for error analysis if necessary
429 logger("INFO: Device-URL for user '" . local_user() . "' has been updated with '" . $device_url . "'");
430 return "Device-URL updated successfully!";
433 // update_counterunseen is used to reset the counter to zero from Windows Phone app
434 function windowsphonepush_updatecounterunseen()
437 return "Not Authenticated";
440 // no updating if user hasn't enabled the addon
441 $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
443 return "Plug-in not enabled";
446 PConfig::set(local_user(), 'windowsphonepush', 'counterunseen', 0);
447 return "Counter set to zero";
450 /* helper function to login to the server with the specified Network credentials
451 * (mainly copied from api.php)
453 function windowsphonepush_login(App $a)
455 if (!isset($_SERVER['PHP_AUTH_USER'])) {
456 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
457 header('WWW-Authenticate: Basic realm="Friendica"');
458 header('HTTP/1.0 401 Unauthorized');
459 die('This api requires login');
462 $user_id = User::authenticate($_SERVER['PHP_AUTH_USER'], trim($_SERVER['PHP_AUTH_PW']));
465 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
467 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
468 header('WWW-Authenticate: Basic realm="Friendica"');
469 header('HTTP/1.0 401 Unauthorized');
470 die('This api requires login');
473 require_once 'include/security.php';
474 authenticate_success($record);
475 $_SESSION["allow_api"] = true;
476 Addon::callHooks('logged_in', $a->user);