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\Authentication;
34 use Friendica\Core\L10n;
35 use Friendica\Core\Logger;
36 use Friendica\Core\PConfig;
37 use Friendica\Database\DBA;
38 use Friendica\Model\Item;
39 use Friendica\Model\User;
41 function windowsphonepush_install()
43 /* Our addon will attach in three places.
44 * The first is within cron - so the push notifications will be
45 * sent every 10 minutes (or whatever is set in crontab).
47 Addon::registerHook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
49 /* Then we'll attach into the addon settings page, and also the
50 * settings post hook so that we can create and update
51 * user preferences. User shall be able to activate the addon and
52 * define whether he allows pushing first characters of item text
54 Addon::registerHook('addon_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
55 Addon::registerHook('addon_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
57 Logger::log("installed windowsphonepush");
60 function windowsphonepush_uninstall()
62 /* uninstall unregisters any hooks created with register_hook
63 * during install. Don't delete data in table `pconfig`.
65 Addon::unregisterHook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
66 Addon::unregisterHook('addon_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
67 Addon::unregisterHook('addon_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
69 Logger::log("removed windowsphonepush");
72 /* declare the windowsphonepush function so that /windowsphonepush url requests will land here */
73 function windowsphonepush_module()
78 /* Callback from the settings post function.
79 * $post contains the $_POST array.
80 * We will make sure we've got a valid user account
81 * and if so set our configuration setting for this person.
83 function windowsphonepush_settings_post($a, $post)
85 if (!local_user() || (!x($_POST, 'windowsphonepush-submit'))) {
88 $enable = intval($_POST['windowsphonepush']);
89 PConfig::set(local_user(), 'windowsphonepush', 'enable', $enable);
92 PConfig::set(local_user(), 'windowsphonepush', 'counterunseen', 0);
95 PConfig::set(local_user(), 'windowsphonepush', 'senditemtext', intval($_POST['windowsphonepush-senditemtext']));
97 info(L10n::t('WindowsPhonePush settings updated.') . EOL);
100 /* Called from the Addon Setting form.
101 * Add our own settings info to the page.
103 function windowsphonepush_settings(&$a, &$s)
109 /* Add our stylesheet to the page so we can make our settings look nice */
110 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/windowsphonepush/windowsphonepush.css' . '" media="all" />' . "\r\n";
112 /* Get the current state of our config variables */
113 $enabled = PConfig::get(local_user(), 'windowsphonepush', 'enable');
114 $checked_enabled = (($enabled) ? ' checked="checked" ' : '');
116 $senditemtext = PConfig::get(local_user(), 'windowsphonepush', 'senditemtext');
117 $checked_senditemtext = (($senditemtext) ? ' checked="checked" ' : '');
119 $device_url = PConfig::get(local_user(), 'windowsphonepush', 'device_url');
121 /* Add some HTML to the existing form */
122 $s .= '<div class="settings-block">';
123 $s .= '<h3>' . L10n::t('WindowsPhonePush Settings') . '</h3>';
125 $s .= '<div id="windowsphonepush-enable-wrapper">';
126 $s .= '<label id="windowsphonepush-enable-label" for="windowsphonepush-enable-chk">' . L10n::t('Enable WindowsPhonePush Addon') . '</label>';
127 $s .= '<input id="windowsphonepush-enable-chk" type="checkbox" name="windowsphonepush" value="1" ' . $checked_enabled . '/>';
128 $s .= '</div><div class="clear"></div>';
130 $s .= '<div id="windowsphonepush-senditemtext-wrapper">';
131 $s .= '<label id="windowsphonepush-senditemtext-label" for="windowsphonepush-senditemtext-chk">' . L10n::t('Push text of new item') . '</label>';
132 $s .= '<input id="windowsphonepush-senditemtext-chk" type="checkbox" name="windowsphonepush-senditemtext" value="1" ' . $checked_senditemtext . '/>';
133 $s .= '</div><div class="clear"></div>';
135 /* provide a submit button - enable und senditemtext can be changed by the user */
136 $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>';
138 /* provide further read-only information concerning the addon (useful for */
139 $s .= '<div id="windowsphonepush-device_url-wrapper">';
140 $s .= '<label id="windowsphonepush-device_url-label" for="windowsphonepush-device_url-text">Device-URL</label>';
141 $s .= '<input id="windowsphonepush-device_url-text" type="text" readonly value=' . $device_url . '/>';
142 $s .= '</div><div class="clear"></div></div>';
147 /* Cron function used to regularly check all users on the server with active windowsphonepushaddon and send
148 * notifications to the Microsoft servers and consequently to the Windows Phone device
150 function windowsphonepush_cron()
152 // retrieve all UID's for which the addon windowsphonepush is enabled and loop through every user
153 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'windowsphonepush' AND `k` = 'enable' AND `v` = 1");
155 foreach ($r as $rr) {
156 // load stored information for the user-id of the current loop
157 $device_url = PConfig::get($rr['uid'], 'windowsphonepush', 'device_url');
158 $lastpushid = PConfig::get($rr['uid'], 'windowsphonepush', 'lastpushid');
160 // pushing only possible if device_url (the URI on Microsoft server) is available or not "NA" (which will be sent
161 // by app if user has switched the server setting in app - sending blank not possible as this would return an update error)
162 if (( $device_url == "" ) || ( $device_url == "NA" )) {
163 // no Device-URL for the user availabe, but addon is enabled --> write info to Logger
164 Logger::log("WARN: windowsphonepush is enable for user " . $rr['uid'] . ", but no Device-URL is specified for the user.");
166 // retrieve the number of unseen items and the id of the latest one (if there are more than
167 // one new entries since last poller run, only the latest one will be pushed)
168 $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']));
170 // send number of unseen items to the device (the number will be displayed on Start screen until
171 // App will be started by user) - this update will be sent every 10 minutes to update the number to 0 if
172 // user has loaded the timeline through app or website
173 $res_tile = send_tile_update($device_url, "", $count[0]['count'], "");
174 switch (trim($res_tile)) {
176 // ok, count has been pushed, let's save it in personal settings
177 PConfig::set($rr['uid'], 'windowsphonepush', 'counterunseen', $count[0]['count']);
180 // maximum of 30 messages reached, server rejects any further push notification until device reconnects
181 Logger::log("INFO: Device-URL '" . $device_url . "' returns a QueueFull.");
184 // notification received and dropped as something in app was not enabled
185 Logger::log("WARN. Device-URL '" . $device_url . "' returns a Suppressed. Unexpected error in Mobile App?");
188 // mostly combines with Expired, in that case Device-URL will be deleted from pconfig (function send_push)
191 // error, mostly called by "" which means that the url (not "" which has been checked)
192 // didn't not received Microsoft Notification Server -> wrong url
193 Logger::log("ERROR: specified Device-URL '" . $device_url . "' didn't produced any response.");
196 // additionally user receives the text of the newest item (function checks against last successfully pushed item)
197 if (intval($count[0]['max']) > intval($lastpushid)) {
198 // user can define if he wants to see the text of the item in the push notification
199 // this has been implemented as the device_url is not a https uri (not so secure)
200 $senditemtext = PConfig::get($rr['uid'], 'windowsphonepush', 'senditemtext');
201 if ($senditemtext == 1) {
202 // load item with the max id
203 $item = Item::selectFirst(['author-name', 'body'], ['id' => $count[0]['max']]);
205 // as user allows to send the item, we want to show the sender of the item in the toast
206 // toasts are limited to one line, therefore place is limited - author shall be in
207 // max. 15 chars (incl. dots); author is displayed in bold font
208 $author = $item['author-name'];
209 $author = ((strlen($author) > 12) ? substr($author, 0, 12) . "..." : $author);
211 // normally we show the body of the item, however if it is an url or an image we cannot
212 // show this in the toast (only test), therefore changing to an alternate text
213 // Otherwise BBcode-Tags will be eliminated and plain text cutted to 140 chars (incl. dots)
214 // BTW: information only possible in English
215 $body = $item['body'];
216 if (substr($body, 0, 4) == "[url") {
217 $body = "URL/Image ...";
219 $body = BBCode::convert($body, false, 2, true);
220 $body = HTML::toPlaintext($body, 0);
221 $body = ((strlen($body) > 137) ? substr($body, 0, 137) . "..." : $body);
224 // if user wishes higher privacy, we only display "Friendica - New timeline entry arrived"
225 $author = "Friendica";
226 $body = "New timeline entry arrived ...";
228 // only if toast push notification returns the Notification status "Received" we will update th settings with the
229 // new indicator max-id is checked against (QueueFull, Suppressed, N/A, Dropped shall qualify to resend
230 // the push notification some minutes later (BTW: if resulting in Expired for subscription status the
231 // device_url will be deleted (no further try on this url, see send_push)
232 // further log information done on count pushing with send_tile (see above)
233 $res_toast = send_toast($device_url, $author, $body);
234 if (trim($res_toast) === 'Received') {
235 PConfig::set($rr['uid'], 'windowsphonepush', 'lastpushid', $count[0]['max']);
243 /* Tile push notification change the number in the icon of the App in Start Screen of
244 * a Windows Phone Device, Image could be changed, not used for App "Friendica Mobile"
246 function send_tile_update($device_url, $image_url, $count, $title, $priority = 1)
248 $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
249 "<wp:Notification xmlns:wp=\"WPNotification\">" .
251 "<wp:BackgroundImage>" . $image_url . "</wp:BackgroundImage>" .
252 "<wp:Count>" . $count . "</wp:Count>" .
253 "<wp:Title>" . $title . "</wp:Title>" .
255 "</wp:Notification>";
257 $result = send_push($device_url, [
258 'X-WindowsPhone-Target: token',
259 'X-NotificationClass: ' . $priority,
264 /* Toast push notification send information to the top of the display
265 * if the user is not currently using the Friendica Mobile App, however
266 * there is only one line for displaying the information
268 function send_toast($device_url, $title, $message, $priority = 2)
270 $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
271 "<wp:Notification xmlns:wp=\"WPNotification\">" .
273 "<wp:Text1>" . $title . "</wp:Text1>" .
274 "<wp:Text2>" . $message . "</wp:Text2>" .
275 "<wp:Param></wp:Param>" .
277 "</wp:Notification>";
279 $result = send_push($device_url, [
280 'X-WindowsPhone-Target: toast',
281 'X-NotificationClass: ' . $priority,
286 // General function to send the push notification via cURL
287 function send_push($device_url, $headers, $msg)
290 curl_setopt($ch, CURLOPT_URL, $device_url);
291 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
292 curl_setopt($ch, CURLOPT_POST, true);
293 curl_setopt($ch, CURLOPT_HEADER, true);
294 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers + [
295 'Content-Type: text/xml',
297 'Accept: application/*',
300 curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
302 $output = curl_exec($ch);
305 // if we received "Expired" from Microsoft server we will delete the obsolete device-URL
307 $subscriptionStatus = get_header_value($output, 'X-SubscriptionStatus');
308 if ($subscriptionStatus == "Expired") {
309 PConfig::set(local_user(), 'windowsphonepush', 'device_url', "");
310 Logger::log("ERROR: the stored Device-URL " . $device_url . "returned an 'Expired' error, it has been deleted now.");
313 // the notification status shall be returned to windowsphonepush_cron (will
314 // update settings if 'Received' otherwise keep old value in settings (on QueuedFull. Suppressed, N/A, Dropped)
315 $notificationStatus = get_header_value($output, 'X-NotificationStatus');
316 return $notificationStatus;
319 // helper function to receive statuses from webresponse of Microsoft server
320 function get_header_value($content, $header)
322 return preg_match_all("/$header: (.*)/i", $content, $match) ? $match[1][0] : "";
325 /* reading information from url and deciding which function to start
326 * show_settings = delivering settings to check
327 * update_settings = set the device_url
328 * update_counterunseen = set counter for unseen elements to zero
330 function windowsphonepush_content(App $a)
332 // Login with the specified Network credentials (like in api.php)
333 windowsphonepush_login($a);
336 $path2 = $a->argv[1];
337 if ($path == "windowsphonepush") {
339 case "show_settings":
340 windowsphonepush_showsettings($a);
343 case "update_settings":
344 $ret = windowsphonepush_updatesettings($a);
345 header("Content-Type: application/json; charset=utf-8");
346 echo json_encode(['status' => $ret]);
349 case "update_counterunseen":
350 $ret = windowsphonepush_updatecounterunseen();
351 header("Content-Type: application/json; charset=utf-8");
352 echo json_encode(['status' => $ret]);
361 // return settings for windowsphonepush addon to be able to check them in WP app
362 function windowsphonepush_showsettings()
368 $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
369 $device_url = PConfig::get(local_user(), 'windowsphonepush', 'device_url');
370 $senditemtext = PConfig::get(local_user(), 'windowsphonepush', 'senditemtext');
371 $lastpushid = PConfig::get(local_user(), 'windowsphonepush', 'lastpushid');
372 $counterunseen = PConfig::get(local_user(), 'windowsphonepush', 'counterunseen');
373 $addonversion = "2.0";
383 header("Content-Type: application/json");
384 echo json_encode(['uid' => local_user(),
386 'device_url' => $device_url,
387 'senditemtext' => $senditemtext,
388 'lastpushid' => $lastpushid,
389 'counterunseen' => $counterunseen,
390 'addonversion' => $addonversion]);
393 /* update_settings is used to transfer the device_url from WP device to the Friendica server
394 * return the status of the operation to the server
396 function windowsphonepush_updatesettings()
399 return "Not Authenticated";
402 // no updating if user hasn't enabled the addon
403 $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
405 return "Plug-in not enabled";
408 // check if sent url is empty - don't save and send return code to app
409 $device_url = $_POST['deviceurl'];
410 if ($device_url == "") {
411 Logger::log("ERROR: no valid Device-URL specified - client transferred '" . $device_url . "'");
412 return "No valid Device-URL specified";
415 // check if sent url is already stored in database for another user, we assume that there was a change of
416 // the user on the Windows Phone device and that device url is no longer true for the other user, so we
417 // et the device_url for the OTHER user blank (should normally not occur as App should include User/server
418 // in url request to Microsoft Push Notification server)
419 $r = q("SELECT * FROM `pconfig` WHERE `uid` <> " . local_user() . " AND
420 `cat` = 'windowsphonepush' AND
421 `k` = 'device_url' AND
422 `v` = '" . $device_url . "'");
424 foreach ($r as $rr) {
425 PConfig::set($rr['uid'], 'windowsphonepush', 'device_url', '');
426 Logger::log("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() . "'.");
430 PConfig::set(local_user(), 'windowsphonepush', 'device_url', $device_url);
431 // output the successfull update of the device URL to the logger for error analysis if necessary
432 Logger::log("INFO: Device-URL for user '" . local_user() . "' has been updated with '" . $device_url . "'");
433 return "Device-URL updated successfully!";
436 // update_counterunseen is used to reset the counter to zero from Windows Phone app
437 function windowsphonepush_updatecounterunseen()
440 return "Not Authenticated";
443 // no updating if user hasn't enabled the addon
444 $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
446 return "Plug-in not enabled";
449 PConfig::set(local_user(), 'windowsphonepush', 'counterunseen', 0);
450 return "Counter set to zero";
453 /* helper function to login to the server with the specified Network credentials
454 * (mainly copied from api.php)
456 function windowsphonepush_login(App $a)
458 if (!isset($_SERVER['PHP_AUTH_USER'])) {
459 Logger::log('API_login: ' . print_r($_SERVER, true), Logger::DEBUG);
460 header('WWW-Authenticate: Basic realm="Friendica"');
461 header('HTTP/1.0 401 Unauthorized');
462 die('This api requires login');
465 $user_id = User::authenticate($_SERVER['PHP_AUTH_USER'], trim($_SERVER['PHP_AUTH_PW']));
468 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
470 Logger::log('API_login failure: ' . print_r($_SERVER, true), Logger::DEBUG);
471 header('WWW-Authenticate: Basic realm="Friendica"');
472 header('HTTP/1.0 401 Unauthorized');
473 die('This api requires login');
476 Authentication::setAuthenticatedSessionForUser($record);
477 $_SESSION["allow_api"] = true;
478 Addon::callHooks('logged_in', $a->user);