]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
Constants moved
[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         private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
187         {
188                 logger('Deliver ' . $target_item["guid"] . ' via DFRN to ' . $contact['addr']);
189
190                 if ($cmd == self::MAIL) {
191                         $item = $target_item;
192                         $item['body'] = Item::fixPrivatePhotos($item['body'], $owner['uid'], null, $item['contact-id']);
193                         $atom = DFRN::mail($item, $owner);
194                 } elseif ($cmd == self::SUGGESTION) {
195                         $item = $target_item;
196                         $atom = DFRN::fsuggest($item, $owner);
197                         dba::delete('fsuggest', ['id' => $item['id']]);
198                 } elseif ($cmd == self::RELOCATION) {
199                         $atom = DFRN::relocate($owner, $owner['uid']);
200                 } elseif ($followup) {
201                         $msgitems = [$target_item];
202                         $atom = DFRN::entries($msgitems, $owner);
203                 } else {
204                         $msgitems = [];
205                         foreach ($items as $item) {
206                                 // Only add the parent when we don't delete other items.
207                                 if (($target_item['id'] == $item['id']) || ($cmd != self::DELETION)) {
208                                         $item["entry:comment-allow"] = true;
209                                         $item["entry:cid"] = ($top_level ? $contact['id'] : 0);
210                                         $msgitems[] = $item;
211                                 }
212                         }
213                         $atom = DFRN::entries($msgitems, $owner);
214                 }
215
216                 logger('Notifier entry: ' . $contact["url"] . ' ' . $target_item["guid"] . ' entry: ' . $atom, LOGGER_DATA);
217
218                 $basepath =  implode('/', array_slice(explode('/', $contact['url']), 0, 3));
219
220                 // perform local delivery if we are on the same site
221
222                 if (link_compare($basepath, System::baseUrl())) {
223                         $condition = ['nurl' => normalise_link($contact['url']), 'self' => true];
224                         $target_self = dba::selectFirst('contact', ['uid'], $condition);
225                         if (!DBM::is_result($target_self)) {
226                                 return;
227                         }
228                         $target_uid = $target_self['uid'];
229
230                         // Check if the user has got this contact
231                         $cid = Contact::getIdForURL($owner['url'], $target_uid);
232                         if (!$cid) {
233                                 // Otherwise there should be a public contact
234                                 $cid = Contact::getIdForURL($owner['url']);
235                                 if (!$cid) {
236                                         return;
237                                 }
238                         }
239
240                         // We now have some contact, so we fetch it
241                         $target_importer = dba::fetch_first("SELECT *, `name` as `senderName`
242                                                         FROM `contact`
243                                                         WHERE NOT `blocked` AND `id` = ? LIMIT 1",
244                                                         $cid);
245
246                         // This should never fail
247                         if (!DBM::is_result($target_importer)) {
248                                 return;
249                         }
250
251                         // Set the user id. This is important if this is a public contact
252                         $target_importer['importer_uid']  = $target_uid;
253                         DFRN::import($atom, $target_importer);
254                         return;
255                 }
256
257                 // We don't have a relationship with contacts on a public post.
258                 // Se we transmit with the new method and via Diaspora as a fallback
259                 if ($items[0]['uid'] == 0) {
260                         $deliver_status = DFRN::transmit($owner, $contact, $atom);
261                         if ($deliver_status < 200) {
262                                 // Transmit via Diaspora if not possible via Friendica
263                                 self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup);
264                                 return;
265                         }
266                 } else {
267                         $deliver_status = DFRN::deliver($owner, $contact, $atom);
268                 }
269
270                 logger('Delivery to ' . $contact["url"] . ' with guid ' . $target_item["guid"] . ' returns ' . $deliver_status);
271
272                 if ($deliver_status < 0) {
273                         logger('Delivery failed: queuing message ' . $target_item["guid"] );
274                         Queue::add($contact['id'], NETWORK_DFRN, $atom, false, $target_item['guid']);
275                 }
276
277                 if (($deliver_status >= 200) && ($deliver_status <= 299)) {
278                         // We successfully delivered a message, the contact is alive
279                         Contact::unmarkForArchival($contact);
280                 } else {
281                         // The message could not be delivered. We mark the contact as "dead"
282                         Contact::markForArchival($contact);
283                 }
284         }
285
286         private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup)
287         {
288                 // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
289                 $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY);
290
291                 if ($public_message) {
292                         $loc = 'public batch ' . $contact['batch'];
293                 } else {
294                         $loc = $contact['addr'];
295                 }
296
297                 logger('Deliver ' . $target_item["guid"] . ' via Diaspora to ' . $loc);
298
299                 if (Config::get('system', 'dfrn_only') || !Config::get('system', 'diaspora_enabled')) {
300                         return;
301                 }
302                 if ($cmd == self::MAIL) {
303                         Diaspora::sendMail($target_item, $owner, $contact);
304                         return;
305                 }
306
307                 if ($cmd == self::SUGGESTION) {
308                         return;
309                 }
310                 if (!$contact['pubkey'] && !$public_message) {
311                         return;
312                 }
313                 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
314                         // top-level retraction
315                         logger('diaspora retract: ' . $loc);
316                         Diaspora::sendRetraction($target_item, $owner, $contact, $public_message);
317                         return;
318                 } elseif ($cmd == self::RELOCATION) {
319                         Diaspora::sendAccountMigration($owner, $contact, $owner['uid']);
320                         return;
321                 } elseif ($followup) {
322                         // send comments and likes to owner to relay
323                         logger('diaspora followup: ' . $loc);
324                         Diaspora::sendFollowup($target_item, $owner, $contact, $public_message);
325                         return;
326                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
327                         // we are the relay - send comments, likes and relayable_retractions to our conversants
328                         logger('diaspora relay: ' . $loc);
329                         Diaspora::sendRelay($target_item, $owner, $contact, $public_message);
330                         return;
331                 } elseif ($top_level && !$walltowall) {
332                         // currently no workable solution for sending walltowall
333                         logger('diaspora status: ' . $loc);
334                         Diaspora::sendStatus($target_item, $owner, $contact, $public_message);
335                         return;
336                 }
337
338                 logger('Unknown mode ' . $cmd . ' for ' . $loc);
339         }
340
341         private static function deliverMail($cmd, $contact, $owner, $target_item)
342         {
343                 if (Config::get('system','dfrn_only')) {
344                         return;
345                 }
346                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
347
348                 $addr = $contact['addr'];
349                 if (!strlen($addr)) {
350                         return;
351                 }
352
353                 if (!in_array($cmd, [self::POST, self::COMMENT])) {
354                         return;
355                 }
356
357                 $local_user = dba::selectFirst('user', [], ['uid' => $owner['uid']]);
358                 if (!DBM::is_result($local_user)) {
359                         return;
360                 }
361
362                 logger('Deliver ' . $target_item["guid"] . ' via mail to ' . $contact['addr']);
363
364                 $reply_to = '';
365                 $mailacct = dba::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]);
366                 if (DBM::is_result($mailacct) && !empty($mailacct['reply_to'])) {
367                         $reply_to = $mailacct['reply_to'];
368                 }
369
370                 $subject  = ($target_item['title'] ? Email::encodeHeader($target_item['title'], 'UTF-8') : L10n::t("\x28no subject\x29"));
371
372                 // only expose our real email address to true friends
373
374                 if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
375                         if ($reply_to) {
376                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to.'>' . "\n";
377                                 $headers .= 'Sender: ' . $local_user['email'] . "\n";
378                         } else {
379                                 $headers  = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8').' <' . $local_user['email'] . '>' . "\n";
380                         }
381                 } else {
382                         $headers  = 'From: '. Email::encodeHeader($local_user['username'], 'UTF-8') . ' <noreply@' . self::getApp()->get_hostname() . '>' . "\n";
383                 }
384
385                 $headers .= 'Message-Id: <' . Email::iri2msgid($target_item['uri']) . '>' . "\n";
386
387                 if ($target_item['uri'] !== $target_item['parent-uri']) {
388                         $headers .= "References: <" . Email::iri2msgid($target_item["parent-uri"]) . ">";
389
390                         // If Threading is enabled, write down the correct parent
391                         if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
392                                 $headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
393                         }
394                         $headers .= "\n";
395
396                         if (empty($target_item['title'])) {
397                                 $condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
398                                 $title = dba::selectFirst('item', ['title'], $condition);
399                                 if (DBM::is_result($title) && ($title['title'] != '')) {
400                                         $subject = $title['title'];
401                                 } else {
402                                         $condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
403                                         $title = dba::selectFirst('item', ['title'], $condition);
404                                         if (DBM::is_result($title) && ($title['title'] != '')) {
405                                                 $subject = $title['title'];
406                                         }
407                                 }
408                         }
409                         if (strncasecmp($subject, 'RE:', 3)) {
410                                 $subject = 'Re: ' . $subject;
411                         }
412                 }
413                 Email::send($addr, $subject, $headers, $target_item);
414         }
415 }