Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
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.

885 lines
32 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. <?php
  2. /**
  3. * @file include/enotify.php
  4. */
  5. use Friendica\Content\Text\BBCode;
  6. use Friendica\Core\Config;
  7. use Friendica\Core\Hook;
  8. use Friendica\Core\L10n;
  9. use Friendica\Core\Logger;
  10. use Friendica\Core\Renderer;
  11. use Friendica\Core\System;
  12. use Friendica\Database\DBA;
  13. use Friendica\Model\Item;
  14. use Friendica\Model\User;
  15. use Friendica\Util\DateTimeFormat;
  16. use Friendica\Util\Emailer;
  17. use Friendica\Util\Strings;
  18. /**
  19. * @brief Creates a notification entry and possibly sends a mail
  20. *
  21. * @param array $params Array with the elements:
  22. * uid, item, parent, type, otype, verb, event,
  23. * link, subject, body, to_name, to_email, source_name,
  24. * source_link, activity, preamble, notify_flags,
  25. * language, show_in_notification_page
  26. * @return bool
  27. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  28. */
  29. function notification($params)
  30. {
  31. $a = \get_app();
  32. // Temporary logging for finding the origin
  33. if (!isset($params['uid'])) {
  34. Logger::notice('Missing parameters "uid".', ['params' => $params, 'callstack' => System::callstack()]);
  35. }
  36. // Ensure that the important fields are set at any time
  37. $fields = ['notify-flags', 'language', 'username', 'email'];
  38. $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
  39. if (!DBA::isResult($user)) {
  40. Logger::error('Unknown user', ['uid' => $params['uid']]);
  41. return false;
  42. }
  43. $params['notify_flags'] = ($params['notify_flags'] ?? '') ?: $user['notify-flags'];
  44. $params['language'] = ($params['language'] ?? '') ?: $user['language'];
  45. $params['to_name'] = ($params['to_name'] ?? '') ?: $user['username'];
  46. $params['to_email'] = ($params['to_email'] ?? '') ?: $user['email'];
  47. // from here on everything is in the recipients language
  48. L10n::pushLang($params['language']);
  49. $banner = L10n::t('Friendica Notification');
  50. $product = FRIENDICA_PLATFORM;
  51. $siteurl = System::baseUrl(true);
  52. $thanks = L10n::t('Thank You,');
  53. $sitename = Config::get('config', 'sitename');
  54. if (Config::get('config', 'admin_name')) {
  55. $site_admin = L10n::t('%1$s, %2$s Administrator', Config::get('config', 'admin_name'), $sitename);
  56. } else {
  57. $site_admin = L10n::t('%s Administrator', $sitename);
  58. }
  59. $sender_name = $sitename;
  60. $hostname = $a->getHostName();
  61. if (strpos($hostname, ':')) {
  62. $hostname = substr($hostname, 0, strpos($hostname, ':'));
  63. }
  64. $sender_email = $a->getSenderEmailAddress();
  65. if ($params['type'] != SYSTEM_EMAIL) {
  66. $user = DBA::selectFirst('user', ['nickname', 'page-flags'],
  67. ['uid' => $params['uid']]);
  68. // There is no need to create notifications for forum accounts
  69. if (!DBA::isResult($user) || in_array($user["page-flags"], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_PRVGROUP])) {
  70. return false;
  71. }
  72. $nickname = $user["nickname"];
  73. } else {
  74. $nickname = '';
  75. }
  76. // with $params['show_in_notification_page'] == false, the notification isn't inserted into
  77. // the database, and an email is sent if applicable.
  78. // default, if not specified: true
  79. $show_in_notification_page = isset($params['show_in_notification_page']) ? $params['show_in_notification_page'] : true;
  80. $additional_mail_header = "";
  81. $additional_mail_header .= "Precedence: list\n";
  82. $additional_mail_header .= "X-Friendica-Host: ".$hostname."\n";
  83. $additional_mail_header .= "X-Friendica-Account: <".$nickname."@".$hostname.">\n";
  84. $additional_mail_header .= "X-Friendica-Platform: ".FRIENDICA_PLATFORM."\n";
  85. $additional_mail_header .= "X-Friendica-Version: ".FRIENDICA_VERSION."\n";
  86. $additional_mail_header .= "List-ID: <notification.".$hostname.">\n";
  87. $additional_mail_header .= "List-Archive: <".System::baseUrl()."/notifications/system>\n";
  88. if (array_key_exists('item', $params)) {
  89. $title = $params['item']['title'];
  90. $body = $params['item']['body'];
  91. } else {
  92. $title = $body = '';
  93. }
  94. if (isset($params['item']['id'])) {
  95. $item_id = $params['item']['id'];
  96. } else {
  97. $item_id = 0;
  98. }
  99. if (isset($params['parent'])) {
  100. $parent_id = $params['parent'];
  101. } else {
  102. $parent_id = 0;
  103. }
  104. $epreamble = '';
  105. $preamble = '';
  106. $subject = '';
  107. $sitelink = '';
  108. $tsitelink = '';
  109. $hsitelink = '';
  110. $itemlink = '';
  111. if ($params['type'] == NOTIFY_MAIL) {
  112. $itemlink = $siteurl.'/message/'.$params['item']['id'];
  113. $params["link"] = $itemlink;
  114. $subject = L10n::t('[Friendica:Notify] New mail received at %s', $sitename);
  115. $preamble = L10n::t('%1$s sent you a new private message at %2$s.', $params['source_name'], $sitename);
  116. $epreamble = L10n::t('%1$s sent you %2$s.', '[url='.$params['source_link'].']'.$params['source_name'].'[/url]', '[url=' . $itemlink . ']'.L10n::t('a private message').'[/url]');
  117. $sitelink = L10n::t('Please visit %s to view and/or reply to your private messages.');
  118. $tsitelink = sprintf($sitelink, $siteurl.'/message/'.$params['item']['id']);
  119. $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'/message/'.$params['item']['id'].'">'.$sitename.'</a>');
  120. }
  121. if ($params['type'] == NOTIFY_COMMENT || $params['type'] == NOTIFY_TAGSELF) {
  122. $thread = Item::selectFirstThreadForUser($params['uid'], ['ignored'], ['iid' => $parent_id, 'deleted' => false]);
  123. if (DBA::isResult($thread) && $thread['ignored']) {
  124. Logger::log('Thread ' . $parent_id . ' will be ignored', Logger::DEBUG);
  125. L10n::popLang();
  126. return false;
  127. }
  128. // Check to see if there was already a tag notify or comment notify for this post.
  129. // If so don't create a second notification
  130. $condition = ['type' => [NOTIFY_TAGSELF, NOTIFY_COMMENT, NOTIFY_SHARE],
  131. 'link' => $params['link'], 'uid' => $params['uid']];
  132. if (DBA::exists('notify', $condition)) {
  133. L10n::popLang();
  134. return false;
  135. }
  136. // if it's a post figure out who's post it is.
  137. $item = null;
  138. if ($params['otype'] === 'item' && $parent_id) {
  139. $item = Item::selectFirstForUser($params['uid'], Item::ITEM_FIELDLIST, ['id' => $parent_id, 'deleted' => false]);
  140. }
  141. $item_post_type = Item::postType($item);
  142. $itemlink = $item['plink'];
  143. // "a post"
  144. if ($params['type'] == NOTIFY_TAGSELF) {
  145. $dest_str = L10n::t('%1$s tagged you on [url=%2$s]a %3$s[/url]',
  146. '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
  147. $itemlink,
  148. $item_post_type
  149. );
  150. } else {
  151. $dest_str = L10n::t('%1$s commented on [url=%2$s]a %3$s[/url]',
  152. '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
  153. $itemlink,
  154. $item_post_type
  155. );
  156. }
  157. // "George Bull's post"
  158. if (DBA::isResult($item)) {
  159. if ($params['type'] == NOTIFY_TAGSELF) {
  160. $dest_str = L10n::t('%1$s tagged you on [url=%2$s]%3$s\'s %4$s[/url]',
  161. '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
  162. $itemlink,
  163. $item['author-name'],
  164. $item_post_type
  165. );
  166. } else {
  167. $dest_str = L10n::t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]',
  168. '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
  169. $itemlink,
  170. $item['author-name'],
  171. $item_post_type
  172. );
  173. }
  174. }
  175. // "your post"
  176. if (DBA::isResult($item) && $item['owner-id'] == $item['author-id'] && $item['wall']) {
  177. if ($params['type'] == NOTIFY_TAGSELF) {
  178. $dest_str = L10n::t('%1$s tagged you on [url=%2$s]your %3$s[/url]',
  179. '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
  180. $itemlink,
  181. $item_post_type
  182. );
  183. } else {
  184. $dest_str = L10n::t('%1$s commented on [url=%2$s]your %3$s[/url]',
  185. '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
  186. $itemlink,
  187. $item_post_type
  188. );
  189. }
  190. }
  191. // "their post"
  192. if (DBA::isResult($item) && $item['author-link'] == $params['source_link']) {
  193. if ($params['type'] == NOTIFY_TAGSELF) {
  194. $dest_str = L10n::t('%1$s tagged you on [url=%2$s]their %3$s[/url]',
  195. '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
  196. $itemlink,
  197. $item_post_type
  198. );
  199. } else {
  200. $dest_str = L10n::t('%1$s commented on [url=%2$s]their %3$s[/url]',
  201. '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
  202. $itemlink,
  203. $item_post_type
  204. );
  205. }
  206. }
  207. // Some mail software relies on subject field for threading.
  208. // So, we cannot have different subjects for notifications of the same thread.
  209. // Before this we have the name of the replier on the subject rendering
  210. // different subjects for messages on the same thread.
  211. if ($params['type'] == NOTIFY_TAGSELF) {
  212. $subject = L10n::t('[Friendica:Notify] %s tagged you', $params['source_name']);
  213. $preamble = L10n::t('%1$s tagged you at %2$s', $params['source_name'], $sitename);
  214. } else {
  215. $subject = L10n::t('[Friendica:Notify] Comment to conversation #%1$d by %2$s', $parent_id, $params['source_name']);
  216. $preamble = L10n::t('%s commented on an item/conversation you have been following.', $params['source_name']);
  217. }
  218. $epreamble = $dest_str;
  219. $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
  220. $tsitelink = sprintf($sitelink, $siteurl);
  221. $hsitelink = sprintf($sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
  222. $itemlink = $params['link'];
  223. }
  224. if ($params['type'] == NOTIFY_WALL) {
  225. $subject = L10n::t('[Friendica:Notify] %s posted to your profile wall', $params['source_name']);
  226. $preamble = L10n::t('%1$s posted to your profile wall at %2$s', $params['source_name'], $sitename);
  227. $epreamble = L10n::t('%1$s posted to [url=%2$s]your wall[/url]',
  228. '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
  229. $params['link']
  230. );
  231. $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
  232. $tsitelink = sprintf($sitelink, $siteurl);
  233. $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
  234. $itemlink = $params['link'];
  235. }
  236. if ($params['type'] == NOTIFY_SHARE) {
  237. $subject = L10n::t('[Friendica:Notify] %s shared a new post', $params['source_name']);
  238. $preamble = L10n::t('%1$s shared a new post at %2$s', $params['source_name'], $sitename);
  239. $epreamble = L10n::t('%1$s [url=%2$s]shared a post[/url].',
  240. '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
  241. $params['link']
  242. );
  243. $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
  244. $tsitelink = sprintf($sitelink, $siteurl);
  245. $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
  246. $itemlink = $params['link'];
  247. }
  248. if ($params['type'] == NOTIFY_POKE) {
  249. $subject = L10n::t('[Friendica:Notify] %1$s poked you', $params['source_name']);
  250. $preamble = L10n::t('%1$s poked you at %2$s', $params['source_name'], $sitename);
  251. $epreamble = L10n::t('%1$s [url=%2$s]poked you[/url].',
  252. '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
  253. $params['link']
  254. );
  255. $subject = str_replace('poked', L10n::t($params['activity']), $subject);
  256. $preamble = str_replace('poked', L10n::t($params['activity']), $preamble);
  257. $epreamble = str_replace('poked', L10n::t($params['activity']), $epreamble);
  258. $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
  259. $tsitelink = sprintf($sitelink, $siteurl);
  260. $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
  261. $itemlink = $params['link'];
  262. }
  263. if ($params['type'] == NOTIFY_TAGSHARE) {
  264. $itemlink = $params['link'];
  265. $subject = L10n::t('[Friendica:Notify] %s tagged your post', $params['source_name']);
  266. $preamble = L10n::t('%1$s tagged your post at %2$s', $params['source_name'], $sitename);
  267. $epreamble = L10n::t('%1$s tagged [url=%2$s]your post[/url]',
  268. '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
  269. $itemlink
  270. );
  271. $sitelink = L10n::t('Please visit %s to view and/or reply to the conversation.');
  272. $tsitelink = sprintf($sitelink, $siteurl);
  273. $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
  274. }
  275. if ($params['type'] == NOTIFY_INTRO) {
  276. $itemlink = $params['link'];
  277. $subject = L10n::t('[Friendica:Notify] Introduction received');
  278. $preamble = L10n::t('You\'ve received an introduction from \'%1$s\' at %2$s', $params['source_name'], $sitename);
  279. $epreamble = L10n::t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.',
  280. $itemlink,
  281. '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
  282. );
  283. $body = L10n::t('You may visit their profile at %s', $params['source_link']);
  284. $sitelink = L10n::t('Please visit %s to approve or reject the introduction.');
  285. $tsitelink = sprintf($sitelink, $siteurl);
  286. $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
  287. switch ($params['verb']) {
  288. case ACTIVITY_FRIEND:
  289. // someone started to share with user (mostly OStatus)
  290. $subject = L10n::t('[Friendica:Notify] A new person is sharing with you');
  291. $preamble = L10n::t('%1$s is sharing with you at %2$s', $params['source_name'], $sitename);
  292. $epreamble = L10n::t('%1$s is sharing with you at %2$s',
  293. '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
  294. $sitename
  295. );
  296. break;
  297. case ACTIVITY_FOLLOW:
  298. // someone started to follow the user (mostly OStatus)
  299. $subject = L10n::t('[Friendica:Notify] You have a new follower');
  300. $preamble = L10n::t('You have a new follower at %2$s : %1$s', $params['source_name'], $sitename);
  301. $epreamble = L10n::t('You have a new follower at %2$s : %1$s',
  302. '[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
  303. $sitename
  304. );
  305. break;
  306. default:
  307. // ACTIVITY_REQ_FRIEND is default activity for notifications
  308. break;
  309. }
  310. }
  311. if ($params['type'] == NOTIFY_SUGGEST) {
  312. $itemlink = $params['link'];
  313. $subject = L10n::t('[Friendica:Notify] Friend suggestion received');
  314. $preamble = L10n::t('You\'ve received a friend suggestion from \'%1$s\' at %2$s', $params['source_name'], $sitename);
  315. $epreamble = L10n::t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.',
  316. $itemlink,
  317. '[url='.$params['item']['url'].']'.$params['item']['name'].'[/url]',
  318. '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
  319. );
  320. $body = L10n::t('Name:').' '.$params['item']['name']."\n";
  321. $body .= L10n::t('Photo:').' '.$params['item']['photo']."\n";
  322. $body .= L10n::t('You may visit their profile at %s', $params['item']['url']);
  323. $sitelink = L10n::t('Please visit %s to approve or reject the suggestion.');
  324. $tsitelink = sprintf($sitelink, $siteurl);
  325. $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
  326. }
  327. if ($params['type'] == NOTIFY_CONFIRM) {
  328. if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection
  329. $itemlink = $params['link'];
  330. $subject = L10n::t('[Friendica:Notify] Connection accepted');
  331. $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
  332. $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
  333. $itemlink,
  334. '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
  335. );
  336. $body = L10n::t('You are now mutual friends and may exchange status updates, photos, and email without restriction.');
  337. $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
  338. $tsitelink = sprintf($sitelink, $siteurl);
  339. $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
  340. } else { // ACTIVITY_FOLLOW
  341. $itemlink = $params['link'];
  342. $subject = L10n::t('[Friendica:Notify] Connection accepted');
  343. $preamble = L10n::t('\'%1$s\' has accepted your connection request at %2$s', $params['source_name'], $sitename);
  344. $epreamble = L10n::t('%2$s has accepted your [url=%1$s]connection request[/url].',
  345. $itemlink,
  346. '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
  347. );
  348. $body = L10n::t('\'%1$s\' has chosen to accept you a fan, which restricts some forms of communication - such as private messaging and some profile interactions. If this is a celebrity or community page, these settings were applied automatically.', $params['source_name']);
  349. $body .= "\n\n";
  350. $body .= L10n::t('\'%1$s\' may choose to extend this into a two-way or more permissive relationship in the future.', $params['source_name']);
  351. $sitelink = L10n::t('Please visit %s if you wish to make any changes to this relationship.');
  352. $tsitelink = sprintf($sitelink, $siteurl);
  353. $hsitelink = sprintf($sitelink, '<a href="'.$siteurl.'">'.$sitename.'</a>');
  354. }
  355. }
  356. if ($params['type'] == NOTIFY_SYSTEM) {
  357. switch($params['event']) {
  358. case "SYSTEM_REGISTER_REQUEST":
  359. $itemlink = $params['link'];
  360. $subject = L10n::t('[Friendica System Notify]') . ' ' . L10n::t('registration request');
  361. $preamble = L10n::t('You\'ve received a registration request from \'%1$s\' at %2$s', $params['source_name'], $sitename);
  362. $epreamble = L10n::t('You\'ve received a [url=%1$s]registration request[/url] from %2$s.',
  363. $itemlink,
  364. '[url='.$params['source_link'].']'.$params['source_name'].'[/url]'
  365. );
  366. $body = L10n::t("Full Name: %s\nSite Location: %s\nLogin Name: %s (%s)",
  367. $params['source_name'],
  368. $siteurl, $params['source_mail'],
  369. $params['source_nick']
  370. );
  371. $sitelink = L10n::t('Please visit %s to approve or reject the request.');
  372. $tsitelink = sprintf($sitelink, $params['link']);
  373. $hsitelink = sprintf($sitelink, '<a href="'.$params['link'].'">'.$sitename.'</a><br><br>');
  374. break;
  375. case "SYSTEM_DB_UPDATE_FAIL":
  376. break;
  377. }
  378. }
  379. if ($params['type'] == SYSTEM_EMAIL) {
  380. // not part of the notifications.
  381. // it just send a mail to the user.
  382. // It will be used by the system to send emails to users (like
  383. // password reset, invitations and so) using one look (but without
  384. // add a notification to the user, with could be inexistent)
  385. if (!isset($params['subject'])) {
  386. Logger::warning('subject isn\'t set.', ['type' => $params['type']]);
  387. }
  388. $subject = $params['subject'] ?? '';
  389. if (!isset($params['preamble'])) {
  390. Logger::warning('preamble isn\'t set.', ['type' => $params['type'], 'subject' => $subject]);
  391. }
  392. $preamble = $params['preamble'] ?? '';
  393. if (!isset($params['body'])) {
  394. Logger::warning('body isn\'t set.', ['type' => $params['type'], 'subject' => $subject, 'preamble' => $preamble]);
  395. }
  396. $body = $params['body'] ?? '';
  397. $show_in_notification_page = false;
  398. }
  399. $subject .= " (".$nickname."@".$hostname.")";
  400. $h = [
  401. 'params' => $params,
  402. 'subject' => $subject,
  403. 'preamble' => $preamble,
  404. 'epreamble' => $epreamble,
  405. 'body' => $body,
  406. 'sitelink' => $sitelink,
  407. 'tsitelink' => $tsitelink,
  408. 'hsitelink' => $hsitelink,
  409. 'itemlink' => $itemlink
  410. ];
  411. Hook::callAll('enotify', $h);
  412. $subject = $h['subject'];
  413. $preamble = $h['preamble'];
  414. $epreamble = $h['epreamble'];
  415. $body = $h['body'];
  416. $tsitelink = $h['tsitelink'];
  417. $hsitelink = $h['hsitelink'];
  418. $itemlink = $h['itemlink'];
  419. $notify_id = 0;
  420. if ($show_in_notification_page) {
  421. Logger::log("adding notification entry", Logger::DEBUG);
  422. do {
  423. $dups = false;
  424. $hash = Strings::getRandomHex();
  425. if (DBA::exists('notify', ['hash' => $hash])) {
  426. $dups = true;
  427. }
  428. } while ($dups == true);
  429. /// @TODO One statement is enough
  430. $datarray = [];
  431. $datarray['hash'] = $hash;
  432. $datarray['name'] = $params['source_name'];
  433. $datarray['name_cache'] = strip_tags(BBCode::convert($params['source_name']));
  434. $datarray['url'] = $params['source_link'];
  435. $datarray['photo'] = $params['source_photo'];
  436. $datarray['date'] = DateTimeFormat::utcNow();
  437. $datarray['uid'] = $params['uid'];
  438. $datarray['link'] = $itemlink;
  439. $datarray['iid'] = $item_id;
  440. $datarray['parent'] = $parent_id;
  441. $datarray['type'] = $params['type'];
  442. $datarray['verb'] = $params['verb'];
  443. $datarray['otype'] = $params['otype'];
  444. $datarray['abort'] = false;
  445. Hook::callAll('enotify_store', $datarray);
  446. if ($datarray['abort']) {
  447. L10n::popLang();
  448. return false;
  449. }
  450. // create notification entry in DB
  451. $fields = ['hash' => $datarray['hash'], 'name' => $datarray['name'], 'url' => $datarray['url'],
  452. 'photo' => $datarray['photo'], 'date' => $datarray['date'], 'uid' => $datarray['uid'],
  453. 'link' => $datarray['link'], 'iid' => $datarray['iid'], 'parent' => $datarray['parent'],
  454. 'type' => $datarray['type'], 'verb' => $datarray['verb'], 'otype' => $datarray['otype'],
  455. 'name_cache' => $datarray["name_cache"]];
  456. DBA::insert('notify', $fields);
  457. $notify_id = DBA::lastInsertId();
  458. // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
  459. // After we've stored everything, look again to see if there are any duplicates and if so remove them
  460. $p = q("SELECT `id` FROM `notify` WHERE `type` IN (%d, %d) AND `link` = '%s' AND `uid` = %d ORDER BY `id`",
  461. intval(NOTIFY_TAGSELF),
  462. intval(NOTIFY_COMMENT),
  463. DBA::escape($params['link']),
  464. intval($params['uid'])
  465. );
  466. if ($p && (count($p) > 1)) {
  467. for ($d = 1; $d < count($p); $d ++) {
  468. DBA::delete('notify', ['id' => $p[$d]['id']]);
  469. }
  470. // only continue on if we stored the first one
  471. if ($notify_id != $p[0]['id']) {
  472. L10n::popLang();
  473. return false;
  474. }
  475. }
  476. $itemlink = System::baseUrl().'/notify/view/'.$notify_id;
  477. $msg = Renderer::replaceMacros($epreamble, ['$itemlink' => $itemlink]);
  478. $msg_cache = format_notification_message($datarray['name_cache'], strip_tags(BBCode::convert($msg)));
  479. $fields = ['msg' => $msg, 'msg_cache' => $msg_cache];
  480. $condition = ['id' => $notify_id, 'uid' => $params['uid']];
  481. DBA::update('notify', $fields, $condition);
  482. }
  483. // send email notification if notification preferences permit
  484. if ((intval($params['notify_flags']) & intval($params['type']))
  485. || $params['type'] == NOTIFY_SYSTEM
  486. || $params['type'] == SYSTEM_EMAIL) {
  487. Logger::log('sending notification email');
  488. if (isset($params['parent']) && (intval($params['parent']) != 0)) {
  489. $id_for_parent = $params['parent']."@".$hostname;
  490. // Is this the first email notification for this parent item and user?
  491. if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
  492. Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
  493. $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
  494. 'receiver-uid' => $params['uid'], 'parent-item' => 0];
  495. DBA::insert('notify-threads', $fields);
  496. $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
  497. $log_msg = "include/enotify: No previous notification found for this parent:\n".
  498. " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
  499. Logger::log($log_msg, Logger::DEBUG);
  500. } else {
  501. // If not, just "follow" the thread.
  502. $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
  503. Logger::log("There's already a notification for this parent.", Logger::DEBUG);
  504. }
  505. }
  506. $textversion = BBCode::toPlaintext($body);
  507. $htmlversion = BBCode::convert($body);
  508. $datarray = [];
  509. $datarray['banner'] = $banner;
  510. $datarray['product'] = $product;
  511. $datarray['preamble'] = $preamble;
  512. $datarray['sitename'] = $sitename;
  513. $datarray['siteurl'] = $siteurl;
  514. $datarray['type'] = $params['type'];
  515. $datarray['parent'] = $parent_id;
  516. $datarray['source_name'] = $params['source_name'] ?? '';
  517. $datarray['source_link'] = $params['source_link'] ?? '';
  518. $datarray['source_photo'] = $params['source_photo'] ?? '';
  519. $datarray['uid'] = $params['uid'];
  520. $datarray['username'] = $params['to_name'] ?? '';
  521. $datarray['hsitelink'] = $hsitelink;
  522. $datarray['tsitelink'] = $tsitelink;
  523. $datarray['hitemlink'] = '<a href="'.$itemlink.'">'.$itemlink.'</a>';
  524. $datarray['titemlink'] = $itemlink;
  525. $datarray['thanks'] = $thanks;
  526. $datarray['site_admin'] = $site_admin;
  527. $datarray['title'] = stripslashes($title);
  528. $datarray['htmlversion'] = $htmlversion;
  529. $datarray['textversion'] = $textversion;
  530. $datarray['subject'] = $subject;
  531. $datarray['headers'] = $additional_mail_header;
  532. Hook::callAll('enotify_mail', $datarray);
  533. // check whether sending post content in email notifications is allowed
  534. // always true for SYSTEM_EMAIL
  535. $content_allowed = ((!Config::get('system', 'enotify_no_content')) || ($params['type'] == SYSTEM_EMAIL));
  536. // load the template for private message notifications
  537. $tpl = Renderer::getMarkupTemplate('email_notify_html.tpl');
  538. $email_html_body = Renderer::replaceMacros($tpl, [
  539. '$banner' => $datarray['banner'],
  540. '$product' => $datarray['product'],
  541. '$preamble' => str_replace("\n", "<br>\n", $datarray['preamble']),
  542. '$sitename' => $datarray['sitename'],
  543. '$siteurl' => $datarray['siteurl'],
  544. '$source_name' => $datarray['source_name'],
  545. '$source_link' => $datarray['source_link'],
  546. '$source_photo' => $datarray['source_photo'],
  547. '$username' => $datarray['username'],
  548. '$hsitelink' => $datarray['hsitelink'],
  549. '$hitemlink' => $datarray['hitemlink'],
  550. '$thanks' => $datarray['thanks'],
  551. '$site_admin' => $datarray['site_admin'],
  552. '$title' => $datarray['title'],
  553. '$htmlversion' => $datarray['htmlversion'],
  554. '$content_allowed' => $content_allowed,
  555. ]);
  556. // load the template for private message notifications
  557. $tpl = Renderer::getMarkupTemplate('email_notify_text.tpl');
  558. $email_text_body = Renderer::replaceMacros($tpl, [
  559. '$banner' => $datarray['banner'],
  560. '$product' => $datarray['product'],
  561. '$preamble' => $datarray['preamble'],
  562. '$sitename' => $datarray['sitename'],
  563. '$siteurl' => $datarray['siteurl'],
  564. '$source_name' => $datarray['source_name'],
  565. '$source_link' => $datarray['source_link'],
  566. '$source_photo' => $datarray['source_photo'],
  567. '$username' => $datarray['username'],
  568. '$tsitelink' => $datarray['tsitelink'],
  569. '$titemlink' => $datarray['titemlink'],
  570. '$thanks' => $datarray['thanks'],
  571. '$site_admin' => $datarray['site_admin'],
  572. '$title' => $datarray['title'],
  573. '$textversion' => $datarray['textversion'],
  574. '$content_allowed' => $content_allowed,
  575. ]);
  576. L10n::popLang();
  577. // use the Emailer class to send the message
  578. return Emailer::send([
  579. 'uid' => $params['uid'],
  580. 'fromName' => $sender_name,
  581. 'fromEmail' => $sender_email,
  582. 'replyTo' => $sender_email,
  583. 'toEmail' => $params['to_email'],
  584. 'messageSubject' => $datarray['subject'],
  585. 'htmlVersion' => $email_html_body,
  586. 'textVersion' => $email_text_body,
  587. 'additionalMailHeader' => $datarray['headers']
  588. ]);
  589. }
  590. L10n::popLang();
  591. return false;
  592. }
  593. /**
  594. * @brief Checks for users who should be notified
  595. *
  596. * @param int $itemid ID of the item for which the check should be done
  597. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  598. */
  599. function check_user_notification($itemid) {
  600. // fetch all users in the thread
  601. $users = DBA::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
  602. INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
  603. WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
  604. while ($user = DBA::fetch($users)) {
  605. check_item_notification($itemid, $user['uid']);
  606. }
  607. DBA::close($users);
  608. }
  609. /**
  610. * @brief Checks for item related notifications and sends them
  611. *
  612. * @param int $itemid ID of the item for which the check should be done
  613. * @param int $uid User ID
  614. * @param string $defaulttype (Optional) Forces a notification with this type.
  615. * @return bool
  616. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  617. */
  618. function check_item_notification($itemid, $uid, $defaulttype = "") {
  619. $notification_data = ["uid" => $uid, "profiles" => []];
  620. Hook::callAll('check_item_notification', $notification_data);
  621. $profiles = $notification_data["profiles"];
  622. $fields = ['nickname'];
  623. $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
  624. if (!DBA::isResult($user)) {
  625. return false;
  626. }
  627. $owner = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
  628. if (!DBA::isResult($owner)) {
  629. return false;
  630. }
  631. // This is our regular URL format
  632. $profiles[] = $owner["url"];
  633. // Notifications from Diaspora are often with an URL in the Diaspora format
  634. $profiles[] = System::baseUrl()."/u/".$user["nickname"];
  635. $profiles2 = [];
  636. foreach ($profiles AS $profile) {
  637. // Check for invalid profile urls. 13 should be the shortest possible profile length:
  638. // http://a.bc/d
  639. // Additionally check for invalid urls that would return the normalised value "http:"
  640. if ((strlen($profile) >= 13) && (Strings::normaliseLink($profile) != "http:")) {
  641. if (!in_array($profile, $profiles2))
  642. $profiles2[] = $profile;
  643. $profile = Strings::normaliseLink($profile);
  644. if (!in_array($profile, $profiles2))
  645. $profiles2[] = $profile;
  646. $profile = str_replace("http://", "https://", $profile);
  647. if (!in_array($profile, $profiles2))
  648. $profiles2[] = $profile;
  649. }
  650. }
  651. $profiles = $profiles2;
  652. $ret = DBA::select('contact', ['id'], ['uid' => 0, 'nurl' => $profiles]);
  653. $contacts = [];
  654. while ($contact = DBA::fetch($ret)) {
  655. $contacts[] = $contact['id'];
  656. }
  657. DBA::close($ret);
  658. // Only act if it is a "real" post
  659. // We need the additional check for the "local_profile" because of mixed situations on connector networks
  660. $fields = ['id', 'mention', 'tag', 'parent', 'title', 'body',
  661. 'author-link', 'author-name', 'author-avatar', 'author-id',
  662. 'guid', 'parent-uri', 'uri', 'contact-id', 'network'];
  663. $condition = ['id' => $itemid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'deleted' => false];
  664. $item = Item::selectFirstForUser($uid, $fields, $condition);
  665. if (!DBA::isResult($item) || in_array($item['author-id'], $contacts)) {
  666. return false;
  667. }
  668. // Generate the notification array
  669. $params = [];
  670. $params["uid"] = $uid;
  671. $params["item"] = $item;
  672. $params["parent"] = $item["parent"];
  673. $params["link"] = System::baseUrl().'/display/'.urlencode($item["guid"]);
  674. $params["otype"] = 'item';
  675. $params["source_name"] = $item["author-name"];
  676. $params["source_link"] = $item["author-link"];
  677. $params["source_photo"] = $item["author-avatar"];
  678. if ($item["parent-uri"] === $item["uri"]) {
  679. // Send a notification for every new post?
  680. $send_notification = DBA::exists('contact', ['id' => $item['contact-id'], 'notify_new_posts' => true]);
  681. if (!$send_notification) {
  682. $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
  683. intval(TERM_OBJ_POST), intval($itemid), intval(TERM_MENTION), intval($uid));
  684. if (DBA::isResult($tags)) {
  685. foreach ($tags AS $tag) {
  686. $condition = ['nurl' => Strings::normaliseLink($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
  687. $r = DBA::exists('contact', $condition);
  688. if ($r) {
  689. $send_notification = true;
  690. }
  691. }
  692. }
  693. }
  694. if ($send_notification) {
  695. $params["type"] = NOTIFY_SHARE;
  696. $params["verb"] = ACTIVITY_TAG;
  697. }
  698. }
  699. // Is the user mentioned in this post?
  700. $tagged = false;
  701. foreach ($profiles AS $profile) {
  702. if (strpos($item["tag"], "=".$profile."]") || strpos($item["body"], "=".$profile."]"))
  703. $tagged = true;
  704. }
  705. if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) {
  706. $params["type"] = NOTIFY_TAGSELF;
  707. $params["verb"] = ACTIVITY_TAG;
  708. }
  709. // Is it a post that the user had started?
  710. $fields = ['ignored', 'mention'];
  711. $thread = Item::selectFirstThreadForUser($params['uid'], $fields, ['iid' => $item["parent"], 'deleted' => false]);
  712. if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) {
  713. $params["type"] = NOTIFY_COMMENT;
  714. $params["verb"] = ACTIVITY_POST;
  715. }
  716. // And now we check for participation of one of our contacts in the thread
  717. $condition = ['parent' => $item["parent"], 'author-id' => $contacts, 'deleted' => false];
  718. if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) {
  719. $params["type"] = NOTIFY_COMMENT;
  720. $params["verb"] = ACTIVITY_POST;
  721. }
  722. if (isset($params["type"])) {
  723. notification($params);
  724. }
  725. }
  726. /**
  727. * @brief Formats a notification message with the notification author
  728. *
  729. * Replace the name with {0} but ensure to make that only once. The {0} is used
  730. * later and prints the name in bold.
  731. *
  732. * @param string $name
  733. * @param string $message
  734. * @return string Formatted message
  735. */
  736. function format_notification_message($name, $message) {
  737. if ($name != '') {
  738. $pos = strpos($message, $name);
  739. } else {
  740. $pos = false;
  741. }
  742. if ($pos !== false) {
  743. $message = substr_replace($message, '{0}', $pos, strlen($name));
  744. }
  745. return $message;
  746. }