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