]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
d8ab8822439ff6f5c290cf0ae24d51dc14ef0c07
[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         const MAIL =       'mail';
25         const SUGGESTION = 'suggest';
26         const RELOCATION = 'relocate';
27         const DELETION =   'drop';
28         const POST =       'wall-new';
29         const COMMENT =    'comment-new';
30
31         public static function execute($cmd, $item_id, $contact_id) {
32                 logger('Invoked: ' . $cmd . ': ' . $item_id . ' to ' . $contact_id, LOGGER_DEBUG);
33
34                 $top_level = false;
35                 $followup = false;
36                 $public_message = false;
37
38                 if ($cmd == self::MAIL) {
39                         $target_item = dba::selectFirst('mail', [], ['id' => $item_id]);
40                         if (!DBM::is_result($message)) {
41                                 return;
42                         }
43                         $uid = $target_item['uid'];
44                 } elseif ($cmd == self::SUGGESTION) {
45                         $target_item = dba::selectFirst('fsuggest', [], ['id' => $item_id]);
46                         if (!DBM::is_result($message)) {
47                                 return;
48                         }
49                         $uid = $target_item['uid'];
50                 } elseif ($cmd == self::RELOCATION) {
51                         $uid = $item_id;
52                 } else {
53                         $item = dba::selectFirst('item', ['parent'], ['id' => $item_id]);
54                         if (!DBM::is_result($item) || empty($item['parent'])) {
55                                 return;
56                         }
57                         $parent_id = intval($item['parent']);
58
59                         $itemdata = dba::p("SELECT `item`.*, `contact`.`uid` AS `cuid`,
60                                                         `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
61                                                 FROM `item`
62                                                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
63                                                 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
64                                                 WHERE `item`.`id` IN (?, ?) AND `visible` AND NOT `moderated`
65                                                 ORDER BY `item`.`id`",
66                                         $item_id, $parent_id);
67                         $items = [];
68                         while ($item = dba::fetch($itemdata)) {
69                                 if ($item['id'] == $parent_id) {
70                                         $parent = $item;
71                                 }
72                                 if ($item['id'] == $item_id) {
73                                         $target_item = $item;
74                                 }
75                                 $items[] = $item;
76                         }
77                         dba::close($itemdata);
78
79                         $uid = $target_item['cuid'];
80
81                         // avoid race condition with deleting entries
82                         if ($items[0]['deleted']) {
83                                 foreach ($items as $item) {
84                                         $item['deleted'] = 1;
85                                 }
86                         }
87
88                         // When commenting too fast after delivery, a post wasn't recognized as top level post.
89                         // The count then showed more than one entry. The additional check should help.
90                         // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
91                         if ((($parent['id'] == $item_id) || (count($items) == 1)) && ($parent['uri'] === $parent['parent-uri'])) {
92                                 logger('Top level post');
93                                 $top_level = true;
94                         }
95
96                         // This is IMPORTANT!!!!
97
98                         // We will only send a "notify owner to relay" or followup message if the referenced post
99                         // originated on our system by virtue of having our hostname somewhere
100                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
101                         // if $parent['wall'] == 1 we will already have the parent message in our array
102                         // and we will relay the whole lot.
103
104                         $localhost = self::getApp()->get_hostname();
105                         if (strpos($localhost, ':')) {
106                                 $localhost = substr($localhost, 0, strpos($localhost, ':'));
107                         }
108                         /**
109                          *
110                          * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
111                          * have been known to cause runaway conditions which affected several servers, along with
112                          * permissions issues.
113                          *
114                          */
115
116                         if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) {
117                                 logger('Followup ' . $target_item["guid"], LOGGER_DEBUG);
118                                 // local followup to remote post
119                                 $followup = true;
120                         }
121
122                         if (empty($parent['allow_cid'])
123                                 && empty($parent['allow_gid'])
124                                 && empty($parent['deny_cid'])
125                                 && empty($parent['deny_gid'])
126                                 && !$parent["private"]) {
127                                 $public_message = true;
128                         }
129                 }
130
131                 $owner = User::getOwnerDataById($uid);
132                 if (!DBM::is_result($owner)) {
133                         return;
134                 }
135
136                 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
137                 $contact = dba::selectFirst('contact', [],
138                         ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
139                 );
140                 if (!DBM::is_result($contact)) {
141                         return;
142                 }
143
144                 // Transmit via Diaspora if the thread had started as Diaspora post
145                 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
146                 if (isset($parent) && ($parent['network'] == NETWORK_DIASPORA) && ($contact['network'] == NETWORK_DFRN)) {
147                         $contact['network'] = NETWORK_DIASPORA;
148                 }
149
150                 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
151
152                 switch ($contact['network']) {
153
154                         case NETWORK_DFRN:
155                                 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
156                                 break;
157
158                         case NETWORK_DIASPORA:
159                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
160                                 break;
161
162                         case NETWORK_OSTATUS:
163                                 // Do not send to otatus if we are not configured to send to public networks
164                                 if ($owner['prvnets']) {
165                                         break;
166                                 }
167                                 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
168                                         break;
169                                 }
170
171                                 // There is currently no code here to distribute anything to OStatus.
172                                 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
173                                 break;
174
175                         case NETWORK_MAIL:
176                                 self::deliverMail($cmd, $contact, $owner, $target_item);
177                                 break;
178
179                         default:
180                                 break;
181                 }
182
183                 return;
184         }
185
186         /**
187          * @brief Deliver content via DFRN
188          *
189          * @param string  $cmd            Command
190          * @param array   $contact        Contact record of the receiver
191          * @param array   $owner          Owner record of the sender
192          * @param array   $items          Item record of the content and the parent
193          * @param array   $target_item    Item record of the content
194          * @param boolean $public_message Is the content public?
195          * @param boolean $top_level      Is it a thread starter?
196          * @param boolean $followup       Is it an answer to a remote post?
197          */
198         private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
199         {
200                 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . $contact['addr']);
201
202                 if ($cmd == self::MAIL) {
203                         $item = $target_item;
204                         $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
205                         $atom = DFRN::mail($item, $owner);
206                 } elseif ($cmd == self::SUGGESTION) {
207                         $item = $target_item;
208                         $atom = DFRN::fsuggest($item, $owner);
209                         dba::delete('fsuggest', ['id' => $item['id']]);
210                 } elseif ($cmd == self::RELOCATION) {
211                         $atom = DFRN::relocate($owner, $owner['uid']);
212                 } elseif ($followup) {
213                         $msgitems = [$target_item];
214                         $atom = DFRN::entries($msgitems, $owner);
215                 } else {
216                         $msgitems = [];
217                         foreach ($items as $item) {
218                                 // Only add the parent when we don't delete other items.
219                                 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
220                                         $item["entry:comment-allow"] = true;
221                                         $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
222                                         $msgitems[] = $item;
223                                 }
224                         }
225                         $atom = DFRN::entries($msgitems, $owner);
226                 }
227
228                 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
229
230                 $basepath =  implode('/', array_slice(explode('/', $contact['url']), 0, 3));
231
232                 // perform local delivery if we are on the same site
233
234                 if (link_compare($basepath, System::baseUrl())) {
235                         $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
236                         $target_self = dba::selectFirst('contact', ['uid'], $condition);
237                         if (!DBM::is_result($target_self)) {
238                                 return;
239                         }
240                         $target_uid = $target_self['uid'];
241
242                         // Check if the user has got this contact
243                         $cid = Contact::getIdForURL($owner['url'], $target_uid);
244                         if (!$cid) {
245                                 // Otherwise there should be a public contact
246                                 $cid = Contact::getIdForURL($owner['url']);
247                                 if (!$cid) {
248                                         return;
249                                 }
250                         }
251
252                         // We now have some contact, so we fetch it
253                         $target_importer = dba::fetch_first("SELECT *, `name` as `senderName`
254                                                         FROM `contact`
255                                                         WHERE NOT `blocked` AND `id` = ? LIMIT 1",
256                                                         $cid);
257
258                         // This should never fail
259                         if (!DBM::is_result($target_importer)) {
260                                 return;
261                         }
262
263                         // Set the user id. This is important if this is a public contact
264                         $target_importer['importer_uid']  = $target_uid;
265                         DFRN::import($atom, $target_importer);
266                         return;
267                 }
268
269                 // We don't have a relationship with contacts on a public post.
270                 // Se we transmit with the new method and via Diaspora as a fallback
271                 if ($items[0]['uid'] == 0) {
272                         // Transmit in public if it's a relay post
273                         $public_dfrn = ($contact['contact-type'] == ACCOUNT_TYPE_RELAY);
274
275                         $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
276                         if (($deliver_status < 200) || ($deliver_status > 299)) {
277                                 // Transmit via Diaspora if not possible via Friendica
278                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
279                                 return;
280                         }
281                 } else {
282                         $deliver_status = DFRN::deliver($owner, $contact, $atom);
283                 }
284
285                 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
286
287                 if ($deliver_status < 0) {
288                         logger('Delivery failed: queuing message ' . $target_item["guid"] );
289                         Queue::add($contact['id'], NETWORK_DFRN, $atom, false, $target_item['guid']);
290                 }
291
292                 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
293                         // We successfully delivered a message, the contact is alive
294                         Contact::unmarkForArchival($contact);
295                 } else {
296                         // The message could not be delivered. We mark the contact as "dead"
297                         Contact::markForArchival($contact);
298                 }
299         }
300
301         /**
302          * @brief Deliver content via Diaspora
303          *
304          * @param string  $cmd            Command
305          * @param array   $contact        Contact record of the receiver
306          * @param array   $owner          Owner record of the sender
307          * @param array   $items          Item record of the content and the parent
308          * @param array   $target_item    Item record of the content
309          * @param boolean $public_message Is the content public?
310          * @param boolean $top_level      Is it a thread starter?
311          * @param boolean $followup       Is it an answer to a remote post?
312          */
313         private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
314         {
315                 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
316                 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY);
317
318                 if ($public_message) {
319                         $loc = 'public batch ' . $contact['batch'];
320                 } else {
321                         $loc = $contact['addr'];
322                 }
323
324                 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
325
326                 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
327                         return;
328                 }
329                 if ($cmd == self::MAIL) {
330                         Diaspora::sendMail($target_item, $owner, $contact);
331                         return;
332                 }
333
334                 if ($cmd == self::SUGGESTION) {
335                         return;
336                 }
337                 if (!$contact['pubkey'] && !$public_message) {
338                         return;
339                 }
340                 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
341                         // top-level retraction
342                         logger('diaspora retract: ' . $loc);
343                         Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
344                         return;
345                 } elseif ($cmd == self::RELOCATION) {
346                         Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
347                         return;
348                 } elseif ($followup) {
349                         // send comments and likes to owner to relay
350                         logger('diaspora followup: ' . $loc);
351                         Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
352                         return;
353                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
354                         // we are the relay - send comments, likes and relayable_retractions to our conversants
355                         logger('diaspora relay: ' . $loc);
356                         Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
357                         return;
358                 } elseif ($top_level && !$walltowall) {
359                         // currently no workable solution for sending walltowall
360                         logger('diaspora status: ' . $loc);
361                         Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
362                         return;
363                 }
364
365                 logger('Unknown mode ' . $cmd . ' for ' . $loc);
366         }
367
368         /**
369          * @brief Deliver content via mail
370          *
371          * @param string $cmd         Command
372          * @param array  $contact     Contact record of the receiver
373          * @param array  $owner       Owner record of the sender
374          * @param array  $target_item Item record of the content
375          */
376         private static function deliverMail($cmd, $contact, $owner, $target_item)
377         {
378                 if (Config::get('system','dfrn_only')) {
379                         return;
380                 }
381                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
382
383                 $addr = $contact['addr'];
384                 if (!strlen($addr)) {
385                         return;
386                 }
387
388                 if (!in_array($cmd, [self::POST, self::COMMENT])) {
389                         return;
390                 }
391
392                 $local_user = dba::selectFirst('user', [], ['uid' => $owner['uid']]);
393                 if (!DBM::is_result($local_user)) {
394                         return;
395                 }
396
397                 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
398
399                 $reply_to = '';
400                 $mailacct = dba::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
401                 if (DBM::is_result($mailacct) && !empty($mailacct['reply_to'])) {
402                         $reply_to = $mailacct['reply_to'];
403                 }
404
405                 $subject  = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
406
407                 // only expose our real email address to true friends
408
409                 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
410                         if ($reply_to) {
411                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
412                                 $headers .= 'Sender: ' . $local_user['email'] . "\n";
413                         } else {
414                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
415                         }
416                 } else {
417                         $headers  = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->get_hostname() . '>' . "\n";
418                 }
419
420                 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
421
422                 if ($target_item['uri'] !== $target_item['parent-uri']) {
423                         $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
424
425                         // If Threading is enabled, write down the correct parent
426                         if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
427                                 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
428                         }
429                         $headers .= "\n";
430
431                         if (empty($target_item['title'])) {
432                                 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
433                                 $title = dba::selectFirst('item', ['title'], $condition);
434                                 if (DBM::is_result($title) && ($title['title'] != '')) {
435                                         $subject = $title['title'];
436                                 } else {
437                                         $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
438                                         $title = dba::selectFirst('item', ['title'], $condition);
439                                         if (DBM::is_result($title) && ($title['title'] != '')) {
440                                                 $subject = $title['title'];
441                                         }
442                                 }
443                         }
444                         if (strncasecmp($subject, 'RE:', 3)) {
445                                 $subject = 'Re: ' . $subject;
446                         }
447                 }
448                 Email::send($addr, $subject, $headers, $target_item);
449         }
450 }