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