]> git.mxchange.org Git - friendica.git/blob - include/delivery.php
482a759498dd035b4e0980d42ee8c86a8ef44088
[friendica.git] / include / delivery.php
1 <?php
2 require_once("boot.php");
3 require_once('include/queue_fn.php');
4 require_once('include/html2plain.php');
5 require_once("include/Scrape.php");
6 require_once('include/diaspora.php');
7 require_once("include/ostatus.php");
8 require_once("include/dfrn.php");
9
10 function delivery_run(&$argv, &$argc){
11         global $a, $db;
12
13         if(is_null($a)){
14                 $a = new App;
15         }
16
17         if(is_null($db)) {
18                 @include(".htconfig.php");
19                 require_once("include/dba.php");
20                 $db = new dba($db_host, $db_user, $db_pass, $db_data);
21                 unset($db_host, $db_user, $db_pass, $db_data);
22         }
23
24         require_once("include/session.php");
25         require_once("include/datetime.php");
26         require_once('include/items.php');
27         require_once('include/bbcode.php');
28         require_once('include/email.php');
29
30         load_config('config');
31         load_config('system');
32
33         load_hooks();
34
35         if($argc < 3)
36                 return;
37
38         $a->set_baseurl(get_config('system','url'));
39
40         logger('delivery: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
41
42         $cmd        = $argv[1];
43         $item_id    = intval($argv[2]);
44
45         for($x = 3; $x < $argc; $x ++) {
46
47                 $contact_id = intval($argv[$x]);
48
49                 // Some other process may have delivered this item already.
50
51                 $r = q("SELECT * FROM `deliverq` WHERE `cmd` = '%s' AND `item` = %d AND `contact` = %d LIMIT 1",
52                         dbesc($cmd),
53                         dbesc($item_id),
54                         dbesc($contact_id)
55                 );
56                 if(! count($r)) {
57                         continue;
58                 }
59
60                 $maxsysload = intval(get_config('system','maxloadavg'));
61                 if($maxsysload < 1)
62                         $maxsysload = 50;
63
64                 $load = current_load();
65                 if($load) {
66                         if(intval($load) > $maxsysload) {
67                                 logger('system: load ' . $load . ' too high. Delivery deferred to next queue run.');
68                                 return;
69                         }
70                 }
71
72                 // It's ours to deliver. Remove it from the queue.
73
74                 q("DELETE FROM `deliverq` WHERE `cmd` = '%s' AND `item` = %d AND `contact` = %d",
75                         dbesc($cmd),
76                         dbesc($item_id),
77                         dbesc($contact_id)
78                 );
79
80                 if((! $item_id) || (! $contact_id))
81                         continue;
82
83                 $expire = false;
84                 $mail = false;
85                 $fsuggest = false;
86                 $relocate = false;
87                 $top_level = false;
88                 $recipients = array();
89                 $url_recipients = array();
90                 $followup = false;
91
92                 $normal_mode = true;
93
94                 $recipients[] = $contact_id;
95
96                 if($cmd === 'mail') {
97                         $normal_mode = false;
98                         $mail = true;
99                         $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
100                                         intval($item_id)
101                         );
102                         if(! count($message)){
103                                 return;
104                         }
105                         $uid = $message[0]['uid'];
106                         $recipients[] = $message[0]['contact-id'];
107                         $item = $message[0];
108                 }
109                 elseif($cmd === 'expire') {
110                         $normal_mode = false;
111                         $expire = true;
112                         $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
113                                 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 30 MINUTE",
114                                 intval($item_id)
115                         );
116                         $uid = $item_id;
117                         $item_id = 0;
118                         if(! count($items))
119                                 continue;
120                 }
121                 elseif($cmd === 'suggest') {
122                         $normal_mode = false;
123                         $fsuggest = true;
124
125                         $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
126                                 intval($item_id)
127                         );
128                         if(! count($suggest))
129                                 return;
130                         $uid = $suggest[0]['uid'];
131                         $recipients[] = $suggest[0]['cid'];
132                         $item = $suggest[0];
133                 } elseif($cmd === 'relocate') {
134                         $normal_mode = false;
135                         $relocate = true;
136                         $uid = $item_id;
137                 } else {
138                         // find ancestors
139                         $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
140                                 intval($item_id)
141                         );
142
143                         if((! count($r)) || (! intval($r[0]['parent']))) {
144                                 continue;
145                         }
146
147                         $target_item = $r[0];
148                         $parent_id = intval($r[0]['parent']);
149                         $uid = $r[0]['uid'];
150                         $updated = $r[0]['edited'];
151
152                         $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
153                                 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
154                                 intval($parent_id)
155                         );
156
157                         if(! count($items)) {
158                                 continue;
159                         }
160
161                         $icontacts = null;
162                         $contacts_arr = array();
163                         foreach($items as $item)
164                                 if(! in_array($item['contact-id'],$contacts_arr))
165                                         $contacts_arr[] = intval($item['contact-id']);
166                         if(count($contacts_arr)) {
167                                 $str_contacts = implode(',',$contacts_arr);
168                                 $icontacts = q("SELECT * FROM `contact`
169                                         WHERE `id` IN ( $str_contacts ) "
170                                 );
171                         }
172                         if( ! ($icontacts && count($icontacts)))
173                                 continue;
174
175                         // avoid race condition with deleting entries
176
177                         if($items[0]['deleted']) {
178                                 foreach($items as $item)
179                                         $item['deleted'] = 1;
180                         }
181
182                         if((count($items) == 1) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
183                                 logger('delivery: top level post');
184                                 $top_level = true;
185                         }
186                 }
187
188                 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
189                         `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
190                         `user`.`page-flags`, `user`.`prvnets`
191                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
192                         WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
193                         intval($uid)
194                 );
195
196                 if(! count($r))
197                         continue;
198
199                 $owner = $r[0];
200
201                 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
202
203                 $public_message = true;
204
205                 if(! ($mail || $fsuggest || $relocate)) {
206                         require_once('include/group.php');
207
208                         $parent = $items[0];
209
210                         // This is IMPORTANT!!!!
211
212                         // We will only send a "notify owner to relay" or followup message if the referenced post
213                         // originated on our system by virtue of having our hostname somewhere
214                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
215                         // if $parent['wall'] == 1 we will already have the parent message in our array
216                         // and we will relay the whole lot.
217
218                         // expire sends an entire group of expire messages and cannot be forwarded.
219                         // However the conversation owner will be a part of the conversation and will
220                         // be notified during this run.
221                         // Other DFRN conversation members will be alerted during polled updates.
222
223                         // Diaspora members currently are not notified of expirations, and other networks have
224                         // either limited or no ability to process deletions. We should at least fix Diaspora
225                         // by stringing togther an array of retractions and sending them onward.
226
227
228                         $localhost = $a->get_hostname();
229                         if(strpos($localhost,':'))
230                                 $localhost = substr($localhost,0,strpos($localhost,':'));
231
232                         /**
233                          *
234                          * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
235                          * have been known to cause runaway conditions which affected several servers, along with
236                          * permissions issues.
237                          *
238                          */
239
240                         $relay_to_owner = false;
241
242                         if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
243                                 $relay_to_owner = true;
244                         }
245
246                         if($relay_to_owner) {
247                                 logger('followup '.$target_item["guid"], LOGGER_DEBUG);
248                                 // local followup to remote post
249                                 $followup = true;
250                         }
251
252                         if((strlen($parent['allow_cid']))
253                                 || (strlen($parent['allow_gid']))
254                                 || (strlen($parent['deny_cid']))
255                                 || (strlen($parent['deny_gid']))) {
256                                 $public_message = false; // private recipients, not public
257                         }
258
259                 }
260
261                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
262                         intval($contact_id)
263                 );
264
265                 if(count($r))
266                         $contact = $r[0];
267
268                 $hubxml = feed_hublinks();
269
270                 if($contact['self'])
271                         continue;
272
273                 $deliver_status = 0;
274
275                 logger("main delivery by delivery: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate - network ".$contact['network']);
276
277                 switch($contact['network']) {
278
279                         case NETWORK_DFRN:
280                                 logger('notifier: '.$target_item["guid"].' dfrndelivery: ' . $contact['name']);
281
282                                 if ($mail) {
283                                         $item["body"] = $body;
284                                         $atom = dfrn_mail($item, $owner);
285                                 } elseif ($fsuggest) {
286                                         $atom = dfrn_fsuggest($item, $owner);
287                                         // q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1", intval($item['id'])
288                                 } elseif ($relocate)
289                                         $atom = dfrn_relocate($owner, $uid);
290                                 elseif($followup) {
291                                         $msgitems = array();
292                                         foreach($items as $item) {  // there is only one item
293                                                 if(!$item['parent'])
294                                                         continue;
295                                                 if($item['id'] == $item_id) {
296                                                         logger('followup: item: ' . print_r($item,true), LOGGER_DATA);
297                                                         $msgitems[] = $item;
298                                                 }
299                                         }
300                                         $atom = dfrn_entries($msgitems,$owner);
301                                 } else {
302                                         $msgitems = array();
303                                         foreach($items as $item) {
304                                                 if(!$item['parent'])
305                                                         continue;
306
307                                                 // private emails may be in included in public conversations. Filter them.
308                                                 if(($public_message) && $item['private'])
309                                                         continue;
310
311                                                 $item_contact = get_item_contact($item,$icontacts);
312                                                 if(!$item_contact)
313                                                         continue;
314
315                                                 if($normal_mode) {
316                                                         if($item_id == $item['id'] || $item['id'] == $item['parent']) {
317                                                                 $item["entry:comment-allow"] = true;
318                                                                 $item["entry:cid"] = (($top_level) ? $contact['id'] : 0);
319                                                                 $msgitems[] = $item;
320                                                         }
321                                                 } else {
322                                                         $item["entry:comment-allow"] = true;
323                                                         $msgitems[] = $item;
324                                                 }
325                                         }
326                                         $atom = dfrn_entries($msgitems,$owner);
327                                 }
328 /*
329                                 $feed_template = get_markup_template('atom_feed.tpl');
330                                 $mail_template = get_markup_template('atom_mail.tpl');
331
332                                 $atom = '';
333
334
335                                 $birthday = feed_birthday($owner['uid'],$owner['timezone']);
336
337                                 if(strlen($birthday))
338                                         $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
339
340                                 $atom .= replace_macros($feed_template, array(
341                                                 '$version'      => xmlify(FRIENDICA_VERSION),
342                                                 '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
343                                                 '$feed_title'   => xmlify($owner['name']),
344                                                 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
345                                                 '$hub'          => $hubxml,
346                                                 '$salmon'       => '',  // private feed, we don't use salmon here
347                                                 '$name'         => xmlify($owner['name']),
348                                                 '$profile_page' => xmlify($owner['url']),
349                                                 '$photo'        => xmlify($owner['photo']),
350                                                 '$thumb'        => xmlify($owner['thumb']),
351                                                 '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
352                                                 '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
353                                                 '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
354                                                 '$birthday'     => $birthday,
355                                                 '$community'    => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
356                                 ));
357
358                                 if($mail) {
359                                         $public_message = false;  // mail is  not public
360
361                                         $body = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
362
363                                         $atom .= replace_macros($mail_template, array(
364                                                 '$name'         => xmlify($owner['name']),
365                                                 '$profile_page' => xmlify($owner['url']),
366                                                 '$thumb'        => xmlify($owner['thumb']),
367                                                 '$item_id'      => xmlify($item['uri']),
368                                                 '$subject'      => xmlify($item['title']),
369                                                 '$created'      => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
370                                                 '$content'      => xmlify($body),
371                                                 '$parent_id'    => xmlify($item['parent-uri'])
372                                         ));
373                                 } elseif($fsuggest) {
374                                         $public_message = false;  // suggestions are not public
375
376                                         $sugg_template = get_markup_template('atom_suggest.tpl');
377
378                                         $atom .= replace_macros($sugg_template, array(
379                                                 '$name'         => xmlify($item['name']),
380                                                 '$url'          => xmlify($item['url']),
381                                                 '$photo'        => xmlify($item['photo']),
382                                                 '$request'      => xmlify($item['request']),
383                                                 '$note'         => xmlify($item['note'])
384                                         ));
385
386                                         // We don't need this any more
387
388                                         q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
389                                                 intval($item['id'])
390                                         );
391                                 } elseif($relocate) {
392                                         $public_message = false;  // suggestions are not public
393
394                                         $sugg_template = get_markup_template('atom_relocate.tpl');
395
396                                         // get site pubkey. this could be a new installation with no site keys
397                                         $pubkey = get_config('system','site_pubkey');
398                                         if(! $pubkey) {
399                                                 $res = new_keypair(1024);
400                                                 set_config('system','site_prvkey', $res['prvkey']);
401                                                 set_config('system','site_pubkey', $res['pubkey']);
402                                         }
403
404                                         $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
405                                                         WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
406                                         $photos = array();
407                                         $ext = Photo::supportedTypes();
408                                         foreach($rp as $p){
409                                                 $photos[$p['scale']] = $a->get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
410                                         }
411                                         unset($rp, $ext);
412
413                                         $atom .= replace_macros($sugg_template, array(
414                                                                 '$name' => xmlify($owner['name']),
415                                                                 '$photo' => xmlify($photos[4]),
416                                                                 '$thumb' => xmlify($photos[5]),
417                                                                 '$micro' => xmlify($photos[6]),
418                                                                 '$url' => xmlify($owner['url']),
419                                                                 '$request' => xmlify($owner['request']),
420                                                                 '$confirm' => xmlify($owner['confirm']),
421                                                                 '$notify' => xmlify($owner['notify']),
422                                                                 '$poll' => xmlify($owner['poll']),
423                                                                 '$sitepubkey' => xmlify(get_config('system','site_pubkey')),
424                                                                 //'$pubkey' => xmlify($owner['pubkey']),
425                                                                 //'$prvkey' => xmlify($owner['prvkey']),
426                                                 ));
427                                         unset($photos);
428                                 } elseif($followup) {
429                                         foreach($items as $item) {  // there is only one item
430                                                 if(! $item['parent'])
431                                                         continue;
432                                                 if($item['id'] == $item_id) {
433                                                         logger('followup: item: ' . print_r($item,true), LOGGER_DATA);
434                                                         $atom .= atom_entry($item,'text',null,$owner,false);
435                                                 }
436                                         }
437                                 } else {
438                                         foreach($items as $item) {
439                                                 if(! $item['parent'])
440                                                         continue;
441
442                                                 // private emails may be in included in public conversations. Filter them.
443                                                 if(($public_message) && $item['private'] == 1)
444                                                         continue;
445
446                                                 $item_contact = get_item_contact($item,$icontacts);
447                                                 if(! $item_contact)
448                                                         continue;
449
450                                                 if($normal_mode) {
451                                                         if($item_id == $item['id'] || $item['id'] == $item['parent'])
452                                                                 $atom .= atom_entry($item,'text',null,$owner,true,(($top_level) ? $contact['id'] : 0));
453                                                 } else
454                                                         $atom .= atom_entry($item,'text',null,$owner,true);
455                                         }
456                                 }
457
458                                 $atom .= '</feed>' . "\r\n";
459 */
460                                 logger('notifier entry: '.$contact["url"].' '.$target_item["guid"].' entry: '.$atom, LOGGER_DEBUG);
461
462                                 logger('notifier: ' . $atom, LOGGER_DATA);
463                                 $basepath =  implode('/', array_slice(explode('/',$contact['url']),0,3));
464
465                                 // perform local delivery if we are on the same site
466
467                                 if(link_compare($basepath,$a->get_baseurl())) {
468
469                                         $nickname = basename($contact['url']);
470                                         if($contact['issued-id'])
471                                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
472                                         else
473                                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
474
475                                         $x = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
476                                                 `contact`.`pubkey` AS `cpubkey`,
477                                                 `contact`.`prvkey` AS `cprvkey`,
478                                                 `contact`.`thumb` AS `thumb`,
479                                                 `contact`.`url` as `url`,
480                                                 `contact`.`name` as `senderName`,
481                                                 `user`.*
482                                                 FROM `contact`
483                                                 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
484                                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
485                                                 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
486                                                 $sql_extra
487                                                 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
488                                                 dbesc(NETWORK_DFRN),
489                                                 dbesc($nickname)
490                                         );
491
492                                         if($x && count($x)) {
493                                                 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
494                                                 if((($owner['page-flags'] == PAGE_COMMUNITY) || ($write_flag)) && (! $x[0]['writable'])) {
495                                                         q("update contact set writable = 1 where id = %d",
496                                                                 intval($x[0]['id'])
497                                                         );
498                                                         $x[0]['writable'] = 1;
499                                                 }
500
501                                                 $ssl_policy = get_config('system','ssl_policy');
502                                                 fix_contact_ssl_policy($x[0],$ssl_policy);
503
504                                                 // If we are setup as a soapbox we aren't accepting top level posts from this person
505
506                                                 if (($x[0]['page-flags'] == PAGE_SOAPBOX) AND $top_level)
507                                                         break;
508
509                                                 logger('mod-delivery: local delivery');
510                                                 local_delivery($x[0],$atom);
511                                                 break;
512                                         }
513                                 }
514
515                                 if(! was_recently_delayed($contact['id']))
516                                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
517                                 else
518                                         $deliver_status = (-1);
519
520                                 logger('notifier: dfrn_delivery to '.$contact["url"].' with guid '.$target_item["guid"].' returns '.$deliver_status);
521
522                                 if($deliver_status == (-1)) {
523                                         logger('notifier: delivery failed: queuing message');
524                                         add_to_queue($contact['id'],NETWORK_DFRN,$atom);
525                                 }
526                                 break;
527
528                         case NETWORK_OSTATUS:
529                                 // Do not send to otatus if we are not configured to send to public networks
530                                 if($owner['prvnets'])
531                                         break;
532                                 if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
533                                         break;
534
535                                 // There is currently no code here to distribute anything to OStatus.
536                                 // This is done in "notifier.php" (See "url_recipients" and "push_notify")
537                                 break;
538
539                         case NETWORK_MAIL:
540                         case NETWORK_MAIL2:
541
542                                 if(get_config('system','dfrn_only'))
543                                         break;
544                                 // WARNING: does not currently convert to RFC2047 header encodings, etc.
545
546                                 $addr = $contact['addr'];
547                                 if(! strlen($addr))
548                                         break;
549
550                                 if($cmd === 'wall-new' || $cmd === 'comment-new') {
551
552                                         $it = null;
553                                         if($cmd === 'wall-new')
554                                                 $it = $items[0];
555                                         else {
556                                                 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
557                                                         intval($argv[2]),
558                                                         intval($uid)
559                                                 );
560                                                 if(count($r))
561                                                         $it = $r[0];
562                                         }
563                                         if(! $it)
564                                                 break;
565
566
567                                         $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
568                                                 intval($uid)
569                                         );
570                                         if(! count($local_user))
571                                                 break;
572
573                                         $reply_to = '';
574                                         $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
575                                                 intval($uid)
576                                         );
577                                         if($r1 && $r1[0]['reply_to'])
578                                                 $reply_to = $r1[0]['reply_to'];
579
580                                         $subject  = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
581
582                                         // only expose our real email address to true friends
583
584                                         if(($contact['rel'] == CONTACT_IS_FRIEND) && (! $contact['blocked'])) {
585                                                 if($reply_to) {
586                                                         $headers  = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$reply_to.'>'."\n";
587                                                         $headers .= 'Sender: '.$local_user[0]['email']."\n";
588                                                 } else
589                                                         $headers  = 'From: '.email_header_encode($local_user[0]['username'],'UTF-8').' <'.$local_user[0]['email'].'>'."\n";
590                                         } else
591                                                 $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
592
593                                         //if($reply_to)
594                                         //      $headers .= 'Reply-to: ' . $reply_to . "\n";
595
596                                         $headers .= 'Message-Id: <' . iri2msgid($it['uri']). '>' . "\n";
597
598                                         //logger("Mail: uri: ".$it['uri']." parent-uri ".$it['parent-uri'], LOGGER_DEBUG);
599                                         //logger("Mail: Data: ".print_r($it, true), LOGGER_DEBUG);
600                                         //logger("Mail: Data: ".print_r($it, true), LOGGER_DATA);
601
602                                         if($it['uri'] !== $it['parent-uri']) {
603                                                 $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
604
605                                                 // If Threading is enabled, write down the correct parent
606                                                 if (($it["thr-parent"] != "") and ($it["thr-parent"] != $it["parent-uri"]))
607                                                         $headers .= " <".iri2msgid($it["thr-parent"]).">";
608                                                 $headers .= "\n";
609
610                                                 if(!$it['title']) {
611                                                         $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
612                                                                 dbesc($it['parent-uri']),
613                                                                 intval($uid));
614
615                                                         if(count($r) AND ($r[0]['title'] != ''))
616                                                                 $subject = $r[0]['title'];
617                                                         else {
618                                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
619                                                                         dbesc($it['parent-uri']),
620                                                                         intval($uid));
621
622                                                                 if(count($r) AND ($r[0]['title'] != ''))
623                                                                         $subject = $r[0]['title'];
624                                                         }
625                                                 }
626                                                 if(strncasecmp($subject,'RE:',3))
627                                                         $subject = 'Re: '.$subject;
628                                         }
629                                         email_send($addr, $subject, $headers, $it);
630                                 }
631                                 break;
632
633                         case NETWORK_DIASPORA:
634                                 if($public_message)
635                                         $loc = 'public batch ' . $contact['batch'];
636                                 else
637                                         $loc = $contact['name'];
638
639                                 logger('delivery: diaspora batch deliver: ' . $loc);
640
641                                 if(get_config('system','dfrn_only') || (!get_config('system','diaspora_enabled')))
642                                         break;
643
644                                 if($mail) {
645                                         diaspora_send_mail($item,$owner,$contact);
646                                         break;
647                                 }
648
649                                 if(!$normal_mode)
650                                         break;
651
652                                 if((! $contact['pubkey']) && (! $public_message))
653                                         break;
654
655                                 $unsupported_activities = array(ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE);
656
657                                 //don't transmit activities which are not supported by diaspora
658                                 foreach($unsupported_activities as $act) {
659                                         if(activity_match($target_item['verb'],$act)) {
660                                                 break 2;
661                                         }
662                                 }
663
664                                 if(($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
665                                         // top-level retraction
666                                         logger('delivery: diaspora retract: ' . $loc);
667
668                                         diaspora_send_retraction($target_item,$owner,$contact,$public_message);
669                                         break;
670                                 } elseif($followup) {
671                                         // send comments and likes to owner to relay
672                                         diaspora_send_followup($target_item,$owner,$contact,$public_message);
673                                         break;
674                                 } elseif($target_item['uri'] !== $target_item['parent-uri']) {
675                                         // we are the relay - send comments, likes and relayable_retractions to our conversants
676                                         logger('delivery: diaspora relay: ' . $loc);
677
678                                         diaspora_send_relay($target_item,$owner,$contact,$public_message);
679                                         break;
680                                 } elseif(($top_level) && (! $walltowall)) {
681                                         // currently no workable solution for sending walltowall
682                                         logger('delivery: diaspora status: ' . $loc);
683                                         diaspora_send_status($target_item,$owner,$contact,$public_message);
684                                         break;
685                                 }
686
687                                 logger('delivery: diaspora unknown mode: ' . $contact['name']);
688
689                                 break;
690
691                         default:
692                                 break;
693                 }
694         }
695
696         return;
697 }
698
699 if (array_search(__file__,get_included_files())===0){
700   delivery_run($_SERVER["argv"],$_SERVER["argc"]);
701   killme();
702 }