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\Protocol;
11 use Friendica\Core\System;
12 use Friendica\Database\DBA;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Item;
15 use Friendica\Model\Queue;
16 use Friendica\Model\User;
17 use Friendica\Protocol\DFRN;
18 use Friendica\Protocol\Diaspora;
19 use Friendica\Protocol\Email;
21 require_once 'include/items.php';
23 class Delivery extends BaseObject
26 const SUGGESTION = 'suggest';
27 const RELOCATION = 'relocate';
28 const DELETION = 'drop';
29 const POST = 'wall-new';
30 const COMMENT = 'comment-new';
31 const REMOVAL = 'removeme';
32 const PROFILEUPDATE = 'profileupdate';
34 public static function execute($cmd, $item_id, $contact_id)
36 logger('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, LOGGER_DEBUG);
40 $public_message = false;
42 if ($cmd == self::MAIL) {
43 $target_item = DBA::selectFirst('mail', [], ['id' => $item_id]);
44 if (!DBA::isResult($target_item)) {
47 $uid = $target_item['uid'];
49 } elseif ($cmd == self::SUGGESTION) {
50 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $item_id]);
51 if (!DBA::isResult($target_item)) {
54 $uid = $target_item['uid'];
55 } elseif ($cmd == self::RELOCATION) {
58 $item = Item::selectFirst(['parent'], ['id' => $item_id]);
59 if (!DBA::isResult($item) || empty($item['parent'])) {
62 $parent_id = intval($item['parent']);
64 $condition = ['id' => [$item_id, $parent_id], 'moderated' => false];
65 $params = ['order' => ['id']];
66 $itemdata = Item::select([], $condition, $params);
69 while ($item = Item::fetch($itemdata)) {
70 if ($item['id'] == $parent_id) {
73 if ($item['id'] == $item_id) {
78 DBA::close($itemdata);
80 if (empty($target_item)) {
81 logger('Item ' . $item_id . "wasn't found. Quitting here.");
86 logger('Parent ' . $parent_id . ' for item ' . $item_id . "wasn't found. Quitting here.");
90 $uid = $target_item['contact-uid'];
92 // avoid race condition with deleting entries
93 if ($items[0]['deleted']) {
94 foreach ($items as $item) {
99 // When commenting too fast after delivery, a post wasn't recognized as top level post.
100 // The count then showed more than one entry. The additional check should help.
101 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
102 if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
103 logger('Top level post');
107 // This is IMPORTANT!!!!
109 // We will only send a "notify owner to relay" or followup message if the referenced post
110 // originated on our system by virtue of having our hostname somewhere
111 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
112 // if $parent['wall'] == 1 we will already have the parent message in our array
113 // and we will relay the whole lot.
115 $localhost = self::getApp()->get_hostname();
116 if (strpos($localhost, ':')) {
117 $localhost = substr($localhost, 0, strpos($localhost, ':'));
121 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
122 * have been known to cause runaway conditions which affected several servers, along with
123 * permissions issues.
127 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
128 logger('Followup ' . $target_item["guid"], LOGGER_DEBUG);
129 // local followup to remote post
133 if (empty($parent['allow_cid'])
134 && empty($parent['allow_gid'])
135 && empty($parent['deny_cid'])
136 && empty($parent['deny_gid'])
137 && !$parent["private"]) {
138 $public_message = true;
143 logger('No delivery data for ' . $cmd . ' - Item ID: ' .$item_id . ' - Contact ID: ' . $contact_id);
146 $owner = User::getOwnerDataById($uid);
147 if (!DBA::isResult($owner)) {
151 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
152 $contact = DBA::selectFirst('contact', [],
153 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
155 if (!DBA::isResult($contact)) {
159 // Transmit via Diaspora if the thread had started as Diaspora post
160 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
161 if (isset($parent) && ($parent['network'] == Protocol::DIASPORA) && ($contact['network'] == Protocol::DFRN)) {
162 $contact['network'] = Protocol::DIASPORA;
165 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
167 switch ($contact['network']) {
170 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
173 case Protocol::DIASPORA:
174 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
177 case Protocol::OSTATUS:
178 // Do not send to otatus if we are not configured to send to public networks
179 if ($owner['prvnets']) {
182 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
186 // There is currently no code here to distribute anything to OStatus.
187 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
191 self::deliverMail($cmd, $contact, $owner, $target_item);
202 * @brief Deliver content via DFRN
204 * @param string $cmd Command
205 * @param array $contact Contact record of the receiver
206 * @param array $owner Owner record of the sender
207 * @param array $items Item record of the content and the parent
208 * @param array $target_item Item record of the content
209 * @param boolean $public_message Is the content public?
210 * @param boolean $top_level Is it a thread starter?
211 * @param boolean $followup Is it an answer to a remote post?
213 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
215 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
217 if ($cmd == self::MAIL) {
218 $item = $target_item;
219 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
220 $atom = DFRN::mail($item, $owner);
221 } elseif ($cmd == self::SUGGESTION) {
222 $item = $target_item;
223 $atom = DFRN::fsuggest($item, $owner);
224 DBA::delete('fsuggest', ['id' => $item['id']]);
225 } elseif ($cmd == self::RELOCATION) {
226 $atom = DFRN::relocate($owner, $owner['uid']);
227 } elseif ($followup) {
228 $msgitems = [$target_item];
229 $atom = DFRN::entries($msgitems, $owner);
232 foreach ($items as $item) {
233 // Only add the parent when we don't delete other items.
234 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
235 $item["entry:comment-allow"] = true;
236 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
240 $atom = DFRN::entries($msgitems, $owner);
243 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
245 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
247 // perform local delivery if we are on the same site
249 if (link_compare($basepath, System::baseUrl())) {
250 $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
251 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
252 if (!DBA::isResult($target_self)) {
255 $target_uid = $target_self['uid'];
257 // Check if the user has got this contact
258 $cid = Contact::getIdForURL($owner['url'], $target_uid);
260 // Otherwise there should be a public contact
261 $cid = Contact::getIdForURL($owner['url']);
267 $target_importer = DFRN::getImporter($cid, $target_uid);
268 if (empty($target_importer)) {
269 // This should never happen
273 DFRN::import($atom, $target_importer);
277 // We don't have a relationship with contacts on a public post.
278 // Se we transmit with the new method and via Diaspora as a fallback
279 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
280 // Transmit in public if it's a relay post
281 $public_dfrn = ($contact['contact-type'] == Contact::ACCOUNT_TYPE_RELAY);
283 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
285 // We never spool failed relay deliveries
287 logger('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
291 if (($deliver_status < 200) || ($deliver_status > 299)) {
292 // Transmit via Diaspora if not possible via Friendica
293 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
296 } elseif ($cmd != self::RELOCATION) {
297 $deliver_status = DFRN::deliver($owner, $contact, $atom);
299 $deliver_status = DFRN::deliver($owner, $contact, $atom, false, true);
302 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
304 if ($deliver_status < 0) {
305 logger('Delivery failed: queuing message ' . $target_item["guid"] );
306 Queue::add($contact['id'], Protocol::DFRN, $atom, false, $target_item['guid']);
309 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
310 // We successfully delivered a message, the contact is alive
311 Contact::unmarkForArchival($contact);
313 // The message could not be delivered. We mark the contact as "dead"
314 Contact::markForArchival($contact);
316 // Transmit via Diaspora when all other methods (legacy DFRN and new one) are failing.
317 // This is a fallback for systems that don't know the new methods.
318 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
323 * @brief Deliver content via Diaspora
325 * @param string $cmd Command
326 * @param array $contact Contact record of the receiver
327 * @param array $owner Owner record of the sender
328 * @param array $items Item record of the content and the parent
329 * @param array $target_item Item record of the content
330 * @param boolean $public_message Is the content public?
331 * @param boolean $top_level Is it a thread starter?
332 * @param boolean $followup Is it an answer to a remote post?
334 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
336 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
337 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY);
339 if ($public_message) {
340 $loc = 'public batch ' . $contact['batch'];
342 $loc = $contact['addr'];
345 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
347 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
350 if ($cmd == self::MAIL) {
351 Diaspora::sendMail($target_item, $owner, $contact);
355 if ($cmd == self::SUGGESTION) {
358 if (!$contact['pubkey'] && !$public_message) {
361 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
362 // top-level retraction
363 logger('diaspora retract: ' . $loc);
364 Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
366 } elseif ($cmd == self::RELOCATION) {
367 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
369 } elseif ($followup) {
370 // send comments and likes to owner to relay
371 logger('diaspora followup: ' . $loc);
372 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
374 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
375 // we are the relay - send comments, likes and relayable_retractions to our conversants
376 logger('diaspora relay: ' . $loc);
377 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
379 } elseif ($top_level && !$walltowall) {
380 // currently no workable solution for sending walltowall
381 logger('diaspora status: ' . $loc);
382 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
386 logger('Unknown mode ' . $cmd . ' for ' . $loc);
390 * @brief Deliver content via mail
392 * @param string $cmd Command
393 * @param array $contact Contact record of the receiver
394 * @param array $owner Owner record of the sender
395 * @param array $target_item Item record of the content
397 private static function deliverMail($cmd, $contact, $owner, $target_item)
399 if (Config::get('system','dfrn_only')) {
402 // WARNING: does not currently convert to RFC2047 header encodings, etc.
404 $addr = $contact['addr'];
405 if (!strlen($addr)) {
409 if (!in_array($cmd, [self::POST, self::COMMENT])) {
413 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
414 if (!DBA::isResult($local_user)) {
418 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
421 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
422 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
423 $reply_to = $mailacct['reply_to'];
426 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
428 // only expose our real email address to true friends
430 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
432 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
433 $headers .= 'Sender: ' . $local_user['email'] . "\n";
435 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
438 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->get_hostname() . '>' . "\n";
441 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
443 if ($target_item['uri'] !== $target_item['parent-uri']) {
444 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
446 // If Threading is enabled, write down the correct parent
447 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
448 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
453 if (empty($target_item['title'])) {
454 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
455 $title = Item::selectFirst(['title'], $condition);
457 if (DBA::isResult($title) && ($title['title'] != '')) {
458 $subject = $title['title'];
460 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
461 $title = Item::selectFirst(['title'], $condition);
463 if (DBA::isResult($title) && ($title['title'] != '')) {
464 $subject = $title['title'];
469 if (strncasecmp($subject, 'RE:', 3)) {
470 $subject = 'Re: ' . $subject;
474 Email::send($addr, $subject, $headers, $target_item);