]> git.mxchange.org Git - friendica.git/blob - include/notifier.php
Send a salmon notification to every mentioned person.
[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                         if ($parent['network'] == NETWORK_OSTATUS) {
305                                 logger('Parent is OStatus', LOGGER_DEBUG);
306
307                                 $push_notify = true;
308
309                                 // Send a salmon notification to every person we mentioned in the post
310                                 $arr = explode(',',$target_item['tag']);
311                                 foreach($arr as $x) {
312                                         logger('Checking tag '.$x, LOGGER_DEBUG);
313                                         $matches = null;
314                                         if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
315                                                 $probed_contact = probe_url($matches[1]);
316                                                 if ($probed_contact["notify"] != "") {
317                                                         logger('scrape data for slapper: '.print_r($probed_contact, true));
318                                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
319                                                 }
320                                         }
321                                 }
322
323 /*
324                                 // Check if the recipient isn't in your contact list, try to slap it
325                                 // Not sure if it is working or not.
326                                 $r = q("SELECT `url` FROM `contact` WHERE `id` = %d", $parent['contact-id']);
327                                 if (count($r)) {
328
329                                         $thrparent = q("SELECT `author-link` FROM `item` WHERE `uri` = '%s'", dbesc($target_item["thr-parent"]));
330                                         if (count($thrparent) AND (normalise_link($r[0]["url"]) != normalise_link($thrparent[0]["author-link"]))) {
331                                                 $probed_contact = probe_url($thrparent[0]["author-link"]);
332                                                 if ($probed_contact["notify"] != "") {
333                                                         logger('scrape data for slapper: '.print_r($probed_contact, true));
334                                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
335                                                 }
336                                         }
337                                 }
338 */
339                                 if (count($url_recipients))
340                                         logger("url_recipients ".print_r($url_recipients,true));
341                         }
342                 } else {
343                         $followup = false;
344
345                         // don't send deletions onward for other people's stuff
346
347                         if($target_item['deleted'] && (! intval($target_item['wall']))) {
348                                 logger('notifier: ignoring delete notification for non-wall item');
349                                 return;
350                         }
351
352                         if((strlen($parent['allow_cid']))
353                                 || (strlen($parent['allow_gid']))
354                                 || (strlen($parent['deny_cid']))
355                                 || (strlen($parent['deny_gid']))) {
356                                 $public_message = false; // private recipients, not public
357                         }
358
359                         $allow_people = expand_acl($parent['allow_cid']);
360                         $allow_groups = expand_groups(expand_acl($parent['allow_gid']),true);
361                         $deny_people  = expand_acl($parent['deny_cid']);
362                         $deny_groups  = expand_groups(expand_acl($parent['deny_gid']));
363
364                         // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
365                         // a delivery fork. private groups (forum_mode == 2) do not uplink
366
367                         if((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
368                                 proc_run('php','include/notifier.php','uplink',$item_id);
369                         }
370
371                         $conversants = array();
372
373                         foreach($items as $item) {
374                                 $recipients[] = $item['contact-id'];
375                                 $conversants[] = $item['contact-id'];
376                                 // pull out additional tagged people to notify (if public message)
377                                 if($public_message && strlen($item['inform'])) {
378                                         $people = explode(',',$item['inform']);
379                                         foreach($people as $person) {
380                                                 if(substr($person,0,4) === 'cid:') {
381                                                         $recipients[] = intval(substr($person,4));
382                                                         $conversants[] = intval(substr($person,4));
383                                                 }
384                                                 else {
385                                                         $url_recipients[] = substr($person,4);
386                                                 }
387                                         }
388                                 }
389                         }
390
391                         if (count($url_recipients))
392                                 logger('notifier: url_recipients ' . print_r($url_recipients,true));
393
394                         $conversants = array_unique($conversants);
395
396
397                         $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
398                         $deny = array_unique(array_merge($deny_people,$deny_groups));
399                         $recipients = array_diff($recipients,$deny);
400
401                         $conversant_str = dbesc(implode(', ',$conversants));
402                 }
403
404                 $r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
405
406                 if(count($r))
407                         $contacts = $r;
408         }
409
410         $feed_template = get_markup_template('atom_feed.tpl');
411         $mail_template = get_markup_template('atom_mail.tpl');
412
413         $atom = '';
414         $slaps = array();
415
416         $hubxml = feed_hublinks();
417
418         $birthday = feed_birthday($owner['uid'],$owner['timezone']);
419
420         if(strlen($birthday))
421                 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
422
423         $atom .= replace_macros($feed_template, array(
424                         '$version'      => xmlify(FRIENDICA_VERSION),
425                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
426                         '$feed_title'   => xmlify($owner['name']),
427                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
428                         '$hub'          => $hubxml,
429                         '$salmon'       => '',  // private feed, we don't use salmon here
430                         '$name'         => xmlify($owner['name']),
431                         '$profile_page' => xmlify($owner['url']),
432                         '$photo'        => xmlify($owner['photo']),
433                         '$thumb'        => xmlify($owner['thumb']),
434                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
435                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
436                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
437                         '$birthday'     => $birthday,
438                         '$community'    => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
439
440         ));
441
442         if($mail) {
443                 $public_message = false;  // mail is  not public
444
445                 $body = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
446
447                 $atom .= replace_macros($mail_template, array(
448                         '$name'         => xmlify($owner['name']),
449                         '$profile_page' => xmlify($owner['url']),
450                         '$thumb'        => xmlify($owner['thumb']),
451                         '$item_id'      => xmlify($item['uri']),
452                         '$subject'      => xmlify($item['title']),
453                         '$created'      => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
454                         '$content'      => xmlify($body),
455                         '$parent_id'    => xmlify($item['parent-uri'])
456                 ));
457         } elseif($fsuggest) {
458                 $public_message = false;  // suggestions are not public
459
460                 $sugg_template = get_markup_template('atom_suggest.tpl');
461
462                 $atom .= replace_macros($sugg_template, array(
463                         '$name'         => xmlify($item['name']),
464                         '$url'          => xmlify($item['url']),
465                         '$photo'        => xmlify($item['photo']),
466                         '$request'      => xmlify($item['request']),
467                         '$note'         => xmlify($item['note'])
468                 ));
469
470                 // We don't need this any more
471
472                 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
473                         intval($item['id'])
474                 );
475
476         } elseif($relocate) {
477                 $public_message = false;  // suggestions are not public
478
479                 $sugg_template = get_markup_template('atom_relocate.tpl');
480
481                 /* get site pubkey. this could be a new installation with no site keys*/
482                 $pubkey = get_config('system','site_pubkey');
483                 if(! $pubkey) {
484                         $res = new_keypair(1024);
485                         set_config('system','site_prvkey', $res['prvkey']);
486                         set_config('system','site_pubkey', $res['pubkey']);
487                 }
488
489                 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo` 
490                                                 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
491                 $photos = array();
492                 $ext = Photo::supportedTypes();
493                 foreach($rp as $p){
494                         $photos[$p['scale']] = $a->get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
495                 }
496                 unset($rp, $ext);
497
498                 $atom .= replace_macros($sugg_template, array(
499                                         '$name' => xmlify($owner['name']),
500                                         '$photo' => xmlify($photos[4]),
501                                         '$thumb' => xmlify($photos[5]),
502                                         '$micro' => xmlify($photos[6]),
503                                         '$url' => xmlify($owner['url']),
504                                         '$request' => xmlify($owner['request']),
505                                         '$confirm' => xmlify($owner['confirm']),
506                                         '$notify' => xmlify($owner['notify']),
507                                         '$poll' => xmlify($owner['poll']),
508                                         '$sitepubkey' => xmlify(get_config('system','site_pubkey')),
509                                         //'$pubkey' => xmlify($owner['pubkey']),
510                                         //'$prvkey' => xmlify($owner['prvkey']),
511                         ));
512                 $recipients_relocate = q("SELECT * FROM contact WHERE uid = %d  AND self = 0 AND network = '%s'" , intval($uid), NETWORK_DFRN);
513                 unset($photos);
514         } else {
515                 if($followup) {
516                         foreach($items as $item) {  // there is only one item
517                                 if(! $item['parent'])
518                                         continue;
519                                 if($item['id'] == $item_id) {
520                                         logger('notifier: followup: item: ' . print_r($item,true), LOGGER_DATA);
521                                         $slap  = atom_entry($item,'html',null,$owner,false);
522                                         $atom .= atom_entry($item,'text',null,$owner,false);
523                                 }
524                         }
525                 } else {
526                         foreach($items as $item) {
527
528                                 if(! $item['parent'])
529                                         continue;
530
531                                 // private emails may be in included in public conversations. Filter them.
532
533                                 if(($public_message) && $item['private'] == 1)
534                                         continue;
535
536
537                                 $contact = get_item_contact($item,$contacts);
538
539                                 if(! $contact)
540                                         continue;
541
542                                 if($normal_mode) {
543
544                                         // we only need the current item, but include the parent because without it
545                                         // older sites without a corresponding dfrn_notify change may do the wrong thing.
546
547                                     if($item_id == $item['id'] || $item['id'] == $item['parent'])
548                                                 $atom .= atom_entry($item,'text',null,$owner,true);
549                                 } else
550                                         $atom .= atom_entry($item,'text',null,$owner,true);
551
552                                 if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire))
553                                         $slaps[] = atom_entry($item,'html',null,$owner,true);
554                         }
555                 }
556         }
557         $atom .= '</feed>' . "\r\n";
558
559         logger('notifier: ' . $atom, LOGGER_DATA);
560
561         logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
562
563         // If this is a public message and pubmail is set on the parent, include all your email contacts
564
565         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
566
567         if(! $mail_disabled) {
568                 if((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
569                         && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
570                         && (intval($target_item['pubmail']))) {
571                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
572                                 intval($uid),
573                                 dbesc(NETWORK_MAIL)
574                         );
575                         if(count($r)) {
576                                 foreach($r as $rr)
577                                         $recipients[] = $rr['id'];
578                         }
579                 }
580         }
581
582         if($followup)
583                 $recip_str = $parent['contact-id'];
584         else
585                 $recip_str = implode(', ', $recipients);
586
587         if ($relocate)
588                 $r = $recipients_relocate;
589         else
590                 $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ",
591                         dbesc($recip_str)
592                 );
593
594
595         require_once('include/salmon.php');
596
597         $interval = ((get_config('system','delivery_interval') === false) ? 2 : intval(get_config('system','delivery_interval')));
598
599         // delivery loop
600
601         if(count($r)) {
602
603                 foreach($r as $contact) {
604                         if((! $mail) && (! $fsuggest) && (! $followup) && (!$relocate) && (! $contact['self'])) {
605                                 if(($contact['network'] === NETWORK_DIASPORA) && ($public_message))
606                                         continue;
607                                 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
608                                         dbesc($cmd),
609                                         intval($item_id),
610                                         intval($contact['id'])
611                                 );
612                         }
613                 }
614
615
616                 // This controls the number of deliveries to execute with each separate delivery process.
617                 // By default we'll perform one delivery per process. Assuming a hostile shared hosting
618                 // provider, this provides the greatest chance of deliveries if processes start getting 
619                 // killed. We can also space them out with the delivery_interval to also help avoid them
620                 // getting whacked.
621
622                 // If $deliveries_per_process > 1, we will chain this number of multiple deliveries
623                 // together into a single process. This will reduce the overall number of processes
624                 // spawned for each delivery, but they will run longer.
625
626                 $deliveries_per_process = intval(get_config('system','delivery_batch_count'));
627                 if($deliveries_per_process <= 0)
628                         $deliveries_per_process = 1;
629
630                 $this_batch = array();
631
632                 for($x = 0; $x < count($r); $x ++) {
633                         $contact = $r[$x];
634
635                         if($contact['self'])
636                                 continue;
637
638                         logger("Deliver to ".$contact['url'], LOGGER_DEBUG);
639
640                         // potentially more than one recipient. Start a new process and space them out a bit.
641                         // we will deliver single recipient types of message and email recipients here.
642
643                         if((! $mail) && (! $fsuggest) && (!$relocate) && (! $followup)) {
644
645                                 $this_batch[] = $contact['id'];
646
647                                 if(count($this_batch) == $deliveries_per_process) {
648                                         proc_run('php','include/delivery.php',$cmd,$item_id,$this_batch);
649                                         $this_batch = array();
650                                         if($interval)
651                                                 @time_sleep_until(microtime(true) + (float) $interval);
652                                 }
653                                 continue;
654                         }
655                         // be sure to pick up any stragglers
656                         if(count($this_batch))
657                                 proc_run('php','include/delivery.php',$cmd,$item_id,$this_batch);
658
659
660                         $deliver_status = 0;
661
662                         logger("main delivery by notifier: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate");
663
664                         switch($contact['network']) {
665                                 case NETWORK_DFRN:
666
667                                         // perform local delivery if we are on the same site
668
669                                         $basepath =  implode('/', array_slice(explode('/',$contact['url']),0,3));
670
671                                         if(link_compare($basepath,$a->get_baseurl())) {
672
673                                                 $nickname = basename($contact['url']);
674                                                 if($contact['issued-id'])
675                                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
676                                                 else
677                                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
678
679                                                 $x = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`,
680                                                         `contact`.`pubkey` AS `cpubkey`,
681                                                         `contact`.`prvkey` AS `cprvkey`,
682                                                         `contact`.`thumb` AS `thumb`,
683                                                         `contact`.`url` as `url`,
684                                                         `contact`.`name` as `senderName`,
685                                                         `user`.*
686                                                         FROM `contact`
687                                                         INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
688                                                         WHERE `contact`.`blocked` = 0 AND `contact`.`archive` = 0
689                                                         AND `contact`.`pending` = 0
690                                                         AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
691                                                         $sql_extra
692                                                         AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
693                                                         dbesc(NETWORK_DFRN),
694                                                         dbesc($nickname)
695                                                 );
696
697                                                 if($x && count($x)) {
698                                                         $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
699                                                         if((($owner['page-flags'] == PAGE_COMMUNITY) || ($write_flag)) && (! $x[0]['writable'])) {
700                                                                 q("update contact set writable = 1 where id = %d",
701                                                                         intval($x[0]['id'])
702                                                                 );
703                                                                 $x[0]['writable'] = 1;
704                                                         }
705
706                                                         // if contact's ssl policy changed, which we just determined
707                                                         // is on our own server, update our contact links
708
709                                                         $ssl_policy = get_config('system','ssl_policy');
710                                                         fix_contact_ssl_policy($x[0],$ssl_policy);
711
712                                                         // If we are setup as a soapbox we aren't accepting input from this person
713
714                                                         if($x[0]['page-flags'] == PAGE_SOAPBOX)
715                                                                 break;
716
717                                                         require_once('library/simplepie/simplepie.inc');
718                                                         logger('mod-delivery: local delivery');
719                                                         local_delivery($x[0],$atom);
720                                                         break;
721                                                 }
722                                         }
723
724                                         logger('notifier: dfrndelivery: ' . $contact['name']);
725                                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
726
727                                         logger('notifier: dfrn_delivery returns ' . $deliver_status);
728
729                                         if($deliver_status == (-1)) {
730                                                 logger('notifier: delivery failed: queuing message');
731                                                 // queue message for redelivery
732                                                 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
733                                         }
734                                         break;
735                                 case NETWORK_OSTATUS:
736
737                                         // Do not send to ostatus if we are not configured to send to public networks
738                                         if($owner['prvnets'])
739                                                 break;
740
741                                         if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
742                                                 break;
743
744                                         if($followup && $contact['notify']) {
745                                                 logger('slapdelivery followup item '.$item_id.' to ' . $contact['name']);
746                                                 $deliver_status = slapper($owner,$contact['notify'],$slap);
747
748                                                 if($deliver_status == (-1)) {
749                                                         // queue message for redelivery
750                                                         add_to_queue($contact['id'],NETWORK_OSTATUS,$slap);
751                                                 }
752                                         } else {
753
754                                                 // only send salmon if public - e.g. if it's ok to notify
755                                                 // a public hub, it's ok to send a salmon
756
757                                                 if((count($slaps)) && ($public_message) && (! $expire)) {
758                                                         logger('slapdelivery item '.$item_id.' to ' . $contact['name']);
759                                                         foreach($slaps as $slappy) {
760                                                                 if($contact['notify']) {
761                                                                         $deliver_status = slapper($owner,$contact['notify'],$slappy);
762                                                                         if($deliver_status == (-1)) {
763                                                                                 // queue message for redelivery
764                                                                                 add_to_queue($contact['id'],NETWORK_OSTATUS,$slappy);
765                                                                         }
766                                                                 }
767                                                         }
768                                                 }
769                                         }
770                                         break;
771
772                                 case NETWORK_MAIL:
773                                 case NETWORK_MAIL2:
774
775                                         if(get_config('system','dfrn_only'))
776                                                 break;
777
778                                         // WARNING: does not currently convert to RFC2047 header encodings, etc.
779
780                                         $addr = $contact['addr'];
781                                         if(! strlen($addr))
782                                                 break;
783
784                                         if($cmd === 'wall-new' || $cmd === 'comment-new') {
785
786                                                 $it = null;
787                                                 if($cmd === 'wall-new') 
788                                                         $it = $items[0];
789                                                 else {
790                                                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", 
791                                                                 intval($argv[2]),
792                                                                 intval($uid)
793                                                         );
794                                                         if(count($r))
795                                                                 $it = $r[0];
796                                                 }
797                                                 if(! $it)
798                                                         break;
799
800
801
802                                                 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
803                                                         intval($uid)
804                                                 );
805                                                 if(! count($local_user))
806                                                         break;
807
808                                                 $reply_to = '';
809                                                 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
810                                                         intval($uid)
811                                                 );
812                                                 if($r1 && $r1[0]['reply_to'])
813                                                         $reply_to = $r1[0]['reply_to'];
814
815                                                 $subject  = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
816
817                                                 // only expose our real email address to true friends
818                                                 if(($contact['rel'] == CONTACT_IS_FRIEND) && (! $contact['blocked']))
819                                                         if($reply_to) {
820                                                                 $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
821                                                                 $headers .= 'Sender: '.$local_user[0]['email']."\n";
822                                                         } else
823                                                                 $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $local_user[0]['email'] . '>' . "\n";
824                                                 else
825                                                         $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
826
827                                                 //if($reply_to)
828                                                 //      $headers .= 'Reply-to: ' . $reply_to . "\n";
829
830                                                 $headers .= 'Message-Id: <' . iri2msgid($it['uri']) . '>' . "\n";
831
832                                                 if($it['uri'] !== $it['parent-uri']) {
833                                                         $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
834
835                                                         // If Threading is enabled, write down the correct parent
836                                                         if (($it["thr-parent"] != "") and ($it["thr-parent"] != $it["parent-uri"]))
837                                                                 $headers .= " <".iri2msgid($it["thr-parent"]).">";
838                                                         $headers .= "\n";
839
840                                                         if(!$it['title']) {
841                                                                 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
842                                                                         dbesc($it['parent-uri']),
843                                                                         intval($uid));
844
845                                                                 if(count($r) AND ($r[0]['title'] != ''))
846                                                                         $subject = $r[0]['title'];
847                                                                 else {
848                                                                         $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
849                                                                                 dbesc($it['parent-uri']),
850                                                                                 intval($uid));
851
852                                                                         if(count($r) AND ($r[0]['title'] != ''))
853                                                                                 $subject = $r[0]['title'];
854                                                                 }
855                                                         }
856                                                         if(strncasecmp($subject,'RE:',3))
857                                                                 $subject = 'Re: '.$subject;
858                                                 }
859                                                 email_send($addr, $subject, $headers, $it);
860                                         }
861                                         break;
862                                 case NETWORK_DIASPORA:
863                                         require_once('include/diaspora.php');
864
865                                         if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')))
866                                                 break;
867
868                                         if($mail) {
869                                                 diaspora_send_mail($item,$owner,$contact);
870                                                 break;
871                                         }
872
873                                         if(! $normal_mode)
874                                                 break;
875
876                                         // special handling for followup to public post
877                                         // all other public posts processed as public batches further below
878
879                                         if($public_message) {
880                                                 if($followup)
881                                                         diaspora_send_followup($target_item,$owner,$contact, true);
882                                                 break;
883                                         }
884
885                                         if(! $contact['pubkey'])
886                                                 break;
887
888                                         if($target_item['verb'] === ACTIVITY_DISLIKE) {
889                                                 // unsupported
890                                                 break;
891                                         }
892                                         elseif(($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
893                                                 // send both top-level retractions and relayable retractions for owner to relay
894                                                 diaspora_send_retraction($target_item,$owner,$contact);
895                                                 break;
896                                         }
897                                         elseif($followup) {
898                                                 // send comments and likes to owner to relay
899                                                 diaspora_send_followup($target_item,$owner,$contact);
900                                                 break;
901                                         }
902                                         elseif($target_item['uri'] !== $target_item['parent-uri']) {
903                                                 // we are the relay - send comments, likes and relayable_retractions
904                                                 // (of comments and likes) to our conversants
905                                                 diaspora_send_relay($target_item,$owner,$contact);
906                                                 break;
907                                         }
908                                         elseif(($top_level) && (! $walltowall)) {
909                                                 // currently no workable solution for sending walltowall
910                                                 diaspora_send_status($target_item,$owner,$contact);
911                                                 break;
912                                         }
913
914                                         break;
915
916                                 case NETWORK_FEED:
917                                 case NETWORK_FACEBOOK:
918                                         if(get_config('system','dfrn_only'))
919                                                 break;
920                                 case NETWORK_PUMPIO:
921                                         if(get_config('system','dfrn_only'))
922                                                 break;
923                                 default:
924                                         break;
925                         }
926                 }
927         }
928
929         // send additional slaps to mentioned remote tags (@foo@example.com)
930
931         if($slap && count($url_recipients) && ($followup || $top_level) && ($public_message || $push_notify) && (! $expire)) {
932                 if(! get_config('system','dfrn_only')) {
933                         foreach($url_recipients as $url) {
934                                 if($url) {
935                                         logger('notifier: urldelivery: ' . $url);
936                                         $deliver_status = slapper($owner,$url,$slap);
937                                         // TODO: redeliver/queue these items on failure, though there is no contact record
938                                 }
939                         }
940                 }
941         }
942
943
944         if($public_message) {
945
946                 $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s'
947                         AND `uid` = %d AND `rel` != %d group by `batch` ORDER BY rand() ",
948                         dbesc(NETWORK_DIASPORA),
949                         intval($owner['uid']),
950                         intval(CONTACT_IS_SHARING)
951                 );
952
953                 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
954                         WHERE `network` in ( '%s', '%s')  AND `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0
955                         AND `rel` != %d order by rand() ",
956                         dbesc(NETWORK_DFRN),
957                         dbesc(NETWORK_MAIL2),
958                         intval($owner['uid']),
959                         intval(CONTACT_IS_SHARING)
960                 );
961
962                 $r = array_merge($r2,$r1);
963
964                 if(count($r)) {
965                         logger('pubdeliver: ' . print_r($r,true), LOGGER_DEBUG);
966
967                         // throw everything into the queue in case we get killed
968
969                         foreach($r as $rr) {
970                                 if((! $mail) && (! $fsuggest) && (! $followup)) {
971                                         q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
972                                                 dbesc($cmd),
973                                                 intval($item_id),
974                                                 intval($rr['id'])
975                                         );
976                                 }
977                         }
978
979                         foreach($r as $rr) {
980
981                                 // except for Diaspora batch jobs
982                                 // Don't deliver to folks who have already been delivered to
983
984                                 if(($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
985                                         logger('notifier: already delivered id=' . $rr['id']);
986                                         continue;
987                                 }
988
989                                 if((! $mail) && (! $fsuggest) && (! $followup)) {
990                                         logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']);
991                                         proc_run('php','include/delivery.php',$cmd,$item_id,$rr['id']);
992                                         if($interval)
993                                                 @time_sleep_until(microtime(true) + (float) $interval);
994                                 }
995                         }
996                 }
997
998                 $push_notify = true;
999
1000         }
1001
1002
1003         if($push_notify AND strlen($hub)) {
1004                 $hubs = explode(',', $hub);
1005                 if(count($hubs)) {
1006                         foreach($hubs as $h) {
1007                                 $h = trim($h);
1008                                 if(! strlen($h))
1009                                         continue;
1010
1011                                 if ($h === '[internal]') {
1012                                         // Set push flag for PuSH subscribers to this topic,
1013                                         // they will be notified in queue.php
1014                                         q("UPDATE `push_subscriber` SET `push` = 1 " .
1015                                           "WHERE `nickname` = '%s'", dbesc($owner['nickname']));
1016
1017                                         logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
1018
1019                                 } else {
1020
1021                                         $params = 'hub.mode=publish&hub.url=' . urlencode( $a->get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
1022                                         post_url($h,$params);
1023                                         logger('publish for item '.$item_id.' ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
1024                                 }
1025                                 if(count($hubs) > 1)
1026                                         sleep(7);                               // try and avoid multiple hubs responding at precisely the same time
1027                         }
1028                 }
1029
1030                 // Handling the pubsubhubbub requests
1031                 proc_run('php','include/pubsubpublish.php');
1032         }
1033
1034         // If the item was deleted, clean up the `sign` table
1035         if($target_item['deleted']) {
1036                 $r = q("DELETE FROM sign where `retract_iid` = %d",
1037                         intval($target_item['id'])
1038                 );
1039         }
1040
1041         logger('notifier: calling hooks', LOGGER_DEBUG);
1042
1043         if($normal_mode)
1044                 call_hooks('notifier_normal',$target_item);
1045
1046         call_hooks('notifier_end',$target_item);
1047
1048         return;
1049 }
1050
1051
1052 if (array_search(__file__,get_included_files())===0){
1053         notifier_run($_SERVER["argv"],$_SERVER["argc"]);
1054         killme();
1055 }