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.

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