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