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