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\Queue;
17 use Friendica\Model\User;
18 use Friendica\Protocol\DFRN;
19 use Friendica\Protocol\Diaspora;
20 use Friendica\Protocol\Email;
21 use Friendica\Util\Strings;
22 use Friendica\Util\Network;
24 class Delivery extends BaseObject
27 const SUGGESTION = 'suggest';
28 const RELOCATION = 'relocate';
29 const DELETION = 'drop';
30 const POST = 'wall-new';
31 const COMMENT = 'comment-new';
32 const REMOVAL = 'removeme';
33 const PROFILEUPDATE = 'profileupdate';
35 public static function execute($cmd, $item_id, $contact_id)
37 Logger::log('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, Logger::DEBUG);
41 $public_message = false;
44 if ($cmd == self::MAIL) {
45 $target_item = DBA::selectFirst('mail', [], ['id' => $item_id]);
46 if (!DBA::isResult($target_item)) {
49 $uid = $target_item['uid'];
50 } elseif ($cmd == self::SUGGESTION) {
51 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $item_id]);
52 if (!DBA::isResult($target_item)) {
55 $uid = $target_item['uid'];
56 } elseif ($cmd == self::RELOCATION) {
60 $item = Item::selectFirst(['parent'], ['id' => $item_id]);
61 if (!DBA::isResult($item) || empty($item['parent'])) {
64 $parent_id = intval($item['parent']);
66 $condition = ['id' => [$item_id, $parent_id], 'moderated' => false];
67 $params = ['order' => ['id']];
68 $itemdata = Item::select([], $condition, $params);
70 while ($item = Item::fetch($itemdata)) {
71 if ($item['id'] == $parent_id) {
74 if ($item['id'] == $item_id) {
79 DBA::close($itemdata);
81 if (empty($target_item)) {
82 Logger::log('Item ' . $item_id . "wasn't found. Quitting here.");
87 Logger::log('Parent ' . $parent_id . ' for item ' . $item_id . "wasn't found. Quitting here.");
91 if (!empty($target_item['contact-uid'])) {
92 $uid = $target_item['contact-uid'];
93 } elseif (!empty($target_item['uid'])) {
94 $uid = $target_item['uid'];
96 Logger::log('Only public users for item ' . $item_id, Logger::DEBUG);
100 // avoid race condition with deleting entries
101 if ($items[0]['deleted']) {
102 foreach ($items as $item) {
103 $item['deleted'] = 1;
107 // When commenting too fast after delivery, a post wasn't recognized as top level post.
108 // The count then showed more than one entry. The additional check should help.
109 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
110 if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
111 Logger::log('Top level post');
115 // This is IMPORTANT!!!!
117 // We will only send a "notify owner to relay" or followup message if the referenced post
118 // originated on our system by virtue of having our hostname somewhere
119 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
120 // if $parent['wall'] == 1 we will already have the parent message in our array
121 // and we will relay the whole lot.
123 $localhost = self::getApp()->getHostName();
124 if (strpos($localhost, ':')) {
125 $localhost = substr($localhost, 0, strpos($localhost, ':'));
129 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
130 * have been known to cause runaway conditions which affected several servers, along with
131 * permissions issues.
135 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
136 Logger::log('Followup ' . $target_item["guid"], Logger::DEBUG);
137 // local followup to remote post
141 if (empty($parent['allow_cid'])
142 && empty($parent['allow_gid'])
143 && empty($parent['deny_cid'])
144 && empty($parent['deny_gid'])
145 && !$parent["private"]) {
146 $public_message = true;
151 Logger::log('No delivery data for ' . $cmd . ' - Item ID: ' .$item_id . ' - Contact ID: ' . $contact_id);
154 $owner = User::getOwnerDataById($uid);
155 if (!DBA::isResult($owner)) {
159 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
160 $contact = DBA::selectFirst('contact', [],
161 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
163 if (!DBA::isResult($contact)) {
167 if (Network::isUrlBlocked($contact['url'])) {
171 // Transmit via Diaspora if the thread had started as Diaspora post
172 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
173 if (isset($parent) && ($parent['network'] == Protocol::DIASPORA) && ($contact['network'] == Protocol::DFRN)) {
174 $contact['network'] = Protocol::DIASPORA;
177 Logger::log("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
179 switch ($contact['network']) {
182 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
185 case Protocol::DIASPORA:
186 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
189 case Protocol::OSTATUS:
190 // Do not send to otatus if we are not configured to send to public networks
191 if ($owner['prvnets']) {
194 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
198 // There is currently no code here to distribute anything to OStatus.
199 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
203 self::deliverMail($cmd, $contact, $owner, $target_item);
214 * @brief Deliver content via DFRN
216 * @param string $cmd Command
217 * @param array $contact Contact record of the receiver
218 * @param array $owner Owner record of the sender
219 * @param array $items Item record of the content and the parent
220 * @param array $target_item Item record of the content
221 * @param boolean $public_message Is the content public?
222 * @param boolean $top_level Is it a thread starter?
223 * @param boolean $followup Is it an answer to a remote post?
225 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
227 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
229 if ($cmd == self::MAIL) {
230 $item = $target_item;
231 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
232 $atom = DFRN::mail($item, $owner);
233 } elseif ($cmd == self::SUGGESTION) {
234 $item = $target_item;
235 $atom = DFRN::fsuggest($item, $owner);
236 DBA::delete('fsuggest', ['id' => $item['id']]);
237 } elseif ($cmd == self::RELOCATION) {
238 $atom = DFRN::relocate($owner, $owner['uid']);
239 } elseif ($followup) {
240 $msgitems = [$target_item];
241 $atom = DFRN::entries($msgitems, $owner);
244 foreach ($items as $item) {
245 // Only add the parent when we don't delete other items.
246 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
247 $item["entry:comment-allow"] = true;
248 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
252 $atom = DFRN::entries($msgitems, $owner);
255 Logger::log('Notifier entry: ' . $contact["url"] . ' ' . defaults($target_item, 'guid', $target_item['id']) . ' entry: ' . $atom, Logger::DATA);
257 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
259 // perform local delivery if we are on the same site
261 if (Strings::compareLink($basepath, System::baseUrl())) {
262 $condition = ['nurl' => Strings::normaliseLink($contact['url']), 'self' => true];
263 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
264 if (!DBA::isResult($target_self)) {
267 $target_uid = $target_self['uid'];
269 // Check if the user has got this contact
270 $cid = Contact::getIdForURL($owner['url'], $target_uid);
272 // Otherwise there should be a public contact
273 $cid = Contact::getIdForURL($owner['url']);
279 $target_importer = DFRN::getImporter($cid, $target_uid);
280 if (empty($target_importer)) {
281 // This should never happen
285 DFRN::import($atom, $target_importer);
289 // We don't have a relationship with contacts on a public post.
290 // Se we transmit with the new method and via Diaspora as a fallback
291 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
292 // Transmit in public if it's a relay post
293 $public_dfrn = ($contact['contact-type'] == Contact::ACCOUNT_TYPE_RELAY);
295 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
297 // We never spool failed relay deliveries
299 Logger::log('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
303 if (($deliver_status < 200) || ($deliver_status > 299)) {
304 // Transmit via Diaspora if not possible via Friendica
305 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
308 } elseif ($cmd != self::RELOCATION) {
309 $deliver_status = DFRN::deliver($owner, $contact, $atom);
311 $deliver_status = DFRN::deliver($owner, $contact, $atom, false, true);
314 Logger::log('Delivery to ' . $contact['url'] . ' with guid ' . defaults($target_item, 'guid', $target_item['id']) . ' returns ' . $deliver_status);
316 if ($deliver_status < 0) {
317 Logger::log('Delivery failed: queuing message ' . defaults($target_item, 'guid', $target_item['id']));
318 Queue::add($contact['id'], Protocol::DFRN, $atom, false, $target_item['guid']);
321 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
322 // We successfully delivered a message, the contact is alive
323 Contact::unmarkForArchival($contact);
325 // The message could not be delivered. We mark the contact as "dead"
326 Contact::markForArchival($contact);
328 // Transmit via Diaspora when all other methods (legacy DFRN and new one) are failing.
329 // This is a fallback for systems that don't know the new methods.
330 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
335 * @brief Deliver content via Diaspora
337 * @param string $cmd Command
338 * @param array $contact Contact record of the receiver
339 * @param array $owner Owner record of the sender
340 * @param array $items Item record of the content and the parent
341 * @param array $target_item Item record of the content
342 * @param boolean $public_message Is the content public?
343 * @param boolean $top_level Is it a thread starter?
344 * @param boolean $followup Is it an answer to a remote post?
346 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
348 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
349 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY);
351 if ($public_message) {
352 $loc = 'public batch ' . $contact['batch'];
354 $loc = $contact['addr'];
357 Logger::log('Deliver ' . defaults($target_item, 'guid', $target_item['id']) . ' via Diaspora to ' . $loc);
359 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
362 if ($cmd == self::MAIL) {
363 Diaspora::sendMail($target_item, $owner, $contact);
367 if ($cmd == self::SUGGESTION) {
370 if (!$contact['pubkey'] && !$public_message) {
373 if ($cmd == self::RELOCATION) {
374 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
376 } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
377 // top-level retraction
378 Logger::log('diaspora retract: ' . $loc);
379 Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
381 } elseif ($followup) {
382 // send comments and likes to owner to relay
383 Logger::log('diaspora followup: ' . $loc);
384 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
386 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
387 // we are the relay - send comments, likes and relayable_retractions to our conversants
388 Logger::log('diaspora relay: ' . $loc);
389 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
391 } elseif ($top_level && !$walltowall) {
392 // currently no workable solution for sending walltowall
393 Logger::log('diaspora status: ' . $loc);
394 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
398 Logger::log('Unknown mode ' . $cmd . ' for ' . $loc);
402 * @brief Deliver content via mail
404 * @param string $cmd Command
405 * @param array $contact Contact record of the receiver
406 * @param array $owner Owner record of the sender
407 * @param array $target_item Item record of the content
409 private static function deliverMail($cmd, $contact, $owner, $target_item)
411 if (Config::get('system','dfrn_only')) {
414 // WARNING: does not currently convert to RFC2047 header encodings, etc.
416 $addr = $contact['addr'];
417 if (!strlen($addr)) {
421 if (!in_array($cmd, [self::POST, self::COMMENT])) {
425 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
426 if (!DBA::isResult($local_user)) {
430 Logger::log('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
433 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
434 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
435 $reply_to = $mailacct['reply_to'];
438 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
440 // only expose our real email address to true friends
442 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
444 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
445 $headers .= 'Sender: ' . $local_user['email'] . "\n";
447 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
450 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->getHostName() . '>' . "\n";
453 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
455 if ($target_item['uri'] !== $target_item['parent-uri']) {
456 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
458 // If Threading is enabled, write down the correct parent
459 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
460 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
465 if (empty($target_item['title'])) {
466 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
467 $title = Item::selectFirst(['title'], $condition);
469 if (DBA::isResult($title) && ($title['title'] != '')) {
470 $subject = $title['title'];
472 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
473 $title = Item::selectFirst(['title'], $condition);
475 if (DBA::isResult($title) && ($title['title'] != '')) {
476 $subject = $title['title'];
481 if (strncasecmp($subject, 'RE:', 3)) {
482 $subject = 'Re: ' . $subject;
486 Email::send($addr, $subject, $headers, $target_item);