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.

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