ca615205f081a7dc0d967c2fd7a1ac15ac5f053e
[friendica-addons.git] / windowsphonepush / windowsphonepush.php
1 <?php
2
3 /**
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)
6  * Version: 2.0
7  * Author: Gerhard Seeber <http://friendica.seeber.at/profile/admin>
8  *
9  *
10  * Pre-requisite: Windows Phone mobile device (at least WP 7.0)
11  *                Friendica mobile app on Windows Phone
12  *
13  * When plugin is installed, the system calls the plugin
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.
18  *
19  * Version history:
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)
27  */
28 use Friendica\App;
29 use Friendica\Core\PConfig;
30 use Friendica\Model\User;
31
32 function windowsphonepush_install()
33 {
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).
37          */
38         register_hook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
39
40         /* Then we'll attach into the plugin settings page, and also the
41          * settings post hook so that we can create and update
42          * user preferences. User shall be able to activate the plugin and
43          * define whether he allows pushing first characters of item text
44          */
45         register_hook('plugin_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
46         register_hook('plugin_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
47
48         logger("installed windowsphonepush");
49 }
50
51 function windowsphonepush_uninstall()
52 {
53         /* uninstall unregisters any hooks created with register_hook
54          * during install. Don't delete data in table `pconfig`.
55          */
56         unregister_hook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron');
57         unregister_hook('plugin_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings');
58         unregister_hook('plugin_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post');
59
60         logger("removed windowsphonepush");
61 }
62
63 /* declare the windowsphonepush function so that /windowsphonepush url requests will land here */
64 function windowsphonepush_module()
65 {
66
67 }
68
69 /* Callback from the settings post function.
70  * $post contains the $_POST array.
71  * We will make sure we've got a valid user account
72  * and if so set our configuration setting for this person.
73  */
74 function windowsphonepush_settings_post($a, $post)
75 {
76         if (!local_user() || (!x($_POST, 'windowsphonepush-submit'))) {
77                 return;
78         }
79         $enable = intval($_POST['windowsphonepush']);
80         PConfig::set(local_user(), 'windowsphonepush', 'enable', $enable);
81
82         if ($enable) {
83                 PConfig::set(local_user(), 'windowsphonepush', 'counterunseen', 0);
84         }
85
86         PConfig::set(local_user(), 'windowsphonepush', 'senditemtext', intval($_POST['windowsphonepush-senditemtext']));
87
88         info(t('WindowsPhonePush settings updated.') . EOL);
89 }
90
91 /* Called from the Plugin Setting form.
92  * Add our own settings info to the page.
93  */
94 function windowsphonepush_settings(&$a, &$s)
95 {
96         if (!local_user()) {
97                 return;
98         }
99
100         /* Add our stylesheet to the page so we can make our settings look nice */
101         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/windowsphonepush/windowsphonepush.css' . '" media="all" />' . "\r\n";
102
103         /* Get the current state of our config variables */
104         $enabled = PConfig::get(local_user(), 'windowsphonepush', 'enable');
105         $checked_enabled = (($enabled) ? ' checked="checked" ' : '');
106
107         $senditemtext = PConfig::get(local_user(), 'windowsphonepush', 'senditemtext');
108         $checked_senditemtext = (($senditemtext) ? ' checked="checked" ' : '');
109
110         $device_url = PConfig::get(local_user(), 'windowsphonepush', 'device_url');
111
112         /* Add some HTML to the existing form */
113         $s .= '<div class="settings-block">';
114         $s .= '<h3>' . t('WindowsPhonePush Settings') . '</h3>';
115
116         $s .= '<div id="windowsphonepush-enable-wrapper">';
117         $s .= '<label id="windowsphonepush-enable-label" for="windowsphonepush-enable-chk">' . t('Enable WindowsPhonePush Plugin') . '</label>';
118         $s .= '<input id="windowsphonepush-enable-chk" type="checkbox" name="windowsphonepush" value="1" ' . $checked_enabled . '/>';
119         $s .= '</div><div class="clear"></div>';
120
121         $s .= '<div id="windowsphonepush-senditemtext-wrapper">';
122         $s .= '<label id="windowsphonepush-senditemtext-label" for="windowsphonepush-senditemtext-chk">' . t('Push text of new item') . '</label>';
123         $s .= '<input id="windowsphonepush-senditemtext-chk" type="checkbox" name="windowsphonepush-senditemtext" value="1" ' . $checked_senditemtext . '/>';
124         $s .= '</div><div class="clear"></div>';
125
126         /* provide a submit button - enable und senditemtext can be changed by the user */
127         $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>';
128
129         /* provide further read-only information concerning the addon (useful for */
130         $s .= '<div id="windowsphonepush-device_url-wrapper">';
131         $s .= '<label id="windowsphonepush-device_url-label" for="windowsphonepush-device_url-text">Device-URL</label>';
132         $s .= '<input id="windowsphonepush-device_url-text" type="text" readonly value=' . $device_url . '/>';
133         $s .= '</div><div class="clear"></div></div>';
134
135         return;
136 }
137
138 /* Cron function used to regularly check all users on the server with active windowsphonepushplugin and send
139  * notifications to the Microsoft servers and consequently to the Windows Phone device
140  */
141 function windowsphonepush_cron()
142 {
143         // retrieve all UID's for which the plugin windowsphonepush is enabled and loop through every user
144         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'windowsphonepush' AND `k` = 'enable' AND `v` = 1");
145         if (count($r)) {
146                 foreach ($r as $rr) {
147                         // load stored information for the user-id of the current loop
148                         $device_url = PConfig::get($rr['uid'], 'windowsphonepush', 'device_url');
149                         $lastpushid = PConfig::get($rr['uid'], 'windowsphonepush', 'lastpushid');
150
151                         // pushing only possible if device_url (the URI on Microsoft server) is available or not "NA" (which will be sent
152                         // by app if user has switched the server setting in app - sending blank not possible as this would return an update error)
153                         if (( $device_url == "" ) || ( $device_url == "NA" )) {
154                                 // no Device-URL for the user availabe, but plugin is enabled --> write info to Logger
155                                 logger("WARN: windowsphonepush is enable for user " . $rr['uid'] . ", but no Device-URL is specified for the user.");
156                         } else {
157                                 // retrieve the number of unseen items and the id of the latest one (if there are more than
158                                 // one new entries since last poller run, only the latest one will be pushed)
159                                 $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']));
160
161                                 // send number of unseen items to the device (the number will be displayed on Start screen until
162                                 // App will be started by user) - this update will be sent every 10 minutes to update the number to 0 if
163                                 // user has loaded the timeline through app or website
164                                 $res_tile = send_tile_update($device_url, "", $count[0]['count'], "");
165                                 switch (trim($res_tile)) {
166                                         case "Received":
167                                                 // ok, count has been pushed, let's save it in personal settings
168                                                 PConfig::set($rr['uid'], 'windowsphonepush', 'counterunseen', $count[0]['count']);
169                                                 break;
170                                         case "QueueFull":
171                                                 // maximum of 30 messages reached, server rejects any further push notification until device reconnects
172                                                 logger("INFO: Device-URL '" . $device_url . "' returns a QueueFull.");
173                                                 break;
174                                         case "Suppressed":
175                                                 // notification received and dropped as something in app was not enabled
176                                                 logger("WARN. Device-URL '" . $device_url . "' returns a Suppressed. Unexpected error in Mobile App?");
177                                                 break;
178                                         case "Dropped":
179                                                 // mostly combines with Expired, in that case Device-URL will be deleted from pconfig (function send_push)
180                                                 break;
181                                         default:
182                                                 // error, mostly called by "" which means that the url (not "" which has been checked)
183                                                 // didn't not received Microsoft Notification Server -> wrong url
184                                                 logger("ERROR: specified Device-URL '" . $device_url . "' didn't produced any response.");
185                                 }
186
187                                 // additionally user receives the text of the newest item (function checks against last successfully pushed item)
188                                 if (intval($count[0]['max']) > intval($lastpushid)) {
189                                         // user can define if he wants to see the text of the item in the push notification
190                                         // this has been implemented as the device_url is not a https uri (not so secure)
191                                         $senditemtext = PConfig::get($rr['uid'], 'windowsphonepush', 'senditemtext');
192                                         if ($senditemtext == 1) {
193                                                 // load item with the max id
194                                                 $item = q("SELECT `author-name` as author, `body` as body FROM `item` where `id` = %d", intval($count[0]['max']));
195
196                                                 // as user allows to send the item, we want to show the sender of the item in the toast
197                                                 // toasts are limited to one line, therefore place is limited - author shall be in
198                                                 // max. 15 chars (incl. dots); author is displayed in bold font
199                                                 $author = $item[0]['author'];
200                                                 $author = ((strlen($author) > 12) ? substr($author, 0, 12) . "..." : $author);
201
202                                                 // normally we show the body of the item, however if it is an url or an image we cannot
203                                                 // show this in the toast (only test), therefore changing to an alternate text
204                                                 // Otherwise BBcode-Tags will be eliminated and plain text cutted to 140 chars (incl. dots)
205                                                 // BTW: information only possible in English
206                                                 $body = $item[0]['body'];
207                                                 if (substr($body, 0, 4) == "[url") {
208                                                         $body = "URL/Image ...";
209                                                 } else {
210                                                         require_once('include/bbcode.php');
211                                                         require_once("include/html2plain.php");
212                                                         $body = bbcode($body, false, false, 2, true);
213                                                         $body = html2plain($body, 0);
214                                                         $body = ((strlen($body) > 137) ? substr($body, 0, 137) . "..." : $body);
215                                                 }
216                                         } else {
217                                                 // if user wishes higher privacy, we only display "Friendica - New timeline entry arrived"
218                                                 $author = "Friendica";
219                                                 $body = "New timeline entry arrived ...";
220                                         }
221                                         // only if toast push notification returns the Notification status "Received" we will update th settings with the
222                                         // new indicator max-id is checked against (QueueFull, Suppressed, N/A, Dropped shall qualify to resend
223                                         // the push notification some minutes later (BTW: if resulting in Expired for subscription status the
224                                         // device_url will be deleted (no further try on this url, see send_push)
225                                         // further log information done on count pushing with send_tile (see above)
226                                         $res_toast = send_toast($device_url, $author, $body);
227                                         if (trim($res_toast) === 'Received') {
228                                                 PConfig::set($rr['uid'], 'windowsphonepush', 'lastpushid', $count[0]['max']);
229                                         }
230                                 }
231                         }
232                 }
233         }
234 }
235
236 /* Tile push notification change the number in the icon of the App in Start Screen of
237  * a Windows Phone Device, Image could be changed, not used for App "Friendica Mobile"
238  */
239 function send_tile_update($device_url, $image_url, $count, $title, $priority = 1)
240 {
241         $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
242                 "<wp:Notification xmlns:wp=\"WPNotification\">" .
243                 "<wp:Tile>" .
244                 "<wp:BackgroundImage>" . $image_url . "</wp:BackgroundImage>" .
245                 "<wp:Count>" . $count . "</wp:Count>" .
246                 "<wp:Title>" . $title . "</wp:Title>" .
247                 "</wp:Tile> " .
248                 "</wp:Notification>";
249
250         $result = send_push($device_url, array(
251                 'X-WindowsPhone-Target: token',
252                 'X-NotificationClass: ' . $priority,
253                 ), $msg);
254         return $result;
255 }
256
257 /* Toast push notification send information to the top of the display
258  * if the user is not currently using the Friendica Mobile App, however
259  * there is only one line for displaying the information
260  */
261 function send_toast($device_url, $title, $message, $priority = 2)
262 {
263         $msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" .
264                 "<wp:Notification xmlns:wp=\"WPNotification\">" .
265                 "<wp:Toast>" .
266                 "<wp:Text1>" . $title . "</wp:Text1>" .
267                 "<wp:Text2>" . $message . "</wp:Text2>" .
268                 "<wp:Param></wp:Param>" .
269                 "</wp:Toast>" .
270                 "</wp:Notification>";
271
272         $result = send_push($device_url, array(
273                 'X-WindowsPhone-Target: toast',
274                 'X-NotificationClass: ' . $priority,
275                 ), $msg);
276         return $result;
277 }
278
279 // General function to send the push notification via cURL
280 function send_push($device_url, $headers, $msg)
281 {
282         $ch = curl_init();
283         curl_setopt($ch, CURLOPT_URL, $device_url);
284         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
285         curl_setopt($ch, CURLOPT_POST, true);
286         curl_setopt($ch, CURLOPT_HEADER, true);
287         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers + array(
288                 'Content-Type: text/xml',
289                 'charset=utf-8',
290                 'Accept: application/*',
291                 )
292         );
293         curl_setopt($ch, CURLOPT_POSTFIELDS, $msg);
294
295         $output = curl_exec($ch);
296         curl_close($ch);
297
298         // if we received "Expired" from Microsoft server we will delete the obsolete device-URL
299         // and log this fact
300         $subscriptionStatus = get_header_value($output, 'X-SubscriptionStatus');
301         if ($subscriptionStatus == "Expired") {
302                 PConfig::set(local_user(), 'windowsphonepush', 'device_url', "");
303                 logger("ERROR: the stored Device-URL " . $device_url . "returned an 'Expired' error, it has been deleted now.");
304         }
305
306         // the notification status shall be returned to windowsphonepush_cron (will
307         // update settings if 'Received' otherwise keep old value in settings (on QueuedFull. Suppressed, N/A, Dropped)
308         $notificationStatus = get_header_value($output, 'X-NotificationStatus');
309         return $notificationStatus;
310 }
311
312 // helper function to receive statuses from webresponse of Microsoft server
313 function get_header_value($content, $header)
314 {
315         return preg_match_all("/$header: (.*)/i", $content, $match) ? $match[1][0] : "";
316 }
317
318 /* reading information from url and deciding which function to start
319  * show_settings = delivering settings to check
320  * update_settings = set the device_url
321  * update_counterunseen = set counter for unseen elements to zero
322  */
323 function windowsphonepush_content(App $a)
324 {
325         // Login with the specified Network credentials (like in api.php)
326         windowsphonepush_login($a);
327
328         $path = $a->argv[0];
329         $path2 = $a->argv[1];
330         if ($path == "windowsphonepush") {
331                 switch ($path2) {
332                         case "show_settings":
333                                 windowsphonepush_showsettings($a);
334                                 killme();
335                                 break;
336                         case "update_settings":
337                                 $ret = windowsphonepush_updatesettings($a);
338                                 header("Content-Type: application/json; charset=utf-8");
339                                 echo json_encode(array('status' => $ret));
340                                 killme();
341                                 break;
342                         case "update_counterunseen":
343                                 $ret = windowsphonepush_updatecounterunseen();
344                                 header("Content-Type: application/json; charset=utf-8");
345                                 echo json_encode(array('status' => $ret));
346                                 killme();
347                                 break;
348                         default:
349                                 echo "Fehler";
350                 }
351         }
352 }
353
354 // return settings for windowsphonepush addon to be able to check them in WP app
355 function windowsphonepush_showsettings()
356 {
357         if (!local_user()) {
358                 return;
359         }
360
361         $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
362         $device_url = PConfig::get(local_user(), 'windowsphonepush', 'device_url');
363         $senditemtext = PConfig::get(local_user(), 'windowsphonepush', 'senditemtext');
364         $lastpushid = PConfig::get(local_user(), 'windowsphonepush', 'lastpushid');
365         $counterunseen = PConfig::get(local_user(), 'windowsphonepush', 'counterunseen');
366         $addonversion = "2.0";
367
368         if (!$device_url) {
369                 $device_url = "";
370         }
371
372         if (!$lastpushid) {
373                 $lastpushid = 0;
374         }
375
376         header("Content-Type: application/json");
377         echo json_encode(array('uid' => local_user(),
378                 'enable' => $enable,
379                 'device_url' => $device_url,
380                 'senditemtext' => $senditemtext,
381                 'lastpushid' => $lastpushid,
382                 'counterunseen' => $counterunseen,
383                 'addonversion' => $addonversion));
384 }
385
386 /* update_settings is used to transfer the device_url from WP device to the Friendica server
387  * return the status of the operation to the server
388  */
389 function windowsphonepush_updatesettings()
390 {
391         if (!local_user()) {
392                 return "Not Authenticated";
393         }
394
395         // no updating if user hasn't enabled the plugin
396         $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
397         if (!$enable) {
398                 return "Plug-in not enabled";
399         }
400
401         // check if sent url is empty - don't save and send return code to app
402         $device_url = $_POST['deviceurl'];
403         if ($device_url == "") {
404                 logger("ERROR: no valid Device-URL specified - client transferred '" . $device_url . "'");
405                 return "No valid Device-URL specified";
406         }
407
408         // check if sent url is already stored in database for another user, we assume that there was a change of
409         // the user on the Windows Phone device and that device url is no longer true for the other user, so we
410         // et the device_url for the OTHER user blank (should normally not occur as App should include User/server
411         // in url request to Microsoft Push Notification server)
412         $r = q("SELECT * FROM `pconfig` WHERE `uid` <> " . local_user() . " AND
413                                                 `cat` = 'windowsphonepush' AND
414                                                 `k` = 'device_url' AND
415                                                 `v` = '" . $device_url . "'");
416         if (count($r)) {
417                 foreach ($r as $rr) {
418                         PConfig::set($rr['uid'], 'windowsphonepush', 'device_url', '');
419                         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() . "'.");
420                 }
421         }
422
423         PConfig::set(local_user(), 'windowsphonepush', 'device_url', $device_url);
424         // output the successfull update of the device URL to the logger for error analysis if necessary
425         logger("INFO: Device-URL for user '" . local_user() . "' has been updated with '" . $device_url . "'");
426         return "Device-URL updated successfully!";
427 }
428
429 // update_counterunseen is used to reset the counter to zero from Windows Phone app
430 function windowsphonepush_updatecounterunseen()
431 {
432         if (!local_user()) {
433                 return "Not Authenticated";
434         }
435
436         // no updating if user hasn't enabled the plugin
437         $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable');
438         if (!$enable) {
439                 return "Plug-in not enabled";
440         }
441
442         PConfig::set(local_user(), 'windowsphonepush', 'counterunseen', 0);
443         return "Counter set to zero";
444 }
445
446 /* helper function to login to the server with the specified Network credentials
447  * (mainly copied from api.php)
448  */
449 function windowsphonepush_login(App $a)
450 {
451         if (!isset($_SERVER['PHP_AUTH_USER'])) {
452                 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
453                 header('WWW-Authenticate: Basic realm="Friendica"');
454                 header('HTTP/1.0 401 Unauthorized');
455                 die('This api requires login');
456         }
457
458         $user_id = User::authenticate($_SERVER['PHP_AUTH_USER'], trim($_SERVER['PHP_AUTH_PW']));
459
460         if ($user_id) {
461                 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
462         } else {
463                 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
464                 header('WWW-Authenticate: Basic realm="Friendica"');
465                 header('HTTP/1.0 401 Unauthorized');
466                 die('This api requires login');
467         }
468
469         require_once 'include/security.php';
470         authenticate_success($record);
471         $_SESSION["allow_api"] = true;
472         call_hooks('logged_in', $a->user);
473 }