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