]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
fc7f884f6ab6fa9b8bd36cb942704864511b4773
[friendica.git] / src / Worker / Delivery.php
1 <?php
2 /**
3  * @file src/Worker/Delivery.php
4  */
5
6 namespace Friendica\Worker;
7
8 use Friendica\App;
9 use Friendica\Core\System;
10 use Friendica\Core\Config;
11 use Friendica\Database\DBM;
12 use Friendica\Model\Contact;
13 use Friendica\Model\User;
14 use Friendica\Protocol\Diaspora;
15 use Friendica\Protocol\DFRN;
16 use Friendica\Protocol\Email;
17 use dba;
18
19 require_once 'include/queue_fn.php';
20 require_once 'include/html2plain.php';
21 require_once 'include/datetime.php';
22 require_once 'include/items.php';
23 require_once 'include/bbcode.php';
24
25 /// @todo This is some ugly code that needs to be split into several methods
26
27 class Delivery {
28         public static function execute($cmd, $item_id, $contact_id) {
29                 global $a;
30
31                 logger('delivery: invoked: '.$cmd.': '.$item_id.' to '.$contact_id, LOGGER_DEBUG);
32
33                 $expire = false;
34                 $mail = false;
35                 $fsuggest = false;
36                 $relocate = false;
37                 $top_level = false;
38                 $recipients = array();
39                 $url_recipients = array();
40                 $followup = false;
41
42                 $normal_mode = true;
43
44                 $recipients[] = $contact_id;
45
46                 if ($cmd === 'mail') {
47                         $normal_mode = false;
48                         $mail = true;
49                         $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
50                                         intval($item_id)
51                         );
52                         if (!count($message)) {
53                                 return;
54                         }
55                         $uid = $message[0]['uid'];
56                         $recipients[] = $message[0]['contact-id'];
57                         $item = $message[0];
58                 } elseif ($cmd === 'expire') {
59                         $normal_mode = false;
60                         $expire = true;
61                         $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
62                                 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
63                                 intval($item_id)
64                         );
65                         $uid = $item_id;
66                         $item_id = 0;
67                         if (!count($items)) {
68                                 return;
69                         }
70                 } elseif ($cmd === 'suggest') {
71                         $normal_mode = false;
72                         $fsuggest = true;
73
74                         $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
75                                 intval($item_id)
76                         );
77                         if (!count($suggest)) {
78                                 return;
79                         }
80                         $uid = $suggest[0]['uid'];
81                         $recipients[] = $suggest[0]['cid'];
82                         $item = $suggest[0];
83                 } elseif ($cmd === 'relocate') {
84                         $normal_mode = false;
85                         $relocate = true;
86                         $uid = $item_id;
87                 } else {
88                         // find ancestors
89                         $target_item = dba::fetch_first("SELECT `item`.*, `contact`.`uid` AS `cuid` FROM `item`
90                                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
91                                                         WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $item_id);
92
93                         if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
94                                 return;
95                         }
96
97                         $parent_id = intval($target_item['parent']);
98                         $uid = $target_item['cuid'];
99                         $updated = $target_item['edited'];
100
101                         $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
102                                 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
103                                 intval($parent_id)
104                         );
105
106                         if (!count($items)) {
107                                 return;
108                         }
109
110                         $icontacts = null;
111                         $contacts_arr = array();
112                         foreach ($items as $item) {
113                                 if (!in_array($item['contact-id'],$contacts_arr)) {
114                                         $contacts_arr[] = intval($item['contact-id']);
115                                 }
116                         }
117                         if (count($contacts_arr)) {
118                                 $str_contacts = implode(',',$contacts_arr);
119                                 $icontacts = q("SELECT * FROM `contact`
120                                         WHERE `id` IN ( $str_contacts ) "
121                                 );
122                         }
123                         if ( !($icontacts && count($icontacts))) {
124                                 return;
125                         }
126
127                         // avoid race condition with deleting entries
128
129                         if ($items[0]['deleted']) {
130                                 foreach ($items as $item) {
131                                         $item['deleted'] = 1;
132                                 }
133                         }
134
135                         // When commenting too fast after delivery, a post wasn't recognized as top level post.
136                         // The count then showed more than one entry. The additional check should help.
137                         // The check for the "count" should be superfluous, but I'm not totally sure by now, so we keep it.
138                         if ((($items[0]['id'] == $item_id) || (count($items) == 1)) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
139                                 logger('delivery: top level post');
140                                 $top_level = true;
141                         }
142                 }
143
144                 $owner = User::getOwnerDataById($uid);
145                 if (!$owner) {
146                         return;
147                 }
148
149                 $walltowall = (($top_level && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
150
151                 $public_message = true;
152
153                 if (!$mail && !$fsuggest && !$relocate) {
154                         $parent = $items[0];
155
156                         // This is IMPORTANT!!!!
157
158                         // We will only send a "notify owner to relay" or followup message if the referenced post
159                         // originated on our system by virtue of having our hostname somewhere
160                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
161                         // if $parent['wall'] == 1 we will already have the parent message in our array
162                         // and we will relay the whole lot.
163
164                         // expire sends an entire group of expire messages and cannot be forwarded.
165                         // However the conversation owner will be a part of the conversation and will
166                         // be notified during this run.
167                         // Other DFRN conversation members will be alerted during polled updates.
168
169                         // Diaspora members currently are not notified of expirations, and other networks have
170                         // either limited or no ability to process deletions. We should at least fix Diaspora
171                         // by stringing togther an array of retractions and sending them onward.
172
173
174                         $localhost = $a->get_hostname();
175                         if (strpos($localhost,':')) {
176                                 $localhost = substr($localhost,0,strpos($localhost,':'));
177                         }
178                         /**
179                          *
180                          * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
181                          * have been known to cause runaway conditions which affected several servers, along with
182                          * permissions issues.
183                          *
184                          */
185
186                         $relay_to_owner = false;
187
188                         if (!$top_level && ($parent['wall'] == 0) && !$expire && stristr($target_item['uri'],$localhost)) {
189                                 $relay_to_owner = true;
190                         }
191
192                         if ($relay_to_owner) {
193                                 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
194                                 // local followup to remote post
195                                 $followup = true;
196                         }
197
198                         if (strlen($parent['allow_cid'])
199                                 || strlen($parent['allow_gid'])
200                                 || strlen($parent['deny_cid'])
201                                 || strlen($parent['deny_gid'])
202                                 || $parent["private"]) {
203                                 $public_message = false; // private recipients, not public
204                         }
205
206                 }
207
208                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
209                         intval($contact_id)
210                 );
211
212                 if (DBM::is_result($r)) {
213                         $contact = $r[0];
214                 }
215                 if ($contact['self']) {
216                         return;
217                 }
218                 $deliver_status = 0;
219
220                 // Transmit via Diaspora if not possible via Friendica
221                 if (($item['uid'] == 0) && ($contact['network'] == NETWORK_DFRN)) {
222                         $contact['network'] = NETWORK_DIASPORA;
223                 }
224
225                 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
226
227                 switch ($contact['network']) {
228
229                         case NETWORK_DFRN:
230                                 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
231
232                                 if ($mail) {
233                                         $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
234                                         $atom = DFRN::mail($item, $owner);
235                                 } elseif ($fsuggest) {
236                                         $atom = DFRN::fsuggest($item, $owner);
237                                         q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
238                                 } elseif ($relocate) {
239                                         $atom = DFRN::relocate($owner, $uid);
240                                 } elseif ($followup) {
241                                         $msgitems = array();
242                                         foreach ($items as $item) {  // there is only one item
243                                                 if (!$item['parent']) {
244                                                         return;
245                                                 }
246                                                 if ($item['id'] == $item_id) {
247                                                         logger('followup: item: '. print_r($item,true), LOGGER_DATA);
248                                                         $msgitems[] = $item;
249                                                 }
250                                         }
251                                         $atom = DFRN::entries($msgitems,$owner);
252                                 } else {
253                                         $msgitems = array();
254                                         foreach ($items as $item) {
255                                                 if (!$item['parent']) {
256                                                         return;
257                                                 }
258
259                                                 // private emails may be in included in public conversations. Filter them.
260                                                 if ($public_message && $item['private']) {
261                                                         return;
262                                                 }
263
264                                                 $item_contact = get_item_contact($item,$icontacts);
265                                                 if (!$item_contact) {
266                                                         return;
267                                                 }
268
269                                                 if ($normal_mode) {
270                                                         if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
271                                                                 $item["entry:comment-allow"] = true;
272                                                                 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
273                                                                 $msgitems[] = $item;
274                                                         }
275                                                 } else {
276                                                         $item["entry:comment-allow"] = true;
277                                                         $msgitems[] = $item;
278                                                 }
279                                         }
280                                         $atom = DFRN::entries($msgitems,$owner);
281                                 }
282
283                                 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
284
285                                 logger('notifier: '.$atom, LOGGER_DATA);
286                                 $basepath =  implode('/', array_slice(explode('/',$contact['url']),0,3));
287
288                                 // perform local delivery if we are on the same site
289
290                                 if (link_compare($basepath,System::baseUrl())) {
291                                         $nickname = basename($contact['url']);
292                                         if ($contact['issued-id']) {
293                                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
294                                         } else {
295                                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
296                                         }
297
298                                         $x = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
299                                                 `contact`.`pubkey` AS `cpubkey`,
300                                                 `contact`.`prvkey` AS `cprvkey`,
301                                                 `contact`.`thumb` AS `thumb`,
302                                                 `contact`.`url` as `url`,
303                                                 `contact`.`name` as `senderName`,
304                                                 `user`.*
305                                                 FROM `contact`
306                                                 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
307                                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
308                                                 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
309                                                 $sql_extra
310                                                 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
311                                                 dbesc(NETWORK_DFRN),
312                                                 dbesc($nickname)
313                                         );
314
315                                         if ($x && count($x)) {
316                                                 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
317                                                 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
318                                                         q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
319                                                                 intval($x[0]['id'])
320                                                         );
321                                                         $x[0]['writable'] = 1;
322                                                 }
323
324                                                 $ssl_policy = Config::get('system','ssl_policy');
325                                                 fix_contact_ssl_policy($x[0],$ssl_policy);
326
327                                                 // If we are setup as a soapbox we aren't accepting top level posts from this person
328
329                                                 if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
330                                                         break;
331                                                 }
332                                                 logger('mod-delivery: local delivery');
333                                                 DFRN::import($atom, $x[0]);
334                                                 break;
335                                         }
336                                 }
337
338                                 if (!was_recently_delayed($contact['id'])) {
339                                         $deliver_status = DFRN::deliver($owner,$contact,$atom);
340                                 } else {
341                                         $deliver_status = (-1);
342                                 }
343
344                                 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
345
346                                 if ($deliver_status < 0) {
347                                         logger('notifier: delivery failed: queuing message');
348                                         add_to_queue($contact['id'],NETWORK_DFRN,$atom);
349
350                                         // The message could not be delivered. We mark the contact as "dead"
351                                         Contact::markForArchival($contact);
352                                 } else {
353                                         // We successfully delivered a message, the contact is alive
354                                         Contact::unmarkForArchival($contact);
355                                 }
356
357                                 break;
358
359                         case NETWORK_OSTATUS:
360                                 // Do not send to otatus if we are not configured to send to public networks
361                                 if ($owner['prvnets']) {
362                                         break;
363                                 }
364                                 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
365                                         break;
366                                 }
367
368                                 // There is currently no code here to distribute anything to OStatus.
369                                 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
370                                 break;
371
372                         case NETWORK_MAIL:
373
374                                 if (Config::get('system','dfrn_only')) {
375                                         break;
376                                 }
377                                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
378
379                                 $addr = $contact['addr'];
380                                 if (!strlen($addr)) {
381                                         break;
382                                 }
383
384                                 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
385                                         $it = null;
386                                         if ($cmd === 'wall-new') {
387                                                 $it = $items[0];
388                                         } else {
389                                                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
390                                                         intval($item_id)
391                                                 );
392                                                 if (DBM::is_result($r)) {
393                                                         $it = $r[0];
394                                                 }
395                                         }
396                                         if (!$it) {
397                                                 break;
398                                         }
399
400                                         $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
401                                                 intval($uid)
402                                         );
403                                         if (!count($local_user)) {
404                                                 break;
405                                         }
406
407                                         $reply_to = '';
408                                         $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
409                                                 intval($uid)
410                                         );
411                                         if ($r1 && $r1[0]['reply_to']) {
412                                                 $reply_to = $r1[0]['reply_to'];
413                                         }
414
415                                         $subject  = (($it['title']) ? Email::encodeHeader($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
416
417                                         // only expose our real email address to true friends
418
419                                         if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
420                                                 if ($reply_to) {
421                                                         $headers  = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
422                                                         $headers .= 'Sender: '.$local_user[0]['email']."\n";
423                                                 } else {
424                                                         $headers  = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
425                                                 }
426                                         } else {
427                                                 $headers  = 'From: '. Email::encodeHeader($local_user[0]['username'],'UTF-8') .' <'. t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
428                                         }
429
430                                         //if ($reply_to)
431                                         //      $headers .= 'Reply-to: '.$reply_to . "\n";
432
433                                         $headers .= 'Message-Id: <'. Email::iri2msgid($it['uri']).'>'. "\n";
434
435                                         //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
436                                         //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
437                                         //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
438
439                                         if ($it['uri'] !== $it['parent-uri']) {
440                                                 $headers .= "References: <".Email::iri2msgid($it["parent-uri"]).">";
441
442                                                 // If Threading is enabled, write down the correct parent
443                                                 if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"])) {
444                                                         $headers .= " <".Email::iri2msgid($it["thr-parent"]).">";
445                                                 }
446                                                 $headers .= "\n";
447
448                                                 if (!$it['title']) {
449                                                         $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
450                                                                 dbesc($it['parent-uri']),
451                                                                 intval($uid));
452
453                                                         if (DBM::is_result($r) && ($r[0]['title'] != '')) {
454                                                                 $subject = $r[0]['title'];
455                                                         } else {
456                                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
457                                                                         dbesc($it['parent-uri']),
458                                                                         intval($uid));
459
460                                                                 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
461                                                                         $subject = $r[0]['title'];
462                                                                 }
463                                                         }
464                                                 }
465                                                 if (strncasecmp($subject,'RE:',3)) {
466                                                         $subject = 'Re: '.$subject;
467                                                 }
468                                         }
469                                         Email::send($addr, $subject, $headers, $it);
470                                 }
471                                 break;
472
473                         case NETWORK_DIASPORA:
474                                 if ($public_message) {
475                                         $loc = 'public batch '.$contact['batch'];
476                                 } else {
477                                         $loc = $contact['name'];
478                                 }
479
480                                 logger('delivery: diaspora batch deliver: '.$loc);
481
482                                 if (Config::get('system','dfrn_only') || !Config::get('system','diaspora_enabled')) {
483                                         break;
484                                 }
485                                 if ($mail) {
486                                         Diaspora::sendMail($item,$owner,$contact);
487                                         break;
488                                 }
489
490                                 if (!$normal_mode) {
491                                         break;
492                                 }
493                                 if (!$contact['pubkey'] && !$public_message) {
494                                         break;
495                                 }
496                                 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
497                                         // top-level retraction
498                                         logger('diaspora retract: '.$loc);
499                                         Diaspora::sendRetraction($target_item,$owner,$contact,$public_message);
500                                         break;
501                                 } elseif ($relocate) {
502                                         Diaspora::sendAccountMigration($owner, $contact, $uid);
503                                         break;
504                                 } elseif ($followup) {
505                                         // send comments and likes to owner to relay
506                                         logger('diaspora followup: '.$loc);
507                                         Diaspora::sendFollowup($target_item,$owner,$contact,$public_message);
508                                         break;
509                                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
510                                         // we are the relay - send comments, likes and relayable_retractions to our conversants
511                                         logger('diaspora relay: '.$loc);
512                                         Diaspora::sendRelay($target_item,$owner,$contact,$public_message);
513                                         break;
514                                 } elseif ($top_level && !$walltowall) {
515                                         // currently no workable solution for sending walltowall
516                                         logger('diaspora status: '.$loc);
517                                         Diaspora::sendStatus($target_item,$owner,$contact,$public_message);
518                                         break;
519                                 }
520
521                                 logger('delivery: diaspora unknown mode: '.$contact['name']);
522
523                                 break;
524
525                         default:
526                                 break;
527                 }
528
529                 return;
530         }
531 }