]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
Merge branch 'direct-dfrn' of github.com:annando/friendica into direct-dfrn
[friendica.git] / src / Worker / Delivery.php
1 <?php
2 /**
3  * @file src/Worker/Delivery.php
4  */
5 namespace Friendica\Worker;
6
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;
19 use dba;
20
21 require_once 'include/items.php';
22
23 class Delivery extends BaseObject
24 {
25         const MAIL =       'mail';
26         const SUGGESTION = 'suggest';
27         const RELOCATION = 'relocate';
28         const DELETION =   'drop';
29         const POST =       'wall-new';
30         const COMMENT =    'comment-new';
31
32         public static function execute($cmd, $item_id, $contact_id)
33         {
34                 logger('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, LOGGER_DEBUG);
35
36                 $top_level = false;
37                 $followup = false;
38                 $public_message = false;
39
40                 if ($cmd == self::MAIL) {
41                         $target_item = dba::selectFirst('mail', [], ['id' => $item_id]);
42                         if (!DBM::is_result($message)) {
43                                 return;
44                         }
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)) {
49                                 return;
50                         }
51                         $uid = $target_item['uid'];
52                 } elseif ($cmd == self::RELOCATION) {
53                         $uid = $item_id;
54                 } else {
55                         $item = dba::selectFirst('item', ['parent'], ['id' => $item_id]);
56                         if (!DBM::is_result($item) || empty($item['parent'])) {
57                                 return;
58                         }
59                         $parent_id = intval($item['parent']);
60
61                         $itemdata = dba::p("SELECT `item`.*, `contact`.`uid` AS `cuid`,
62                                                         `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
63                                                 FROM `item`
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);
69                         $items = [];
70                         while ($item = dba::fetch($itemdata)) {
71                                 if ($item['id'] == $parent_id) {
72                                         $parent = $item;
73                                 }
74                                 if ($item['id'] == $item_id) {
75                                         $target_item = $item;
76                                 }
77                                 $items[] = $item;
78                         }
79                         dba::close($itemdata);
80
81                         $uid = $target_item['cuid'];
82
83                         // avoid race condition with deleting entries
84                         if ($items[0]['deleted']) {
85                                 foreach ($items as $item) {
86                                         $item['deleted'] = 1;
87                                 }
88                         }
89
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');
95                                 $top_level = true;
96                         }
97
98                         // This is IMPORTANT!!!!
99
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.
105
106                         $localhost = self::getApp()->get_hostname();
107                         if (strpos($localhost, ':')) {
108                                 $localhost = substr($localhost, 0, strpos($localhost, ':'));
109                         }
110                         /**
111                          *
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.
115                          *
116                          */
117
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
121                                 $followup = true;
122                         }
123
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;
130                         }
131                 }
132
133                 $owner = User::getOwnerDataById($uid);
134                 if (!DBM::is_result($owner)) {
135                         return;
136                 }
137
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]
141                 );
142                 if (!DBM::is_result($contact)) {
143                         return;
144                 }
145
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;
150                 }
151
152                 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
153
154                 switch ($contact['network']) {
155
156                         case NETWORK_DFRN:
157                                 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
158                                 break;
159
160                         case NETWORK_DIASPORA:
161                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
162                                 break;
163
164                         case NETWORK_OSTATUS:
165                                 // Do not send to otatus if we are not configured to send to public networks
166                                 if ($owner['prvnets']) {
167                                         break;
168                                 }
169                                 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
170                                         break;
171                                 }
172
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")
175                                 break;
176
177                         case NETWORK_MAIL:
178                                 self::deliverMail($cmd, $contact, $owner, $target_item);
179                                 break;
180
181                         default:
182                                 break;
183                 }
184
185                 return;
186         }
187
188         /**
189          * @brief Deliver content via DFRN
190          *
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?
199          */
200         private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
201         {
202                 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
203
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);
217                 } else {
218                         $msgitems = [];
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);
224                                         $msgitems[] = $item;
225                                 }
226                         }
227                         $atom = DFRN::entries($msgitems, $owner);
228                 }
229
230                 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
231
232                 $basepath =  implode('/', array_slice(explode('/', $contact['url']), 0, 3));
233
234                 // perform local delivery if we are on the same site
235
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)) {
240                                 return;
241                         }
242                         $target_uid = $target_self['uid'];
243
244                         // Check if the user has got this contact
245                         $cid = Contact::getIdForURL($owner['url'], $target_uid);
246                         if (!$cid) {
247                                 // Otherwise there should be a public contact
248                                 $cid = Contact::getIdForURL($owner['url']);
249                                 if (!$cid) {
250                                         return;
251                                 }
252                         }
253
254                         // We now have some contact, so we fetch it
255                         $target_importer = dba::fetch_first("SELECT *, `name` as `senderName`
256                                                         FROM `contact`
257                                                         WHERE NOT `blocked` AND `id` = ? LIMIT 1",
258                                                         $cid);
259
260                         // This should never fail
261                         if (!DBM::is_result($target_importer)) {
262                                 return;
263                         }
264
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);
268                         return;
269                 }
270
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) || ($contact['uid'] == 0)) {
274                         // Transmit in public if it's a relay post
275                         $public_dfrn = ($contact['contact-type'] == ACCOUNT_TYPE_RELAY);
276
277                         $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
278
279                         // We never spool failed relay deliveries
280                         if ($public_dfrn) {
281                                 logger('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
282                                 return;
283                         }
284
285                         if (($deliver_status < 200) || ($deliver_status > 299)) {
286                                 // Transmit via Diaspora if not possible via Friendica
287                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
288                                 return;
289                         }
290                 } else {
291                         $deliver_status = DFRN::deliver($owner, $contact, $atom);
292                 }
293
294                 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
295
296                 if ($deliver_status < 0) {
297                         logger('Delivery failed: queuing message ' . $target_item["guid"] );
298                         Queue::add($contact['id'], NETWORK_DFRN, $atom, false, $target_item['guid']);
299                 }
300
301                 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
302                         // We successfully delivered a message, the contact is alive
303                         Contact::unmarkForArchival($contact);
304                 } else {
305                         // The message could not be delivered. We mark the contact as "dead"
306                         Contact::markForArchival($contact);
307                 }
308         }
309
310         /**
311          * @brief Deliver content via Diaspora
312          *
313          * @param string  $cmd            Command
314          * @param array   $contact        Contact record of the receiver
315          * @param array   $owner          Owner record of the sender
316          * @param array   $items          Item record of the content and the parent
317          * @param array   $target_item    Item record of the content
318          * @param boolean $public_message Is the content public?
319          * @param boolean $top_level      Is it a thread starter?
320          * @param boolean $followup       Is it an answer to a remote post?
321          */
322         private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
323         {
324                 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
325                 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY);
326
327                 if ($public_message) {
328                         $loc = 'public batch ' . $contact['batch'];
329                 } else {
330                         $loc = $contact['addr'];
331                 }
332
333                 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
334
335                 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
336                         return;
337                 }
338                 if ($cmd == self::MAIL) {
339                         Diaspora::sendMail($target_item, $owner, $contact);
340                         return;
341                 }
342
343                 if ($cmd == self::SUGGESTION) {
344                         return;
345                 }
346                 if (!$contact['pubkey'] && !$public_message) {
347                         return;
348                 }
349                 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
350                         // top-level retraction
351                         logger('diaspora retract: ' . $loc);
352                         Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
353                         return;
354                 } elseif ($cmd == self::RELOCATION) {
355                         Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
356                         return;
357                 } elseif ($followup) {
358                         // send comments and likes to owner to relay
359                         logger('diaspora followup: ' . $loc);
360                         Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
361                         return;
362                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
363                         // we are the relay - send comments, likes and relayable_retractions to our conversants
364                         logger('diaspora relay: ' . $loc);
365                         Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
366                         return;
367                 } elseif ($top_level && !$walltowall) {
368                         // currently no workable solution for sending walltowall
369                         logger('diaspora status: ' . $loc);
370                         Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
371                         return;
372                 }
373
374                 logger('Unknown mode ' . $cmd . ' for ' . $loc);
375         }
376
377         /**
378          * @brief Deliver content via mail
379          *
380          * @param string $cmd         Command
381          * @param array  $contact     Contact record of the receiver
382          * @param array  $owner       Owner record of the sender
383          * @param array  $target_item Item record of the content
384          */
385         private static function deliverMail($cmd, $contact, $owner, $target_item)
386         {
387                 if (Config::get('system','dfrn_only')) {
388                         return;
389                 }
390                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
391
392                 $addr = $contact['addr'];
393                 if (!strlen($addr)) {
394                         return;
395                 }
396
397                 if (!in_array($cmd, [self::POST, self::COMMENT])) {
398                         return;
399                 }
400
401                 $local_user = dba::selectFirst('user', [], ['uid' => $owner['uid']]);
402                 if (!DBM::is_result($local_user)) {
403                         return;
404                 }
405
406                 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
407
408                 $reply_to = '';
409                 $mailacct = dba::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
410                 if (DBM::is_result($mailacct) && !empty($mailacct['reply_to'])) {
411                         $reply_to = $mailacct['reply_to'];
412                 }
413
414                 $subject  = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
415
416                 // only expose our real email address to true friends
417
418                 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
419                         if ($reply_to) {
420                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
421                                 $headers .= 'Sender: ' . $local_user['email'] . "\n";
422                         } else {
423                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
424                         }
425                 } else {
426                         $headers  = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->get_hostname() . '>' . "\n";
427                 }
428
429                 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
430
431                 if ($target_item['uri'] !== $target_item['parent-uri']) {
432                         $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
433
434                         // If Threading is enabled, write down the correct parent
435                         if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
436                                 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
437                         }
438                         $headers .= "\n";
439
440                         if (empty($target_item['title'])) {
441                                 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
442                                 $title = dba::selectFirst('item', ['title'], $condition);
443                                 if (DBM::is_result($title) && ($title['title'] != '')) {
444                                         $subject = $title['title'];
445                                 } else {
446                                         $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
447                                         $title = dba::selectFirst('item', ['title'], $condition);
448                                         if (DBM::is_result($title) && ($title['title'] != '')) {
449                                                 $subject = $title['title'];
450                                         }
451                                 }
452                         }
453                         if (strncasecmp($subject, 'RE:', 3)) {
454                                 $subject = 'Re: ' . $subject;
455                         }
456                 }
457                 Email::send($addr, $subject, $headers, $target_item);
458         }
459 }