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