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\DBM;
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;
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';
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 (!DBM::is_result($message)) {
45 $uid = $target_item['uid'];
46 } elseif ($cmd == self::SUGGESTION) {
47 $target_item = dba::selectFirst('fsuggest', [], ['id' => $item_id]);
48 if (!DBM::is_result($message)) {
51 $uid = $target_item['uid'];
52 } elseif ($cmd == self::RELOCATION) {
55 $item = dba::selectFirst('item', ['parent'], ['id' => $item_id]);
56 if (!DBM::is_result($item) || empty($item['parent'])) {
59 $parent_id = intval($item['parent']);
61 $itemdata = dba::p("SELECT `item`.*, `contact`.`uid` AS `cuid`,
62 `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
64 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
65 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
66 WHERE `item`.`id` IN (?, ?) AND `visible` AND NOT `moderated`
67 ORDER BY `item`.`id`",
68 $item_id, $parent_id);
70 while ($item = dba::fetch($itemdata)) {
71 if ($item['id'] == $parent_id) {
74 if ($item['id'] == $item_id) {
79 dba::close($itemdata);
81 $uid = $target_item['cuid'];
83 // avoid race condition with deleting entries
84 if ($items[0]['deleted']) {
85 foreach ($items as $item) {
90 // When commenting too fast after delivery, a post wasn't recognized as top level post.
91 // The count then showed more than one entry. The additional check should help.
92 // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
93 if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
94 logger('Top level post');
98 // This is IMPORTANT!!!!
100 // We will only send a "notify owner to relay" or followup message if the referenced post
101 // originated on our system by virtue of having our hostname somewhere
102 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
103 // if $parent['wall'] == 1 we will already have the parent message in our array
104 // and we will relay the whole lot.
106 $localhost = self::getApp()->get_hostname();
107 if (strpos($localhost, ':')) {
108 $localhost = substr($localhost, 0, strpos($localhost, ':'));
112 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
113 * have been known to cause runaway conditions which affected several servers, along with
114 * permissions issues.
118 if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
119 logger('Followup ' . $target_item["guid"], LOGGER_DEBUG);
120 // local followup to remote post
124 if (empty($parent['allow_cid'])
125 && empty($parent['allow_gid'])
126 && empty($parent['deny_cid'])
127 && empty($parent['deny_gid'])
128 && !$parent["private"]) {
129 $public_message = true;
133 $owner = User::getOwnerDataById($uid);
134 if (!DBM::is_result($owner)) {
138 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
139 $contact = dba::selectFirst('contact', [],
140 ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
142 if (!DBM::is_result($contact)) {
146 // Transmit via Diaspora if the thread had started as Diaspora post
147 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
148 if (isset($parent) && ($parent['network'] == NETWORK_DIASPORA) && ($contact['network'] == NETWORK_DFRN)) {
149 $contact['network'] = NETWORK_DIASPORA;
152 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
154 switch ($contact['network']) {
157 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
160 case NETWORK_DIASPORA:
161 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
164 case NETWORK_OSTATUS:
165 // Do not send to otatus if we are not configured to send to public networks
166 if ($owner['prvnets']) {
169 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
173 // There is currently no code here to distribute anything to OStatus.
174 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
178 self::deliverMail($cmd, $contact, $owner, $target_item);
189 * @brief Deliver content via DFRN
191 * @param string $cmd Command
192 * @param array $contact Contact record of the receiver
193 * @param array $owner Owner record of the sender
194 * @param array $items Item record of the content and the parent
195 * @param array $target_item Item record of the content
196 * @param boolean $public_message Is the content public?
197 * @param boolean $top_level Is it a thread starter?
198 * @param boolean $followup Is it an answer to a remote post?
200 private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
202 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . $contact['addr']);
204 if ($cmd == self::MAIL) {
205 $item = $target_item;
206 $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
207 $atom = DFRN::mail($item, $owner);
208 } elseif ($cmd == self::SUGGESTION) {
209 $item = $target_item;
210 $atom = DFRN::fsuggest($item, $owner);
211 dba::delete('fsuggest', ['id' => $item['id']]);
212 } elseif ($cmd == self::RELOCATION) {
213 $atom = DFRN::relocate($owner, $owner['uid']);
214 } elseif ($followup) {
215 $msgitems = [$target_item];
216 $atom = DFRN::entries($msgitems, $owner);
219 foreach ($items as $item) {
220 // Only add the parent when we don't delete other items.
221 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
222 $item["entry:comment-allow"] = true;
223 $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
227 $atom = DFRN::entries($msgitems, $owner);
230 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
232 $basepath = implode('/', array_slice(explode('/', $contact['url']), 0, 3));
234 // perform local delivery if we are on the same site
236 if (link_compare($basepath, System::baseUrl())) {
237 $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
238 $target_self = dba::selectFirst('contact', ['uid'], $condition);
239 if (!DBM::is_result($target_self)) {
242 $target_uid = $target_self['uid'];
244 // Check if the user has got this contact
245 $cid = Contact::getIdForURL($owner['url'], $target_uid);
247 // Otherwise there should be a public contact
248 $cid = Contact::getIdForURL($owner['url']);
254 // We now have some contact, so we fetch it
255 $target_importer = dba::fetch_first("SELECT *, `name` as `senderName`
257 WHERE NOT `blocked` AND `id` = ? LIMIT 1",
260 // This should never fail
261 if (!DBM::is_result($target_importer)) {
265 // Set the user id. This is important if this is a public contact
266 $target_importer['importer_uid'] = $target_uid;
267 DFRN::import($atom, $target_importer);
271 // We don't have a relationship with contacts on a public post.
272 // Se we transmit with the new method and via Diaspora as a fallback
273 if ($items[0]['uid'] == 0) {
274 // Transmit in public if it's a relay post
275 $public_dfrn = ($contact['contact-type'] == ACCOUNT_TYPE_RELAY);
277 $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
278 if (($deliver_status < 200) || ($deliver_status > 299)) {
279 // Transmit via Diaspora if not possible via Friendica
280 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
284 $deliver_status = DFRN::deliver($owner, $contact, $atom);
287 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
289 if ($deliver_status < 0) {
290 logger('Delivery failed: queuing message ' . $target_item["guid"] );
291 Queue::add($contact['id'], NETWORK_DFRN, $atom, false, $target_item['guid']);
294 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
295 // We successfully delivered a message, the contact is alive
296 Contact::unmarkForArchival($contact);
298 // The message could not be delivered. We mark the contact as "dead"
299 Contact::markForArchival($contact);
304 * @brief Deliver content via Diaspora
306 * @param string $cmd Command
307 * @param array $contact Contact record of the receiver
308 * @param array $owner Owner record of the sender
309 * @param array $items Item record of the content and the parent
310 * @param array $target_item Item record of the content
311 * @param boolean $public_message Is the content public?
312 * @param boolean $top_level Is it a thread starter?
313 * @param boolean $followup Is it an answer to a remote post?
315 private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
317 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
318 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY);
320 if ($public_message) {
321 $loc = 'public batch ' . $contact['batch'];
323 $loc = $contact['addr'];
326 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
328 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
331 if ($cmd == self::MAIL) {
332 Diaspora::sendMail($target_item, $owner, $contact);
336 if ($cmd == self::SUGGESTION) {
339 if (!$contact['pubkey'] && !$public_message) {
342 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
343 // top-level retraction
344 logger('diaspora retract: ' . $loc);
345 Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
347 } elseif ($cmd == self::RELOCATION) {
348 Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
350 } elseif ($followup) {
351 // send comments and likes to owner to relay
352 logger('diaspora followup: ' . $loc);
353 Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
355 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
356 // we are the relay - send comments, likes and relayable_retractions to our conversants
357 logger('diaspora relay: ' . $loc);
358 Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
360 } elseif ($top_level && !$walltowall) {
361 // currently no workable solution for sending walltowall
362 logger('diaspora status: ' . $loc);
363 Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
367 logger('Unknown mode ' . $cmd . ' for ' . $loc);
371 * @brief Deliver content via mail
373 * @param string $cmd Command
374 * @param array $contact Contact record of the receiver
375 * @param array $owner Owner record of the sender
376 * @param array $target_item Item record of the content
378 private static function deliverMail($cmd, $contact, $owner, $target_item)
380 if (Config::get('system','dfrn_only')) {
383 // WARNING: does not currently convert to RFC2047 header encodings, etc.
385 $addr = $contact['addr'];
386 if (!strlen($addr)) {
390 if (!in_array($cmd, [self::POST, self::COMMENT])) {
394 $local_user = dba::selectFirst('user', [], ['uid' => $owner['uid']]);
395 if (!DBM::is_result($local_user)) {
399 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
402 $mailacct = dba::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
403 if (DBM::is_result($mailacct) && !empty($mailacct['reply_to'])) {
404 $reply_to = $mailacct['reply_to'];
407 $subject = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
409 // only expose our real email address to true friends
411 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
413 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
414 $headers .= 'Sender: ' . $local_user['email'] . "\n";
416 $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
419 $headers = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->get_hostname() . '>' . "\n";
422 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
424 if ($target_item['uri'] !== $target_item['parent-uri']) {
425 $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
427 // If Threading is enabled, write down the correct parent
428 if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
429 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
433 if (empty($target_item['title'])) {
434 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
435 $title = dba::selectFirst('item', ['title'], $condition);
436 if (DBM::is_result($title) && ($title['title'] != '')) {
437 $subject = $title['title'];
439 $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
440 $title = dba::selectFirst('item', ['title'], $condition);
441 if (DBM::is_result($title) && ($title['title'] != '')) {
442 $subject = $title['title'];
446 if (strncasecmp($subject, 'RE:', 3)) {
447 $subject = 'Re: ' . $subject;
450 Email::send($addr, $subject, $headers, $target_item);