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