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