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