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