3 * @file src/Worker/Delivery.php
5 namespace Friendica\Worker;
7 use Friendica\BaseObject;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Model\ItemDeliveryData;
17 use Friendica\Model\Queue;
18 use Friendica\Model\User;
19 use Friendica\Protocol\DFRN;
20 use Friendica\Protocol\Diaspora;
21 use Friendica\Protocol\Email;
22 use Friendica\Util\Strings;
23 use Friendica\Util\Network;
25 class Delivery extends BaseObject
28 const SUGGESTION = 'suggest';
29 const RELOCATION = 'relocate';
30 const DELETION = 'drop';
31 const POST = 'wall-new';
32 const COMMENT = 'comment-new';
33 const REMOVAL = 'removeme';
34 const PROFILEUPDATE = 'profileupdate';
36 public static function execute($cmd, $target_id, $contact_id)
38 Logger::log('Invoked: ' . $cmd . ': ' . $target_id . ' to ' . $contact_id, Logger::DEBUG);
42 $public_message = false;
45 if ($cmd == self::MAIL) {
46 $target_item = DBA::selectFirst('mail', [], ['id' => $target_id]);
47 if (!DBA::isResult($target_item)) {
50 $uid = $target_item['uid'];
51 } elseif ($cmd == self::SUGGESTION) {
52 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $target_id]);
53 if (!DBA::isResult($target_item)) {
56 $uid = $target_item['uid'];
57 } elseif ($cmd == self::RELOCATION) {
61 $item = Item::selectFirst(['parent'], ['id' => $target_id]);
62 if (!DBA::isResult($item) || empty($item['parent'])) {
65 $parent_id = intval($item['parent']);
67 $condition = ['id' => [$target_id, $parent_id], 'moderated' => false];
68 $params = ['order' => ['id']];
69 $itemdata = Item::select([], $condition, $params);
71 while ($item = Item::fetch($itemdata)) {
72 if ($item['id'] == $parent_id) {
75 if ($item['id'] == $target_id) {
80 DBA::close($itemdata);
82 if (empty($target_item)) {
83 Logger::log('Item ' . $target_id . "wasn't found. Quitting here.");
88 Logger::log('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here.");
92 if (!empty($target_item['contact-uid'])) {
93 $uid = $target_item['contact-uid'];
94 } elseif (!empty($target_item['uid'])) {
95 $uid = $target_item['uid'];
97 Logger::log('Only public users for item ' . $item_id, Logger::DEBUG);
101 // avoid race condition with deleting entries
102 if ($items[0]['deleted']) {
103 foreach ($items as $item) {
104 $item['deleted'] = 1;
108 // When commenting too fast after delivery, a post wasn't recognized as top level post.
109 // The count then showed more than one entry. The additional check should help.
110 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
111 if ((($parent['id'] == $target_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
112 Logger::log('Top level post');
116 // This is IMPORTANT!!!!
118 // We will only send a "notify owner to relay" or followup message if the referenced post
119 // originated on our system by virtue of having our hostname somewhere
120 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
121 // if $parent['wall'] == 1 we will already have the parent message in our array
122 // and we will relay the whole lot.
124 $localhost = self::getApp()->getHostName();
125 if (strpos($localhost, ':')) {
126 $localhost = substr($localhost, 0, strpos($localhost, ':'));
130 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
131 * have been known to cause runaway conditions which affected several servers, along with
132 * permissions issues.
136 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
137 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
138 // local followup to remote post
142 if (empty($parent['allow_cid'])
143 && empty($parent['allow_gid'])
144 && empty($parent['deny_cid'])
145 && empty($parent['deny_gid'])
146 && !$parent["private"]) {
147 $public_message = true;
152 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$target_id . ' - Contact ID: ' . $contact_id);
155 $owner = User::getOwnerDataById($uid);
156 if (!DBA::isResult($owner)) {
160 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
161 $contact = DBA::selectFirst('contact', [],
162 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
164 if (!DBA::isResult($contact)) {
168 if (Network::isUrlBlocked($contact['url'])) {
172 // Transmit via Diaspora if the thread had started as Diaspora post
173 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
174 if (isset($parent) && ($parent['network'] == Protocol::DIASPORA) && ($contact['network'] == Protocol::DFRN)) {
175 $contact['network'] = Protocol::DIASPORA;
178 Logger::log("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
180 switch ($contact['network']) {
183 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
185 if (in_array($cmd, [Delivery::POST, Delivery::COMMENT])) {
186 ItemDeliveryData::incrementQueueDone($target_id);
190 case Protocol::DIASPORA:
191 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
193 if (in_array($cmd, [Delivery::POST, Delivery::COMMENT])) {
194 ItemDeliveryData::incrementQueueDone($target_id);
198 case Protocol::OSTATUS:
199 // Do not send to otatus if we are not configured to send to public networks
200 if ($owner['prvnets']) {
203 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
207 // There is currently no code here to distribute anything to OStatus.
208 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
212 self::deliverMail($cmd, $contact, $owner, $target_item);
223 * @brief Deliver content via DFRN
225 * @param string $cmd Command
226 * @param array $contact Contact record of the receiver
227 * @param array $owner Owner record of the sender
228 * @param array $items Item record of the content and the parent
229 * @param array $target_item Item record of the content
230 * @param boolean $public_message Is the content public?
231 * @param boolean $top_level Is it a thread starter?
232 * @param boolean $followup Is it an answer to a remote post?
234 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
236 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
238 if ($cmd == self::MAIL) {
239 $item = $target_item;
240 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
241 $atom = DFRN::mail($item, $owner);
242 } elseif ($cmd == self::SUGGESTION) {
243 $item = $target_item;
244 $atom = DFRN::fsuggest($item, $owner);
245 DBA::delete('fsuggest', ['id' => $item['id']]);
246 } elseif ($cmd == self::RELOCATION) {
247 $atom = DFRN::relocate($owner, $owner['uid']);
248 } elseif ($followup) {
249 $msgitems = [$target_item];
250 $atom = DFRN::entries($msgitems, $owner);
253 foreach ($items as $item) {
254 // Only add the parent when we don't delete other items.
255 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
256 $item["entry:comment-allow"] = true;
257 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
261 $atom = DFRN::entries($msgitems, $owner);
264 Logger::log('Notifier entry: ' . $contact["url"] . ' ' . defaults($target_item, 'guid', $target_item['id']) . ' entry: ' . $atom, Logger::DATA);
266 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
268 // perform local delivery if we are on the same site
270 if (Strings::compareLink($basepath, System::baseUrl())) {
271 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
272 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
273 if (!DBA::isResult($target_self)) {
276 $target_uid = $target_self['uid'];
278 // Check if the user has got this contact
279 $cid = Contact::getIdForURL($owner['url'], $target_uid);
281 // Otherwise there should be a public contact
282 $cid = Contact::getIdForURL($owner['url']);
288 $target_importer = DFRN::getImporter($cid, $target_uid);
289 if (empty($target_importer)) {
290 // This should never happen
294 DFRN::import($atom, $target_importer);
298 // We don't have a relationship with contacts on a public post.
299 // Se we transmit with the new method and via Diaspora as a fallback
300 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
301 // Transmit in public if it's a relay post
302 $public_dfrn = ($contact['contact-type'] == Contact::ACCOUNT_TYPE_RELAY);
304 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
306 // We never spool failed relay deliveries
308 Logger::log('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
312 if (($deliver_status < 200) || ($deliver_status > 299)) {
313 // Transmit via Diaspora if not possible via Friendica
314 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
317 } elseif ($cmd != self::RELOCATION) {
318 $deliver_status = DFRN::deliver($owner, $contact, $atom);
320 $deliver_status = DFRN::deliver($owner, $contact, $atom, false, true);
323 Logger::log('Delivery to ' . $contact['url'] . ' with guid ' . defaults($target_item, 'guid', $target_item['id']) . ' returns ' . $deliver_status);
325 if ($deliver_status < 0) {
326 Logger::log('Delivery failed: queuing message ' . defaults($target_item, 'guid', $target_item['id']));
327 Queue::add($contact['id'], Protocol::DFRN, $atom, false, $target_item['guid']);
330 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
331 // We successfully delivered a message, the contact is alive
332 Contact::unmarkForArchival($contact);
334 // The message could not be delivered. We mark the contact as "dead"
335 Contact::markForArchival($contact);
337 // Transmit via Diaspora when all other methods (legacy DFRN and new one) are failing.
338 // This is a fallback for systems that don't know the new methods.
339 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
344 * @brief Deliver content via Diaspora
346 * @param string $cmd Command
347 * @param array $contact Contact record of the receiver
348 * @param array $owner Owner record of the sender
349 * @param array $items Item record of the content and the parent
350 * @param array $target_item Item record of the content
351 * @param boolean $public_message Is the content public?
352 * @param boolean $top_level Is it a thread starter?
353 * @param boolean $followup Is it an answer to a remote post?
355 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
357 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
358 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY);
360 if ($public_message) {
361 $loc = 'public batch ' . $contact['batch'];
363 $loc = $contact['addr'];
366 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via Diaspora to ' . $loc);
368 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
371 if ($cmd == self::MAIL) {
372 Diaspora::sendMail($target_item, $owner, $contact);
376 if ($cmd == self::SUGGESTION) {
379 if (!$contact['pubkey'] && !$public_message) {
382 if ($cmd == self::RELOCATION) {
383 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
385 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
386 // top-level retraction
387 Logger::log('diaspora retract: ' . $loc);
388 Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
390 } elseif ($followup) {
391 // send comments and likes to owner to relay
392 Logger::log('diaspora followup: ' . $loc);
393 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
395 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
396 // we are the relay - send comments, likes and relayable_retractions to our conversants
397 Logger::log('diaspora relay: ' . $loc);
398 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
400 } elseif ($top_level && !$walltowall) {
401 // currently no workable solution for sending walltowall
402 Logger::log('diaspora status: ' . $loc);
403 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
407 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
411 * @brief Deliver content via mail
413 * @param string $cmd Command
414 * @param array $contact Contact record of the receiver
415 * @param array $owner Owner record of the sender
416 * @param array $target_item Item record of the content
418 private static function deliverMail($cmd, $contact, $owner, $target_item)
420 if (Config::get('system','dfrn_only')) {
423 // WARNING: does not currently convert to RFC2047 header encodings, etc.
425 $addr = $contact['addr'];
426 if (!strlen($addr)) {
430 if (!in_array($cmd, [self::POST, self::COMMENT])) {
434 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
435 if (!DBA::isResult($local_user)) {
439 Logger::log('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
442 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
443 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
444 $reply_to = $mailacct['reply_to'];
447 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
449 // only expose our real email address to true friends
451 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
453 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
454 $headers .= 'Sender: ' . $local_user['email'] . "\n";
456 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
459 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->getHostName() . '>' . "\n";
462 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
464 if ($target_item['uri'] !== $target_item['parent-uri']) {
465 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
467 // If Threading is enabled, write down the correct parent
468 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
469 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
474 if (empty($target_item['title'])) {
475 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
476 $title = Item::selectFirst(['title'], $condition);
478 if (DBA::isResult($title) && ($title['title'] != '')) {
479 $subject = $title['title'];
481 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
482 $title = Item::selectFirst(['title'], $condition);
484 if (DBA::isResult($title) && ($title['title'] != '')) {
485 $subject = $title['title'];
490 if (strncasecmp($subject, 'RE:', 3)) {
491 $subject = 'Re: ' . $subject;
495 Email::send($addr, $subject, $headers, $target_item);