]> git.mxchange.org Git - friendica.git/blob - src/Worker/Delivery.php
Don't show the connect link in the profile on the "follow" page
[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                 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
221
222                 switch($contact['network']) {
223
224                         case NETWORK_DFRN:
225                                 logger('notifier: '.$target_item["guid"].' dfrndelivery: '.$contact['name']);
226
227                                 if ($mail) {
228                                         $item['body'] = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
229                                         $atom = DFRN::mail($item, $owner);
230                                 } elseif ($fsuggest) {
231                                         $atom = DFRN::fsuggest($item, $owner);
232                                         q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id']));
233                                 } elseif ($relocate) {
234                                         $atom = DFRN::relocate($owner, $uid);
235                                 } elseif ($followup) {
236                                         $msgitems = array();
237                                         foreach ($items as $item) {  // there is only one item
238                                                 if (!$item['parent']) {
239                                                         return;
240                                                 }
241                                                 if ($item['id'] == $item_id) {
242                                                         logger('followup: item: '. print_r($item,true), LOGGER_DATA);
243                                                         $msgitems[] = $item;
244                                                 }
245                                         }
246                                         $atom = DFRN::entries($msgitems,$owner);
247                                 } else {
248                                         $msgitems = array();
249                                         foreach ($items as $item) {
250                                                 if (!$item['parent']) {
251                                                         return;
252                                                 }
253
254                                                 // private emails may be in included in public conversations. Filter them.
255                                                 if ($public_message && $item['private']) {
256                                                         return;
257                                                 }
258
259                                                 $item_contact = get_item_contact($item,$icontacts);
260                                                 if (!$item_contact) {
261                                                         return;
262                                                 }
263
264                                                 if ($normal_mode) {
265                                                         if ($item_id == $item['id'] || $item['id'] == $item['parent']) {
266                                                                 $item["entry:comment-allow"] = true;
267                                                                 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
268                                                                 $msgitems[] = $item;
269                                                         }
270                                                 } else {
271                                                         $item["entry:comment-allow"] = true;
272                                                         $msgitems[] = $item;
273                                                 }
274                                         }
275                                         $atom = DFRN::entries($msgitems,$owner);
276                                 }
277
278                                 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
279
280                                 logger('notifier: '.$atom, LOGGER_DATA);
281                                 $basepath =  implode('/', array_slice(explode('/',$contact['url']),0,3));
282
283                                 // perform local delivery if we are on the same site
284
285                                 if (link_compare($basepath,System::baseUrl())) {
286                                         $nickname = basename($contact['url']);
287                                         if ($contact['issued-id']) {
288                                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
289                                         } else {
290                                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
291                                         }
292
293                                         $x = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
294                                                 `contact`.`pubkey` AS `cpubkey`,
295                                                 `contact`.`prvkey` AS `cprvkey`,
296                                                 `contact`.`thumb` AS `thumb`,
297                                                 `contact`.`url` as `url`,
298                                                 `contact`.`name` as `senderName`,
299                                                 `user`.*
300                                                 FROM `contact`
301                                                 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
302                                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
303                                                 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
304                                                 $sql_extra
305                                                 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
306                                                 dbesc(NETWORK_DFRN),
307                                                 dbesc($nickname)
308                                         );
309
310                                         if ($x && count($x)) {
311                                                 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
312                                                 if ((($owner['page-flags'] == PAGE_COMMUNITY) || $write_flag) && !$x[0]['writable']) {
313                                                         q("UPDATE `contact` SET `writable` = 1 WHERE `id` = %d",
314                                                                 intval($x[0]['id'])
315                                                         );
316                                                         $x[0]['writable'] = 1;
317                                                 }
318
319                                                 $ssl_policy = Config::get('system','ssl_policy');
320                                                 fix_contact_ssl_policy($x[0],$ssl_policy);
321
322                                                 // If we are setup as a soapbox we aren't accepting top level posts from this person
323
324                                                 if (($x[0]['page-flags'] == PAGE_SOAPBOX) && $top_level) {
325                                                         break;
326                                                 }
327                                                 logger('mod-delivery: local delivery');
328                                                 DFRN::import($atom, $x[0]);
329                                                 break;
330                                         }
331                                 }
332
333                                 if (!was_recently_delayed($contact['id'])) {
334                                         $deliver_status = DFRN::deliver($owner,$contact,$atom);
335                                 } else {
336                                         $deliver_status = (-1);
337                                 }
338
339                                 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
340
341                                 if ($deliver_status < 0) {
342                                         logger('notifier: delivery failed: queuing message');
343                                         add_to_queue($contact['id'],NETWORK_DFRN,$atom);
344
345                                         // The message could not be delivered. We mark the contact as "dead"
346                                         Contact::markForArchival($contact);
347                                 } else {
348                                         // We successfully delivered a message, the contact is alive
349                                         Contact::unmarkForArchival($contact);
350                                 }
351
352                                 break;
353
354                         case NETWORK_OSTATUS:
355                                 // Do not send to otatus if we are not configured to send to public networks
356                                 if ($owner['prvnets']) {
357                                         break;
358                                 }
359                                 if (Config::get('system','ostatus_disabled') || Config::get('system','dfrn_only')) {
360                                         break;
361                                 }
362
363                                 // There is currently no code here to distribute anything to OStatus.
364                                 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
365                                 break;
366
367                         case NETWORK_MAIL:
368
369                                 if (Config::get('system','dfrn_only')) {
370                                         break;
371                                 }
372                                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
373
374                                 $addr = $contact['addr'];
375                                 if (!strlen($addr)) {
376                                         break;
377                                 }
378
379                                 if ($cmd === 'wall-new' || $cmd === 'comment-new') {
380                                         $it = null;
381                                         if ($cmd === 'wall-new') {
382                                                 $it = $items[0];
383                                         } else {
384                                                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
385                                                         intval($item_id)
386                                                 );
387                                                 if (DBM::is_result($r)) {
388                                                         $it = $r[0];
389                                                 }
390                                         }
391                                         if (!$it) {
392                                                 break;
393                                         }
394
395                                         $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
396                                                 intval($uid)
397                                         );
398                                         if (!count($local_user)) {
399                                                 break;
400                                         }
401
402                                         $reply_to = '';
403                                         $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
404                                                 intval($uid)
405                                         );
406                                         if ($r1 && $r1[0]['reply_to']) {
407                                                 $reply_to = $r1[0]['reply_to'];
408                                         }
409
410                                         $subject  = (($it['title']) ? Email::encodeHeader($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
411
412                                         // only expose our real email address to true friends
413
414                                         if (($contact['rel'] == CONTACT_IS_FRIEND) && !$contact['blocked']) {
415                                                 if ($reply_to) {
416                                                         $headers  = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
417                                                         $headers .= 'Sender: '.$local_user[0]['email']."\n";
418                                                 } else {
419                                                         $headers  = 'From: '.Email::encodeHeader($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
420                                                 }
421                                         } else {
422                                                 $headers  = 'From: '. Email::encodeHeader($local_user[0]['username'],'UTF-8') .' <'. t('noreply') .'@'.$a->get_hostname() .'>'. "\n";
423                                         }
424
425                                         //if ($reply_to)
426                                         //      $headers .= 'Reply-to: '.$reply_to . "\n";
427
428                                         $headers .= 'Message-Id: <'. Email::iri2msgid($it['uri']).'>'. "\n";
429
430                                         //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
431                                         //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
432                                         //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
433
434                                         if ($it['uri'] !== $it['parent-uri']) {
435                                                 $headers .= "References: <".Email::iri2msgid($it["parent-uri"]).">";
436
437                                                 // If Threading is enabled, write down the correct parent
438                                                 if (($it["thr-parent"] != "") && ($it["thr-parent"] != $it["parent-uri"])) {
439                                                         $headers .= " <".Email::iri2msgid($it["thr-parent"]).">";
440                                                 }
441                                                 $headers .= "\n";
442
443                                                 if (!$it['title']) {
444                                                         $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
445                                                                 dbesc($it['parent-uri']),
446                                                                 intval($uid));
447
448                                                         if (DBM::is_result($r) && ($r[0]['title'] != '')) {
449                                                                 $subject = $r[0]['title'];
450                                                         } else {
451                                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
452                                                                         dbesc($it['parent-uri']),
453                                                                         intval($uid));
454
455                                                                 if (DBM::is_result($r) && ($r[0]['title'] != '')) {
456                                                                         $subject = $r[0]['title'];
457                                                                 }
458                                                         }
459                                                 }
460                                                 if (strncasecmp($subject,'RE:',3)) {
461                                                         $subject = 'Re: '.$subject;
462                                                 }
463                                         }
464                                         Email::send($addr, $subject, $headers, $it);
465                                 }
466                                 break;
467
468                         case NETWORK_DIASPORA:
469                                 if ($public_message) {
470                                         $loc = 'public batch '.$contact['batch'];
471                                 } else {
472                                         $loc = $contact['name'];
473                                 }
474
475                                 logger('delivery: diaspora batch deliver: '.$loc);
476
477                                 if (Config::get('system','dfrn_only') || !Config::get('system','diaspora_enabled')) {
478                                         break;
479                                 }
480                                 if ($mail) {
481                                         Diaspora::sendMail($item,$owner,$contact);
482                                         break;
483                                 }
484
485                                 if (!$normal_mode) {
486                                         break;
487                                 }
488                                 if (!$contact['pubkey'] && !$public_message) {
489                                         break;
490                                 }
491                                 if (($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
492                                         // top-level retraction
493                                         logger('diaspora retract: '.$loc);
494                                         Diaspora::sendRetraction($target_item,$owner,$contact,$public_message);
495                                         break;
496                                 } elseif ($relocate) {
497                                         Diaspora::sendAccountMigration($owner, $contact, $uid);
498                                         break;
499                                 } elseif ($followup) {
500                                         // send comments and likes to owner to relay
501                                         logger('diaspora followup: '.$loc);
502                                         Diaspora::sendFollowup($target_item,$owner,$contact,$public_message);
503                                         break;
504                                 } elseif ($target_item['uri'] !== $target_item['parent-uri']) {
505                                         // we are the relay - send comments, likes and relayable_retractions to our conversants
506                                         logger('diaspora relay: '.$loc);
507                                         Diaspora::sendRelay($target_item,$owner,$contact,$public_message);
508                                         break;
509                                 } elseif ($top_level && !$walltowall) {
510                                         // currently no workable solution for sending walltowall
511                                         logger('diaspora status: '.$loc);
512                                         Diaspora::sendStatus($target_item,$owner,$contact,$public_message);
513                                         break;
514                                 }
515
516                                 logger('delivery: diaspora unknown mode: '.$contact['name']);
517
518                                 break;
519
520                         default:
521                                 break;
522                 }
523
524                 return;
525         }
526 }