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