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\System;
11 use Friendica\Database\DBA;
12 use Friendica\Model\Contact;
13 use Friendica\Model\Item;
14 use Friendica\Model\Queue;
15 use Friendica\Model\User;
16 use Friendica\Protocol\DFRN;
17 use Friendica\Protocol\Diaspora;
18 use Friendica\Protocol\Email;
20 require_once 'include/items.php';
22 class Delivery extends BaseObject
25 const SUGGESTION = 'suggest';
26 const RELOCATION = 'relocate';
27 const DELETION = 'drop';
28 const POST = 'wall-new';
29 const COMMENT = 'comment-new';
30 const REMOVAL = 'removeme';
32 public static function execute($cmd, $item_id, $contact_id)
34 logger('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, LOGGER_DEBUG);
38 $public_message = false;
40 if ($cmd == self::MAIL) {
41 $target_item = DBA::selectFirst('mail', [], ['id' => $item_id]);
42 if (!DBA::isResult($target_item)) {
45 $uid = $target_item['uid'];
47 } elseif ($cmd == self::SUGGESTION) {
48 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $item_id]);
49 if (!DBA::isResult($target_item)) {
52 $uid = $target_item['uid'];
53 } elseif ($cmd == self::RELOCATION) {
56 $item = Item::selectFirst(['parent'], ['id' => $item_id]);
57 if (!DBA::isResult($item) || empty($item['parent'])) {
60 $parent_id = intval($item['parent']);
62 $condition = ['id' => [$item_id, $parent_id], 'moderated' => false];
63 $params = ['order' => ['id']];
64 $itemdata = Item::select([], $condition, $params);
67 while ($item = Item::fetch($itemdata)) {
68 if ($item['id'] == $parent_id) {
71 if ($item['id'] == $item_id) {
76 DBA::close($itemdata);
78 if (empty($target_item)) {
79 logger('Item ' . $item_id . "wasn't found. Quitting here.");
84 logger('Parent ' . $parent_id . ' for item ' . $item_id . "wasn't found. Quitting here.");
88 $uid = $target_item['contact-uid'];
90 // avoid race condition with deleting entries
91 if ($items[0]['deleted']) {
92 foreach ($items as $item) {
97 // When commenting too fast after delivery, a post wasn't recognized as top level post.
98 // The count then showed more than one entry. The additional check should help.
99 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
100 if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
101 logger('Top level post');
105 // This is IMPORTANT!!!!
107 // We will only send a "notify owner to relay" or followup message if the referenced post
108 // originated on our system by virtue of having our hostname somewhere
109 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
110 // if $parent['wall'] == 1 we will already have the parent message in our array
111 // and we will relay the whole lot.
113 $localhost = self::getApp()->get_hostname();
114 if (strpos($localhost, ':')) {
115 $localhost = substr($localhost, 0, strpos($localhost, ':'));
119 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
120 * have been known to cause runaway conditions which affected several servers, along with
121 * permissions issues.
125 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
126 logger('Followup ' . $target_item["guid"], LOGGER_DEBUG);
127 // local followup to remote post
131 if (empty($parent['allow_cid'])
132 && empty($parent['allow_gid'])
133 && empty($parent['deny_cid'])
134 && empty($parent['deny_gid'])
135 && !$parent["private"]) {
136 $public_message = true;
141 logger('No delivery data for ' . $cmd . ' - Item ID: ' .$item_id . ' - Contact ID: ' . $contact_id);
144 $owner = User::getOwnerDataById($uid);
145 if (!DBA::isResult($owner)) {
149 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
150 $contact = DBA::selectFirst('contact', [],
151 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
153 if (!DBA::isResult($contact)) {
157 // Transmit via Diaspora if the thread had started as Diaspora post
158 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
159 if (isset($parent) && ($parent['network'] == NETWORK_DIASPORA) && ($contact['network'] == NETWORK_DFRN)) {
160 $contact['network'] = NETWORK_DIASPORA;
163 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
165 switch ($contact['network']) {
168 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
171 case NETWORK_DIASPORA:
172 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
175 case NETWORK_OSTATUS:
176 // Do not send to otatus if we are not configured to send to public networks
177 if ($owner['prvnets']) {
180 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
184 // There is currently no code here to distribute anything to OStatus.
185 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
189 self::deliverMail($cmd, $contact, $owner, $target_item);
200 * @brief Deliver content via DFRN
202 * @param string $cmd Command
203 * @param array $contact Contact record of the receiver
204 * @param array $owner Owner record of the sender
205 * @param array $items Item record of the content and the parent
206 * @param array $target_item Item record of the content
207 * @param boolean $public_message Is the content public?
208 * @param boolean $top_level Is it a thread starter?
209 * @param boolean $followup Is it an answer to a remote post?
211 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
213 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
215 if ($cmd == self::MAIL) {
216 $item = $target_item;
217 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
218 $atom = DFRN::mail($item, $owner);
219 } elseif ($cmd == self::SUGGESTION) {
220 $item = $target_item;
221 $atom = DFRN::fsuggest($item, $owner);
222 DBA::delete('fsuggest', ['id' => $item['id']]);
223 } elseif ($cmd == self::RELOCATION) {
224 $atom = DFRN::relocate($owner, $owner['uid']);
225 } elseif ($followup) {
226 $msgitems = [$target_item];
227 $atom = DFRN::entries($msgitems, $owner);
230 foreach ($items as $item) {
231 // Only add the parent when we don't delete other items.
232 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
233 $item["entry:comment-allow"] = true;
234 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
238 $atom = DFRN::entries($msgitems, $owner);
241 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
243 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
245 // perform local delivery if we are on the same site
247 if (link_compare($basepath, System::baseUrl())) {
248 $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
249 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
250 if (!DBA::isResult($target_self)) {
253 $target_uid = $target_self['uid'];
255 // Check if the user has got this contact
256 $cid = Contact::getIdForURL($owner['url'], $target_uid);
258 // Otherwise there should be a public contact
259 $cid = Contact::getIdForURL($owner['url']);
265 // We now have some contact, so we fetch it
266 $target_importer = DBA::fetchFirst("SELECT *, `name` as `senderName`
268 WHERE NOT `blocked` AND `id` = ? LIMIT 1",
271 // This should never fail
272 if (!DBA::isResult($target_importer)) {
276 $user = DBA::selectFirst('user', [], ['uid' => $target_uid]);
278 $target_importer = array_merge($target_importer, $user);
280 // Set the user id. This is important if this is a public contact
281 $target_importer['importer_uid'] = $target_uid;
282 DFRN::import($atom, $target_importer);
286 // We don't have a relationship with contacts on a public post.
287 // Se we transmit with the new method and via Diaspora as a fallback
288 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
289 // Transmit in public if it's a relay post
290 $public_dfrn = ($contact['contact-type'] == Contact::ACCOUNT_TYPE_RELAY);
292 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
294 // We never spool failed relay deliveries
296 logger('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
300 if (($deliver_status < 200) || ($deliver_status > 299)) {
301 // Transmit via Diaspora if not possible via Friendica
302 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
306 $deliver_status = DFRN::deliver($owner, $contact, $atom);
309 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
311 if ($deliver_status < 0) {
312 logger('Delivery failed: queuing message ' . $target_item["guid"] );
313 Queue::add($contact['id'], NETWORK_DFRN, $atom, false, $target_item['guid']);
316 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
317 // We successfully delivered a message, the contact is alive
318 Contact::unmarkForArchival($contact);
320 // The message could not be delivered. We mark the contact as "dead"
321 Contact::markForArchival($contact);
323 // Transmit via Diaspora when all other methods (legacy DFRN and new one) are failing.
324 // This is a fallback for systems that don't know the new methods.
325 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
330 * @brief Deliver content via Diaspora
332 * @param string $cmd Command
333 * @param array $contact Contact record of the receiver
334 * @param array $owner Owner record of the sender
335 * @param array $items Item record of the content and the parent
336 * @param array $target_item Item record of the content
337 * @param boolean $public_message Is the content public?
338 * @param boolean $top_level Is it a thread starter?
339 * @param boolean $followup Is it an answer to a remote post?
341 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
343 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
344 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY);
346 if ($public_message) {
347 $loc = 'public batch ' . $contact['batch'];
349 $loc = $contact['addr'];
352 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
354 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
357 if ($cmd == self::MAIL) {
358 Diaspora::sendMail($target_item, $owner, $contact);
362 if ($cmd == self::SUGGESTION) {
365 if (!$contact['pubkey'] && !$public_message) {
368 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
369 // top-level retraction
370 logger('diaspora retract: ' . $loc);
371 Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
373 } elseif ($cmd == self::RELOCATION) {
374 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
376 } elseif ($followup) {
377 // send comments and likes to owner to relay
378 logger('diaspora followup: ' . $loc);
379 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
381 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
382 // we are the relay - send comments, likes and relayable_retractions to our conversants
383 logger('diaspora relay: ' . $loc);
384 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
386 } elseif ($top_level && !$walltowall) {
387 // currently no workable solution for sending walltowall
388 logger('diaspora status: ' . $loc);
389 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
393 logger('Unknown mode ' . $cmd . ' for ' . $loc);
397 * @brief Deliver content via mail
399 * @param string $cmd Command
400 * @param array $contact Contact record of the receiver
401 * @param array $owner Owner record of the sender
402 * @param array $target_item Item record of the content
404 private static function deliverMail($cmd, $contact, $owner, $target_item)
406 if (Config::get('system','dfrn_only')) {
409 // WARNING: does not currently convert to RFC2047 header encodings, etc.
411 $addr = $contact['addr'];
412 if (!strlen($addr)) {
416 if (!in_array($cmd, [self::POST, self::COMMENT])) {
420 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
421 if (!DBA::isResult($local_user)) {
425 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
428 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
429 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
430 $reply_to = $mailacct['reply_to'];
433 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
435 // only expose our real email address to true friends
437 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
439 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
440 $headers .= 'Sender: ' . $local_user['email'] . "\n";
442 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
445 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->get_hostname() . '>' . "\n";
448 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
450 if ($target_item['uri'] !== $target_item['parent-uri']) {
451 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
453 // If Threading is enabled, write down the correct parent
454 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
455 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
459 if (empty($target_item['title'])) {
460 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
461 $title = Item::selectFirst(['title'], $condition);
462 if (DBA::isResult($title) && ($title['title'] != '')) {
463 $subject = $title['title'];
465 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
466 $title = Item::selectFirst(['title'], $condition);
467 if (DBA::isResult($title) && ($title['title'] != '')) {
468 $subject = $title['title'];
472 if (strncasecmp($subject, 'RE:', 3)) {
473 $subject = 'Re: ' . $subject;
476 Email::send($addr, $subject, $headers, $target_item);