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