Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

838 linhas
30 KiB

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