3 * @file src/Worker/Notifier.php
5 namespace Friendica\Worker;
7 use Friendica\Core\Config;
8 use Friendica\Core\Worker;
9 use Friendica\Database\DBM;
10 use Friendica\Model\Contact;
11 use Friendica\Model\Group;
12 use Friendica\Model\User;
13 use Friendica\Network\Probe;
14 use Friendica\Protocol\Diaspora;
15 use Friendica\Protocol\OStatus;
16 use Friendica\Protocol\Salmon;
19 require_once 'include/dba.php';
20 require_once 'include/queue_fn.php';
21 require_once 'include/html2plain.php';
22 require_once 'include/datetime.php';
23 require_once 'include/items.php';
24 require_once 'include/bbcode.php';
27 * This file was at one time responsible for doing all deliveries, but this caused
28 * big problems when the process was killed or stalled during the delivery process.
29 * It now invokes separate queues that are delivering via delivery.php and pubsubpublish.php.
33 * The notifier is typically called with:
35 * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
37 * where COMMAND is one of the following:
39 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
40 * comment-import (in diaspora.php, items.php)
41 * comment-new (in item.php)
42 * drop (in diaspora.php, items.php, photos.php)
43 * edit_post (in item.php)
44 * event (in events.php)
45 * expire (in items.php)
46 * like (in like.php, poke.php)
47 * mail (in message.php)
48 * suggest (in fsuggest.php)
49 * tag (in photos.php, poke.php, tagger.php)
50 * tgroup (in items.php)
51 * wall-new (in photos.php, item.php)
52 * removeme (in Contact.php)
53 * relocate (in uimport.php)
55 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
59 public static function execute($cmd, $item_id) {
62 logger('notifier: invoked: '.$cmd.': '.$item_id, LOGGER_DEBUG);
69 $recipients = array();
70 $url_recipients = array();
74 if ($cmd === 'mail') {
77 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
80 if (!count($message)) {
83 $uid = $message[0]['uid'];
84 $recipients[] = $message[0]['contact-id'];
87 } elseif ($cmd === 'expire') {
90 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
91 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
99 } elseif ($cmd === 'suggest') {
100 $normal_mode = false;
103 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
106 if (!count($suggest)) {
109 $uid = $suggest[0]['uid'];
110 $recipients[] = $suggest[0]['cid'];
112 } elseif ($cmd === 'removeme') {
113 $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
114 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
115 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
116 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
117 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
124 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
128 foreach ($r as $contact) {
129 Contact::terminateFriendship($user, $contact);
132 } elseif ($cmd === 'relocate') {
133 $normal_mode = false;
137 $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
138 intval($uid), NETWORK_DFRN, NETWORK_DIASPORA);
141 $target_item = dba::fetch_first("SELECT `item`.*, `contact`.`uid` AS `cuid` FROM `item`
142 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
143 WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $item_id);
145 if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
149 $parent_id = intval($target_item['parent']);
150 $uid = $target_item['cuid'];
151 $updated = $target_item['edited'];
153 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
154 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible AND NOT moderated ORDER BY `id` ASC",
158 if (!count($items)) {
162 // avoid race condition with deleting entries
163 if ($items[0]['deleted']) {
164 foreach ($items as $item) {
165 $item['deleted'] = 1;
169 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
170 logger('notifier: top level post');
175 $owner = User::getOwnerDataById($uid);
180 $walltowall = ($top_level && ($owner['id'] != $items[0]['contact-id']) ? true : false);
182 // Should the post be transmitted to Diaspora?
183 $diaspora_delivery = true;
185 // If this is a public conversation, notify the feed hub
186 $public_message = true;
189 $push_notify = false;
191 // Deliver directly to a forum, don't PuSH
192 $direct_forum_delivery = false;
194 // fill this in with a single salmon slap if applicable
197 if (! ($mail || $fsuggest || $relocate)) {
199 $slap = OStatus::salmon($target_item, $owner);
203 $thr_parent = q("SELECT `network`, `author-link`, `owner-link` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
204 dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
206 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
208 // This is IMPORTANT!!!!
210 // We will only send a "notify owner to relay" or followup message if the referenced post
211 // originated on our system by virtue of having our hostname somewhere
212 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
214 // if $parent['wall'] == 1 we will already have the parent message in our array
215 // and we will relay the whole lot.
217 // expire sends an entire group of expire messages and cannot be forwarded.
218 // However the conversation owner will be a part of the conversation and will
219 // be notified during this run.
220 // Other DFRN conversation members will be alerted during polled updates.
224 // Diaspora members currently are not notified of expirations, and other networks have
225 // either limited or no ability to process deletions. We should at least fix Diaspora
226 // by stringing togther an array of retractions and sending them onward.
229 $localhost = str_replace('www.','',$a->get_hostname());
230 if (strpos($localhost,':')) {
231 $localhost = substr($localhost,0,strpos($localhost,':'));
235 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
236 * have been known to cause runaway conditions which affected several servers, along with
237 * permissions issues.
241 $relay_to_owner = false;
243 if (!$top_level && ($parent['wall'] == 0) && !$expire && (stristr($target_item['uri'],$localhost))) {
244 $relay_to_owner = true;
248 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
249 $relay_to_owner = true;
252 // until the 'origin' flag has been in use for several months
253 // we will just use it as a fallback test
254 // later we will be able to use it as the primary test of whether or not to relay.
256 if (!$target_item['origin']) {
257 $relay_to_owner = false;
259 if ($parent['origin']) {
260 $relay_to_owner = false;
263 // Special treatment for forum posts
264 if (($target_item['author-link'] != $target_item['owner-link']) &&
265 ($owner['id'] != $target_item['contact-id']) &&
266 ($target_item['uri'] === $target_item['parent-uri'])) {
268 $fields = array('forum', 'prv');
269 $condition = array('id' => $target_item['contact-id']);
270 $contact = dba::select('contact', $fields, $condition, array('limit' => 1));
271 if (!DBM::is_result($contact)) {
272 // Should never happen
276 // Is the post from a forum?
277 if ($contact['forum'] || $contact['prv']) {
278 $relay_to_owner = true;
279 $direct_forum_delivery = true;
282 if ($relay_to_owner) {
283 // local followup to remote post
285 $public_message = false; // not public
286 $conversant_str = dbesc($parent['contact-id']);
287 $recipients = array($parent['contact-id']);
288 $recipients_followup = array($parent['contact-id']);
290 logger('notifier: followup '.$target_item["guid"].' to '.$conversant_str, LOGGER_DEBUG);
292 //if (!$target_item['private'] && $target_item['wall'] &&
293 if (!$target_item['private'] &&
294 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
295 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
298 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
301 if ($parent["network"] == NETWORK_OSTATUS) {
302 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
303 // Currently it is work at progress
304 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
308 if (DBM::is_result($r)) {
309 foreach ($r as $rr) {
310 $recipients_followup[] = $rr['id'];
316 if ($direct_forum_delivery) {
317 $push_notify = false;
320 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
324 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
326 // don't send deletions onward for other people's stuff
328 if ($target_item['deleted'] && !intval($target_item['wall'])) {
329 logger('notifier: ignoring delete notification for non-wall item');
333 if (strlen($parent['allow_cid'])
334 || strlen($parent['allow_gid'])
335 || strlen($parent['deny_cid'])
336 || strlen($parent['deny_gid'])) {
337 $public_message = false; // private recipients, not public
340 $allow_people = expand_acl($parent['allow_cid']);
341 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
342 $deny_people = expand_acl($parent['deny_cid']);
343 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
345 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
346 // a delivery fork. private groups (forum_mode == 2) do not uplink
348 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
349 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
352 $conversants = array();
354 foreach ($items as $item) {
355 $recipients[] = $item['contact-id'];
356 $conversants[] = $item['contact-id'];
357 // pull out additional tagged people to notify (if public message)
358 if ($public_message && strlen($item['inform'])) {
359 $people = explode(',',$item['inform']);
360 foreach ($people as $person) {
361 if (substr($person,0,4) === 'cid:') {
362 $recipients[] = intval(substr($person,4));
363 $conversants[] = intval(substr($person,4));
365 $url_recipients[] = substr($person,4);
371 if (count($url_recipients)) {
372 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
375 $conversants = array_unique($conversants);
377 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
378 $deny = array_unique(array_merge($deny_people,$deny_groups));
379 $recipients = array_diff($recipients,$deny);
381 $conversant_str = dbesc(implode(', ',$conversants));
384 // If the thread parent is OStatus then do some magic to distribute the messages.
385 // We have not only to look at the parent, since it could be a Friendica thread.
386 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
387 $diaspora_delivery = false;
389 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent[0]['author-link']." - Owner: ".$thr_parent[0]['owner-link'], LOGGER_DEBUG);
391 // Send a salmon to the parent author
392 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
393 dbesc(normalise_link($thr_parent[0]['author-link'])),
395 if (DBM::is_result($r)) {
396 $probed_contact = $r[0];
398 $probed_contact = Probe::uri($thr_parent[0]['author-link']);
401 if ($probed_contact["notify"] != "") {
402 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
403 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
406 // Send a salmon to the parent owner
407 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
408 dbesc(normalise_link($thr_parent[0]['owner-link'])),
410 if (DBM::is_result($r)) {
411 $probed_contact = $r[0];
413 $probed_contact = Probe::uri($thr_parent[0]['owner-link']);
416 if ($probed_contact["notify"] != "") {
417 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
418 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
421 // Send a salmon notification to every person we mentioned in the post
422 $arr = explode(',',$target_item['tag']);
423 foreach ($arr as $x) {
424 //logger('Checking tag '.$x, LOGGER_DEBUG);
426 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
427 $probed_contact = Probe::uri($matches[1]);
428 if ($probed_contact["notify"] != "") {
429 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
430 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
435 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
436 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."')";
438 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."', '".NETWORK_DIASPORA."', '".NETWORK_MAIL."')";
441 $public_message = false;
444 // If this is a public message and pubmail is set on the parent, include all your email contacts
446 $mail_disabled = ((function_exists('imap_open') && (!Config::get('system','imap_disabled'))) ? 0 : 1);
448 if (!$mail_disabled) {
449 if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
450 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
451 && intval($target_item['pubmail'])) {
452 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
456 if (DBM::is_result($r)) {
457 foreach ($r as $rr) {
458 $recipients[] = $rr['id'];
465 $recip_str = implode(', ', $recipients_followup);
467 $recip_str = implode(', ', $recipients);
470 $r = $recipients_relocate;
472 $r = q("SELECT `id`, `url`, `network`, `self` FROM `contact`
473 WHERE `id` IN (%s) AND NOT `blocked` AND NOT `pending` AND NOT `archive`".$sql_extra,
480 if (DBM::is_result($r)) {
481 foreach ($r as $contact) {
482 if ($contact['self']) {
485 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
487 Worker::add(array('priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true),
488 'Delivery', $cmd, $item_id, (int)$contact['id']);
492 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
493 // They are especially used for notifications to OStatus users that don't follow us.
495 if ($slap && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
496 if (!Config::get('system', 'dfrn_only')) {
497 foreach ($url_recipients as $url) {
499 logger('notifier: urldelivery: ' . $url);
500 $deliver_status = Salmon::slapper($owner, $url, $slap);
501 /// @TODO Redeliver/queue these items on failure, though there is no contact record
508 if ($public_message) {
513 if ($diaspora_delivery) {
515 $r0 = Diaspora::relayList();
518 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
519 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
520 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
521 dbesc(NETWORK_DIASPORA),
522 intval($owner['uid']),
523 intval(CONTACT_IS_SHARING)
527 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
528 WHERE `network` in ('%s') AND `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `rel` != %d",
530 intval($owner['uid']),
531 intval(CONTACT_IS_SHARING)
534 $r = array_merge($r2,$r1,$r0);
536 if (DBM::is_result($r)) {
537 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
539 foreach ($r as $rr) {
541 // except for Diaspora batch jobs
542 // Don't deliver to folks who have already been delivered to
544 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
545 logger('notifier: already delivered id=' . $rr['id']);
549 if (!$mail && !$fsuggest && !$followup) {
550 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
551 Worker::add(array('priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true),
552 'Delivery', $cmd, $item_id, (int)$rr['id']);
561 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
563 // Set push flag for PuSH subscribers to this topic,
564 // they will be notified in queue.php
565 q("UPDATE `push_subscriber` SET `push` = 1 ".
566 "WHERE `nickname` = '%s' AND `push` = 0", dbesc($owner['nickname']));
568 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
570 // Handling the pubsubhubbub requests
571 Worker::add(array('priority' => PRIORITY_HIGH, 'created' => $a->queue['created'], 'dont_fork' => true),
575 logger('notifier: calling hooks', LOGGER_DEBUG);
578 call_hooks('notifier_normal',$target_item);
581 call_hooks('notifier_end',$target_item);