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.

811 lines
29KB

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