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