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