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