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)
29 use Friendica\Core\Addon;
30 use Friendica\Core\PConfig;
31 use Friendica\Model\User;
33 function windowsphonepush_install()
35 /* Our addon will attach in three places.
36 * The first is within cron - so the push notifications will be
37 * sent every 10 minutes (or whatever is set in crontab).
39 Addon::registerHook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
41 /* Then we'll attach into the addon settings page, and also the
42 * settings post hook so that we can create and update
43 * user preferences. User shall be able to activate the addon and
44 * define whether he allows pushing first characters of item text
46 Addon::registerHook('addon_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
47 Addon::registerHook('addon_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
49 logger("installed windowsphonepush");
52 function windowsphonepush_uninstall()
54 /* uninstall unregisters any hooks created with register_hook
55 * during install. Don't delete data in table `pconfig`.
57 Addon::unregisterHook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
58 Addon::unregisterHook('addon_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
59 Addon::unregisterHook('addon_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
61 logger("removed windowsphonepush");
64 /* declare the windowsphonepush function so that /windowsphonepush url requests will land here */
65 function windowsphonepush_module()
70 /* Callback from the settings post function.
71 * $post contains the $_POST array.
72 * We will make sure we've got a valid user account
73 * and if so set our configuration setting for this person.
75 function windowsphonepush_settings_post($a, $post)
77 if (!local_user() || (!x($_POST, 'windowsphonepush-submit'))) {
80 $enable = intval($_POST['windowsphonepush']);
81 PConfig::set(local_user(), 'windowsphonepush', 'enable', $enable);
84 PConfig::set(local_user(), 'windowsphonepush', 'counterunseen', 0);
87 PConfig::set(local_user(), 'windowsphonepush', 'senditemtext', intval($_POST['windowsphonepush-senditemtext']));
89 info(t('WindowsPhonePush settings updated.') . EOL);
92 /* Called from the Addon Setting form.
93 * Add our own settings info to the page.
95 function windowsphonepush_settings(&$a, &$s)
101 /* Add our stylesheet to the page so we can make our settings look nice */
102 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/windowsphonepush/windowsphonepush.css' . '" media="all" />' . "\r\n";
104 /* Get the current state of our config variables */
105 $enabled = PConfig::get(local_user(), 'windowsphonepush', 'enable');
106 $checked_enabled = (($enabled) ? ' checked="checked" ' : '');
108 $senditemtext = PConfig::get(local_user(), 'windowsphonepush', 'senditemtext');
109 $checked_senditemtext = (($senditemtext) ? ' checked="checked" ' : '');
111 $device_url = PConfig::get(local_user(), 'windowsphonepush', 'device_url');
113 /* Add some HTML to the existing form */
114 $s .= '<div class="settings-block">';
115 $s .= '<h3>' . t('WindowsPhonePush Settings') . '</h3>';
117 $s .= '<div id="windowsphonepush-enable-wrapper">';
118 $s .= '<label id="windowsphonepush-enable-label" for="windowsphonepush-enable-chk">' . t('Enable WindowsPhonePush Addon') . '</label>';
119 $s .= '<input id="windowsphonepush-enable-chk" type="checkbox" name="windowsphonepush" value="1" ' . $checked_enabled . '/>';
120 $s .= '</div><div class="clear"></div>';
122 $s .= '<div id="windowsphonepush-senditemtext-wrapper">';
123 $s .= '<label id="windowsphonepush-senditemtext-label" for="windowsphonepush-senditemtext-chk">' . t('Push text of new item') . '</label>';
124 $s .= '<input id="windowsphonepush-senditemtext-chk" type="checkbox" name="windowsphonepush-senditemtext" value="1" ' . $checked_senditemtext . '/>';
125 $s .= '</div><div class="clear"></div>';
127 /* provide a submit button - enable und senditemtext can be changed by the user */
128 $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>';
130 /* provide further read-only information concerning the addon (useful for */
131 $s .= '<div id="windowsphonepush-device_url-wrapper">';
132 $s .= '<label id="windowsphonepush-device_url-label" for="windowsphonepush-device_url-text">Device-URL</label>';
133 $s .= '<input id="windowsphonepush-device_url-text" type="text" readonly value=' . $device_url . '/>';
134 $s .= '</div><div class="clear"></div></div>';
139 /* Cron function used to regularly check all users on the server with active windowsphonepushaddon and send
140 * notifications to the Microsoft servers and consequently to the Windows Phone device
142 function windowsphonepush_cron()
144 // retrieve all UID's for which the addon windowsphonepush is enabled and loop through every user
145 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'windowsphonepush' AND `k` = 'enable' AND `v` = 1");
147 foreach ($r as $rr) {
148 // load stored information for the user-id of the current loop
149 $device_url = PConfig::get($rr['uid'], 'windowsphonepush', 'device_url');
150 $lastpushid = PConfig::get($rr['uid'], 'windowsphonepush', 'lastpushid');
152 // pushing only possible if device_url (the URI on Microsoft server) is available or not "NA" (which will be sent
153 // by app if user has switched the server setting in app - sending blank not possible as this would return an update error)
154 if (( $device_url == "" ) || ( $device_url == "NA" )) {
155 // no Device-URL for the user availabe, but addon is enabled --> write info to Logger
156 logger("WARN: windowsphonepush is enable for user " . $rr['uid'] . ", but no Device-URL is specified for the user.");
158 // retrieve the number of unseen items and the id of the latest one (if there are more than
159 // one new entries since last poller run, only the latest one will be pushed)
160 $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']));
162 // send number of unseen items to the device (the number will be displayed on Start screen until
163 // App will be started by user) - this update will be sent every 10 minutes to update the number to 0 if
164 // user has loaded the timeline through app or website
165 $res_tile = send_tile_update($device_url, "", $count[0]['count'], "");
166 switch (trim($res_tile)) {
168 // ok, count has been pushed, let's save it in personal settings
169 PConfig::set($rr['uid'], 'windowsphonepush', 'counterunseen', $count[0]['count']);
172 // maximum of 30 messages reached, server rejects any further push notification until device reconnects
173 logger("INFO: Device-URL '" . $device_url . "' returns a QueueFull.");
176 // notification received and dropped as something in app was not enabled
177 logger("WARN. Device-URL '" . $device_url . "' returns a Suppressed. Unexpected error in Mobile App?");
180 // mostly combines with Expired, in that case Device-URL will be deleted from pconfig (function send_push)
183 // error, mostly called by "" which means that the url (not "" which has been checked)
184 // didn't not received Microsoft Notification Server -> wrong url
185 logger("ERROR: specified Device-URL '" . $device_url . "' didn't produced any response.");
188 // additionally user receives the text of the newest item (function checks against last successfully pushed item)
189 if (intval($count[0]['max']) > intval($lastpushid)) {
190 // user can define if he wants to see the text of the item in the push notification
191 // this has been implemented as the device_url is not a https uri (not so secure)
192 $senditemtext = PConfig::get($rr['uid'], 'windowsphonepush', 'senditemtext');
193 if ($senditemtext == 1) {
194 // load item with the max id
195 $item = q("SELECT `author-name` as author, `body` as body FROM `item` where `id` = %d", intval($count[0]['max']));
197 // as user allows to send the item, we want to show the sender of the item in the toast
198 // toasts are limited to one line, therefore place is limited - author shall be in
199 // max. 15 chars (incl. dots); author is displayed in bold font
200 $author = $item[0]['author'];
201 $author = ((strlen($author) > 12) ? substr($author, 0, 12) . "..." : $author);
203 // normally we show the body of the item, however if it is an url or an image we cannot
204 // show this in the toast (only test), therefore changing to an alternate text
205 // Otherwise BBcode-Tags will be eliminated and plain text cutted to 140 chars (incl. dots)
206 // BTW: information only possible in English
207 $body = $item[0]['body'];
208 if (substr($body, 0, 4) == "[url") {
209 $body = "URL/Image ...";
211 require_once('include/bbcode.php');
212 require_once("include/html2plain.php");
213 $body = bbcode($body, false, false, 2, true);
214 $body = html2plain($body, 0);
215 $body = ((strlen($body) > 137) ? substr($body, 0, 137) . "..." : $body);
218 // if user wishes higher privacy, we only display "Friendica - New timeline entry arrived"
219 $author = "Friendica";
220 $body = "New timeline entry arrived ...";
222 // only if toast push notification returns the Notification status "Received" we will update th settings with the
223 // new indicator max-id is checked against (QueueFull, Suppressed, N/A, Dropped shall qualify to resend
224 // the push notification some minutes later (BTW: if resulting in Expired for subscription status the
225 // device_url will be deleted (no further try on this url, see send_push)
226 // further log information done on count pushing with send_tile (see above)
227 $res_toast = send_toast($device_url, $author, $body);
228 if (trim($res_toast) === 'Received') {
229 PConfig::set($rr['uid'], 'windowsphonepush', 'lastpushid', $count[0]['max']);
237 /* Tile push notification change the number in the icon of the App in Start Screen of
238 * a Windows Phone Device, Image could be changed, not used for App "Friendica Mobile"
240 function send_tile_update($device_url, $image_url, $count, $title, $priority = 1)
242 $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
243 "<wp:Notification xmlns:wp=\"WPNotification\">" .
245 "<wp:BackgroundImage>" . $image_url . "</wp:BackgroundImage>" .
246 "<wp:Count>" . $count . "</wp:Count>" .
247 "<wp:Title>" . $title . "</wp:Title>" .
249 "</wp:Notification>";
251 $result = send_push($device_url, [
252 'X-WindowsPhone-Target: token',
253 'X-NotificationClass: ' . $priority,
258 /* Toast push notification send information to the top of the display
259 * if the user is not currently using the Friendica Mobile App, however
260 * there is only one line for displaying the information
262 function send_toast($device_url, $title, $message, $priority = 2)
264 $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
265 "<wp:Notification xmlns:wp=\"WPNotification\">" .
267 "<wp:Text1>" . $title . "</wp:Text1>" .
268 "<wp:Text2>" . $message . "</wp:Text2>" .
269 "<wp:Param></wp:Param>" .
271 "</wp:Notification>";
273 $result = send_push($device_url, [
274 'X-WindowsPhone-Target: toast',
275 'X-NotificationClass: ' . $priority,
280 // General function to send the push notification via cURL
281 function send_push($device_url, $headers, $msg)
284 curl_setopt($ch, CURLOPT_URL, $device_url);
285 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
286 curl_setopt($ch, CURLOPT_POST, true);
287 curl_setopt($ch, CURLOPT_HEADER, true);
288 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers + [
289 'Content-Type: text/xml',
291 'Accept: application/*',
294 curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
296 $output = curl_exec($ch);
299 // if we received "Expired" from Microsoft server we will delete the obsolete device-URL
301 $subscriptionStatus = get_header_value($output, 'X-SubscriptionStatus');
302 if ($subscriptionStatus == "Expired") {
303 PConfig::set(local_user(), 'windowsphonepush', 'device_url', "");
304 logger("ERROR: the stored Device-URL " . $device_url . "returned an 'Expired' error, it has been deleted now.");
307 // the notification status shall be returned to windowsphonepush_cron (will
308 // update settings if 'Received' otherwise keep old value in settings (on QueuedFull. Suppressed, N/A, Dropped)
309 $notificationStatus = get_header_value($output, 'X-NotificationStatus');
310 return $notificationStatus;
313 // helper function to receive statuses from webresponse of Microsoft server
314 function get_header_value($content, $header)
316 return preg_match_all("/$header: (.*)/i", $content, $match) ? $match[1][0] : "";
319 /* reading information from url and deciding which function to start
320 * show_settings = delivering settings to check
321 * update_settings = set the device_url
322 * update_counterunseen = set counter for unseen elements to zero
324 function windowsphonepush_content(App $a)
326 // Login with the specified Network credentials (like in api.php)
327 windowsphonepush_login($a);
330 $path2 = $a->argv[1];
331 if ($path == "windowsphonepush") {
333 case "show_settings":
334 windowsphonepush_showsettings($a);
337 case "update_settings":
338 $ret = windowsphonepush_updatesettings($a);
339 header("Content-Type: application/json; charset=utf-8");
340 echo json_encode(['status' => $ret]);
343 case "update_counterunseen":
344 $ret = windowsphonepush_updatecounterunseen();
345 header("Content-Type: application/json; charset=utf-8");
346 echo json_encode(['status' => $ret]);
355 // return settings for windowsphonepush addon to be able to check them in WP app
356 function windowsphonepush_showsettings()
362 $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
363 $device_url = PConfig::get(local_user(), 'windowsphonepush', 'device_url');
364 $senditemtext = PConfig::get(local_user(), 'windowsphonepush', 'senditemtext');
365 $lastpushid = PConfig::get(local_user(), 'windowsphonepush', 'lastpushid');
366 $counterunseen = PConfig::get(local_user(), 'windowsphonepush', 'counterunseen');
367 $addonversion = "2.0";
377 header("Content-Type: application/json");
378 echo json_encode(['uid' => local_user(),
380 'device_url' => $device_url,
381 'senditemtext' => $senditemtext,
382 'lastpushid' => $lastpushid,
383 'counterunseen' => $counterunseen,
384 'addonversion' => $addonversion]);
387 /* update_settings is used to transfer the device_url from WP device to the Friendica server
388 * return the status of the operation to the server
390 function windowsphonepush_updatesettings()
393 return "Not Authenticated";
396 // no updating if user hasn't enabled the addon
397 $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
399 return "Plug-in not enabled";
402 // check if sent url is empty - don't save and send return code to app
403 $device_url = $_POST['deviceurl'];
404 if ($device_url == "") {
405 logger("ERROR: no valid Device-URL specified - client transferred '" . $device_url . "'");
406 return "No valid Device-URL specified";
409 // check if sent url is already stored in database for another user, we assume that there was a change of
410 // the user on the Windows Phone device and that device url is no longer true for the other user, so we
411 // et the device_url for the OTHER user blank (should normally not occur as App should include User/server
412 // in url request to Microsoft Push Notification server)
413 $r = q("SELECT * FROM `pconfig` WHERE `uid` <> " . local_user() . " AND
414 `cat` = 'windowsphonepush' AND
415 `k` = 'device_url' AND
416 `v` = '" . $device_url . "'");
418 foreach ($r as $rr) {
419 PConfig::set($rr['uid'], 'windowsphonepush', 'device_url', '');
420 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() . "'.");
424 PConfig::set(local_user(), 'windowsphonepush', 'device_url', $device_url);
425 // output the successfull update of the device URL to the logger for error analysis if necessary
426 logger("INFO: Device-URL for user '" . local_user() . "' has been updated with '" . $device_url . "'");
427 return "Device-URL updated successfully!";
430 // update_counterunseen is used to reset the counter to zero from Windows Phone app
431 function windowsphonepush_updatecounterunseen()
434 return "Not Authenticated";
437 // no updating if user hasn't enabled the addon
438 $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
440 return "Plug-in not enabled";
443 PConfig::set(local_user(), 'windowsphonepush', 'counterunseen', 0);
444 return "Counter set to zero";
447 /* helper function to login to the server with the specified Network credentials
448 * (mainly copied from api.php)
450 function windowsphonepush_login(App $a)
452 if (!isset($_SERVER['PHP_AUTH_USER'])) {
453 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
454 header('WWW-Authenticate: Basic realm="Friendica"');
455 header('HTTP/1.0 401 Unauthorized');
456 die('This api requires login');
459 $user_id = User::authenticate($_SERVER['PHP_AUTH_USER'], trim($_SERVER['PHP_AUTH_PW']));
462 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
464 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
465 header('WWW-Authenticate: Basic realm="Friendica"');
466 header('HTTP/1.0 401 Unauthorized');
467 die('This api requires login');
470 require_once 'include/security.php';
471 authenticate_success($record);
472 $_SESSION["allow_api"] = true;
473 Addon::callHooks('logged_in', $a->user);