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