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\Hook;
33 use Friendica\Core\Logger;
34 use Friendica\Core\Renderer;
35 use Friendica\Database\DBA;
37 use Friendica\Model\Item;
38 use Friendica\Model\Post;
39 use Friendica\Model\User;
40 use Friendica\Network\HTTPException\UnauthorizedException;
42 function windowsphonepush_install()
44 /* Our addon will attach in three places.
45 * The first is within cron - so the push notifications will be
46 * sent every 10 minutes (or whatever is set in crontab).
48 Hook::register('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
50 /* Then we'll attach into the addon settings page, and also the
51 * settings post hook so that we can create and update
52 * user preferences. User shall be able to activate the addon and
53 * define whether he allows pushing first characters of item text
55 Hook::register('addon_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
56 Hook::register('addon_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
58 Logger::notice("installed windowsphonepush");
61 /* declare the windowsphonepush function so that /windowsphonepush url requests will land here */
62 function windowsphonepush_module()
67 /* Callback from the settings post function.
68 * $post contains the $_POST array.
69 * We will make sure we've got a valid user account
70 * and if so set our configuration setting for this person.
72 function windowsphonepush_settings_post($a, $post)
74 if (!local_user() || empty($_POST['windowsphonepush-submit'])) {
77 $enable = intval($_POST['windowsphonepush']);
78 DI::pConfig()->set(local_user(), 'windowsphonepush', 'enable', $enable);
81 DI::pConfig()->set(local_user(), 'windowsphonepush', 'counterunseen', 0);
84 DI::pConfig()->set(local_user(), 'windowsphonepush', 'senditemtext', intval($_POST['windowsphonepush-senditemtext']));
87 /* Called from the Addon Setting form.
88 * Add our own settings info to the page.
90 function windowsphonepush_settings(App &$a, array &$data)
96 $enabled = DI::pConfig()->get(local_user(), 'windowsphonepush', 'enable');
97 $senditemtext = DI::pConfig()->get(local_user(), 'windowsphonepush', 'senditemtext');
98 $device_url = DI::pConfig()->get(local_user(), 'windowsphonepush', 'device_url');
100 $t = Renderer::getMarkupTemplate('settings.tpl', 'addon/windowsphonepush/');
101 $html = Renderer::replaceMacros($t, [
102 '$enabled' => ['windowsphonepush', DI::l10n()->t('Enable WindowsPhonePush Addon'), $enabled],
103 '$senditemtext' => ['windowsphonepush-senditemtext', DI::l10n()->t('Push text of new item'), $senditemtext],
104 '$device_url' => ['', DI::l10n()->t('Device URL'), $device_url, '', false, ' readonly'],
108 'addon' => 'windowsphonepush',
109 'title' => DI::l10n()->t('WindowsPhonePush Settings'),
114 /* Cron function used to regularly check all users on the server with active windowsphonepushaddon and send
115 * notifications to the Microsoft servers and consequently to the Windows Phone device
117 function windowsphonepush_cron()
119 // retrieve all UID's for which the addon windowsphonepush is enabled and loop through every user
120 $pconfigs = DBA::selectToArray('pconfig', ['uid'], ['cat' => 'windowsphonepush', 'k' => 'enable', 'v' => true]);
121 foreach ($pconfigs as $rr) {
122 // load stored information for the user-id of the current loop
123 $device_url = DI::pConfig()->get($rr['uid'], 'windowsphonepush', 'device_url');
124 $lastpushid = DI::pConfig()->get($rr['uid'], 'windowsphonepush', 'lastpushid');
126 // pushing only possible if device_url (the URI on Microsoft server) is available or not "NA" (which will be sent
127 // by app if user has switched the server setting in app - sending blank not possible as this would return an update error)
128 if (( $device_url == "" ) || ( $device_url == "NA" )) {
129 // no Device-URL for the user availabe, but addon is enabled --> write info to Logger
130 Logger::notice("WARN: windowsphonepush is enable for user " . $rr['uid'] . ", but no Device-URL is specified for the user.");
132 // retrieve the number of unseen items and the id of the latest one (if there are more than
133 // one new entries since last poller run, only the latest one will be pushed)
134 $count = DBA::fetchFirst("SELECT count(`id`) AS count, max(`id`) AS max FROM `post-view` WHERE `unseen` AND `type` != ? AND `uid` = ?", 'activity', $rr['uid']);
136 // send number of unseen items to the device (the number will be displayed on Start screen until
137 // App will be started by user) - this update will be sent every 10 minutes to update the number to 0 if
138 // user has loaded the timeline through app or website
139 $res_tile = send_tile_update($device_url, "", $count['count'], "");
140 switch (trim($res_tile)) {
142 // ok, count has been pushed, let's save it in personal settings
143 DI::pConfig()->set($rr['uid'], 'windowsphonepush', 'counterunseen', $count['count']);
146 // maximum of 30 messages reached, server rejects any further push notification until device reconnects
147 Logger::notice("INFO: Device-URL '" . $device_url . "' returns a QueueFull.");
150 // notification received and dropped as something in app was not enabled
151 Logger::notice("WARN. Device-URL '" . $device_url . "' returns a Suppressed. Unexpected error in Mobile App?");
154 // mostly combines with Expired, in that case Device-URL will be deleted from pconfig (function send_push)
157 // error, mostly called by "" which means that the url (not "" which has been checked)
158 // didn't not received Microsoft Notification Server -> wrong url
159 Logger::notice("ERROR: specified Device-URL '" . $device_url . "' didn't produced any response.");
162 // additionally user receives the text of the newest item (function checks against last successfully pushed item)
163 if (intval($count['max']) > intval($lastpushid)) {
164 // user can define if he wants to see the text of the item in the push notification
165 // this has been implemented as the device_url is not a https uri (not so secure)
166 $senditemtext = DI::pConfig()->get($rr['uid'], 'windowsphonepush', 'senditemtext');
167 if ($senditemtext == 1) {
168 // load item with the max id
169 $item = Post::selectFirst(['author-name', 'body', 'uri-id'], ['id' => $count['max']]);
171 // as user allows to send the item, we want to show the sender of the item in the toast
172 // toasts are limited to one line, therefore place is limited - author shall be in
173 // max. 15 chars (incl. dots); author is displayed in bold font
174 $author = $item['author-name'];
175 $author = ((strlen($author) > 12) ? substr($author, 0, 12) . "..." : $author);
177 // normally we show the body of the item, however if it is an url or an image we cannot
178 // show this in the toast (only test), therefore changing to an alternate text
179 // Otherwise BBcode-Tags will be eliminated and plain text cutted to 140 chars (incl. dots)
180 // BTW: information only possible in English
181 $body = $item['body'];
182 if (substr($body, 0, 4) == "[url") {
183 $body = "URL/Image ...";
185 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::API);
186 $body = HTML::toPlaintext($body, 0);
187 $body = ((strlen($body) > 137) ? substr($body, 0, 137) . "..." : $body);
190 // if user wishes higher privacy, we only display "Friendica - New timeline entry arrived"
191 $author = "Friendica";
192 $body = "New timeline entry arrived ...";
194 // only if toast push notification returns the Notification status "Received" we will update th settings with the
195 // new indicator max-id is checked against (QueueFull, Suppressed, N/A, Dropped shall qualify to resend
196 // the push notification some minutes later (BTW: if resulting in Expired for subscription status the
197 // device_url will be deleted (no further try on this url, see send_push)
198 // further log information done on count pushing with send_tile (see above)
199 $res_toast = send_toast($device_url, $author, $body);
200 if (trim($res_toast) === 'Received') {
201 DI::pConfig()->set($rr['uid'], 'windowsphonepush', 'lastpushid', $count['max']);
208 /* Tile push notification change the number in the icon of the App in Start Screen of
209 * a Windows Phone Device, Image could be changed, not used for App "Friendica Mobile"
211 function send_tile_update($device_url, $image_url, $count, $title, $priority = 1)
213 $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
214 "<wp:Notification xmlns:wp=\"WPNotification\">" .
216 "<wp:BackgroundImage>" . $image_url . "</wp:BackgroundImage>" .
217 "<wp:Count>" . $count . "</wp:Count>" .
218 "<wp:Title>" . $title . "</wp:Title>" .
220 "</wp:Notification>";
222 $result = send_push($device_url, [
223 'X-WindowsPhone-Target: token',
224 'X-NotificationClass: ' . $priority,
229 /* Toast push notification send information to the top of the display
230 * if the user is not currently using the Friendica Mobile App, however
231 * there is only one line for displaying the information
233 function send_toast($device_url, $title, $message, $priority = 2)
235 $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
236 "<wp:Notification xmlns:wp=\"WPNotification\">" .
238 "<wp:Text1>" . $title . "</wp:Text1>" .
239 "<wp:Text2>" . $message . "</wp:Text2>" .
240 "<wp:Param></wp:Param>" .
242 "</wp:Notification>";
244 $result = send_push($device_url, [
245 'X-WindowsPhone-Target: toast',
246 'X-NotificationClass: ' . $priority,
251 // General function to send the push notification via cURL
252 function send_push($device_url, $headers, $msg)
255 curl_setopt($ch, CURLOPT_URL, $device_url);
256 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
257 curl_setopt($ch, CURLOPT_POST, true);
258 curl_setopt($ch, CURLOPT_HEADER, true);
259 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers + [
260 'Content-Type: text/xml',
262 'Accept: application/*',
265 curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
267 $output = curl_exec($ch);
270 // if we received "Expired" from Microsoft server we will delete the obsolete device-URL
272 $subscriptionStatus = get_header_value($output, 'X-SubscriptionStatus');
273 if ($subscriptionStatus == "Expired") {
274 DI::pConfig()->set(local_user(), 'windowsphonepush', 'device_url', "");
275 Logger::notice("ERROR: the stored Device-URL " . $device_url . "returned an 'Expired' error, it has been deleted now.");
278 // the notification status shall be returned to windowsphonepush_cron (will
279 // update settings if 'Received' otherwise keep old value in settings (on QueuedFull. Suppressed, N/A, Dropped)
280 $notificationStatus = get_header_value($output, 'X-NotificationStatus');
281 return $notificationStatus;
284 // helper function to receive statuses from webresponse of Microsoft server
285 function get_header_value($content, $header)
287 return preg_match_all("/$header: (.*)/i", $content, $match) ? $match[1][0] : "";
290 /* reading information from url and deciding which function to start
291 * show_settings = delivering settings to check
292 * update_settings = set the device_url
293 * update_counterunseen = set counter for unseen elements to zero
295 function windowsphonepush_content(App $a)
297 // Login with the specified Network credentials (like in api.php)
298 windowsphonepush_login($a);
300 $path = DI::args()->getArgv()[0];
301 $path2 = DI::args()->getArgv()[1];
302 if ($path == "windowsphonepush") {
304 case "show_settings":
305 windowsphonepush_showsettings($a);
308 case "update_settings":
309 $ret = windowsphonepush_updatesettings($a);
310 header("Content-Type: application/json; charset=utf-8");
311 echo json_encode(['status' => $ret]);
314 case "update_counterunseen":
315 $ret = windowsphonepush_updatecounterunseen();
316 header("Content-Type: application/json; charset=utf-8");
317 echo json_encode(['status' => $ret]);
326 // return settings for windowsphonepush addon to be able to check them in WP app
327 function windowsphonepush_showsettings()
333 $enable = DI::pConfig()->get(local_user(), 'windowsphonepush', 'enable');
334 $device_url = DI::pConfig()->get(local_user(), 'windowsphonepush', 'device_url');
335 $senditemtext = DI::pConfig()->get(local_user(), 'windowsphonepush', 'senditemtext');
336 $lastpushid = DI::pConfig()->get(local_user(), 'windowsphonepush', 'lastpushid');
337 $counterunseen = DI::pConfig()->get(local_user(), 'windowsphonepush', 'counterunseen');
338 $addonversion = "2.0";
348 header("Content-Type: application/json");
349 echo json_encode(['uid' => local_user(),
351 'device_url' => $device_url,
352 'senditemtext' => $senditemtext,
353 'lastpushid' => $lastpushid,
354 'counterunseen' => $counterunseen,
355 'addonversion' => $addonversion]);
358 /* update_settings is used to transfer the device_url from WP device to the Friendica server
359 * return the status of the operation to the server
361 function windowsphonepush_updatesettings()
364 return "Not Authenticated";
367 // no updating if user hasn't enabled the addon
368 $enable = DI::pConfig()->get(local_user(), 'windowsphonepush', 'enable');
370 return "Plug-in not enabled";
373 // check if sent url is empty - don't save and send return code to app
374 $device_url = $_POST['deviceurl'];
375 if ($device_url == "") {
376 Logger::notice("ERROR: no valid Device-URL specified - client transferred '" . $device_url . "'");
377 return "No valid Device-URL specified";
380 // check if sent url is already stored in database for another user, we assume that there was a change of
381 // the user on the Windows Phone device and that device url is no longer true for the other user, so we
382 // et the device_url for the OTHER user blank (should normally not occur as App should include User/server
383 // in url request to Microsoft Push Notification server)
384 $pconfigs = DBA::selectToArray('pconfig', ['uid'], ["`uid` != ? AND `cat` = ? AND `k` = ? AND `v` = ?", local_user(), 'windowsphonepush', 'device_url', $device_url]);
385 foreach ($pconfigs as $rr) {
386 DI::pConfig()->set($rr['uid'], 'windowsphonepush', 'device_url', '');
387 Logger::notice("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() . "'.");
390 DI::pConfig()->set(local_user(), 'windowsphonepush', 'device_url', $device_url);
391 // output the successfull update of the device URL to the logger for error analysis if necessary
392 Logger::notice("INFO: Device-URL for user '" . local_user() . "' has been updated with '" . $device_url . "'");
393 return "Device-URL updated successfully!";
396 // update_counterunseen is used to reset the counter to zero from Windows Phone app
397 function windowsphonepush_updatecounterunseen()
400 return "Not Authenticated";
403 // no updating if user hasn't enabled the addon
404 $enable = DI::pConfig()->get(local_user(), 'windowsphonepush', 'enable');
406 return "Plug-in not enabled";
409 DI::pConfig()->set(local_user(), 'windowsphonepush', 'counterunseen', 0);
410 return "Counter set to zero";
413 /* helper function to login to the server with the specified Network credentials
414 * (mainly copied from api.php)
416 function windowsphonepush_login(App $a)
418 if (!isset($_SERVER['PHP_AUTH_USER'])) {
419 Logger::info('API_login: ' . print_r($_SERVER, true));
420 header('WWW-Authenticate: Basic realm="Friendica"');
421 throw new UnauthorizedException('This api requires login');
425 $user_id = User::getIdFromPasswordAuthentication($_SERVER['PHP_AUTH_USER'], trim($_SERVER['PHP_AUTH_PW']));
426 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
427 DI::auth()->setForUser($a, $record);
428 DI::session()->set('allow_api', true);
429 Hook::callAll('logged_in', $record);
430 } catch (Exception $ex) {
431 Logger::info('API_login failure: ' . print_r($_SERVER, true));
432 header('WWW-Authenticate: Basic realm="Friendica"');
433 throw new UnauthorizedException('This api requires login');