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