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