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