]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
Rename Friendica\Database\dba to Friendica\Database\DBA
[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\DBA;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Item;
15 use Friendica\Model\Queue;
16 use Friendica\Model\User;
17 use Friendica\Protocol\DFRN;
18 use Friendica\Protocol\Diaspora;
19 use Friendica\Protocol\Email;
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                         $items = [];
48                 } elseif ($cmd == self::SUGGESTION) {
49                         $target_item = DBA::selectFirst('fsuggest', [], ['id' => $item_id]);
50                         if (!DBM::is_result($target_item)) {
51                                 return;
52                         }
53                         $uid = $target_item['uid'];
54                 } elseif ($cmd == self::RELOCATION) {
55                         $uid = $item_id;
56                 } else {
57                         $item = Item::selectFirst(['parent'], ['id' => $item_id]);
58                         if (!DBM::is_result($item) || empty($item['parent'])) {
59                                 return;
60                         }
61                         $parent_id = intval($item['parent']);
62
63                         $condition = ['id' => [$item_id, $parent_id], 'visible' => true, 'moderated' => false];
64                         $params = ['order' => ['id']];
65                         $itemdata = Item::select([], $condition, $params);
66
67                         $items = [];
68                         while ($item = Item::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['contact-uid'];
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                 if (empty($items)) {
132                         logger('No delivery data for  ' . $cmd . ' - Item ID: ' .$item_id . ' - Contact ID: ' . $contact_id);
133                 }
134
135                 $owner = User::getOwnerDataById($uid);
136                 if (!DBM::is_result($owner)) {
137                         return;
138                 }
139
140                 // We don't deliver our items to blocked or pending contacts, and not to ourselves either
141                 $contact = DBA::selectFirst('contact', [],
142                         ['id' => $contact_id, 'blocked' => false, 'pending' => false, 'self' => false]
143                 );
144                 if (!DBM::is_result($contact)) {
145                         return;
146                 }
147
148                 // Transmit via Diaspora if the thread had started as Diaspora post
149                 // This is done since the uri wouldn't match (Diaspora doesn't transmit it)
150                 if (isset($parent) && ($parent['network'] == NETWORK_DIASPORA) && ($contact['network'] == NETWORK_DFRN)) {
151                         $contact['network'] = NETWORK_DIASPORA;
152                 }
153
154                 logger("Delivering " . $cmd . " followup=$followup - via network " . $contact['network']);
155
156                 switch ($contact['network']) {
157
158                         case NETWORK_DFRN:
159                                 self::deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
160                                 break;
161
162                         case NETWORK_DIASPORA:
163                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
164                                 break;
165
166                         case NETWORK_OSTATUS:
167                                 // Do not send to otatus if we are not configured to send to public networks
168                                 if ($owner['prvnets']) {
169                                         break;
170                                 }
171                                 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
172                                         break;
173                                 }
174
175                                 // There is currently no code here to distribute anything to OStatus.
176                                 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
177                                 break;
178
179                         case NETWORK_MAIL:
180                                 self::deliverMail($cmd, $contact, $owner, $target_item);
181                                 break;
182
183                         default:
184                                 break;
185                 }
186
187                 return;
188         }
189
190         /**
191          * @brief Deliver content via DFRN
192          *
193          * @param string  $cmd            Command
194          * @param array   $contact        Contact record of the receiver
195          * @param array   $owner          Owner record of the sender
196          * @param array   $items          Item record of the content and the parent
197          * @param array   $target_item    Item record of the content
198          * @param boolean $public_message Is the content public?
199          * @param boolean $top_level      Is it a thread starter?
200          * @param boolean $followup       Is it an answer to a remote post?
201          */
202         private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
203         {
204                 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . (empty($contact['addr']) ? $contact['url'] : $contact['addr']));
205
206                 if ($cmd == self::MAIL) {
207                         $item = $target_item;
208                         $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
209                         $atom = DFRN::mail($item, $owner);
210                 } elseif ($cmd == self::SUGGESTION) {
211                         $item = $target_item;
212                         $atom = DFRN::fsuggest($item, $owner);
213                         DBA::delete('fsuggest', ['id' => $item['id']]);
214                 } elseif ($cmd == self::RELOCATION) {
215                         $atom = DFRN::relocate($owner, $owner['uid']);
216                 } elseif ($followup) {
217                         $msgitems = [$target_item];
218                         $atom = DFRN::entries($msgitems, $owner);
219                 } else {
220                         $msgitems = [];
221                         foreach ($items as $item) {
222                                 // Only add the parent when we don't delete other items.
223                                 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
224                                         $item["entry:comment-allow"] = true;
225                                         $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
226                                         $msgitems[] = $item;
227                                 }
228                         }
229                         $atom = DFRN::entries($msgitems, $owner);
230                 }
231
232                 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
233
234                 $basepath =  implode('/', array_slice(explode('/', $contact['url']), 0, 3));
235
236                 // perform local delivery if we are on the same site
237
238                 if (link_compare($basepath, System::baseUrl())) {
239                         $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
240                         $target_self = DBA::selectFirst('contact', ['uid'], $condition);
241                         if (!DBM::is_result($target_self)) {
242                                 return;
243                         }
244                         $target_uid = $target_self['uid'];
245
246                         // Check if the user has got this contact
247                         $cid = Contact::getIdForURL($owner['url'], $target_uid);
248                         if (!$cid) {
249                                 // Otherwise there should be a public contact
250                                 $cid = Contact::getIdForURL($owner['url']);
251                                 if (!$cid) {
252                                         return;
253                                 }
254                         }
255
256                         // We now have some contact, so we fetch it
257                         $target_importer = DBA::fetch_first("SELECT *, `name` as `senderName`
258                                                         FROM `contact`
259                                                         WHERE NOT `blocked` AND `id` = ? LIMIT 1",
260                                                         $cid);
261
262                         // This should never fail
263                         if (!DBM::is_result($target_importer)) {
264                                 return;
265                         }
266
267                         $user = DBA::selectFirst('user', [], ['uid' => $target_uid]);
268
269                         $target_importer = array_merge($target_importer, $user);
270
271                         // Set the user id. This is important if this is a public contact
272                         $target_importer['importer_uid']  = $target_uid;
273                         DFRN::import($atom, $target_importer);
274                         return;
275                 }
276
277                 // We don't have a relationship with contacts on a public post.
278                 // Se we transmit with the new method and via Diaspora as a fallback
279                 if (!empty($items) && (($items[0]['uid'] == 0) || ($contact['uid'] == 0))) {
280                         // Transmit in public if it's a relay post
281                         $public_dfrn = ($contact['contact-type'] == ACCOUNT_TYPE_RELAY);
282
283                         $deliver_status = DFRN::transmit($owner, $contact, $atom, $public_dfrn);
284
285                         // We never spool failed relay deliveries
286                         if ($public_dfrn) {
287                                 logger('Relay delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
288                                 return;
289                         }
290
291                         if (($deliver_status < 200) || ($deliver_status > 299)) {
292                                 // Transmit via Diaspora if not possible via Friendica
293                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
294                                 return;
295                         }
296                 } else {
297                         $deliver_status = DFRN::deliver($owner, $contact, $atom);
298                 }
299
300                 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
301
302                 if ($deliver_status < 0) {
303                         logger('Delivery failed: queuing message ' . $target_item["guid"] );
304                         Queue::add($contact['id'], NETWORK_DFRN, $atom, false, $target_item['guid']);
305                 }
306
307                 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
308                         // We successfully delivered a message, the contact is alive
309                         Contact::unmarkForArchival($contact);
310                 } else {
311                         // The message could not be delivered. We mark the contact as "dead"
312                         Contact::markForArchival($contact);
313                 }
314         }
315
316         /**
317          * @brief Deliver content via Diaspora
318          *
319          * @param string  $cmd            Command
320          * @param array   $contact        Contact record of the receiver
321          * @param array   $owner          Owner record of the sender
322          * @param array   $items          Item record of the content and the parent
323          * @param array   $target_item    Item record of the content
324          * @param boolean $public_message Is the content public?
325          * @param boolean $top_level      Is it a thread starter?
326          * @param boolean $followup       Is it an answer to a remote post?
327          */
328         private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
329         {
330                 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
331                 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY);
332
333                 if ($public_message) {
334                         $loc = 'public batch ' . $contact['batch'];
335                 } else {
336                         $loc = $contact['addr'];
337                 }
338
339                 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
340
341                 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
342                         return;
343                 }
344                 if ($cmd == self::MAIL) {
345                         Diaspora::sendMail($target_item, $owner, $contact);
346                         return;
347                 }
348
349                 if ($cmd == self::SUGGESTION) {
350                         return;
351                 }
352                 if (!$contact['pubkey'] && !$public_message) {
353                         return;
354                 }
355                 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
356                         // top-level retraction
357                         logger('diaspora retract: ' . $loc);
358                         Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
359                         return;
360                 } elseif ($cmd == self::RELOCATION) {
361                         Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
362                         return;
363                 } elseif ($followup) {
364                         // send comments and likes to owner to relay
365                         logger('diaspora followup: ' . $loc);
366                         Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
367                         return;
368                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
369                         // we are the relay - send comments, likes and relayable_retractions to our conversants
370                         logger('diaspora relay: ' . $loc);
371                         Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
372                         return;
373                 } elseif ($top_level && !$walltowall) {
374                         // currently no workable solution for sending walltowall
375                         logger('diaspora status: ' . $loc);
376                         Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
377                         return;
378                 }
379
380                 logger('Unknown mode ' . $cmd . ' for ' . $loc);
381         }
382
383         /**
384          * @brief Deliver content via mail
385          *
386          * @param string $cmd         Command
387          * @param array  $contact     Contact record of the receiver
388          * @param array  $owner       Owner record of the sender
389          * @param array  $target_item Item record of the content
390          */
391         private static function deliverMail($cmd, $contact, $owner, $target_item)
392         {
393                 if (Config::get('system','dfrn_only')) {
394                         return;
395                 }
396                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
397
398                 $addr = $contact['addr'];
399                 if (!strlen($addr)) {
400                         return;
401                 }
402
403                 if (!in_array($cmd, [self::POST, self::COMMENT])) {
404                         return;
405                 }
406
407                 $local_user = DBA::selectFirst('user', [], ['uid' => $owner['uid']]);
408                 if (!DBM::is_result($local_user)) {
409                         return;
410                 }
411
412                 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
413
414                 $reply_to = '';
415                 $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
416                 if (DBM::is_result($mailacct) && !empty($mailacct['reply_to'])) {
417                         $reply_to = $mailacct['reply_to'];
418                 }
419
420                 $subject  = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
421
422                 // only expose our real email address to true friends
423
424                 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
425                         if ($reply_to) {
426                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
427                                 $headers .= 'Sender: ' . $local_user['email'] . "\n";
428                         } else {
429                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
430                         }
431                 } else {
432                         $headers  = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->get_hostname() . '>' . "\n";
433                 }
434
435                 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
436
437                 if ($target_item['uri'] !== $target_item['parent-uri']) {
438                         $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
439
440                         // If Threading is enabled, write down the correct parent
441                         if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
442                                 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
443                         }
444                         $headers .= "\n";
445
446                         if (empty($target_item['title'])) {
447                                 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
448                                 $title = Item::selectFirst(['title'], $condition);
449                                 if (DBM::is_result($title) && ($title['title'] != '')) {
450                                         $subject = $title['title'];
451                                 } else {
452                                         $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
453                                         $title = Item::selectFirst(['title'], $condition);
454                                         if (DBM::is_result($title) && ($title['title'] != '')) {
455                                                 $subject = $title['title'];
456                                         }
457                                 }
458                         }
459                         if (strncasecmp($subject, 'RE:', 3)) {
460                                 $subject = 'Re: ' . $subject;
461                         }
462                 }
463                 Email::send($addr, $subject, $headers, $target_item);
464         }
465 }