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';
33 public static function execute($cmd, $item_id, $contact_id)
35 logger('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, LOGGER_DEBUG);
39 $public_message = false;
41 if ($cmd == self::MAIL) {
42 $target_item = DBA::selectFirst('mail', [], ['id' => $item_id]);
43 if (!DBA::isResult($target_item)) {
46 $uid = $target_item['uid'];
48 } elseif ($cmd == self::SUGGESTION) {
49 $target_item = DBA::selectFirst('fsuggest', [], ['id' => $item_id]);
50 if (!DBA::isResult($target_item)) {
53 $uid = $target_item['uid'];
54 } elseif ($cmd == self::RELOCATION) {
57 $item = Item::selectFirst(['parent'], ['id' => $item_id]);
58 if (!DBA::isResult($item) || empty($item['parent'])) {
61 $parent_id = intval($item['parent']);
63 $condition = ['id' => [$item_id, $parent_id], 'moderated' => false];
64 $params = ['order' => ['id']];
65 $itemdata = Item::select([], $condition, $params);
68 while ($item = Item::fetch($itemdata)) {
69 if ($item['id'] == $parent_id) {
72 if ($item['id'] == $item_id) {
77 DBA::close($itemdata);
79 if (empty($target_item)) {
80 logger('Item ' . $item_id . "wasn't found. Quitting here.");
85 logger('Parent ' . $parent_id . ' for item ' . $item_id . "wasn't found. Quitting here.");
89 $uid = $target_item['contact-uid'];
91 // avoid race condition with deleting entries
92 if ($items[0]['deleted']) {
93 foreach ($items as $item) {
98 // When commenting too fast after delivery, a post wasn't recognized as top level post.
99 // The count then showed more than one entry. The additional check should help.
100 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
101 if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
102 logger('Top level post');
106 // This is IMPORTANT!!!!
108 // We will only send a "notify owner to relay" or followup message if the referenced post
109 // originated on our system by virtue of having our hostname somewhere
110 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
111 // if $parent['wall'] == 1 we will already have the parent message in our array
112 // and we will relay the whole lot.
114 $localhost = self::getApp()->get_hostname();
115 if (strpos($localhost, ':')) {
116 $localhost = substr($localhost, 0, strpos($localhost, ':'));
120 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
121 * have been known to cause runaway conditions which affected several servers, along with
122 * permissions issues.
126 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
127 logger('Followup ' . $target_item["guid"], LOGGER_DEBUG);
128 // local followup to remote post
132 if (empty($parent['allow_cid'])
133 && empty($parent['allow_gid'])
134 && empty($parent['deny_cid'])
135 && empty($parent['deny_gid'])
136 && !$parent["private"]) {
137 $public_message = true;
142 logger('No delivery data for ' . $cmd . ' - Item ID: ' .$item_id . ' - Contact ID: ' . $contact_id);
145 $owner = User::getOwnerDataById($uid);
146 if (!DBA::isResult($owner)) {
150 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
151 $contact = DBA::selectFirst('contact', [],
152 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
154 if (!DBA::isResult($contact)) {
158 // Transmit via Diaspora if the thread had started as Diaspora post
159 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
160 if (isset($parent) && ($parent['network'] == Protocol::DIASPORA) && ($contact['network'] == Protocol::DFRN)) {
161 $contact['network'] = Protocol::DIASPORA;
164 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
166 switch ($contact['network']) {
169 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
172 case Protocol::DIASPORA:
173 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
176 case Protocol::OSTATUS:
177 // Do not send to otatus if we are not configured to send to public networks
178 if ($owner['prvnets']) {
181 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
185 // There is currently no code here to distribute anything to OStatus.
186 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
190 self::deliverMail($cmd, $contact, $owner, $target_item);
201 * @brief Deliver content via DFRN
203 * @param string $cmd Command
204 * @param array $contact Contact record of the receiver
205 * @param array $owner Owner record of the sender
206 * @param array $items Item record of the content and the parent
207 * @param array $target_item Item record of the content
208 * @param boolean $public_message Is the content public?
209 * @param boolean $top_level Is it a thread starter?
210 * @param boolean $followup Is it an answer to a remote post?
212 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
214 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
216 if ($cmd == self::MAIL) {
217 $item = $target_item;
218 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
219 $atom = DFRN::mail($item, $owner);
220 } elseif ($cmd == self::SUGGESTION) {
221 $item = $target_item;
222 $atom = DFRN::fsuggest($item, $owner);
223 DBA::delete('fsuggest', ['id' => $item['id']]);
224 } elseif ($cmd == self::RELOCATION) {
225 $atom = DFRN::relocate($owner, $owner['uid']);
226 } elseif ($followup) {
227 $msgitems = [$target_item];
228 $atom = DFRN::entries($msgitems, $owner);
231 foreach ($items as $item) {
232 // Only add the parent when we don't delete other items.
233 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
234 $item["entry:comment-allow"] = true;
235 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
239 $atom = DFRN::entries($msgitems, $owner);
242 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
244 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
246 // perform local delivery if we are on the same site
248 if (link_compare($basepath, System::baseUrl())) {
249 $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
250 $target_self = DBA::selectFirst('contact', ['uid'], $condition);
251 if (!DBA::isResult($target_self)) {
254 $target_uid = $target_self['uid'];
256 // Check if the user has got this contact
257 $cid = Contact::getIdForURL($owner['url'], $target_uid);
259 // Otherwise there should be a public contact
260 $cid = Contact::getIdForURL($owner['url']);
266 $target_importer = DFRN::getImporter($cid, $target_uid);
267 if (empty($target_importer)) {
268 // This should never happen
272 DFRN::import($atom, $target_importer);
276 // We don't have a relationship with contacts on a public post.
277 // Se we transmit with the new method and via Diaspora as a fallback
278 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
279 // Transmit in public if it's a relay post
280 $public_dfrn = ($contact['contact-type'] == Contact::ACCOUNT_TYPE_RELAY);
282 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
284 // We never spool failed relay deliveries
286 logger('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
290 if (($deliver_status < 200) || ($deliver_status > 299)) {
291 // Transmit via Diaspora if not possible via Friendica
292 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
296 $deliver_status = DFRN::deliver($owner, $contact, $atom);
299 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
301 if ($deliver_status < 0) {
302 logger('Delivery failed: queuing message ' . $target_item["guid"] );
303 Queue::add($contact['id'], Protocol::DFRN, $atom, false, $target_item['guid']);
306 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
307 // We successfully delivered a message, the contact is alive
308 Contact::unmarkForArchival($contact);
310 // The message could not be delivered. We mark the contact as "dead"
311 Contact::markForArchival($contact);
313 // Transmit via Diaspora when all other methods (legacy DFRN and new one) are failing.
314 // This is a fallback for systems that don't know the new methods.
315 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
320 * @brief Deliver content via Diaspora
322 * @param string $cmd Command
323 * @param array $contact Contact record of the receiver
324 * @param array $owner Owner record of the sender
325 * @param array $items Item record of the content and the parent
326 * @param array $target_item Item record of the content
327 * @param boolean $public_message Is the content public?
328 * @param boolean $top_level Is it a thread starter?
329 * @param boolean $followup Is it an answer to a remote post?
331 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
333 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
334 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY);
336 if ($public_message) {
337 $loc = 'public batch ' . $contact['batch'];
339 $loc = $contact['addr'];
342 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
344 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
347 if ($cmd == self::MAIL) {
348 Diaspora::sendMail($target_item, $owner, $contact);
352 if ($cmd == self::SUGGESTION) {
355 if (!$contact['pubkey'] && !$public_message) {
358 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
359 // top-level retraction
360 logger('diaspora retract: ' . $loc);
361 Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
363 } elseif ($cmd == self::RELOCATION) {
364 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
366 } elseif ($followup) {
367 // send comments and likes to owner to relay
368 logger('diaspora followup: ' . $loc);
369 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
371 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
372 // we are the relay - send comments, likes and relayable_retractions to our conversants
373 logger('diaspora relay: ' . $loc);
374 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
376 } elseif ($top_level && !$walltowall) {
377 // currently no workable solution for sending walltowall
378 logger('diaspora status: ' . $loc);
379 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
383 logger('Unknown mode ' . $cmd . ' for ' . $loc);
387 * @brief Deliver content via mail
389 * @param string $cmd Command
390 * @param array $contact Contact record of the receiver
391 * @param array $owner Owner record of the sender
392 * @param array $target_item Item record of the content
394 private static function deliverMail($cmd, $contact, $owner, $target_item)
396 if (Config::get('system','dfrn_only')) {
399 // WARNING: does not currently convert to RFC2047 header encodings, etc.
401 $addr = $contact['addr'];
402 if (!strlen($addr)) {
406 if (!in_array($cmd, [self::POST, self::COMMENT])) {
410 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
411 if (!DBA::isResult($local_user)) {
415 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
418 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
419 if (DBA::isResult($mailacct) && !empty($mailacct['reply_to'])) {
420 $reply_to = $mailacct['reply_to'];
423 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
425 // only expose our real email address to true friends
427 if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) {
429 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
430 $headers .= 'Sender: ' . $local_user['email'] . "\n";
432 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
435 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->get_hostname() . '>' . "\n";
438 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
440 if ($target_item['uri'] !== $target_item['parent-uri']) {
441 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
443 // If Threading is enabled, write down the correct parent
444 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
445 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
450 if (empty($target_item['title'])) {
451 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
452 $title = Item::selectFirst(['title'], $condition);
454 if (DBA::isResult($title) && ($title['title'] != '')) {
455 $subject = $title['title'];
457 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
458 $title = Item::selectFirst(['title'], $condition);
460 if (DBA::isResult($title) && ($title['title'] != '')) {
461 $subject = $title['title'];
466 if (strncasecmp($subject, 'RE:', 3)) {
467 $subject = 'Re: ' . $subject;
471 Email::send($addr, $subject, $headers, $target_item);