]> git.mxchange.org Git - friendica.git/blob - include/notifier.php
PuSH: Publishing moved to a new process. OStatus comments are now published to all...
[friendica.git] / include / notifier.php
1 <?php
2 require_once("boot.php");
3 require_once('include/queue_fn.php');
4 require_once('include/html2plain.php');
5
6 /*
7  * This file was at one time responsible for doing all deliveries, but this caused
8  * big problems on shared hosting systems, where the process might get killed by the
9  * hosting provider and nothing would get delivered.
10  * It now only delivers one message under certain cases, and invokes a queued
11  * delivery mechanism (include/deliver.php) to deliver individual contacts at
12  * controlled intervals.
13  * This has a much better chance of surviving random processes getting killed
14  * by the hosting provider.
15  * A lot of this code is duplicated in include/deliver.php until we have time to go back
16  * and re-structure the delivery procedure based on the obstacles that have been thrown at
17  * us by hosting providers.
18  */
19
20 /*
21  * The notifier is typically called with:
22  *
23  *              proc_run('php', "include/notifier.php", COMMAND, ITEM_ID);
24  *
25  * where COMMAND is one of the following:
26  *
27  *              activity                                (in diaspora.php, dfrn_confirm.php, profiles.php)
28  *              comment-import                  (in diaspora.php, items.php)
29  *              comment-new                             (in item.php)
30  *              drop                                    (in diaspora.php, items.php, photos.php)
31  *              edit_post                               (in item.php)
32  *              event                                   (in events.php)
33  *              expire                                  (in items.php)
34  *              like                                    (in like.php, poke.php)
35  *              mail                                    (in message.php)
36  *              suggest                                 (in fsuggest.php)
37  *              tag                                             (in photos.php, poke.php, tagger.php)
38  *              tgroup                                  (in items.php)
39  *              wall-new                                (in photos.php, item.php)
40  *              removeme                                (in Contact.php)
41  *              relocate                                (in uimport.php)
42  *
43  * and ITEM_ID is the id of the item in the database that needs to be sent to others.
44  */
45
46
47 function notifier_run(&$argv, &$argc){
48         global $a, $db;
49
50         if(is_null($a)){
51                 $a = new App;
52         }
53
54         if(is_null($db)) {
55                 @include(".htconfig.php");
56                 require_once("include/dba.php");
57                 $db = new dba($db_host, $db_user, $db_pass, $db_data);
58                         unset($db_host, $db_user, $db_pass, $db_data);
59         }
60
61         require_once("include/session.php");
62         require_once("include/datetime.php");
63         require_once('include/items.php');
64         require_once('include/bbcode.php');
65         require_once('include/email.php');
66         load_config('config');
67         load_config('system');
68
69         load_hooks();
70
71         if($argc < 3)
72                 return;
73
74         $a->set_baseurl(get_config('system','url'));
75
76         logger('notifier: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
77
78         $cmd = $argv[1];
79
80         switch($cmd) {
81                 case 'mail':
82                 default:
83                         $item_id = intval($argv[2]);
84                         if(! $item_id){
85                                 return;
86                         }
87                         break;
88         }
89
90         $expire = false;
91         $mail = false;
92         $fsuggest = false;
93         $relocate = false;
94         $top_level = false;
95         $recipients = array();
96         $url_recipients = array();
97
98         $normal_mode = true;
99
100         if($cmd === 'mail') {
101                 $normal_mode = false;
102                 $mail = true;
103                 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
104                                 intval($item_id)
105                 );
106                 if(! count($message)){
107                         return;
108                 }
109                 $uid = $message[0]['uid'];
110                 $recipients[] = $message[0]['contact-id'];
111                 $item = $message[0];
112
113         }
114         elseif($cmd === 'expire') {
115                 $normal_mode = false;
116                 $expire = true;
117                 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
118                         AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
119                         intval($item_id)
120                 );
121                 $uid = $item_id;
122                 $item_id = 0;
123                 if(! count($items))
124                         return;
125         }
126         elseif($cmd === 'suggest') {
127                 $normal_mode = false;
128                 $fsuggest = true;
129
130                 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
131                         intval($item_id)
132                 );
133                 if(! count($suggest))
134                         return;
135                 $uid = $suggest[0]['uid'];
136                 $recipients[] = $suggest[0]['cid'];
137                 $item = $suggest[0];
138         } elseif($cmd === 'removeme') {
139                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($item_id));
140                 if (! $r)
141                         return;
142
143                 $user = $r[0];
144                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1", intval($item_id));
145                 if (! $r)
146                         return;
147
148                 $self = $r[0];
149                 $r = q("SELECT * FROM `contact` WHERE `self` = 0 AND `uid` = %d", intval($item_id));
150                 if(! $r)
151                         return;
152
153                 require_once('include/Contact.php');
154                 foreach($r as $contact) {
155                         terminate_friendship($user, $self, $contact);
156                 }
157                 return;
158         } elseif($cmd === 'relocate') {
159                 $normal_mode = false;
160                 $relocate = true;
161                 $uid = $item_id;
162         } else {
163                 // find ancestors
164                 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
165                         intval($item_id)
166                 );
167
168                 if((! count($r)) || (! intval($r[0]['parent']))) {
169                         return;
170                 }
171
172                 $target_item = $r[0];
173                 $parent_id = intval($r[0]['parent']);
174                 $uid = $r[0]['uid'];
175                 $updated = $r[0]['edited'];
176
177                 // POSSIBLE CLEANUP --> The following seems superfluous. We've already checked for "if (! intval($r[0]['parent']))" a few lines up
178                 if(! $parent_id)
179                         return;
180
181                 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
182                         FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
183                         intval($parent_id)
184                 );
185
186                 if(! count($items)) {
187                         return;
188                 }
189
190                 // avoid race condition with deleting entries
191
192                 if($items[0]['deleted']) {
193                         foreach($items as $item)
194                                 $item['deleted'] = 1;
195                 }
196
197                 if((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
198                         logger('notifier: top level post');
199                         $top_level = true;
200                 }
201
202         }
203
204         $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
205                 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
206                 `user`.`page-flags`, `user`.`prvnets`
207                 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
208                 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
209                 intval($uid)
210         );
211
212         if(! count($r))
213                 return;
214
215         $owner = $r[0];
216
217         $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
218
219         $hub = get_config('system','huburl');
220
221         // If this is a public conversation, notify the feed hub
222         $public_message = true;
223
224         // Do a PuSH
225         $push_notify = false;
226
227         // fill this in with a single salmon slap if applicable
228         $slap = '';
229
230         // List of OStatus receiptians of follow up messages
231         $ostatus_recip_str = "";
232
233         if(! ($mail || $fsuggest || $relocate)) {
234
235                 require_once('include/group.php');
236
237                 $parent = $items[0];
238
239                 // This is IMPORTANT!!!!
240
241                 // We will only send a "notify owner to relay" or followup message if the referenced post
242                 // originated on our system by virtue of having our hostname somewhere
243                 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
244
245                 // if $parent['wall'] == 1 we will already have the parent message in our array
246                 // and we will relay the whole lot.
247
248                 // expire sends an entire group of expire messages and cannot be forwarded.
249                 // However the conversation owner will be a part of the conversation and will
250                 // be notified during this run.
251                 // Other DFRN conversation members will be alerted during polled updates.
252
253
254
255                 // Diaspora members currently are not notified of expirations, and other networks have
256                 // either limited or no ability to process deletions. We should at least fix Diaspora
257                 // by stringing togther an array of retractions and sending them onward.
258
259
260                 $localhost = str_replace('www.','',$a->get_hostname());
261                 if(strpos($localhost,':'))
262                         $localhost = substr($localhost,0,strpos($localhost,':'));
263
264                 /**
265                  *
266                  * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
267                  * have been known to cause runaway conditions which affected several servers, along with
268                  * permissions issues.
269                  *
270                  */
271
272                 $relay_to_owner = false;
273
274                 if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
275                         $relay_to_owner = true;
276                 }
277
278
279                 if(($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && (! $top_level)) {
280                         $relay_to_owner = true;
281                 }
282
283                 // until the 'origin' flag has been in use for several months
284                 // we will just use it as a fallback test
285                 // later we will be able to use it as the primary test of whether or not to relay.
286
287                 if(! $target_item['origin'])
288                         $relay_to_owner = false;
289
290                 if($parent['origin'])
291                         $relay_to_owner = false;
292
293                 if($relay_to_owner) {
294                         logger('notifier: followup', LOGGER_DEBUG);
295                         // local followup to remote post
296                         $followup = true;
297                         $public_message = false; // not public
298                         $conversant_str = dbesc($parent['contact-id']);
299                         $recipients = array($parent['contact-id']);
300
301                         if ($parent['network'] == NETWORK_OSTATUS) {
302                                 logger('Parent is OStatus', LOGGER_DEBUG);
303
304                                 $push_notify = true;
305
306 /*                              $ostatus_recipients = array();
307
308                                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'", intval($uid), dbesc(NETWORK_OSTATUS));
309                                 if(count($r)) {
310                                         foreach($r as $rr)
311                                                 $ostatus_recipients[] = $rr['id'];
312
313                                         $ostatus_recip_str = ", ".implode(', ', $ostatus_recipients);
314                                 }
315 */
316                                 // Check if the recipient isn't in your contact list
317                                 $r = q("SELECT `url` FROM `contact` WHERE `id` = %d", $parent['contact-id']);
318                                 if (count($r)) {
319                                         $url_recipients = array();
320
321                                         $thrparent = q("SELECT `author-link` FROM `item` WHERE `uri` = '%s'", dbesc($target_item["thr-parent"]));
322                                         if (count($thrparent) AND (normalise_link($r[0]["url"]) != normalise_link($thrparent[0]["author-link"]))) {
323                                                 require_once("include/Scrape.php");
324                                                 $probed_contact = probe_url($thrparent[0]["author-link"]);
325                                                 if ($probed_contact["notify"] != "") {
326                                                         logger('scrape data for slapper: '.print_r($probed_contact, true));
327                                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
328                                                 }
329                                         }
330                                 }
331                                 logger("url_recipients".print_r($url_recipients,true));
332                         }
333                 } else {
334                         $followup = false;
335
336                         // don't send deletions onward for other people's stuff
337
338                         if($target_item['deleted'] && (! intval($target_item['wall']))) {
339                                 logger('notifier: ignoring delete notification for non-wall item');
340                                 return;
341                         }
342
343                         if((strlen($parent['allow_cid']))
344                                 || (strlen($parent['allow_gid']))
345                                 || (strlen($parent['deny_cid']))
346                                 || (strlen($parent['deny_gid']))) {
347                                 $public_message = false; // private recipients, not public
348                         }
349
350                         $allow_people = expand_acl($parent['allow_cid']);
351                         $allow_groups = expand_groups(expand_acl($parent['allow_gid']),true);
352                         $deny_people  = expand_acl($parent['deny_cid']);
353                         $deny_groups  = expand_groups(expand_acl($parent['deny_gid']));
354
355                         // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
356                         // a delivery fork. private groups (forum_mode == 2) do not uplink
357
358                         if((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
359                                 proc_run('php','include/notifier.php','uplink',$item_id);
360                         }
361
362                         $conversants = array();
363
364                         foreach($items as $item) {
365                                 $recipients[] = $item['contact-id'];
366                                 $conversants[] = $item['contact-id'];
367                                 // pull out additional tagged people to notify (if public message)
368                                 if($public_message && strlen($item['inform'])) {
369                                         $people = explode(',',$item['inform']);
370                                         foreach($people as $person) {
371                                                 if(substr($person,0,4) === 'cid:') {
372                                                         $recipients[] = intval(substr($person,4));
373                                                         $conversants[] = intval(substr($person,4));
374                                                 }
375                                                 else {
376                                                         $url_recipients[] = substr($person,4);
377                                                 }
378                                         }
379                                 }
380                         }
381
382                         logger('notifier: url_recipients' . print_r($url_recipients,true));
383
384                         $conversants = array_unique($conversants);
385
386
387                         $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
388                         $deny = array_unique(array_merge($deny_people,$deny_groups));
389                         $recipients = array_diff($recipients,$deny);
390
391                         $conversant_str = dbesc(implode(', ',$conversants));
392                 }
393
394                 $r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
395
396                 if(count($r))
397                         $contacts = $r;
398         }
399
400         $feed_template = get_markup_template('atom_feed.tpl');
401         $mail_template = get_markup_template('atom_mail.tpl');
402
403         $atom = '';
404         $slaps = array();
405
406         $hubxml = feed_hublinks();
407
408         $birthday = feed_birthday($owner['uid'],$owner['timezone']);
409
410         if(strlen($birthday))
411                 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
412
413         $atom .= replace_macros($feed_template, array(
414                         '$version'      => xmlify(FRIENDICA_VERSION),
415                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
416                         '$feed_title'   => xmlify($owner['name']),
417                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
418                         '$hub'          => $hubxml,
419                         '$salmon'       => '',  // private feed, we don't use salmon here
420                         '$name'         => xmlify($owner['name']),
421                         '$profile_page' => xmlify($owner['url']),
422                         '$photo'        => xmlify($owner['photo']),
423                         '$thumb'        => xmlify($owner['thumb']),
424                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
425                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
426                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
427                         '$birthday'     => $birthday,
428                         '$community'    => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
429
430         ));
431
432         if($mail) {
433                 $public_message = false;  // mail is  not public
434
435                 $body = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
436
437                 $atom .= replace_macros($mail_template, array(
438                         '$name'         => xmlify($owner['name']),
439                         '$profile_page' => xmlify($owner['url']),
440                         '$thumb'        => xmlify($owner['thumb']),
441                         '$item_id'      => xmlify($item['uri']),
442                         '$subject'      => xmlify($item['title']),
443                         '$created'      => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
444                         '$content'      => xmlify($body),
445                         '$parent_id'    => xmlify($item['parent-uri'])
446                 ));
447         } elseif($fsuggest) {
448                 $public_message = false;  // suggestions are not public
449
450                 $sugg_template = get_markup_template('atom_suggest.tpl');
451
452                 $atom .= replace_macros($sugg_template, array(
453                         '$name'         => xmlify($item['name']),
454                         '$url'          => xmlify($item['url']),
455                         '$photo'        => xmlify($item['photo']),
456                         '$request'      => xmlify($item['request']),
457                         '$note'         => xmlify($item['note'])
458                 ));
459
460                 // We don't need this any more
461
462                 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
463                         intval($item['id'])
464                 );
465
466         } elseif($relocate) {
467                 $public_message = false;  // suggestions are not public
468
469                 $sugg_template = get_markup_template('atom_relocate.tpl');
470
471                 /* get site pubkey. this could be a new installation with no site keys*/
472                 $pubkey = get_config('system','site_pubkey');
473                 if(! $pubkey) {
474                         $res = new_keypair(1024);
475                         set_config('system','site_prvkey', $res['prvkey']);
476                         set_config('system','site_pubkey', $res['pubkey']);
477                 }
478
479                 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo` 
480                                                 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
481                 $photos = array();
482                 $ext = Photo::supportedTypes();
483                 foreach($rp as $p){
484                         $photos[$p['scale']] = $a->get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
485                 }
486                 unset($rp, $ext);
487
488                 $atom .= replace_macros($sugg_template, array(
489                                         '$name' => xmlify($owner['name']),
490                                         '$photo' => xmlify($photos[4]),
491                                         '$thumb' => xmlify($photos[5]),
492                                         '$micro' => xmlify($photos[6]),
493                                         '$url' => xmlify($owner['url']),
494                                         '$request' => xmlify($owner['request']),
495                                         '$confirm' => xmlify($owner['confirm']),
496                                         '$notify' => xmlify($owner['notify']),
497                                         '$poll' => xmlify($owner['poll']),
498                                         '$sitepubkey' => xmlify(get_config('system','site_pubkey')),
499                                         //'$pubkey' => xmlify($owner['pubkey']),
500                                         //'$prvkey' => xmlify($owner['prvkey']),
501                         ));
502                 $recipients_relocate = q("SELECT * FROM contact WHERE uid = %d  AND self = 0 AND network = '%s'" , intval($uid), NETWORK_DFRN);
503                 unset($photos);
504         } else {
505                 if($followup) {
506                         foreach($items as $item) {  // there is only one item
507                                 if(! $item['parent'])
508                                         continue;
509                                 if($item['id'] == $item_id) {
510                                         logger('notifier: followup: item: ' . print_r($item,true), LOGGER_DATA);
511                                         $slap  = atom_entry($item,'html',null,$owner,false);
512                                         $atom .= atom_entry($item,'text',null,$owner,false);
513                                 }
514                         }
515                 } else {
516                         foreach($items as $item) {
517
518                                 if(! $item['parent'])
519                                         continue;
520
521                                 // private emails may be in included in public conversations. Filter them.
522
523                                 if(($public_message) && $item['private'] == 1)
524                                         continue;
525
526
527                                 $contact = get_item_contact($item,$contacts);
528
529                                 if(! $contact)
530                                         continue;
531
532                                 if($normal_mode) {
533
534                                         // we only need the current item, but include the parent because without it
535                                         // older sites without a corresponding dfrn_notify change may do the wrong thing.
536
537                                     if($item_id == $item['id'] || $item['id'] == $item['parent'])
538                                                 $atom .= atom_entry($item,'text',null,$owner,true);
539                                 } else
540                                         $atom .= atom_entry($item,'text',null,$owner,true);
541
542                                 if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire))
543                                         $slaps[] = atom_entry($item,'html',null,$owner,true);
544                         }
545                 }
546         }
547         $atom .= '</feed>' . "\r\n";
548
549         logger('notifier: ' . $atom, LOGGER_DATA);
550
551         logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
552
553         // If this is a public message and pubmail is set on the parent, include all your email contacts
554
555         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
556
557         if(! $mail_disabled) {
558                 if((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
559                         && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
560                         && (intval($target_item['pubmail']))) {
561                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
562                                 intval($uid),
563                                 dbesc(NETWORK_MAIL)
564                         );
565                         if(count($r)) {
566                                 foreach($r as $rr)
567                                         $recipients[] = $rr['id'];
568                         }
569                 }
570         }
571
572         if($followup)
573                 $recip_str = $parent['contact-id'].$ostatus_recip_str;
574         else
575                 $recip_str = implode(', ', $recipients);
576
577         if ($relocate)
578                 $r = $recipients_relocate;
579         else
580                 $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ",
581                         dbesc($recip_str)
582                 );
583
584
585         require_once('include/salmon.php');
586
587         $interval = ((get_config('system','delivery_interval') === false) ? 2 : intval(get_config('system','delivery_interval')));
588
589         // delivery loop
590
591         if(count($r)) {
592
593                 foreach($r as $contact) {
594                         if((! $mail) && (! $fsuggest) && (!$followup OR ($parent['contact-id'] != $contact['id'])) && (!$relocate) && (! $contact['self'])) {
595                                 if(($contact['network'] === NETWORK_DIASPORA) && ($public_message))
596                                         continue;
597                                 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
598                                         dbesc($cmd),
599                                         intval($item_id),
600                                         intval($contact['id'])
601                                 );
602                         }
603                 }
604
605
606                 // This controls the number of deliveries to execute with each separate delivery process.
607                 // By default we'll perform one delivery per process. Assuming a hostile shared hosting
608                 // provider, this provides the greatest chance of deliveries if processes start getting 
609                 // killed. We can also space them out with the delivery_interval to also help avoid them
610                 // getting whacked.
611
612                 // If $deliveries_per_process > 1, we will chain this number of multiple deliveries
613                 // together into a single process. This will reduce the overall number of processes
614                 // spawned for each delivery, but they will run longer.
615
616                 $deliveries_per_process = intval(get_config('system','delivery_batch_count'));
617                 if($deliveries_per_process <= 0)
618                         $deliveries_per_process = 1;
619
620                 $this_batch = array();
621
622                 for($x = 0; $x < count($r); $x ++) {
623                         $contact = $r[$x];
624
625                         if($contact['self'])
626                                 continue;
627
628                         logger("Deliver to ".$contact['url'], LOGGER_DEBUG);
629
630                         // potentially more than one recipient. Start a new process and space them out a bit.
631                         // we will deliver single recipient types of message and email recipients here.
632
633                         if((! $mail) && (! $fsuggest) && (!$relocate) && (!$followup OR ($parent['contact-id'] != $contact['id']))) {
634
635                                 $this_batch[] = $contact['id'];
636
637                                 if(count($this_batch) == $deliveries_per_process) {
638                                         proc_run('php','include/delivery.php',$cmd,$item_id,$this_batch);
639                                         $this_batch = array();
640                                         if($interval)
641                                                 @time_sleep_until(microtime(true) + (float) $interval);
642                                 }
643                                 continue;
644                         }
645                         // be sure to pick up any stragglers
646                         if(count($this_batch))
647                                 proc_run('php','include/delivery.php',$cmd,$item_id,$this_batch);
648
649
650                         $deliver_status = 0;
651
652                         logger("main delivery by notifier: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate");
653
654                         switch($contact['network']) {
655                                 case NETWORK_DFRN:
656
657                                         // perform local delivery if we are on the same site
658
659                                         $basepath =  implode('/', array_slice(explode('/',$contact['url']),0,3));
660
661                                         if(link_compare($basepath,$a->get_baseurl())) {
662
663                                                 $nickname = basename($contact['url']);
664                                                 if($contact['issued-id'])
665                                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
666                                                 else
667                                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
668
669                                                 $x = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
670                                                         `contact`.`pubkey` AS `cpubkey`,
671                                                         `contact`.`prvkey` AS `cprvkey`,
672                                                         `contact`.`thumb` AS `thumb`,
673                                                         `contact`.`url` as `url`,
674                                                         `contact`.`name` as `senderName`,
675                                                         `user`.*
676                                                         FROM `contact`
677                                                         INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
678                                                         WHERE `contact`.`blocked` = 0 AND `contact`.`archive` = 0
679                                                         AND `contact`.`pending` = 0
680                                                         AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
681                                                         $sql_extra
682                                                         AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
683                                                         dbesc(NETWORK_DFRN),
684                                                         dbesc($nickname)
685                                                 );
686
687                                                 if($x && count($x)) {
688                                                         $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
689                                                         if((($owner['page-flags'] == PAGE_COMMUNITY) || ($write_flag)) && (! $x[0]['writable'])) {
690                                                                 q("update contact set writable = 1 where id = %d",
691                                                                         intval($x[0]['id'])
692                                                                 );
693                                                                 $x[0]['writable'] = 1;
694                                                         }
695
696                                                         // if contact's ssl policy changed, which we just determined
697                                                         // is on our own server, update our contact links
698
699                                                         $ssl_policy = get_config('system','ssl_policy');
700                                                         fix_contact_ssl_policy($x[0],$ssl_policy);
701
702                                                         // If we are setup as a soapbox we aren't accepting input from this person
703
704                                                         if($x[0]['page-flags'] == PAGE_SOAPBOX)
705                                                                 break;
706
707                                                         require_once('library/simplepie/simplepie.inc');
708                                                         logger('mod-delivery: local delivery');
709                                                         local_delivery($x[0],$atom);
710                                                         break;
711                                                 }
712                                         }
713
714                                         logger('notifier: dfrndelivery: ' . $contact['name']);
715                                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
716
717                                         logger('notifier: dfrn_delivery returns ' . $deliver_status);
718
719                                         if($deliver_status == (-1)) {
720                                                 logger('notifier: delivery failed: queuing message');
721                                                 // queue message for redelivery
722                                                 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
723                                         }
724                                         break;
725                                 case NETWORK_OSTATUS:
726
727                                         // Do not send to ostatus if we are not configured to send to public networks
728                                         if($owner['prvnets'])
729                                                 break;
730
731                                         if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
732                                                 break;
733
734                                         if($followup && $contact['notify']) {
735                                                 logger('slapdelivery followup item '.$item_id.' to ' . $contact['name']);
736                                                 $deliver_status = slapper($owner,$contact['notify'],$slap);
737
738                                                 if($deliver_status == (-1)) {
739                                                         // queue message for redelivery
740                                                         add_to_queue($contact['id'],NETWORK_OSTATUS,$slap);
741                                                 }
742                                         } else {
743
744                                                 // only send salmon if public - e.g. if it's ok to notify
745                                                 // a public hub, it's ok to send a salmon
746
747                                                 if((count($slaps)) && ($public_message) && (! $expire)) {
748                                                         logger('slapdelivery item '.$item_id.' to ' . $contact['name']);
749                                                         foreach($slaps as $slappy) {
750                                                                 if($contact['notify']) {
751                                                                         $deliver_status = slapper($owner,$contact['notify'],$slappy);
752                                                                         if($deliver_status == (-1)) {
753                                                                                 // queue message for redelivery
754                                                                                 add_to_queue($contact['id'],NETWORK_OSTATUS,$slappy);
755                                                                         }
756                                                                 }
757                                                         }
758                                                 }
759                                         }
760                                         break;
761
762                                 case NETWORK_MAIL:
763                                 case NETWORK_MAIL2:
764
765                                         if(get_config('system','dfrn_only'))
766                                                 break;
767
768                                         // WARNING: does not currently convert to RFC2047 header encodings, etc.
769
770                                         $addr = $contact['addr'];
771                                         if(! strlen($addr))
772                                                 break;
773
774                                         if($cmd === 'wall-new' || $cmd === 'comment-new') {
775
776                                                 $it = null;
777                                                 if($cmd === 'wall-new') 
778                                                         $it = $items[0];
779                                                 else {
780                                                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", 
781                                                                 intval($argv[2]),
782                                                                 intval($uid)
783                                                         );
784                                                         if(count($r))
785                                                                 $it = $r[0];
786                                                 }
787                                                 if(! $it)
788                                                         break;
789
790
791
792                                                 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
793                                                         intval($uid)
794                                                 );
795                                                 if(! count($local_user))
796                                                         break;
797
798                                                 $reply_to = '';
799                                                 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
800                                                         intval($uid)
801                                                 );
802                                                 if($r1 && $r1[0]['reply_to'])
803                                                         $reply_to = $r1[0]['reply_to'];
804
805                                                 $subject  = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
806
807                                                 // only expose our real email address to true friends
808                                                 if(($contact['rel'] == CONTACT_IS_FRIEND) && (! $contact['blocked']))
809                                                         if($reply_to) {
810                                                                 $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
811                                                                 $headers .= 'Sender: '.$local_user[0]['email']."\n";
812                                                         } else
813                                                                 $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $local_user[0]['email'] . '>' . "\n";
814                                                 else
815                                                         $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
816
817                                                 //if($reply_to)
818                                                 //      $headers .= 'Reply-to: ' . $reply_to . "\n";
819
820                                                 $headers .= 'Message-Id: <' . iri2msgid($it['uri']) . '>' . "\n";
821
822                                                 if($it['uri'] !== $it['parent-uri']) {
823                                                         $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
824
825                                                         // If Threading is enabled, write down the correct parent
826                                                         if (($it["thr-parent"] != "") and ($it["thr-parent"] != $it["parent-uri"]))
827                                                                 $headers .= " <".iri2msgid($it["thr-parent"]).">";
828                                                         $headers .= "\n";
829
830                                                         if(!$it['title']) {
831                                                                 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
832                                                                         dbesc($it['parent-uri']),
833                                                                         intval($uid));
834
835                                                                 if(count($r) AND ($r[0]['title'] != ''))
836                                                                         $subject = $r[0]['title'];
837                                                                 else {
838                                                                         $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
839                                                                                 dbesc($it['parent-uri']),
840                                                                                 intval($uid));
841
842                                                                         if(count($r) AND ($r[0]['title'] != ''))
843                                                                                 $subject = $r[0]['title'];
844                                                                 }
845                                                         }
846                                                         if(strncasecmp($subject,'RE:',3))
847                                                                 $subject = 'Re: '.$subject;
848                                                 }
849                                                 email_send($addr, $subject, $headers, $it);
850                                         }
851                                         break;
852                                 case NETWORK_DIASPORA:
853                                         require_once('include/diaspora.php');
854
855                                         if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')))
856                                                 break;
857
858                                         if($mail) {
859                                                 diaspora_send_mail($item,$owner,$contact);
860                                                 break;
861                                         }
862
863                                         if(! $normal_mode)
864                                                 break;
865
866                                         // special handling for followup to public post
867                                         // all other public posts processed as public batches further below
868
869                                         if($public_message) {
870                                                 if($followup)
871                                                         diaspora_send_followup($target_item,$owner,$contact, true);
872                                                 break;
873                                         }
874
875                                         if(! $contact['pubkey'])
876                                                 break;
877
878                                         if($target_item['verb'] === ACTIVITY_DISLIKE) {
879                                                 // unsupported
880                                                 break;
881                                         }
882                                         elseif(($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
883                                                 // send both top-level retractions and relayable retractions for owner to relay
884                                                 diaspora_send_retraction($target_item,$owner,$contact);
885                                                 break;
886                                         }
887                                         elseif($followup) {
888                                                 // send comments and likes to owner to relay
889                                                 diaspora_send_followup($target_item,$owner,$contact);
890                                                 break;
891                                         }
892                                         elseif($target_item['uri'] !== $target_item['parent-uri']) {
893                                                 // we are the relay - send comments, likes and relayable_retractions
894                                                 // (of comments and likes) to our conversants
895                                                 diaspora_send_relay($target_item,$owner,$contact);
896                                                 break;
897                                         }
898                                         elseif(($top_level) && (! $walltowall)) {
899                                                 // currently no workable solution for sending walltowall
900                                                 diaspora_send_status($target_item,$owner,$contact);
901                                                 break;
902                                         }
903
904                                         break;
905
906                                 case NETWORK_FEED:
907                                 case NETWORK_FACEBOOK:
908                                         if(get_config('system','dfrn_only'))
909                                                 break;
910                                 case NETWORK_PUMPIO:
911                                         if(get_config('system','dfrn_only'))
912                                                 break;
913                                 default:
914                                         break;
915                         }
916                 }
917         }
918
919         // send additional slaps to mentioned remote tags (@foo@example.com)
920
921         if($slap && count($url_recipients) && ($followup || $top_level) && $public_message && (! $expire)) {
922                 if(! get_config('system','dfrn_only')) {
923                         foreach($url_recipients as $url) {
924                                 if($url) {
925                                         logger('notifier: urldelivery: ' . $url);
926                                         $deliver_status = slapper($owner,$url,$slap);
927                                         // TODO: redeliver/queue these items on failure, though there is no contact record
928                                 }
929                         }
930                 }
931         }
932
933
934         if($public_message) {
935
936                 $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s'
937                         AND `uid` = %d AND `rel` != %d group by `batch` ORDER BY rand() ",
938                         dbesc(NETWORK_DIASPORA),
939                         intval($owner['uid']),
940                         intval(CONTACT_IS_SHARING)
941                 );
942
943                 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
944                         WHERE `network` in ( '%s', '%s')  AND `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0
945                         AND `rel` != %d order by rand() ",
946                         dbesc(NETWORK_DFRN),
947                         dbesc(NETWORK_MAIL2),
948                         intval($owner['uid']),
949                         intval(CONTACT_IS_SHARING)
950                 );
951
952                 $r = array_merge($r2,$r1);
953
954                 if(count($r)) {
955                         logger('pubdeliver: ' . print_r($r,true), LOGGER_DEBUG);
956
957                         // throw everything into the queue in case we get killed
958
959                         foreach($r as $rr) {
960                                 if((! $mail) && (! $fsuggest) && (!$followup OR ($parent['contact-id'] != $contact['id']))) {
961                                         q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
962                                                 dbesc($cmd),
963                                                 intval($item_id),
964                                                 intval($rr['id'])
965                                         );
966                                 }
967                         }
968
969                         foreach($r as $rr) {
970
971                                 // except for Diaspora batch jobs
972                                 // Don't deliver to folks who have already been delivered to
973
974                                 if(($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
975                                         logger('notifier: already delivered id=' . $rr['id']);
976                                         continue;
977                                 }
978
979                                 if((! $mail) && (! $fsuggest) && (! $followup)) {
980                                         logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']);
981                                         proc_run('php','include/delivery.php',$cmd,$item_id,$rr['id']);
982                                         if($interval)
983                                                 @time_sleep_until(microtime(true) + (float) $interval);
984                                 }
985                         }
986                 }
987
988                 $push_notify = true;
989
990         }
991
992
993         if($push_notify AND strlen($hub)) {
994                 $hubs = explode(',', $hub);
995                 if(count($hubs)) {
996                         foreach($hubs as $h) {
997                                 $h = trim($h);
998                                 if(! strlen($h))
999                                         continue;
1000
1001                                 if ($h === '[internal]') {
1002                                         // Set push flag for PuSH subscribers to this topic,
1003                                         // they will be notified in queue.php
1004                                         q("UPDATE `push_subscriber` SET `push` = 1 " .
1005                                           "WHERE `nickname` = '%s'", dbesc($owner['nickname']));
1006
1007                                         logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
1008
1009                                 } else {
1010
1011                                         $params = 'hub.mode=publish&hub.url=' . urlencode( $a->get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
1012                                         post_url($h,$params);
1013                                         logger('publish for item '.$item_id.' ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
1014                                 }
1015                                 if(count($hubs) > 1)
1016                                         sleep(7);                               // try and avoid multiple hubs responding at precisely the same time
1017                         }
1018                 }
1019
1020                 // Handling the pubsubhubbub requests
1021                 proc_run('php','include/pubsubpublish.php');
1022         }
1023
1024         // If the item was deleted, clean up the `sign` table
1025         if($target_item['deleted']) {
1026                 $r = q("DELETE FROM sign where `retract_iid` = %d",
1027                         intval($target_item['id'])
1028                 );
1029         }
1030
1031         logger('notifier: calling hooks', LOGGER_DEBUG);
1032
1033         if($normal_mode)
1034                 call_hooks('notifier_normal',$target_item);
1035
1036         call_hooks('notifier_end',$target_item);
1037
1038         return;
1039 }
1040
1041
1042 if (array_search(__file__,get_included_files())===0){
1043         notifier_run($_SERVER["argv"],$_SERVER["argc"]);
1044         killme();
1045 }