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