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.

810 lines
29KB

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