]> git.mxchange.org Git - friendica.git/blob - include/notifier.php
fix typo
[friendica.git] / include / notifier.php
1 <?php
2
3 require_once("boot.php");
4
5 /*
6  * This file was at one time responsible for doing all deliveries, but this caused
7  * big problems on shared hosting systems, where the process might get killed by the 
8  * hosting provider and nothing would get delivered. 
9  * It now only delivers one message under certain cases, and invokes a queued
10  * delivery mechanism (include/deliver.php) to deliver individual contacts at 
11  * controlled intervals.
12  * This has a much better chance of surviving random processes getting killed
13  * by the hosting provider. 
14  * A lot of this code is duplicated in include/deliver.php until we have time to go back
15  * and re-structure the delivery procedure based on the obstacles that have been thrown at 
16  * us by hosting providers. 
17  */
18
19 function notifier_run($argv, $argc){
20         global $a, $db;
21
22         if(is_null($a)){
23                 $a = new App;
24         }
25   
26         if(is_null($db)) {
27                 @include(".htconfig.php");
28                 require_once("dba.php");
29                 $db = new dba($db_host, $db_user, $db_pass, $db_data);
30                         unset($db_host, $db_user, $db_pass, $db_data);
31         }
32
33         require_once("session.php");
34         require_once("datetime.php");
35         require_once('include/items.php');
36         require_once('include/bbcode.php');
37
38         load_config('config');
39         load_config('system');
40
41         load_hooks();
42
43         if($argc < 3)
44                 return;
45
46         $a->set_baseurl(get_config('system','url'));
47
48         logger('notifier: invoked: ' . print_r($argv,true));
49
50         $cmd = $argv[1];
51
52         switch($cmd) {
53                 case 'mail':
54                 default:
55                         $item_id = intval($argv[2]);
56                         if(! $item_id){
57                                 return;
58                         }
59                         break;
60         }
61
62         $expire = false;
63         $mail = false;
64         $fsuggest = false;
65         $top_level = false;
66         $recipients = array();
67         $url_recipients = array();
68
69         $normal_mode = true;
70
71         if($cmd === 'mail') {
72                 $normal_mode = false;
73                 $mail = true;
74                 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
75                                 intval($item_id)
76                 );
77                 if(! count($message)){
78                         return;
79                 }
80                 $uid = $message[0]['uid'];
81                 $recipients[] = $message[0]['contact-id'];
82                 $item = $message[0];
83
84         }
85         elseif($cmd === 'expire') {
86                 $normal_mode = false;
87                 $expire = true;
88                 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1 
89                         AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
90                         intval($item_id)
91                 );
92                 $uid = $item_id;
93                 $item_id = 0;
94                 if(! count($items))
95                         return;
96         }
97         elseif($cmd === 'suggest') {
98                 $normal_mode = false;
99                 $fsuggest = true;
100
101                 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
102                         intval($item_id)
103                 );
104                 if(! count($suggest))
105                         return;
106                 $uid = $suggest[0]['uid'];
107                 $recipients[] = $suggest[0]['cid'];
108                 $item = $suggest[0];
109         }
110         else {
111
112                 // find ancestors
113                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
114                         intval($item_id)
115                 );
116
117                 if((! count($r)) || (! intval($r[0]['parent']))) {
118                         return;
119                 }
120
121                 $target_item = $r[0];
122                 $parent_id = intval($r[0]['parent']);
123                 $uid = $r[0]['uid'];
124                 $updated = $r[0]['edited'];
125
126                 if(! $parent_id)
127                         return;
128
129                 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer` 
130                         FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d ORDER BY `id` ASC",
131                         intval($parent_id)
132                 );
133
134                 if(! count($items)) {
135                         return;
136                 }
137
138                 // avoid race condition with deleting entries
139
140                 if($items[0]['deleted']) {
141                         foreach($items as $item)
142                                 $item['deleted'] = 1;
143                 }
144
145                 if((count($items) == 1) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
146                         logger('notifier: top level post');
147                         $top_level = true;
148                 }
149
150         }
151
152         $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, 
153                 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, 
154                 `user`.`page-flags`, `user`.`prvnets`
155                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
156                 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
157                 intval($uid)
158         );
159
160         if(! count($r))
161                 return;
162
163         $owner = $r[0];
164
165         $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
166
167         $hub = get_config('system','huburl');
168
169         // If this is a public conversation, notify the feed hub
170         $public_message = true;
171
172         // fill this in with a single salmon slap if applicable
173         $slap = '';
174
175         if(! ($mail || $fsuggest)) {
176
177                 require_once('include/group.php');
178
179                 $parent = $items[0];
180
181                 // This is IMPORTANT!!!!
182
183                 // We will only send a "notify owner to relay" or followup message if the referenced post
184                 // originated on our system by virtue of having our hostname somewhere
185                 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
186                 // if $parent['wall'] == 1 we will already have the parent message in our array
187                 // and we will relay the whole lot.
188  
189                 // expire sends an entire group of expire messages and cannot be forwarded.
190                 // However the conversation owner will be a part of the conversation and will 
191                 // be notified during this run.
192                 // Other DFRN conversation members will be alerted during polled updates.
193
194                 // Diaspora members currently are not notified of expirations, and other networks have
195                 // either limited or no ability to process deletions. We should at least fix Diaspora 
196                 // by stringing togther an array of retractions and sending them onward.
197                  
198         
199                 $localhost = $a->get_hostname();
200                 if(strpos($localhost,':'))
201                         $localhost = substr($localhost,0,strpos($localhost,':'));
202
203                 /**
204                  *
205                  * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes 
206                  * have been known to cause runaway conditions which affected several servers, along with 
207                  * permissions issues. 
208                  *
209                  */
210  
211                 if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
212                         // local followup to remote post
213                         $followup = true;
214                         $public_message = false; // not public
215                         $conversant_str = dbesc($parent['contact-id']);
216                 }
217                 else {
218                         $followup = false;
219
220                         if((strlen($parent['allow_cid'])) 
221                                 || (strlen($parent['allow_gid'])) 
222                                 || (strlen($parent['deny_cid'])) 
223                                 || (strlen($parent['deny_gid']))) {
224                                 $public_message = false; // private recipients, not public
225                         }
226
227                         $allow_people = expand_acl($parent['allow_cid']);
228                         $allow_groups = expand_groups(expand_acl($parent['allow_gid']));
229                         $deny_people  = expand_acl($parent['deny_cid']);
230                         $deny_groups  = expand_groups(expand_acl($parent['deny_gid']));
231
232                         $conversants = array();
233
234                         foreach($items as $item) {
235                                 $recipients[] = $item['contact-id'];
236                                 $conversants[] = $item['contact-id'];
237                                 // pull out additional tagged people to notify (if public message)
238                                 if($public_message && strlen($item['inform'])) {
239                                         $people = explode(',',$item['inform']);
240                                         foreach($people as $person) {
241                                                 if(substr($person,0,4) === 'cid:') {
242                                                         $recipients[] = intval(substr($person,4));
243                                                         $conversants[] = intval(substr($person,4));
244                                                 }
245                                                 else {
246                                                         $url_recipients[] = substr($person,4);
247                                                 }
248                                         }
249                                 }
250                         }
251
252                         logger('notifier: url_recipients' . print_r($url_recipients,true));
253
254                         $conversants = array_unique($conversants);
255
256
257                         $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
258                         $deny = array_unique(array_merge($deny_people,$deny_groups));
259                         $recipients = array_diff($recipients,$deny);
260
261                         $conversant_str = dbesc(implode(', ',$conversants));
262                 }
263
264                 $r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0");
265
266                 if(count($r))
267                         $contacts = $r;
268         }
269
270         $feed_template = get_markup_template('atom_feed.tpl');
271         $mail_template = get_markup_template('atom_mail.tpl');
272
273         $atom = '';
274         $slaps = array();
275
276         $hubxml = feed_hublinks();
277
278         $birthday = feed_birthday($owner['uid'],$owner['timezone']);
279
280         if(strlen($birthday))
281                 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
282
283         $atom .= replace_macros($feed_template, array(
284                         '$version'      => xmlify(FRIENDIKA_VERSION),
285                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
286                         '$feed_title'   => xmlify($owner['name']),
287                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
288                         '$hub'          => $hubxml,
289                         '$salmon'       => '',  // private feed, we don't use salmon here
290                         '$name'         => xmlify($owner['name']),
291                         '$profile_page' => xmlify($owner['url']),
292                         '$photo'        => xmlify($owner['photo']),
293                         '$thumb'        => xmlify($owner['thumb']),
294                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
295                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
296                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
297                         '$birthday'     => $birthday
298         ));
299
300         if($mail) {
301                 $public_message = false;  // mail is  not public
302
303                 $body = fix_private_photos($item['body'],$owner['uid']);
304
305                 $atom .= replace_macros($mail_template, array(
306                         '$name'         => xmlify($owner['name']),
307                         '$profile_page' => xmlify($owner['url']),
308                         '$thumb'        => xmlify($owner['thumb']),
309                         '$item_id'      => xmlify($item['uri']),
310                         '$subject'      => xmlify($item['title']),
311                         '$created'      => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
312                         '$content'      => xmlify($body),
313                         '$parent_id'    => xmlify($item['parent-uri'])
314                 ));
315         }
316         elseif($fsuggest) {
317                 $public_message = false;  // suggestions are not public
318
319                 $sugg_template = get_markup_template('atom_suggest.tpl');
320
321                 $atom .= replace_macros($sugg_template, array(
322                         '$name'         => xmlify($item['name']),
323                         '$url'          => xmlify($item['url']),
324                         '$photo'        => xmlify($item['photo']),
325                         '$request'      => xmlify($item['request']),
326                         '$note'         => xmlify($item['note'])
327                 ));
328
329                 // We don't need this any more
330
331                 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
332                         intval($item['id'])
333                 );
334
335         }
336         else {
337                 if($followup) {
338                         foreach($items as $item) {  // there is only one item
339                                 if(! $item['parent'])
340                                         continue;
341                                 if($item['id'] == $item_id) {
342                                         logger('notifier: followup: item: ' . print_r($item,true), LOGGER_DATA);
343                                         $slap  = atom_entry($item,'html',$owner,$owner,false);
344                                         $atom .= atom_entry($item,'text',$owner,$owner,false);
345                                 }
346                         }
347                 }
348                 else {
349                         foreach($items as $item) {
350
351                                 if(! $item['parent'])
352                                         continue;
353
354                                 // private emails may be in included in public conversations. Filter them.
355
356                                 if(($public_message) && $item['private'])
357                                         continue;
358
359                                 $contact = get_item_contact($item,$contacts);
360                                 if(! $contact)
361                                         continue;
362
363                                 $atom .= atom_entry($item,'text',$contact,$owner,true);
364
365                                 if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire)) 
366                                         $slaps[] = atom_entry($item,'html',$contact,$owner,true);
367                         }
368                 }
369         }
370         $atom .= '</feed>' . "\r\n";
371
372         logger('notifier: ' . $atom, LOGGER_DATA);
373
374         logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
375
376         // If this is a public message and pubmail is set on the parent, include all your email contacts
377
378         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
379
380         if(! $mail_disabled) {
381                 if((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid'])) 
382                         && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid'])) 
383                         && (intval($target_item['pubmail']))) {
384                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
385                                 intval($uid),
386                                 dbesc(NETWORK_MAIL)
387                         );
388                         if(count($r)) {
389                                 foreach($r as $rr)
390                                         $recipients[] = $rr['id'];
391                         }
392                 }
393         }
394
395         if($followup)
396                 $recip_str = $parent['contact-id'];
397         else
398                 $recip_str = implode(', ', $recipients);
399
400         $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ",
401                 dbesc($recip_str)
402         );
403
404
405         require_once('include/salmon.php');
406
407         $interval = ((get_config('system','delivery_interval') === false) ? 2 : intval(get_config('system','delivery_interval')));
408
409         // delivery loop
410
411         if(count($r)) {
412
413                 foreach($r as $contact) {
414                         if((! $mail) && (! $fsuggest) && (! $followup) && (! $contact['self'])) {
415                                 if(($contact['network'] === NETWORK_DIASPORA) && ($public_message))
416                                         continue;
417                                 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
418                                         dbesc($cmd),
419                                         intval($item_id),
420                                         intval($contact['id'])
421                                 );
422                         }
423                 }
424
425                 foreach($r as $contact) {
426                         if($contact['self'])
427                                 continue;
428
429                         // potentially more than one recipient. Start a new process and space them out a bit.
430                         // we will deliver single recipient types of message and email receipients here. 
431
432                         if((! $mail) && (! $fsuggest) && (! $followup)) {
433                                 proc_run('php','include/delivery.php',$cmd,$item_id,$contact['id']);
434                                 if($interval)
435                                         @time_sleep_until(microtime(true) + (float) $interval);
436                                 continue;
437                         }
438
439                         $deliver_status = 0;
440
441                         logger("main delivery by notifier: followup=$followup mail=$mail fsuggest=$fsuggest");
442
443                         switch($contact['network']) {
444                                 case NETWORK_DFRN:
445                                         logger('notifier: dfrndelivery: ' . $contact['name']);
446                                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
447
448                                         logger('notifier: dfrn_delivery returns ' . $deliver_status);
449         
450                                         if($deliver_status == (-1)) {
451                                                 logger('notifier: delivery failed: queuing message');
452                                                 // queue message for redelivery
453                                                 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
454                                                         VALUES ( %d, '%s', '%s', '%s') ",
455                                                         intval($contact['id']),
456                                                         dbesc(datetime_convert()),
457                                                         dbesc(datetime_convert()),
458                                                         dbesc($atom)
459                                                 );
460                                         }
461                                         break;
462                                 case NETWORK_OSTATUS:
463
464                                         // Do not send to otatus if we are not configured to send to public networks
465                                         if($owner['prvnets'])
466                                                 break;
467                                         if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
468                                                 break;
469
470                                         if($followup && $contact['notify']) {
471                                                 logger('notifier: slapdelivery: ' . $contact['name']);
472                                                 $deliver_status = slapper($owner,$contact['notify'],$slap);
473
474                                                 if($deliver_status == (-1)) {
475                                                         // queue message for redelivery
476                                                         q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
477                                                                 VALUES ( %d, '%s', '%s', '%s') ",
478                                                                 intval($contact['id']),
479                                                                 dbesc(datetime_convert()),
480                                                                 dbesc(datetime_convert()),
481                                                                 dbesc($slap)
482                                                         );
483
484                                                 }
485                                         }
486                                         else {
487
488                                                 // only send salmon if public - e.g. if it's ok to notify
489                                                 // a public hub, it's ok to send a salmon
490
491                                                 if((count($slaps)) && ($public_message) && (! $expire)) {
492                                                         logger('notifier: slapdelivery: ' . $contact['name']);
493                                                         foreach($slaps as $slappy) {
494                                                                 if($contact['notify']) {
495                                                                         $deliver_status = slapper($owner,$contact['notify'],$slappy);
496                                                                         if($deliver_status == (-1)) {
497                                                                                 // queue message for redelivery
498                                                                                 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
499                                                                                         VALUES ( %d, '%s', '%s', '%s') ",
500                                                                                         intval($contact['id']),
501                                                                                         dbesc(datetime_convert()),
502                                                                                         dbesc(datetime_convert()),
503                                                                                         dbesc($slappy)
504                                                                                 );                                                              
505                                                                         }
506                                                                 }
507                                                         }
508                                                 }
509                                         }
510                                         break;
511
512                                 case NETWORK_MAIL:
513                                                 
514                                         if(get_config('system','dfrn_only'))
515                                                 break;
516
517                                         // WARNING: does not currently convert to RFC2047 header encodings, etc.
518
519                                         $addr = $contact['addr'];
520                                         if(! strlen($addr))
521                                                 break;
522
523                                         if($cmd === 'wall-new' || $cmd === 'comment-new') {
524
525                                                 $it = null;
526                                                 if($cmd === 'wall-new') 
527                                                         $it = $items[0];
528                                                 else {
529                                                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", 
530                                                                 intval($argv[2]),
531                                                                 intval($uid)
532                                                         );
533                                                         if(count($r))
534                                                                 $it = $r[0];
535                                                 }
536                                                 if(! $it)
537                                                         break;
538                                                 
539
540
541                                                 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
542                                                         intval($uid)
543                                                 );
544                                                 if(! count($local_user))
545                                                         break;
546                                                 
547                                                 $reply_to = '';
548                                                 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
549                                                         intval($uid)
550                                                 );
551                                                 if($r1 && $r1[0]['reply_to'])
552                                                         $reply_to = $r1[0]['reply_to'];
553         
554                                                 $subject  = (($it['title']) ? $it['title'] : t("\x28no subject\x29")) ;
555                                                 $headers  = 'From: ' . $local_user[0]['username'] . ' <' . $local_user[0]['email'] . '>' . "\n";
556
557                                                 if($reply_to)
558                                                         $headers .= 'Reply-to: ' . $reply_to . "\n";
559
560                                                 $headers .= 'Message-id: <' . $it['uri'] . '>' . "\n";
561
562                                                 if($it['uri'] !== $it['parent-uri']) {
563                                                         $header .= 'References: <' . $it['parent-uri'] . '>' . "\n";
564                                                         if(! strlen($it['title'])) {
565                                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
566                                                                         dbesc($it['parent-uri'])
567                                                                 );
568                                                                 if(count($r)) {
569                                                                         $subtitle = $r[0]['title'];
570                                                                         if($subtitle) {
571                                                                                 if(strncasecmp($subtitle,'RE:',3))
572                                                                                         $subject = $subtitle;
573                                                                                 else
574                                                                                         $subject = 'Re: ' . $subtitle;
575                                                                         }
576                                                                 }
577                                                         }
578                                                 }
579
580                                                 $headers .= 'MIME-Version: 1.0' . "\n";
581                                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
582                                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
583                                                 $html    = prepare_body($it);
584                                                 $message = '<html><body>' . $html . '</body></html>';
585                                                 logger('notifier: email delivery to ' . $addr);
586                                                 mail($addr, $subject, $message, $headers);
587                                         }
588                                         break;
589                                 case NETWORK_DIASPORA:
590                                         require_once('include/diaspora.php');
591
592                                         if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')) || (! $normal_mode))
593                                                 break;
594
595                                         // special handling for followup to public post
596                                         // all other public posts processed as public batches further below
597
598                                         if($public_message) {
599                                                 if($followup)
600                                                         diaspora_send_followup($target_item,$owner,$contact, true);
601                                                 break;
602                                         }
603
604                                         if(! $contact['pubkey'])
605                                                 break;
606                                         
607                                         if($target_item['verb'] === ACTIVITY_DISLIKE) {
608                                                 // unsupported
609                                                 break;
610                                         }
611                                         elseif(($target_item['deleted']) && ($target_item['verb'] !== ACTIVITY_LIKE)) {
612                                                 // diaspora delete, 
613                                                 diaspora_send_retraction($target_item,$owner,$contact);
614                                                 break;
615                                         }
616                                         elseif($followup) {
617                                                 // send comments, likes and retractions of likes to owner to relay
618                                                 diaspora_send_followup($target_item,$owner,$contact);
619                                                 break;
620                                         }
621                                         elseif($target_item['parent'] != $target_item['id']) {
622                                                 // we are the relay - send comments, likes and unlikes to our conversants
623                                                 diaspora_send_relay($target_item,$owner,$contact);
624                                                 break;
625                                         }               
626                                         elseif(($top_level) && (! $walltowall)) {
627                                                 // currently no workable solution for sending walltowall
628                                                 diaspora_send_status($target_item,$owner,$contact);
629                                                 break;
630                                         }
631
632                                         break;
633
634                                 case NETWORK_FEED:
635                                 case NETWORK_FACEBOOK:
636                                         if(get_config('system','dfrn_only'))
637                                                 break;
638                                 default:
639                                         break;
640                         }
641                 }
642         }
643                 
644         // send additional slaps to mentioned remote tags (@foo@example.com)
645
646         if($slap && count($url_recipients) && ($followup || $top_level) && $public_message && (! $expire)) {
647                 if(! get_config('system','dfrn_only')) {
648                         foreach($url_recipients as $url) {
649                                 if($url) {
650                                         logger('notifier: urldelivery: ' . $url);
651                                         $deliver_status = slapper($owner,$url,$slap);
652                                         // TODO: redeliver/queue these items on failure, though there is no contact record
653                                 }
654                         }
655                 }
656         }
657
658
659         if($public_message) {
660
661                 $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s' 
662                         AND `uid` = %d AND `rel` != %d ORDER BY rand() ",
663                         dbesc(NETWORK_DIASPORA),
664                         intval($owner['uid']),
665                         intval(CONTACT_IS_SHARING)
666                 );
667                         
668                 $r2 = q("SELECT `id`, `name`,`network` FROM `contact` 
669                         WHERE `network` = '%s' AND `uid` = %d AND `blocked` = 0 AND `pending` = 0
670                         AND `rel` != %d order by rand() ",
671                         dbesc(NETWORK_DFRN),
672                         intval($owner['uid']),
673                         intval(CONTACT_IS_SHARING)
674                 );
675
676                 $r = array_merge($r2,$r1);
677
678                 if(count($r)) {
679                         logger('pubdeliver: ' . print_r($r,true), LOGGER_DEBUG);
680
681                         // throw everything into the queue in case we get killed
682
683                         foreach($r as $rr) {
684                                 if((! $mail) && (! $fsuggest) && (! $followup)) {
685                                         q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
686                                                 dbesc($cmd),
687                                                 intval($item_id),
688                                                 intval($rr['id'])
689                                         );
690                                 }
691                         }
692
693                         foreach($r as $rr) {
694
695                                 // except for Diaspora batch jobs
696                                 // Don't deliver to folks who have already been delivered to
697
698                                 if(($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
699                                         logger('notifier: already delivered id=' . $rr['id']);
700                                         continue;
701                                 }
702
703                                 if((! $mail) && (! $fsuggest) && (! $followup)) {
704                                         logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']); 
705                                         proc_run('php','include/delivery.php',$cmd,$item_id,$rr['id']);
706                                         if($interval)
707                                                 @time_sleep_until(microtime(true) + (float) $interval);
708                                 }
709                         }
710                 }
711
712
713                 if(strlen($hub)) {
714                         $hubs = explode(',', $hub);
715                         if(count($hubs)) {
716                                 foreach($hubs as $h) {
717                                         $h = trim($h);
718                                         if(! strlen($h))
719                                                 continue;
720                                         $params = 'hub.mode=publish&hub.url=' . urlencode($a->get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
721                                         post_url($h,$params);
722                                         logger('pubsub: publish: ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
723                                         if(count($hubs) > 1)
724                                                 sleep(7);                               // try and avoid multiple hubs responding at precisely the same time
725                                 }
726                         }
727                 }
728
729         }
730
731         return;
732 }
733
734 if (array_search(__file__,get_included_files())===0){
735   notifier_run($argv,$argc);
736   killme();
737 }