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.

868 lines
31 KiB

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