Official Addons for the Friendica Communications Platform. (please note that this is a clone of the repository at github, issues are handled there)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

464 lines
19 KiB

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