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