]> git.mxchange.org Git - friendica.git/blob - include/items.php
private group tests, cont.
[friendica.git] / include / items.php
1 <?php
2
3 require_once('include/bbcode.php');
4 require_once('include/oembed.php');
5 require_once('include/salmon.php');
6 require_once('include/crypto.php');
7
8 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
9
10
11         $sitefeed    = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
12         $public_feed = (($dfrn_id) ? false : true);
13         $starred     = false;   // not yet implemented, possible security issues
14         $converse    = false;
15
16         if($public_feed && $a->argc > 2) {
17                 for($x = 2; $x < $a->argc; $x++) {
18                         if($a->argv[$x] == 'converse')
19                                 $converse = true;
20                         if($a->argv[$x] == 'starred')
21                                 $starred = true;
22                         if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
23                                 $category = $a->argv[$x+1];
24                 }
25
26
27         }
28
29         
30
31         // default permissions - anonymous user
32
33         $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid`  = '' AND `deny_gid`  = '' ";
34
35         $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
36                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
37                 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
38                 dbesc($owner_nick)
39         );
40
41         if(! count($r))
42                 killme();
43
44         $owner = $r[0];
45         $owner_id = $owner['user_uid'];
46         $owner_nick = $owner['nickname'];
47
48         $birthday = feed_birthday($owner_id,$owner['timezone']);
49
50         if(! $public_feed) {
51
52                 $sql_extra = '';
53                 switch($direction) {
54                         case (-1):
55                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
56                                 $my_id = $dfrn_id;
57                                 break;
58                         case 0:
59                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
60                                 $my_id = '1:' . $dfrn_id;
61                                 break;
62                         case 1:
63                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
64                                 $my_id = '0:' . $dfrn_id;
65                                 break;
66                         default:
67                                 return false;
68                                 break; // NOTREACHED
69                 }
70
71                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
72                         intval($owner_id)
73                 );
74
75                 if(! count($r))
76                         killme();
77
78                 $contact = $r[0];
79                 $groups = init_groups_visitor($contact['id']);
80
81                 if(count($groups)) {
82                         for($x = 0; $x < count($groups); $x ++) 
83                                 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
84                         $gs = implode('|', $groups);
85                 }
86                 else
87                         $gs = '<<>>' ; // Impossible to match 
88
89                 $sql_extra = sprintf(" 
90                         AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' ) 
91                         AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' ) 
92                         AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
93                         AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s') 
94                 ",
95                         intval($contact['id']),
96                         intval($contact['id']),
97                         dbesc($gs),
98                         dbesc($gs)
99                 );
100         }
101
102         if($public_feed)
103                 $sort = 'DESC';
104         else
105                 $sort = 'ASC';
106
107         if(! strlen($last_update))
108                 $last_update = 'now -30 days';
109
110         if(isset($category)) {
111                 $sql_extra .= file_tag_file_query('item',$category,'category');
112         }
113
114         if($public_feed) {
115                 if(! $converse)
116                         $sql_extra .= " AND `contact`.`self` = 1 ";
117         }
118
119         $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
120
121         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
122                 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`, 
123                 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
124                 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, 
125                 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
126                 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
127                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
128                 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
129                 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0 
130                 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
131                 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
132                 $sql_extra
133                 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
134                 intval($owner_id),
135                 dbesc($check_date),
136                 dbesc($check_date),
137                 dbesc($sort)
138         );
139
140         // Will check further below if this actually returned results.
141         // We will provide an empty feed if that is the case.
142
143         $items = $r;
144
145         $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
146
147         $atom = '';
148
149         $hubxml = feed_hublinks();
150
151         $salmon = feed_salmonlinks($owner_nick);
152
153         $atom .= replace_macros($feed_template, array(
154                 '$version'      => xmlify(FRIENDICA_VERSION),
155                 '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
156                 '$feed_title'   => xmlify($owner['name']),
157                 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
158                 '$hub'          => $hubxml,
159                 '$salmon'       => $salmon,
160                 '$name'         => xmlify($owner['name']),
161                 '$profile_page' => xmlify($owner['url']),
162                 '$photo'        => xmlify($owner['photo']),
163                 '$thumb'        => xmlify($owner['thumb']),
164                 '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
165                 '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
166                 '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) , 
167                 '$birthday'     => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
168                 '$community'    => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
169         ));
170
171         call_hooks('atom_feed', $atom);
172
173         if(! count($items)) {
174
175                 call_hooks('atom_feed_end', $atom);
176
177                 $atom .= '</feed>' . "\r\n";
178                 return $atom;
179         }
180
181         foreach($items as $item) {
182
183                 // public feeds get html, our own nodes use bbcode
184
185                 if($public_feed) {
186                         $type = 'html';
187                         // catch any email that's in a public conversation and make sure it doesn't leak
188                         if($item['private'])
189                                 continue;
190                 }
191                 else {
192                         $type = 'text';
193                 }
194
195                 $atom .= atom_entry($item,$type,null,$owner,true);
196         }
197
198         call_hooks('atom_feed_end', $atom);
199
200         $atom .= '</feed>' . "\r\n";
201
202         return $atom;
203 }
204
205
206 function construct_verb($item) {
207         if($item['verb'])
208                 return $item['verb'];
209         return ACTIVITY_POST;
210 }
211
212 function construct_activity_object($item) {
213
214         if($item['object']) {
215                 $o = '<as:object>' . "\r\n";
216                 $r = parse_xml_string($item['object'],false);
217
218
219                 if(! $r)
220                         return '';
221                 if($r->type)
222                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
223                 if($r->id)
224                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
225                 if($r->title)
226                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
227                 if($r->link) {
228                         if(substr($r->link,0,1) === '<') {
229                                 // patch up some facebook "like" activity objects that got stored incorrectly
230                                 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
231                                 // we can probably remove this hack here and in the following function in a few months time.
232                                 if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
233                                         $r->link = str_replace('&','&amp;', $r->link);
234                                 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
235                                 $o .= $r->link;
236                         }                                       
237                         else
238                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
239                 }
240                 if($r->content)
241                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
242                 $o .= '</as:object>' . "\r\n";
243                 return $o;
244         }
245
246         return '';
247
248
249 function construct_activity_target($item) {
250
251         if($item['target']) {
252                 $o = '<as:target>' . "\r\n";
253                 $r = parse_xml_string($item['target'],false);
254                 if(! $r)
255                         return '';
256                 if($r->type)
257                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
258                 if($r->id)
259                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
260                 if($r->title)
261                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
262                 if($r->link) {
263                         if(substr($r->link,0,1) === '<') {
264                                 if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
265                                         $r->link = str_replace('&','&amp;', $r->link);
266                                 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
267                                 $o .= $r->link;
268                         }                                       
269                         else
270                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
271                 }
272                 if($r->content)
273                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
274                 $o .= '</as:target>' . "\r\n";
275                 return $o;
276         }
277
278         return '';
279
280
281
282
283
284 function get_atom_elements($feed,$item) {
285
286         require_once('library/HTMLPurifier.auto.php');
287         require_once('include/html2bbcode.php');
288
289         $best_photo = array();
290
291         $res = array();
292
293         $author = $item->get_author();
294         if($author) { 
295                 $res['author-name'] = unxmlify($author->get_name());
296                 $res['author-link'] = unxmlify($author->get_link());
297         }
298         else {
299                 $res['author-name'] = unxmlify($feed->get_title());
300                 $res['author-link'] = unxmlify($feed->get_permalink());
301         }
302         $res['uri'] = unxmlify($item->get_id());
303         $res['title'] = unxmlify($item->get_title());
304         $res['body'] = unxmlify($item->get_content());
305         $res['plink'] = unxmlify($item->get_link(0));
306
307         if($res['plink'])
308                 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
309         else
310                 $base_url = '';
311
312         // look for a photo. We should check media size and find the best one,
313         // but for now let's just find any author photo
314
315         $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
316
317         if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
318                 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
319                 foreach($base as $link) {
320                         if(!x($res, 'author-avatar') || !$res['author-avatar']) {
321                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
322                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
323                         }
324                 }
325         }                       
326
327         $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
328
329         if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
330                 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
331                 if($base && count($base)) {
332                         foreach($base as $link) {
333                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
334                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
335                                 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
336                                         if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
337                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
338                                 }
339                         }
340                 }
341         }
342
343         // No photo/profile-link on the item - look at the feed level
344
345         if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
346                 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
347                 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
348                         $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
349                         foreach($base as $link) {
350                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
351                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
352                                 if(! $res['author-avatar']) {
353                                         if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
354                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
355                                 }
356                         }
357                 }                       
358
359                 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
360
361                 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
362                         $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
363
364                         if($base && count($base)) {
365                                 foreach($base as $link) {
366                                         if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
367                                                 $res['author-link'] = unxmlify($link['attribs']['']['href']);
368                                         if(! (x($res,'author-avatar'))) {
369                                                 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
370                                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
371                                         }
372                                 }
373                         }
374                 }
375         }
376
377         $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
378         if($apps && $apps[0]['attribs']['']['source']) {
379                 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
380                 if($res['app'] === 'web')
381                         $res['app'] = 'OStatus';
382         }                  
383
384         // base64 encoded json structure representing Diaspora signature
385
386         $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
387         if($dsig) {
388                 $res['dsprsig'] = unxmlify($dsig[0]['data']);
389         }
390
391         $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
392         if($dguid)
393                 $res['guid'] = unxmlify($dguid[0]['data']);
394
395         $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
396         if($bm)
397                 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
398
399
400         /**
401          * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
402          */
403
404         $have_real_body = false;
405
406         $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
407         if($rawenv) {
408                 $have_real_body = true;
409                 $res['body'] = $rawenv[0]['data'];
410                 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
411                 // make sure nobody is trying to sneak some html tags by us
412                 $res['body'] = notags(base64url_decode($res['body']));
413         }
414
415         $maxlen = get_max_import_size();
416         if($maxlen && (strlen($res['body']) > $maxlen))
417                 $res['body'] = substr($res['body'],0, $maxlen);
418
419         // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust 
420         // the content type. Our own network only emits text normally, though it might have been converted to 
421         // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
422         // have to assume it is all html and needs to be purified.
423
424         // It doesn't matter all that much security wise - because before this content is used anywhere, we are 
425         // going to escape any tags we find regardless, but this lets us import a limited subset of html from 
426         // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining 
427         // html.
428
429         if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
430
431                 $res['body'] = reltoabs($res['body'],$base_url);
432
433                 $res['body'] = html2bb_video($res['body']);
434
435                 $res['body'] = oembed_html2bbcode($res['body']);
436
437                 $config = HTMLPurifier_Config::createDefault();
438                 $config->set('Cache.DefinitionImpl', null);
439
440                 // we shouldn't need a whitelist, because the bbcode converter
441                 // will strip out any unsupported tags.
442
443                 $purifier = new HTMLPurifier($config);
444                 $res['body'] = $purifier->purify($res['body']);
445
446                 $res['body'] = @html2bbcode($res['body']);
447         }
448         elseif(! $have_real_body) {
449
450                 // it's not one of our messages and it has no tags
451                 // so it's probably just text. We'll escape it just to be safe.
452
453                 $res['body'] = escape_tags($res['body']);
454         }
455
456         // this tag is obsolete but we keep it for really old sites
457
458         $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
459         if($allow && $allow[0]['data'] == 1)
460                 $res['last-child'] = 1;
461         else
462                 $res['last-child'] = 0;
463
464         $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
465         if($private && $private[0]['data'] == 1)
466                 $res['private'] = 1;
467         else
468                 $res['private'] = 0;
469
470         $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
471         if($extid && $extid[0]['data'])
472                 $res['extid'] = $extid[0]['data'];
473
474         $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
475         if($rawlocation)
476                 $res['location'] = unxmlify($rawlocation[0]['data']);
477
478
479         $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
480         if($rawcreated)
481                 $res['created'] = unxmlify($rawcreated[0]['data']);
482
483
484         $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
485         if($rawedited)
486                 $res['edited'] = unxmlify($rawedited[0]['data']);
487
488         if((x($res,'edited')) && (! (x($res,'created'))))
489                 $res['created'] = $res['edited']; 
490
491         if(! $res['created'])
492                 $res['created'] = $item->get_date('c');
493
494         if(! $res['edited'])
495                 $res['edited'] = $item->get_date('c');
496
497
498         // Disallow time travelling posts
499
500         $d1 = strtotime($res['created']);
501         $d2 = strtotime($res['edited']);
502         $d3 = strtotime('now');
503
504         if($d1 > $d3)
505                 $res['created'] = datetime_convert();
506         if($d2 > $d3)
507                 $res['edited'] = datetime_convert();
508
509         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
510         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
511                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
512         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
513                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
514         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
515                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
516         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
517                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
518
519         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
520                 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
521
522                 foreach($base as $link) {
523                         if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
524                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')                 
525                                         $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
526                         }
527                 }
528         }
529
530         $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
531         if($rawgeo)
532                 $res['coord'] = unxmlify($rawgeo[0]['data']);
533
534
535         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
536
537         // select between supported verbs
538
539         if($rawverb) {
540                 $res['verb'] = unxmlify($rawverb[0]['data']);
541         }
542
543         // translate OStatus unfollow to activity streams if it happened to get selected
544                 
545         if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
546                 $res['verb'] = ACTIVITY_UNFOLLOW;
547
548         $cats = $item->get_categories();
549         if($cats) {
550                 $tag_arr = array();
551                 foreach($cats as $cat) {
552                         $term = $cat->get_term();
553                         if(! $term)
554                                 $term = $cat->get_label();
555                         $scheme = $cat->get_scheme();
556                         if($scheme && $term && stristr($scheme,'X-DFRN:'))
557                                 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
558                         elseif($term)
559                                 $tag_arr[] = notags(trim($term));
560                 }
561                 $res['tag'] =  implode(',', $tag_arr);
562         }
563
564         $attach = $item->get_enclosures();
565         if($attach) {
566                 $att_arr = array();
567                 foreach($attach as $att) {
568                         $len   = intval($att->get_length());
569                         $link  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
570                         $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
571                         $type  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
572                         if(strpos($type,';'))
573                                 $type = substr($type,0,strpos($type,';'));
574                         if((! $link) || (strpos($link,'http') !== 0))
575                                 continue;
576
577                         if(! $title)
578                                 $title = ' ';
579                         if(! $type)
580                                 $type = 'application/octet-stream';
581
582                         $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]'; 
583                 }
584                 $res['attach'] = implode(',', $att_arr);
585         }
586
587         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
588
589         if($rawobj) {
590                 $res['object'] = '<object>' . "\n";
591                 $child = $rawobj[0]['child'];
592                 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
593                         $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
594                         $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
595                 }       
596                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
597                         $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
598                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
599                         $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
600                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
601                         $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
602                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
603                         $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
604                         if(! $body)
605                                 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
606                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
607                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
608                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
609
610                                 $body = html2bb_video($body);
611
612                                 $config = HTMLPurifier_Config::createDefault();
613                                 $config->set('Cache.DefinitionImpl', null);
614
615                                 $purifier = new HTMLPurifier($config);
616                                 $body = $purifier->purify($body);
617                                 $body = html2bbcode($body);
618                         }
619
620                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
621                 }
622
623                 $res['object'] .= '</object>' . "\n";
624         }
625
626         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
627
628         if($rawobj) {
629                 $res['target'] = '<target>' . "\n";
630                 $child = $rawobj[0]['child'];
631                 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
632                         $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
633                 }       
634                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
635                         $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
636                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
637                         $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
638                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
639                         $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
640                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
641                         $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
642                         if(! $body)
643                                 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
644                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
645                         $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
646                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
647
648                                 $body = html2bb_video($body);
649
650                                 $config = HTMLPurifier_Config::createDefault();
651                                 $config->set('Cache.DefinitionImpl', null);
652
653                                 $purifier = new HTMLPurifier($config);
654                                 $body = $purifier->purify($body);
655                                 $body = html2bbcode($body);
656                         }
657
658                         $res['target'] .= '<content>' . $body . '</content>' . "\n";
659                 }
660
661                 $res['target'] .= '</target>' . "\n";
662         }
663
664         $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
665
666         call_hooks('parse_atom', $arr);
667
668         return $res;
669 }
670
671 function encode_rel_links($links) {
672         $o = '';
673         if(! ((is_array($links)) && (count($links))))
674                 return $o;
675         foreach($links as $link) {
676                 $o .= '<link ';
677                 if($link['attribs']['']['rel'])
678                         $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
679                 if($link['attribs']['']['type'])
680                         $o .= 'type="' . $link['attribs']['']['type'] . '" ';
681                 if($link['attribs']['']['href'])
682                         $o .= 'href="' . $link['attribs']['']['href'] . '" ';
683                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
684                         $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
685                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
686                         $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
687                 $o .= ' />' . "\n" ;
688         }
689         return xmlify($o);
690 }
691
692 function item_store($arr,$force_parent = false) {
693
694         // If a Diaspora signature structure was passed in, pull it out of the 
695         // item array and set it aside for later storage.
696
697         $dsprsig = null;
698         if(x($arr,'dsprsig')) {
699                 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
700                 unset($arr['dsprsig']);
701         }
702
703         if(x($arr, 'gravity'))
704                 $arr['gravity'] = intval($arr['gravity']);
705         elseif($arr['parent-uri'] === $arr['uri'])
706                 $arr['gravity'] = 0;
707         elseif(activity_match($arr['verb'],ACTIVITY_POST))
708                 $arr['gravity'] = 6;
709         else      
710                 $arr['gravity'] = 6;   // extensible catchall
711
712         if(! x($arr,'type'))
713                 $arr['type']      = 'remote';
714
715         // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
716
717         if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false)) 
718                 $arr['body'] = strip_tags($arr['body']);
719
720
721         $arr['wall']          = ((x($arr,'wall'))          ? intval($arr['wall'])                : 0);
722         $arr['uri']           = ((x($arr,'uri'))           ? notags(trim($arr['uri']))           : random_string());
723         $arr['extid']         = ((x($arr,'extid'))         ? notags(trim($arr['extid']))         : '');
724         $arr['author-name']   = ((x($arr,'author-name'))   ? notags(trim($arr['author-name']))   : '');
725         $arr['author-link']   = ((x($arr,'author-link'))   ? notags(trim($arr['author-link']))   : '');
726         $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
727         $arr['owner-name']    = ((x($arr,'owner-name'))    ? notags(trim($arr['owner-name']))    : '');
728         $arr['owner-link']    = ((x($arr,'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
729         $arr['owner-avatar']  = ((x($arr,'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
730         $arr['created']       = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
731         $arr['edited']        = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
732         $arr['commented']     = datetime_convert();
733         $arr['received']      = datetime_convert();
734         $arr['changed']       = datetime_convert();
735         $arr['title']         = ((x($arr,'title'))         ? notags(trim($arr['title']))         : '');
736         $arr['location']      = ((x($arr,'location'))      ? notags(trim($arr['location']))      : '');
737         $arr['coord']         = ((x($arr,'coord'))         ? notags(trim($arr['coord']))         : '');
738         $arr['last-child']    = ((x($arr,'last-child'))    ? intval($arr['last-child'])          : 0 );
739         $arr['visible']       = ((x($arr,'visible') !== false) ? intval($arr['visible'])         : 1 );
740         $arr['deleted']       = 0;
741         $arr['parent-uri']    = ((x($arr,'parent-uri'))    ? notags(trim($arr['parent-uri']))    : '');
742         $arr['verb']          = ((x($arr,'verb'))          ? notags(trim($arr['verb']))          : '');
743         $arr['object-type']   = ((x($arr,'object-type'))   ? notags(trim($arr['object-type']))   : '');
744         $arr['object']        = ((x($arr,'object'))        ? trim($arr['object'])                : '');
745         $arr['target-type']   = ((x($arr,'target-type'))   ? notags(trim($arr['target-type']))   : '');
746         $arr['target']        = ((x($arr,'target'))        ? trim($arr['target'])                : '');
747         $arr['plink']         = ((x($arr,'plink'))         ? notags(trim($arr['plink']))         : '');
748         $arr['allow_cid']     = ((x($arr,'allow_cid'))     ? trim($arr['allow_cid'])             : '');
749         $arr['allow_gid']     = ((x($arr,'allow_gid'))     ? trim($arr['allow_gid'])             : '');
750         $arr['deny_cid']      = ((x($arr,'deny_cid'))      ? trim($arr['deny_cid'])              : '');
751         $arr['deny_gid']      = ((x($arr,'deny_gid'))      ? trim($arr['deny_gid'])              : '');
752         $arr['private']       = ((x($arr,'private'))       ? intval($arr['private'])             : 0 );
753         $arr['bookmark']      = ((x($arr,'bookmark'))      ? intval($arr['bookmark'])            : 0 );
754         $arr['body']          = ((x($arr,'body'))          ? trim($arr['body'])                  : '');
755         $arr['tag']           = ((x($arr,'tag'))           ? notags(trim($arr['tag']))           : '');
756         $arr['attach']        = ((x($arr,'attach'))        ? notags(trim($arr['attach']))        : '');
757         $arr['app']           = ((x($arr,'app'))           ? notags(trim($arr['app']))           : '');
758         $arr['origin']        = ((x($arr,'origin'))        ? intval($arr['origin'])              : 0 );
759         $arr['guid']          = ((x($arr,'guid'))          ? notags(trim($arr['guid']))          : get_guid());
760
761         if($arr['parent-uri'] === $arr['uri']) {
762                 $parent_id = 0;
763                 $parent_deleted = 0;
764                 $allow_cid = $arr['allow_cid'];
765                 $allow_gid = $arr['allow_gid'];
766                 $deny_cid  = $arr['deny_cid'];
767                 $deny_gid  = $arr['deny_gid'];
768         }
769         else { 
770
771                 // find the parent and snarf the item id and ACL's
772                 // and anything else we need to inherit
773
774                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
775                         dbesc($arr['parent-uri']),
776                         intval($arr['uid'])
777                 );
778
779                 if(count($r)) {
780
781                         // is the new message multi-level threaded?
782                         // even though we don't support it now, preserve the info
783                         // and re-attach to the conversation parent.
784
785                         if($r[0]['uri'] != $r[0]['parent-uri']) {
786                                 $arr['thr-parent'] = $arr['parent-uri'];
787                                 $arr['parent-uri'] = $r[0]['parent-uri'];
788                                 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d 
789                                         ORDER BY `id` ASC LIMIT 1",
790                                         dbesc($r[0]['parent-uri']),
791                                         dbesc($r[0]['parent-uri']),
792                                         intval($arr['uid'])
793                                 );
794                                 if($z && count($z))
795                                         $r = $z;
796                         }
797
798                         $parent_id      = $r[0]['id'];
799                         $parent_deleted = $r[0]['deleted'];
800                         $allow_cid      = $r[0]['allow_cid'];
801                         $allow_gid      = $r[0]['allow_gid'];
802                         $deny_cid       = $r[0]['deny_cid'];
803                         $deny_gid       = $r[0]['deny_gid'];
804                         $arr['wall']    = $r[0]['wall'];
805                 }
806                 else {
807
808                         // Allow one to see reply tweets from status.net even when
809                         // we don't have or can't see the original post.
810
811                         if($force_parent) {
812                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
813                                 $parent_id = 0;
814                                 $arr['thr-parent'] = $arr['parent-uri'];
815                                 $arr['parent-uri'] = $arr['uri'];
816                                 $arr['gravity'] = 0;
817                         }
818                         else {
819                                 logger('item_store: item parent was not found - ignoring item');
820                                 return 0;
821                         }
822                         
823                         $parent_deleted = 0;
824                 }
825         }
826
827         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
828                 dbesc($arr['uri']),
829                 intval($arr['uid'])
830         );
831         if($r && count($r)) {
832                 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
833                 return 0;
834         }
835
836         call_hooks('post_remote',$arr);
837
838         if(x($arr,'cancel')) {
839                 logger('item_store: post cancelled by plugin.');
840                 return 0;
841         }
842
843         dbesc_array($arr);
844
845         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
846
847         $r = dbq("INSERT INTO `item` (`" 
848                         . implode("`, `", array_keys($arr)) 
849                         . "`) VALUES ('" 
850                         . implode("', '", array_values($arr)) 
851                         . "')" );
852
853         // find the item we just created
854
855         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
856                 $arr['uri'],           // already dbesc'd
857                 intval($arr['uid'])
858         );
859
860         if(count($r)) {
861                 $current_post = $r[0]['id'];
862                 logger('item_store: created item ' . $current_post);
863         }
864         else {
865                 logger('item_store: could not locate created item');
866                 return 0;
867         }
868         if(count($r) > 1) {
869                 logger('item_store: duplicated post occurred. Removing duplicates.');
870                 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
871                         $arr['uri'],
872                         intval($arr['uid']),
873                         intval($current_post)
874                 );
875         }
876
877         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
878                 $parent_id = $current_post;
879
880         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
881                 $private = 1;
882         else
883                 $private = $arr['private']; 
884
885         // Set parent id - and also make sure to inherit the parent's ACL's.
886
887         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
888                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
889                 intval($parent_id),
890                 dbesc($allow_cid),
891                 dbesc($allow_gid),
892                 dbesc($deny_cid),
893                 dbesc($deny_gid),
894                 intval($private),
895                 intval($parent_deleted),
896                 intval($current_post)
897         );
898
899         // update the commented timestamp on the parent
900
901         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
902                 dbesc(datetime_convert()),
903                 dbesc(datetime_convert()),
904                 intval($parent_id)
905         );
906
907         if($dsprsig) {
908                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
909                         intval($current_post),
910                         dbesc($dsprsig->signed_text),
911                         dbesc($dsprsig->signature),
912                         dbesc($dsprsig->signer)
913                 );
914         }
915
916
917         /**
918          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
919          */
920
921         if($arr['last-child']) {
922                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
923                         dbesc($arr['uri']),
924                         intval($arr['uid']),
925                         intval($current_post)
926                 );
927         }
928
929         tag_deliver($arr['uid'],$current_post);
930
931         return $current_post;
932 }
933
934 function get_item_contact($item,$contacts) {
935         if(! count($contacts) || (! is_array($item)))
936                 return false;
937         foreach($contacts as $contact) {
938                 if($contact['id'] == $item['contact-id']) {
939                         return $contact;
940                         break; // NOTREACHED
941                 }
942         }
943         return false;
944 }
945
946
947 function tag_deliver($uid,$item_id) {
948
949         // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
950
951         $a = get_app();
952
953         $mention = false;
954
955         $u = q("select * from user where uid = %d limit 1",
956                 intval($uid)
957         );
958         if(! count($u))
959                 return;
960
961         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
962         $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
963
964
965         $i = q("select * from item where id = %d and uid = %d limit 1",
966                 intval($item_id),
967                 intval($uid)
968         );
969         if(! count($i))
970                 return;
971
972         $item = $i[0];
973
974         $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
975
976         // Diaspora uses their own hardwired link URL in @-tags
977         // instead of the one we supply with webfinger
978
979         $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
980
981         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
982         if($cnt) {
983                 foreach($matches as $mtch) {
984                         if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
985                                 $mention = true;
986                                 logger('tag_deliver: mention found: ' . $mtch[2]);
987                         }
988                 }
989         }
990
991         if(! $mention)
992                 return;
993
994         // send a notification
995
996         require_once('include/enotify.php');
997         notification(array(
998                 'type'         => NOTIFY_TAGSELF,
999                 'notify_flags' => $u[0]['notify-flags'],
1000                 'language'     => $u[0]['language'],
1001                 'to_name'      => $u[0]['username'],
1002                 'to_email'     => $u[0]['email'],
1003                 'uid'          => $u[0]['uid'],
1004                 'item'         => $item,
1005                 'link'         => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1006                 'source_name'  => $item['author-name'],
1007                 'source_link'  => $item['author-link'],
1008                 'source_photo' => $item['author-avatar'],
1009                 'verb'         => ACTIVITY_TAG,
1010                 'otype'        => 'item'
1011         ));
1012
1013         if((! $community_page) && (! $prvgroup))
1014                 return;
1015
1016
1017         // tgroup delivery - setup a second delivery chain
1018         // prevent delivery looping - only proceed
1019         // if the message originated elsewhere and is a top-level post
1020
1021         if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1022                 return;
1023
1024         // now change this copy of the post to a forum head message and deliver to all the tgroup members
1025
1026
1027         $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1028                 intval($u[0]['uid'])
1029         );
1030         if(! count($c))
1031                 return;
1032
1033         // also reset all the privacy bits to the forum default permissions
1034
1035         $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1036
1037         $forum_mode = (($prvgroup) ? 2 : 1);
1038
1039         q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s', 
1040                 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'  where id = %d limit 1",
1041                 intval($forum_mode),
1042                 dbesc($c[0]['name']),
1043                 dbesc($c[0]['url']),
1044                 dbesc($c[0]['thumb']),
1045                 intval($private),
1046                 dbesc($u[0]['allow_cid']),
1047                 dbesc($u[0]['allow_gid']),
1048                 dbesc($u[0]['deny_cid']),
1049                 dbesc($u[0]['deny_gid']),
1050                 intval($item_id)
1051         );
1052
1053         proc_run('php','include/notifier.php','tgroup',$item_id);                       
1054
1055 }
1056
1057
1058
1059
1060
1061
1062 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1063
1064         $a = get_app();
1065
1066         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1067
1068         if($contact['duplex'] && $contact['dfrn-id'])
1069                 $idtosend = '0:' . $orig_id;
1070         if($contact['duplex'] && $contact['issued-id'])
1071                 $idtosend = '1:' . $orig_id;            
1072
1073         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1074
1075         $rino_enable = get_config('system','rino_encrypt');
1076
1077         if(! $rino_enable)
1078                 $rino = 0;
1079
1080         $ssl_val = intval(get_config('system','ssl_policy'));
1081         $ssl_policy = '';
1082
1083         switch($ssl_val){
1084                 case SSL_POLICY_FULL:
1085                         $ssl_policy = 'full';
1086                         break;
1087                 case SSL_POLICY_SELFSIGN:
1088                         $ssl_policy = 'self';
1089                         break;                  
1090                 case SSL_POLICY_NONE:
1091                 default:
1092                         $ssl_policy = 'none';
1093                         break;
1094         }
1095
1096         $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1097
1098         logger('dfrn_deliver: ' . $url);
1099
1100         $xml = fetch_url($url);
1101
1102         $curl_stat = $a->get_curl_code();
1103         if(! $curl_stat)
1104                 return(-1); // timed out
1105
1106         logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1107
1108         if(! $xml)
1109                 return 3;
1110
1111         if(strpos($xml,'<?xml') === false) {
1112                 logger('dfrn_deliver: no valid XML returned');
1113                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1114                 return 3;
1115         }
1116
1117         $res = parse_xml_string($xml);
1118
1119         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1120                 return (($res->status) ? $res->status : 3);
1121
1122         $postvars     = array();
1123         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1124         $challenge    = hex2bin((string) $res->challenge);
1125         $perm         = (($res->perm) ? $res->perm : null);
1126         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1127         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1128         $page         = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1129
1130         if($owner['page-flags'] == PAGE_PRVGROUP)
1131                 $page = 2;
1132
1133         $final_dfrn_id = '';
1134
1135         if($perm) {
1136                 if((($perm == 'rw') && (! intval($contact['writable']))) 
1137                 || (($perm == 'r') && (intval($contact['writable'])))) {
1138                         q("update contact set writable = %d where id = %d limit 1",
1139                                 intval(($perm == 'rw') ? 1 : 0),
1140                                 intval($contact['id'])
1141                         );
1142                         $contact['writable'] = (string) 1 - intval($contact['writable']);                       
1143                 }
1144         }
1145
1146         if(($contact['duplex'] && strlen($contact['pubkey'])) 
1147                 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1148                 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1149                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1150                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1151         }
1152         else {
1153                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1154                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1155         }
1156
1157         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1158
1159         if(strpos($final_dfrn_id,':') == 1)
1160                 $final_dfrn_id = substr($final_dfrn_id,2);
1161
1162         if($final_dfrn_id != $orig_id) {
1163                 logger('dfrn_deliver: wrong dfrn_id.');
1164                 // did not decode properly - cannot trust this site 
1165                 return 3;
1166         }
1167
1168         $postvars['dfrn_id']      = $idtosend;
1169         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1170         if($dissolve)
1171                 $postvars['dissolve'] = '1';
1172
1173
1174         if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1175                 $postvars['data'] = $atom;
1176                 $postvars['perm'] = 'rw';
1177         }
1178         else {
1179                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1180                 $postvars['perm'] = 'r';
1181         }
1182
1183         $postvars['ssl_policy'] = $ssl_policy;
1184
1185         if($page)
1186                 $postvars['page'] = $page;
1187         
1188         if($rino && $rino_allowed && (! $dissolve)) {
1189                 $key = substr(random_string(),0,16);
1190                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1191                 $postvars['data'] = $data;
1192                 logger('rino: sent key = ' . $key, LOGGER_DEBUG);       
1193
1194
1195                 if($dfrn_version >= 2.1) {      
1196                         if(($contact['duplex'] && strlen($contact['pubkey'])) 
1197                                 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1198                                 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1199
1200                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1201                         }
1202                         else {
1203                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1204                         }
1205                 }
1206                 else {
1207                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1208                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1209                         }
1210                         else {
1211                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1212                         }
1213                 }
1214
1215                 logger('md5 rawkey ' . md5($postvars['key']));
1216
1217                 $postvars['key'] = bin2hex($postvars['key']);
1218         }
1219
1220         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1221
1222         $xml = post_url($contact['notify'],$postvars);
1223
1224         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1225
1226         $curl_stat = $a->get_curl_code();
1227         if((! $curl_stat) || (! strlen($xml)))
1228                 return(-1); // timed out
1229
1230         if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1231                 return(-1);
1232
1233         if(strpos($xml,'<?xml') === false) {
1234                 logger('dfrn_deliver: phase 2: no valid XML returned');
1235                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1236                 return 3;
1237         }
1238
1239         $res = parse_xml_string($xml);
1240
1241         return $res->status; 
1242 }
1243
1244
1245 /**
1246  *
1247  * consume_feed - process atom feed and update anything/everything we might need to update
1248  *
1249  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1250  *
1251  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1252  *             It is this person's stuff that is going to be updated.
1253  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1254  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
1255  *             have a contact record.
1256  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
1257  *        might not) try and subscribe to it.
1258  * $datedir sorts in reverse order
1259  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been 
1260  *      imported prior to its children being seen in the stream unless we are certain
1261  *      of how the feed is arranged/ordered.
1262  * With $pass = 1, we only pull parent items out of the stream.
1263  * With $pass = 2, we only pull children (comments/likes).
1264  *
1265  * So running this twice, first with pass 1 and then with pass 2 will do the right
1266  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1267  * model where comments can have sub-threads. That would require some massive sorting
1268  * to get all the feed items into a mostly linear ordering, and might still require
1269  * recursion.  
1270  */
1271
1272 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1273
1274         require_once('library/simplepie/simplepie.inc');
1275
1276         if(! strlen($xml)) {
1277                 logger('consume_feed: empty input');
1278                 return;
1279         }
1280                 
1281         $feed = new SimplePie();
1282         $feed->set_raw_data($xml);
1283         if($datedir)
1284                 $feed->enable_order_by_date(true);
1285         else
1286                 $feed->enable_order_by_date(false);
1287         $feed->init();
1288
1289         if($feed->error())
1290                 logger('consume_feed: Error parsing XML: ' . $feed->error());
1291
1292         $permalink = $feed->get_permalink();
1293
1294         // Check at the feed level for updated contact name and/or photo
1295
1296         $name_updated  = '';
1297         $new_name = '';
1298         $photo_timestamp = '';
1299         $photo_url = '';
1300         $birthday = '';
1301
1302         $hubs = $feed->get_links('hub');
1303
1304         if(count($hubs))
1305                 $hub = implode(',', $hubs);
1306
1307         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1308         if(! $rawtags)
1309                 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1310         if($rawtags) {
1311                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1312                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1313                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1314                         $new_name = $elems['name'][0]['data'];
1315                 } 
1316                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1317                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1318                         $photo_url = $elems['link'][0]['attribs']['']['href'];
1319                 }
1320
1321                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1322                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1323                 }
1324         }
1325
1326         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1327                 logger('consume_feed: Updating photo for ' . $contact['name']);
1328                 require_once("Photo.php");
1329                 $photo_failure = false;
1330                 $have_photo = false;
1331
1332                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1333                         intval($contact['id']),
1334                         intval($contact['uid'])
1335                 );
1336                 if(count($r)) {
1337                         $resource_id = $r[0]['resource-id'];
1338                         $have_photo = true;
1339                 }
1340                 else {
1341                         $resource_id = photo_new_resource();
1342                 }
1343                         
1344                 $img_str = fetch_url($photo_url,true);
1345                 $img = new Photo($img_str);
1346                 if($img->is_valid()) {
1347                         if($have_photo) {
1348                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1349                                         dbesc($resource_id),
1350                                         intval($contact['id']),
1351                                         intval($contact['uid'])
1352                                 );
1353                         }
1354                                 
1355                         $img->scaleImageSquare(175);
1356                                 
1357                         $hash = $resource_id;
1358                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1359                                 
1360                         $img->scaleImage(80);
1361                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1362
1363                         $img->scaleImage(48);
1364                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1365
1366                         $a = get_app();
1367
1368                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
1369                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1370                                 dbesc(datetime_convert()),
1371                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1372                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1373                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1374                                 intval($contact['uid']),
1375                                 intval($contact['id'])
1376                         );
1377                 }
1378         }
1379
1380         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1381                 $r = q("select * from contact where uid = %d and id = %d limit 1",
1382                         intval($contact['uid']),
1383                         intval($contact['id'])
1384                 );
1385
1386                 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1387                         dbesc(notags(trim($new_name))),
1388                         dbesc(datetime_convert()),
1389                         intval($contact['uid']),
1390                         intval($contact['id'])
1391                 );
1392
1393                 // do our best to update the name on content items
1394
1395                 if(count($r)) {
1396                         q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1397                                 dbesc(notags(trim($new_name))),
1398                                 dbesc($r[0]['name']),
1399                                 dbesc($r[0]['url']),
1400                                 intval($contact['uid'])
1401                         );
1402                 }
1403         }
1404
1405         if(strlen($birthday)) {
1406                 if(substr($birthday,0,4) != $contact['bdyear']) {
1407                         logger('consume_feed: updating birthday: ' . $birthday);
1408
1409                         /**
1410                          *
1411                          * Add new birthday event for this person
1412                          *
1413                          * $bdtext is just a readable placeholder in case the event is shared
1414                          * with others. We will replace it during presentation to our $importer
1415                          * to contain a sparkle link and perhaps a photo. 
1416                          *
1417                          */
1418                          
1419                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1420
1421
1422                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1423                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1424                                 intval($contact['uid']),
1425                                 intval($contact['id']),
1426                                 dbesc(datetime_convert()),
1427                                 dbesc(datetime_convert()),
1428                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1429                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1430                                 dbesc($bdtext),
1431                                 dbesc('birthday')
1432                         );
1433                         
1434
1435                         // update bdyear
1436
1437                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1438                                 dbesc(substr($birthday,0,4)),
1439                                 intval($contact['uid']),
1440                                 intval($contact['id'])
1441                         );
1442
1443                         // This function is called twice without reloading the contact
1444                         // Make sure we only create one event. This is why &$contact 
1445                         // is a reference var in this function
1446
1447                         $contact['bdyear'] = substr($birthday,0,4);
1448                 }
1449
1450         }
1451
1452         $community_page = 0;
1453         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1454         if($rawtags) {
1455                 $community_page = intval($rawtags[0]['data']);
1456         }
1457         if(is_array($contact) && intval($contact['forum']) != $community_page) {
1458                 q("update contact set forum = %d where id = %d limit 1",
1459                         intval($community_page),
1460                         intval($contact['id'])
1461                 );
1462                 $contact['forum'] = (string) $community_page;
1463         }
1464
1465
1466         // process any deleted entries
1467
1468         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1469         if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1470                 foreach($del_entries as $dentry) {
1471                         $deleted = false;
1472                         if(isset($dentry['attribs']['']['ref'])) {
1473                                 $uri = $dentry['attribs']['']['ref'];
1474                                 $deleted = true;
1475                                 if(isset($dentry['attribs']['']['when'])) {
1476                                         $when = $dentry['attribs']['']['when'];
1477                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1478                                 }
1479                                 else
1480                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1481                         }
1482                         if($deleted && is_array($contact)) {
1483                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id` 
1484                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1485                                         dbesc($uri),
1486                                         intval($importer['uid']),
1487                                         intval($contact['id'])
1488                                 );
1489                                 if(count($r)) {
1490                                         $item = $r[0];
1491
1492                                         if(! $item['deleted'])
1493                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1494
1495                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1496                                                 $xo = parse_xml_string($item['object'],false);
1497                                                 $xt = parse_xml_string($item['target'],false);
1498                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
1499                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1500                                                                 dbesc($xt->id),
1501                                                                 intval($importer['importer_uid'])
1502                                                         );
1503                                                         if(count($i)) {
1504
1505                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
1506
1507                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1508                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1509                                                                 $author_copy = (($item['origin']) ? true : false);
1510
1511                                                                 if($owner_remove && $author_copy)
1512                                                                         continue;
1513                                                                 if($author_remove || $owner_remove) {
1514                                                                         $tags = explode(',',$i[0]['tag']);
1515                                                                         $newtags = array();
1516                                                                         if(count($tags)) {
1517                                                                                 foreach($tags as $tag)
1518                                                                                         if(trim($tag) !== trim($xo->body))
1519                                                                                                 $newtags[] = trim($tag);
1520                                                                         }
1521                                                                         q("update item set tag = '%s' where id = %d limit 1",
1522                                                                                 dbesc(implode(',',$newtags)),
1523                                                                                 intval($i[0]['id'])
1524                                                                         );
1525                                                                 }
1526                                                         }
1527                                                 }
1528                                         }
1529
1530                                         if($item['uri'] == $item['parent-uri']) {
1531                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1532                                                         `body` = '', `title` = ''
1533                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1534                                                         dbesc($when),
1535                                                         dbesc(datetime_convert()),
1536                                                         dbesc($item['uri']),
1537                                                         intval($importer['uid'])
1538                                                 );
1539                                         }
1540                                         else {
1541                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1542                                                         `body` = '', `title` = '' 
1543                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1544                                                         dbesc($when),
1545                                                         dbesc(datetime_convert()),
1546                                                         dbesc($uri),
1547                                                         intval($importer['uid'])
1548                                                 );
1549                                                 if($item['last-child']) {
1550                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1551                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1552                                                                 dbesc(datetime_convert()),
1553                                                                 dbesc($item['parent-uri']),
1554                                                                 intval($item['uid'])
1555                                                         );
1556                                                         // who is the last child now? 
1557                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d 
1558                                                                 ORDER BY `created` DESC LIMIT 1",
1559                                                                         dbesc($item['parent-uri']),
1560                                                                         intval($importer['uid'])
1561                                                         );
1562                                                         if(count($r)) {
1563                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1564                                                                         intval($r[0]['id'])
1565                                                                 );
1566                                                         }
1567                                                 }       
1568                                         }
1569                                 }       
1570                         }
1571                 }
1572         }
1573
1574         // Now process the feed
1575
1576         if($feed->get_item_quantity()) {                
1577
1578                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1579
1580         // in inverse date order
1581                 if ($datedir)
1582                         $items = array_reverse($feed->get_items());
1583                 else
1584                         $items = $feed->get_items();
1585
1586
1587                 foreach($items as $item) {
1588
1589                         $is_reply = false;              
1590                         $item_id = $item->get_id();
1591                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1592                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1593                                 $is_reply = true;
1594                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1595                         }
1596
1597                         if(($is_reply) && is_array($contact)) {
1598
1599                                 if($pass == 1)
1600                                         continue;
1601
1602                                 // Have we seen it? If not, import it.
1603         
1604                                 $item_id  = $item->get_id();
1605                                 $datarray = get_atom_elements($feed,$item);
1606
1607
1608                                 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1609                                         $datarray['author-name'] = $contact['name'];
1610                                 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1611                                         $datarray['author-link'] = $contact['url'];
1612                                 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1613                                         $datarray['author-avatar'] = $contact['thumb'];
1614
1615                                 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1616                                         logger('consume_feed: no author information! ' . print_r($datarray,true));
1617                                         continue;
1618                                 }
1619
1620                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1621                                         dbesc($item_id),
1622                                         intval($importer['uid'])
1623                                 );
1624
1625                                 // Update content if 'updated' changes
1626
1627                                 if(count($r)) {
1628                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1629                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1630                                                         dbesc($datarray['title']),
1631                                                         dbesc($datarray['body']),
1632                                                         dbesc($datarray['tag']),
1633                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1634                                                         dbesc($item_id),
1635                                                         intval($importer['uid'])
1636                                                 );
1637                                         }
1638
1639                                         // update last-child if it changes
1640
1641                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1642                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1643                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1644                                                         dbesc(datetime_convert()),
1645                                                         dbesc($parent_uri),
1646                                                         intval($importer['uid'])
1647                                                 );
1648                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1649                                                         intval($allow[0]['data']),
1650                                                         dbesc(datetime_convert()),
1651                                                         dbesc($item_id),
1652                                                         intval($importer['uid'])
1653                                                 );
1654                                         }
1655                                         continue;
1656                                 }
1657
1658                                 $force_parent = false;
1659                                 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1660                                         if($contact['network'] === NETWORK_OSTATUS)
1661                                                 $force_parent = true;
1662                                         if(strlen($datarray['title']))
1663                                                 unset($datarray['title']);
1664                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1665                                                 dbesc(datetime_convert()),
1666                                                 dbesc($parent_uri),
1667                                                 intval($importer['uid'])
1668                                         );
1669                                         $datarray['last-child'] = 1;
1670                                 }
1671
1672                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1673                                         // one way feed - no remote comment ability
1674                                         $datarray['last-child'] = 0;
1675                                 }
1676                                 $datarray['parent-uri'] = $parent_uri;
1677                                 $datarray['uid'] = $importer['uid'];
1678                                 $datarray['contact-id'] = $contact['id'];
1679                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1680                                         $datarray['type'] = 'activity';
1681                                         $datarray['gravity'] = GRAVITY_LIKE;
1682                                         // only one like or dislike per person
1683                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
1684                                                 intval($datarray['uid']),
1685                                                 intval($datarray['contact-id']),
1686                                                 dbesc($datarray['verb'])
1687                                         );
1688                                         if($r && count($r))
1689                                                 continue; 
1690                                 }
1691
1692                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1693                                         $xo = parse_xml_string($datarray['object'],false);
1694                                         $xt = parse_xml_string($datarray['target'],false);
1695
1696                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
1697                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1698                                                         dbesc($xt->id),
1699                                                         intval($importer['importer_uid'])
1700                                                 );
1701                                                 if(! count($r))
1702                                                         continue;
1703
1704                                                 // extract tag, if not duplicate, add to parent item
1705                                                 if($xo->id && $xo->content) {
1706                                                         $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1707                                                         if(! (stristr($r[0]['tag'],$newtag))) {
1708                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1709                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1710                                                                         intval($r[0]['id'])
1711                                                                 );
1712                                                         }
1713                                                 }
1714                                         }
1715                                 }
1716
1717                                 $r = item_store($datarray,$force_parent);
1718                                 continue;
1719                         }
1720
1721                         else {
1722
1723                                 // Head post of a conversation. Have we seen it? If not, import it.
1724
1725                                 $item_id  = $item->get_id();
1726
1727                                 $datarray = get_atom_elements($feed,$item);
1728
1729                                 if(is_array($contact)) {
1730                                         if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1731                                                 $datarray['author-name'] = $contact['name'];
1732                                         if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1733                                                 $datarray['author-link'] = $contact['url'];
1734                                         if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1735                                                 $datarray['author-avatar'] = $contact['thumb'];
1736                                 }
1737
1738                                 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1739                                         logger('consume_feed: no author information! ' . print_r($datarray,true));
1740                                         continue;
1741                                 }
1742
1743                                 // special handling for events
1744
1745                                 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1746                                         $ev = bbtoevent($datarray['body']);
1747                                         if(x($ev,'desc') && x($ev,'start')) {
1748                                                 $ev['uid'] = $importer['uid'];
1749                                                 $ev['uri'] = $item_id;
1750                                                 $ev['edited'] = $datarray['edited'];
1751                                                 $ev['private'] = $datarray['private'];
1752
1753                                                 if(is_array($contact))
1754                                                         $ev['cid'] = $contact['id'];
1755                                                 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1756                                                         dbesc($item_id),
1757                                                         intval($importer['uid'])
1758                                                 );
1759                                                 if(count($r))
1760                                                         $ev['id'] = $r[0]['id'];
1761                                                 $xyz = event_store($ev);
1762                                                 continue;
1763                                         }
1764                                 }
1765
1766                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1767                                         dbesc($item_id),
1768                                         intval($importer['uid'])
1769                                 );
1770
1771                                 // Update content if 'updated' changes
1772
1773                                 if(count($r)) {
1774                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1775                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1776                                                         dbesc($datarray['title']),
1777                                                         dbesc($datarray['body']),
1778                                                         dbesc($datarray['tag']),
1779                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1780                                                         dbesc($item_id),
1781                                                         intval($importer['uid'])
1782                                                 );
1783                                         }
1784
1785                                         // update last-child if it changes
1786
1787                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1788                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1789                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1790                                                         intval($allow[0]['data']),
1791                                                         dbesc(datetime_convert()),
1792                                                         dbesc($item_id),
1793                                                         intval($importer['uid'])
1794                                                 );
1795                                         }
1796                                         continue;
1797                                 }
1798
1799                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1800                                         logger('consume-feed: New follower');
1801                                         new_follower($importer,$contact,$datarray,$item);
1802                                         return;
1803                                 }
1804                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1805                                         lose_follower($importer,$contact,$datarray,$item);
1806                                         return;
1807                                 }
1808
1809                                 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1810                                         logger('consume-feed: New friend request');
1811                                         new_follower($importer,$contact,$datarray,$item,true);
1812                                         return;
1813                                 }
1814                                 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND))  {
1815                                         lose_sharer($importer,$contact,$datarray,$item);
1816                                         return;
1817                                 }
1818
1819
1820                                 if(! is_array($contact))
1821                                         return;
1822
1823                                 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1824                                         if(strlen($datarray['title']))
1825                                                 unset($datarray['title']);
1826                                         $datarray['last-child'] = 1;
1827                                 }
1828
1829                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1830                                         // one way feed - no remote comment ability
1831                                         $datarray['last-child'] = 0;
1832                                 }
1833
1834                                 // This is my contact on another system, but it's really me.
1835                                 // Turn this into a wall post.
1836
1837                                 if($contact['remote_self'])
1838                                         $datarray['wall'] = 1;
1839
1840                                 $datarray['parent-uri'] = $item_id;
1841                                 $datarray['uid'] = $importer['uid'];
1842                                 $datarray['contact-id'] = $contact['id'];
1843
1844                                 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1845                                         // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery, 
1846                                         // but otherwise there's a possible data mixup on the sender's system.
1847                                         // the tgroup delivery code called from item_store will correct it if it's a forum,
1848                                         // but we're going to unconditionally correct it here so that the post will always be owned by our contact. 
1849                                         logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
1850                                         $datarray['owner-name']   = $contact['name'];
1851                                         $datarray['owner-link']   = $contact['url'];
1852                                         $datarray['owner-avatar'] = $contact['thumb'];
1853                                 }
1854
1855                                 $r = item_store($datarray);
1856                                 continue;
1857
1858                         }
1859                 }
1860         }
1861 }
1862
1863 function local_delivery($importer,$data) {
1864
1865         $a = get_app();
1866
1867         if($importer['readonly']) {
1868                 // We aren't receiving stuff from this person. But we will quietly ignore them
1869                 // rather than a blatant "go away" message.
1870                 logger('local_delivery: ignoring');
1871                 return 0;
1872                 //NOTREACHED
1873         }
1874
1875         // Consume notification feed. This may differ from consuming a public feed in several ways
1876         // - might contain email or friend suggestions
1877         // - might contain remote followup to our message
1878         //              - in which case we need to accept it and then notify other conversants
1879         // - we may need to send various email notifications
1880
1881         $feed = new SimplePie();
1882         $feed->set_raw_data($data);
1883         $feed->enable_order_by_date(false);
1884         $feed->init();
1885
1886 /*
1887         // Currently unsupported - needs a lot of work
1888         $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1889         if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1890                 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1891                 $newloc = array();
1892                 $newloc['uid'] = $importer['importer_uid'];
1893                 $newloc['cid'] = $importer['id'];
1894                 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1895                 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1896                 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1897                 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1898                 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1899                 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1900                 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1901                 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1902                 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1903                 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1904                 
1905                 // TODO
1906                 // merge with current record, current contents have priority
1907                 // update record, set url-updated
1908                 // update profile photos
1909                 // schedule a scan?
1910
1911         }
1912 */
1913
1914         // handle friend suggestion notification
1915
1916         $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1917         if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1918                 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1919                 $fsugg = array();
1920                 $fsugg['uid'] = $importer['importer_uid'];
1921                 $fsugg['cid'] = $importer['id'];
1922                 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1923                 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1924                 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1925                 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1926                 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1927
1928                 // Does our member already have a friend matching this description?
1929
1930                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1931                         dbesc($fsugg['name']),
1932                         dbesc(normalise_link($fsugg['url'])),
1933                         intval($fsugg['uid'])
1934                 );
1935                 if(count($r))
1936                         return 0;
1937
1938                 // Do we already have an fcontact record for this person?
1939
1940                 $fid = 0;
1941                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1942                         dbesc($fsugg['url']),
1943                         dbesc($fsugg['name']),
1944                         dbesc($fsugg['request'])
1945                 );
1946                 if(count($r)) {
1947                         $fid = $r[0]['id'];
1948
1949                         // OK, we do. Do we already have an introduction for this person ?
1950                         $r = q("select id from intro where uid = %d and fid = %d limit 1",
1951                                 intval($fsugg['uid']),
1952                                 intval($fid)
1953                         );
1954                         if(count($r))
1955                                 return 0;
1956                 }
1957                 if(! $fid)
1958                         $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1959                         dbesc($fsugg['name']),
1960                         dbesc($fsugg['url']),
1961                         dbesc($fsugg['photo']),
1962                         dbesc($fsugg['request'])
1963                 );
1964                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1965                         dbesc($fsugg['url']),
1966                         dbesc($fsugg['name']),
1967                         dbesc($fsugg['request'])
1968                 );
1969                 if(count($r)) {
1970                         $fid = $r[0]['id'];
1971                 }
1972                 // database record did not get created. Quietly give up.
1973                 else
1974                         return 0;
1975
1976
1977                 $hash = random_string();
1978  
1979                 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1980                         VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1981                         intval($fsugg['uid']),
1982                         intval($fid),
1983                         intval($fsugg['cid']),
1984                         dbesc($fsugg['body']),
1985                         dbesc($hash),
1986                         dbesc(datetime_convert()),
1987                         intval(0)
1988                 );
1989
1990                 notification(array(
1991                         'type'         => NOTIFY_SUGGEST,
1992                         'notify_flags' => $importer['notify-flags'],
1993                         'language'     => $importer['language'],
1994                         'to_name'      => $importer['username'],
1995                         'to_email'     => $importer['email'],
1996                         'uid'          => $importer['importer_uid'],
1997                         'item'         => $fsugg,
1998                         'link'         => $a->get_baseurl() . '/notifications/intros',
1999                         'source_name'  => $importer['name'],
2000                         'source_link'  => $importer['url'],
2001                         'source_photo' => $importer['photo'],
2002                         'verb'         => ACTIVITY_REQ_FRIEND,
2003                         'otype'        => 'intro'
2004                 ));
2005
2006                 return 0;
2007         }
2008
2009         $ismail = false;
2010
2011         $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2012         if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2013
2014                 logger('local_delivery: private message received');
2015
2016                 $ismail = true;
2017                 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2018
2019                 $msg = array();
2020                 $msg['uid'] = $importer['importer_uid'];
2021                 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2022                 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2023                 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2024                 $msg['contact-id'] = $importer['id'];
2025                 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2026                 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2027                 $msg['seen'] = 0;
2028                 $msg['replied'] = 0;
2029                 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2030                 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2031                 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2032                 
2033                 dbesc_array($msg);
2034
2035                 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) 
2036                         . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2037
2038                 // send notifications.
2039
2040                 require_once('include/enotify.php');
2041
2042                 $notif_params = array(
2043                         'type' => NOTIFY_MAIL,
2044                         'notify_flags' => $importer['notify-flags'],
2045                         'language' => $importer['language'],
2046                         'to_name' => $importer['username'],
2047                         'to_email' => $importer['email'],
2048                         'uid' => $importer['importer_uid'],
2049                         'item' => $msg,
2050                         'source_name' => $msg['from-name'],
2051                         'source_link' => $importer['url'],
2052                         'source_photo' => $importer['thumb'],
2053                         'verb' => ACTIVITY_POST,
2054                         'otype' => 'mail'
2055                 );
2056                         
2057                 notification($notif_params);
2058                 return 0;
2059
2060                 // NOTREACHED
2061         }       
2062
2063         $community_page = 0;
2064         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2065         if($rawtags) {
2066                 $community_page = intval($rawtags[0]['data']);
2067         }
2068         if(intval($importer['forum']) != $community_page) {
2069                 q("update contact set forum = %d where id = %d limit 1",
2070                         intval($community_page),
2071                         intval($importer['id'])
2072                 );
2073                 $importer['forum'] = (string) $community_page;
2074         }
2075         
2076         logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2077
2078         // process any deleted entries
2079
2080         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2081         if(is_array($del_entries) && count($del_entries)) {
2082                 foreach($del_entries as $dentry) {
2083                         $deleted = false;
2084                         if(isset($dentry['attribs']['']['ref'])) {
2085                                 $uri = $dentry['attribs']['']['ref'];
2086                                 $deleted = true;
2087                                 if(isset($dentry['attribs']['']['when'])) {
2088                                         $when = $dentry['attribs']['']['when'];
2089                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2090                                 }
2091                                 else
2092                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2093                         }
2094                         if($deleted) {
2095
2096                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2097                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2098                                         dbesc($uri),
2099                                         intval($importer['importer_uid']),
2100                                         intval($importer['id'])
2101                                 );
2102
2103                                 if(count($r)) {
2104                                         $item = $r[0];
2105
2106                                         if($item['deleted'])
2107                                                 continue;
2108
2109                                         logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2110
2111                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2112                                                 $xo = parse_xml_string($item['object'],false);
2113                                                 $xt = parse_xml_string($item['target'],false);
2114
2115                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
2116                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2117                                                                 dbesc($xt->id),
2118                                                                 intval($importer['importer_uid'])
2119                                                         );
2120                                                         if(count($i)) {
2121
2122                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2123                                                                 
2124                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2125                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2126                                                                 $author_copy = (($item['origin']) ? true : false); 
2127
2128                                                                 if($owner_remove && $author_copy)
2129                                                                         continue;
2130                                                                 if($author_remove || $owner_remove) {                                                           
2131                                                                         $tags = explode(',',$i[0]['tag']);
2132                                                                         $newtags = array();
2133                                                                         if(count($tags)) {
2134                                                                                 foreach($tags as $tag)
2135                                                                                         if(trim($tag) !== trim($xo->body))
2136                                                                                                 $newtags[] = trim($tag);
2137                                                                         }
2138                                                                         q("update item set tag = '%s' where id = %d limit 1",
2139                                                                                 dbesc(implode(',',$newtags)),
2140                                                                                 intval($i[0]['id'])
2141                                                                         );
2142                                                                 }
2143                                                         }
2144                                                 }
2145                                         }
2146
2147                                         if($item['uri'] == $item['parent-uri']) {
2148                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2149                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
2150                                                         dbesc($when),
2151                                                         dbesc(datetime_convert()),
2152                                                         dbesc($item['uri']),
2153                                                         intval($importer['importer_uid'])
2154                                                 );
2155                                         }
2156                                         else {
2157                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
2158                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2159                                                         dbesc($when),
2160                                                         dbesc(datetime_convert()),
2161                                                         dbesc($uri),
2162                                                         intval($importer['importer_uid'])
2163                                                 );
2164                                                 if($item['last-child']) {
2165                                                         // ensure that last-child is set in case the comment that had it just got wiped.
2166                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2167                                                                 dbesc(datetime_convert()),
2168                                                                 dbesc($item['parent-uri']),
2169                                                                 intval($item['uid'])
2170                                                         );
2171                                                         // who is the last child now? 
2172                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2173                                                                 ORDER BY `created` DESC LIMIT 1",
2174                                                                         dbesc($item['parent-uri']),
2175                                                                         intval($importer['importer_uid'])
2176                                                         );
2177                                                         if(count($r)) {
2178                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2179                                                                         intval($r[0]['id'])
2180                                                                 );
2181                                                         }       
2182                                                 }
2183                                         }       
2184                                 }
2185                         }
2186                 }
2187         }
2188
2189
2190         foreach($feed->get_items() as $item) {
2191
2192                 $is_reply = false;              
2193                 $item_id = $item->get_id();
2194                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2195                 if(isset($rawthread[0]['attribs']['']['ref'])) {
2196                         $is_reply = true;
2197                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
2198                 }
2199
2200                 if($is_reply) {
2201                         $community = false;
2202
2203                         if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2204                                 $sql_extra = '';
2205                                 $community = true;
2206                                 logger('local_delivery: possible community reply');
2207                         }
2208                         else
2209                                 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2210  
2211                         // was the top-level post for this reply written by somebody on this site? 
2212                         // Specifically, the recipient? 
2213
2214                         $is_a_remote_comment = false;
2215
2216                         $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`, 
2217                                 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` 
2218                                 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` 
2219                                 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2220                                 AND `item`.`uid` = %d 
2221                                 $sql_extra
2222                                 LIMIT 1",
2223                                 dbesc($parent_uri),
2224                                 dbesc($parent_uri),
2225                                 intval($importer['importer_uid'])
2226                         );
2227                         if($r && count($r))
2228                                 $is_a_remote_comment = true;                    
2229
2230                         // Does this have the characteristics of a community or private group comment?
2231                         // If it's a reply to a wall post on a community/prvgroup page it's a 
2232                         // valid community comment. Also forum_mode makes it valid for sure. 
2233                         // If neither, it's not.
2234
2235                         if($is_a_remote_comment && $community) {
2236                                 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2237                                         $is_a_remote_comment = false;
2238                                         logger('local_delivery: not a community reply');
2239                                 }
2240                         }
2241
2242                         if($is_a_remote_comment) {
2243                                 logger('local_delivery: received remote comment');
2244                                 $is_like = false;
2245                                 // remote reply to our post. Import and then notify everybody else.
2246
2247                                 $datarray = get_atom_elements($feed,$item);
2248
2249                                 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body`  FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2250                                         dbesc($item_id),
2251                                         intval($importer['importer_uid'])
2252                                 );
2253
2254                                 // Update content if 'updated' changes
2255
2256                                 if(count($r)) {
2257                                         $iid = $r[0]['id'];
2258                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2259                                                 logger('received updated comment' , LOGGER_DEBUG);
2260                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2261                                                         dbesc($datarray['title']),
2262                                                         dbesc($datarray['body']),
2263                                                         dbesc($datarray['tag']),
2264                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2265                                                         dbesc($item_id),
2266                                                         intval($importer['importer_uid'])
2267                                                 );
2268
2269                                                 proc_run('php',"include/notifier.php","comment-import",$iid);
2270
2271                                         }
2272
2273                                         continue;
2274                                 }
2275
2276
2277                                 // TODO: make this next part work against both delivery threads of a community post
2278
2279 //                              if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2280 //                                      logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] ); 
2281                                         // they won't know what to do so don't report an error. Just quietly die.
2282 //                                      return 0;
2283 //                              }                                       
2284
2285                                 // our user with $importer['importer_uid'] is the owner
2286
2287                                 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2288                                         intval($importer['importer_uid'])
2289                                 );
2290
2291
2292                                 $datarray['type'] = 'remote-comment';
2293                                 $datarray['wall'] = 1;
2294                                 $datarray['parent-uri'] = $parent_uri;
2295                                 $datarray['uid'] = $importer['importer_uid'];
2296                                 $datarray['owner-name'] = $own[0]['name'];
2297                                 $datarray['owner-link'] = $own[0]['url'];
2298                                 $datarray['owner-avatar'] = $own[0]['thumb'];
2299                                 $datarray['contact-id'] = $importer['id'];
2300
2301                                 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2302                                         $is_like = true;
2303                                         $datarray['type'] = 'activity';
2304                                         $datarray['gravity'] = GRAVITY_LIKE;
2305                                         $datarray['last-child'] = 0;
2306                                         // only one like or dislike per person
2307                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2308                                                 intval($datarray['uid']),
2309                                                 intval($datarray['contact-id']),
2310                                                 dbesc($datarray['verb'])
2311                                         );
2312                                         if($r && count($r))
2313                                                 continue; 
2314                                 }
2315
2316                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2317                                         
2318                                         $xo = parse_xml_string($datarray['object'],false);
2319                                         $xt = parse_xml_string($datarray['target'],false);
2320
2321                                         if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2322
2323                                                 // fetch the parent item
2324
2325                                                 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2326                                                         dbesc($xt->id),
2327                                                         intval($importer['importer_uid'])
2328                                                 );
2329                                                 if(! count($tagp))
2330                                                         continue;       
2331
2332                                                 // extract tag, if not duplicate, and this user allows tags, add to parent item                                         
2333
2334                                                 if($xo->id && $xo->content) {
2335                                                         $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2336                                                         if(! (stristr($tagp[0]['tag'],$newtag))) {
2337                                                                 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2338                                                                         intval($importer['importer_uid'])
2339                                                                 );
2340                                                                 if(count($i) && ! intval($i[0]['blocktags'])) {
2341                                                                         q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2342                                                                                 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2343                                                                                 intval($tagp[0]['id']),
2344                                                                                 dbesc(datetime_convert())
2345                                                                         );
2346                                                                 }
2347                                                         }
2348                                                 }                                                                                                       
2349                                         }
2350                                 }
2351
2352 //                              if($community) {
2353 //                                      $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2354 //                                      if(! stristr($datarray['tag'],$newtag)) {
2355 //                                              if(strlen($datarray['tag']))
2356 //                                                      $datarray['tag'] .= ',';
2357 //                                              $datarray['tag'] .= $newtag;
2358 //                                      }
2359 //                              }
2360
2361
2362                                 $posted_id = item_store($datarray);
2363                                 $parent = 0;
2364
2365                                 if($posted_id) {
2366                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2367                                                 intval($posted_id),
2368                                                 intval($importer['importer_uid'])
2369                                         );
2370                                         if(count($r))
2371                                                 $parent = $r[0]['parent'];
2372                         
2373                                         if(! $is_like) {
2374                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2375                                                         dbesc(datetime_convert()),
2376                                                         intval($importer['importer_uid']),
2377                                                         intval($r[0]['parent'])
2378                                                 );
2379
2380                                                 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2381                                                         dbesc(datetime_convert()),
2382                                                         intval($importer['importer_uid']),
2383                                                         intval($posted_id)
2384                                                 );
2385                                         }
2386
2387                                         if($posted_id && $parent) {
2388                                 
2389                                                 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2390                                         
2391                                                 if((! $is_like) && (! $importer['self'])) {
2392
2393                                                         require_once('include/enotify.php');
2394
2395                                                         notification(array(
2396                                                                 'type'         => NOTIFY_COMMENT,
2397                                                                 'notify_flags' => $importer['notify-flags'],
2398                                                                 'language'     => $importer['language'],
2399                                                                 'to_name'      => $importer['username'],
2400                                                                 'to_email'     => $importer['email'],
2401                                                                 'uid'          => $importer['importer_uid'],
2402                                                                 'item'         => $datarray,
2403                                                                 'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2404                                                                 'source_name'  => stripslashes($datarray['author-name']),
2405                                                                 'source_link'  => $datarray['author-link'],
2406                                                                 'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
2407                                                                         ? $importer['thumb'] : $datarray['author-avatar']),
2408                                                                 'verb'         => ACTIVITY_POST,
2409                                                                 'otype'        => 'item',
2410                                                                 'parent'       => $parent,
2411
2412                                                         ));
2413
2414                                                 }
2415                                         }
2416
2417                                         return 0;
2418                                         // NOTREACHED
2419                                 }
2420                         }
2421                         else {
2422
2423                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2424
2425                                 $item_id  = $item->get_id();
2426                                 $datarray = get_atom_elements($feed,$item);
2427
2428                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2429                                         dbesc($item_id),
2430                                         intval($importer['importer_uid'])
2431                                 );
2432
2433                                 // Update content if 'updated' changes
2434
2435                                 if(count($r)) {
2436                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2437                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2438                                                         dbesc($datarray['title']),
2439                                                         dbesc($datarray['body']),
2440                                                         dbesc($datarray['tag']),
2441                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2442                                                         dbesc($item_id),
2443                                                         intval($importer['importer_uid'])
2444                                                 );
2445                                         }
2446
2447                                         // update last-child if it changes
2448
2449                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2450                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2451                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2452                                                         dbesc(datetime_convert()),
2453                                                         dbesc($parent_uri),
2454                                                         intval($importer['importer_uid'])
2455                                                 );
2456                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2457                                                         intval($allow[0]['data']),
2458                                                         dbesc(datetime_convert()),
2459                                                         dbesc($item_id),
2460                                                         intval($importer['importer_uid'])
2461                                                 );
2462                                         }
2463                                         continue;
2464                                 }
2465
2466                                 $datarray['parent-uri'] = $parent_uri;
2467                                 $datarray['uid'] = $importer['importer_uid'];
2468                                 $datarray['contact-id'] = $importer['id'];
2469                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2470                                         $datarray['type'] = 'activity';
2471                                         $datarray['gravity'] = GRAVITY_LIKE;
2472                                         // only one like or dislike per person
2473                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2474                                                 intval($datarray['uid']),
2475                                                 intval($datarray['contact-id']),
2476                                                 dbesc($datarray['verb'])
2477                                         );
2478                                         if($r && count($r))
2479                                                 continue; 
2480
2481                                 }
2482
2483                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2484
2485                                         $xo = parse_xml_string($datarray['object'],false);
2486                                         $xt = parse_xml_string($datarray['target'],false);
2487
2488                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
2489                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2490                                                         dbesc($xt->id),
2491                                                         intval($importer['importer_uid'])
2492                                                 );
2493                                                 if(! count($r))
2494                                                         continue;                               
2495
2496                                                 // extract tag, if not duplicate, add to parent item                                            
2497                                                 if($xo->content) {
2498                                                         if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2499                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2500                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2501                                                                         intval($r[0]['id'])
2502                                                                 );
2503                                                         }
2504                                                 }                                                                                                       
2505                                         }
2506                                 }
2507
2508                                 $posted_id = item_store($datarray);
2509
2510                                 // find out if our user is involved in this conversation and wants to be notified.
2511                         
2512                                 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
2513
2514                                         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
2515                                                 dbesc($parent_uri),
2516                                                 intval($importer['importer_uid'])
2517                                         );
2518
2519                                         if(count($myconv)) {
2520                                                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2521
2522                                                 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2523                                                 if(! link_compare($datarray['author-link'],$importer_url)) {
2524
2525                                                         
2526                                                         foreach($myconv as $conv) {
2527
2528                                                                 // now if we find a match, it means we're in this conversation
2529         
2530                                                                 if(! link_compare($conv['author-link'],$importer_url))
2531                                                                         continue;
2532
2533                                                                 require_once('include/enotify.php');
2534                                                                 
2535                                                                 $conv_parent = $conv['parent'];
2536
2537                                                                 notification(array(
2538                                                                         'type'         => NOTIFY_COMMENT,
2539                                                                         'notify_flags' => $importer['notify-flags'],
2540                                                                         'language'     => $importer['language'],
2541                                                                         'to_name'      => $importer['username'],
2542                                                                         'to_email'     => $importer['email'],
2543                                                                         'uid'          => $importer['importer_uid'],
2544                                                                         'item'         => $datarray,
2545                                                                         'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2546                                                                         'source_name'  => stripslashes($datarray['author-name']),
2547                                                                         'source_link'  => $datarray['author-link'],
2548                                                                         'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
2549                                                                                 ? $importer['thumb'] : $datarray['author-avatar']),
2550                                                                         'verb'         => ACTIVITY_POST,
2551                                                                         'otype'        => 'item',
2552                                                                         'parent'       => $conv_parent,
2553
2554                                                                 ));
2555
2556                                                                 // only send one notification
2557                                                                 break;
2558                                                         }
2559                                                 }
2560                                         }
2561                                 }
2562                                 continue;
2563                         }
2564                 }
2565
2566                 else {
2567
2568                         // Head post of a conversation. Have we seen it? If not, import it.
2569
2570
2571                         $item_id  = $item->get_id();
2572                         $datarray = get_atom_elements($feed,$item);
2573
2574                         if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2575                                 $ev = bbtoevent($datarray['body']);
2576                                 if(x($ev,'desc') && x($ev,'start')) {
2577                                         $ev['cid'] = $importer['id'];
2578                                         $ev['uid'] = $importer['uid'];
2579                                         $ev['uri'] = $item_id;
2580                                         $ev['edited'] = $datarray['edited'];
2581                                         $ev['private'] = $datarray['private'];
2582
2583                                         $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2584                                                 dbesc($item_id),
2585                                                 intval($importer['uid'])
2586                                         );
2587                                         if(count($r))
2588                                                 $ev['id'] = $r[0]['id'];
2589                                         $xyz = event_store($ev);
2590                                         continue;
2591                                 }
2592                         }
2593
2594                         $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2595                                 dbesc($item_id),
2596                                 intval($importer['importer_uid'])
2597                         );
2598
2599                         // Update content if 'updated' changes
2600
2601                         if(count($r)) {
2602                                 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2603                                         $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2604                                                 dbesc($datarray['title']),
2605                                                 dbesc($datarray['body']),
2606                                                 dbesc($datarray['tag']),
2607                                                 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2608                                                 dbesc($item_id),
2609                                                 intval($importer['importer_uid'])
2610                                         );
2611                                 }
2612
2613                                 // update last-child if it changes
2614
2615                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2616                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2617                                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2618                                                 intval($allow[0]['data']),
2619                                                 dbesc(datetime_convert()),
2620                                                 dbesc($item_id),
2621                                                 intval($importer['importer_uid'])
2622                                         );
2623                                 }
2624                                 continue;
2625                         }
2626
2627                         // This is my contact on another system, but it's really me.
2628                         // Turn this into a wall post.
2629
2630                         if($importer['remote_self'])
2631                                 $datarray['wall'] = 1;
2632
2633                         $datarray['parent-uri'] = $item_id;
2634                         $datarray['uid'] = $importer['importer_uid'];
2635                         $datarray['contact-id'] = $importer['id'];
2636
2637                         if(! link_compare($datarray['owner-link'],$contact['url'])) {
2638                                 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery, 
2639                                 // but otherwise there's a possible data mixup on the sender's system.
2640                                 // the tgroup delivery code called from item_store will correct it if it's a forum,
2641                                 // but we're going to unconditionally correct it here so that the post will always be owned by our contact. 
2642                                 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2643                                 $datarray['owner-name']   = $importer['senderName'];
2644                                 $datarray['owner-link']   = $importer['url'];
2645                                 $datarray['owner-avatar'] = $importer['thumb'];
2646                         }
2647
2648                         $r = item_store($datarray);
2649                         continue;
2650                 }
2651         }
2652
2653         return 0;
2654         // NOTREACHED
2655
2656 }
2657
2658
2659 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2660         $url = notags(trim($datarray['author-link']));
2661         $name = notags(trim($datarray['author-name']));
2662         $photo = notags(trim($datarray['author-avatar']));
2663
2664         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2665         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2666                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2667
2668         if(is_array($contact)) {
2669                 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2670                         || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2671                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2672                                 intval(CONTACT_IS_FRIEND),
2673                                 intval($contact['id']),
2674                                 intval($importer['uid'])
2675                         );
2676                 }
2677                 // send email notification to owner?
2678         }
2679         else {
2680         
2681                 // create contact record
2682
2683                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`, 
2684                         `blocked`, `readonly`, `pending`, `writable` )
2685                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2686                         intval($importer['uid']),
2687                         dbesc(datetime_convert()),
2688                         dbesc($url),
2689                         dbesc(normalise_link($url)),
2690                         dbesc($name),
2691                         dbesc($nick),
2692                         dbesc($photo),
2693                         dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2694                         intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2695                 );
2696                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2697                                 intval($importer['uid']),
2698                                 dbesc($url)
2699                 );
2700                 if(count($r))
2701                                 $contact_record = $r[0];
2702
2703                 // create notification  
2704                 $hash = random_string();
2705
2706                 if(is_array($contact_record)) {
2707                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2708                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2709                                 intval($importer['uid']),
2710                                 intval($contact_record['id']),
2711                                 dbesc($hash),
2712                                 dbesc(datetime_convert())
2713                         );
2714                 }
2715                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2716                         intval($importer['uid'])
2717                 );
2718                 $a = get_app();
2719                 if(count($r)) {
2720
2721                         if(intval($r[0]['def_gid'])) {
2722                                 require_once('include/group.php');
2723                                 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
2724                         }
2725
2726                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2727                                 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2728                                 $email = replace_macros($email_tpl, array(
2729                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2730                                         '$url' => $url,
2731                                         '$myname' => $r[0]['username'],
2732                                         '$siteurl' => $a->get_baseurl(),
2733                                         '$sitename' => $a->config['sitename']
2734                                 ));
2735                                 $res = mail($r[0]['email'], 
2736                                         (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2737                                         $email,
2738                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2739                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
2740                                         . 'Content-transfer-encoding: 8bit' );
2741                         
2742                         }
2743                 }
2744         }
2745 }
2746
2747 function lose_follower($importer,$contact,$datarray,$item) {
2748
2749         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2750                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2751                         intval(CONTACT_IS_SHARING),
2752                         intval($contact['id'])
2753                 );
2754         }
2755         else {
2756                 contact_remove($contact['id']);
2757         }
2758 }
2759
2760 function lose_sharer($importer,$contact,$datarray,$item) {
2761
2762         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2763                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2764                         intval(CONTACT_IS_FOLLOWER),
2765                         intval($contact['id'])
2766                 );
2767         }
2768         else {
2769                 contact_remove($contact['id']);
2770         }
2771 }
2772
2773
2774 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2775
2776         if(is_array($importer)) {
2777                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2778                         intval($importer['uid'])
2779                 );
2780         }
2781
2782         // Diaspora has different message-ids in feeds than they do 
2783         // through the direct Diaspora protocol. If we try and use
2784         // the feed, we'll get duplicates. So don't.
2785
2786         if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2787                 return;
2788
2789         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2790
2791         // Use a single verify token, even if multiple hubs
2792
2793         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2794
2795         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2796
2797         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
2798
2799         if(! strlen($contact['hub-verify'])) {
2800                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2801                         dbesc($verify_token),
2802                         intval($contact['id'])
2803                 );
2804         }
2805
2806         post_url($url,$params);                 
2807         return;
2808
2809 }
2810
2811
2812 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2813         $o = '';
2814         if(! $tag)
2815                 return $o;
2816         $name = xmlify($name);
2817         $uri = xmlify($uri);
2818         $h = intval($h);
2819         $w = intval($w);
2820         $photo = xmlify($photo);
2821
2822
2823         $o .= "<$tag>\r\n";
2824         $o .= "<name>$name</name>\r\n";
2825         $o .= "<uri>$uri</uri>\r\n";
2826         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2827         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2828
2829         call_hooks('atom_author', $o);
2830
2831         $o .= "</$tag>\r\n";
2832         return $o;
2833 }
2834
2835 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
2836
2837         $a = get_app();
2838
2839         if(! $item['parent'])
2840                 return;
2841
2842         if($item['deleted'])
2843                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2844
2845
2846         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2847                 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
2848         else
2849                 $body = $item['body'];
2850
2851
2852         $o = "\r\n\r\n<entry>\r\n";
2853
2854         if(is_array($author))
2855                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2856         else
2857                 $o .= atom_author('author',(($item['author-name']) ? $item['author-name'] : $item['name']),(($item['author-link']) ? $item['author-link'] : $item['url']),80,80,(($item['author-avatar']) ? $item['author-avatar'] : $item['thumb']));
2858         if(strlen($item['owner-name']))
2859                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2860
2861         if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2862                 $o .= '<thr:in-reply-to ref="' . xmlify($item['parent-uri']) . '" type="text/html" href="' .  xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
2863
2864         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2865         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2866         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2867         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2868         $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2869         $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2870         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2871         if($comment)
2872                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2873
2874         if($item['location']) {
2875                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2876                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2877         }
2878
2879         if($item['coord'])
2880                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2881
2882         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2883                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2884
2885         if($item['extid'])
2886                 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2887         if($item['bookmark'])
2888                 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2889
2890         if($item['app'])
2891                 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2892
2893         if($item['guid'])
2894                 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2895
2896         if($item['signed_text']) {
2897                 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2898                 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2899         }
2900
2901         $verb = construct_verb($item);
2902         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2903         $actobj = construct_activity_object($item);
2904         if(strlen($actobj))
2905                 $o .= $actobj;
2906         $actarg = construct_activity_target($item);
2907         if(strlen($actarg))
2908                 $o .= $actarg;
2909
2910         $tags = item_getfeedtags($item);
2911         if(count($tags)) {
2912                 foreach($tags as $t) {
2913                         $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2914                 }
2915         }
2916
2917         $o .= item_getfeedattach($item);
2918
2919         $mentioned = get_mentions($item);
2920         if($mentioned)
2921                 $o .= $mentioned;
2922         
2923         call_hooks('atom_entry', $o);
2924
2925         $o .= '</entry>' . "\r\n";
2926         
2927         return $o;
2928 }
2929
2930 function fix_private_photos($s,$uid, $item = null, $cid = 0) {
2931         $a = get_app();
2932
2933         logger('fix_private_photos', LOGGER_DEBUG);
2934         $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
2935
2936         if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2937                 $image = $matches[1];
2938                 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
2939                 if(stristr($image , $site . '/photo/')) {
2940                         $replace = false;
2941                         $i = basename($image);
2942                         $i = str_replace('.jpg','',$i);
2943                         $x = strpos($i,'-');
2944                         if($x) {
2945                                 $res = substr($i,$x+1);
2946                                 $i = substr($i,0,$x);
2947                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2948                                         dbesc($i),
2949                                         intval($res),
2950                                         intval($uid)
2951                                 );
2952                                 if(count($r)) {
2953
2954                                         // Check to see if we should replace this photo link with an embedded image
2955                                         // 1. No need to do so if the photo is public
2956                                         // 2. If there's a contact-id provided, see if they're in the access list
2957                                         //    for the photo. If so, embed it. 
2958                                         // 3. Otherwise, if we have an item, see if the item permissions match the photo
2959                                         //    permissions, regardless of order but first check to see if they're an exact
2960                                         //    match to save some processing overhead.
2961                                 
2962                                         // Currently we only embed one private photo per message so as not to hit import 
2963                                         // size limits at the receiving end.
2964
2965                                         // To embed multiples, we would need to parse out the embedded photos on message
2966                                         // receipt and limit size based only on the text component. Would also need to
2967                                         // ignore all photos during bbcode translation and item localisation, as these
2968                                         // will hit internal regex backtrace limits.  
2969
2970                                         if(has_permissions($r[0])) {
2971                                                 if($cid) {
2972                                                         $recips = enumerate_permissions($r[0]);
2973                                                         if(in_array($cid, $recips)) {
2974                                                                 $replace = true;        
2975                                                         }
2976                                                 }
2977                                                 elseif($item) {
2978                                                         if(compare_permissions($item,$r[0]))
2979                                                                 $replace = true;
2980                                                 }
2981                                         }
2982                                         if($replace) {
2983                                                 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
2984                                                 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2985                                                 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2986                                         }
2987                                 }
2988                         }
2989                 }       
2990         }
2991         return($s);
2992 }
2993
2994
2995 function has_permissions($obj) {
2996         if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
2997                 return true;
2998         return false;
2999 }
3000
3001 function compare_permissions($obj1,$obj2) {
3002         // first part is easy. Check that these are exactly the same. 
3003         if(($obj1['allow_cid'] == $obj2['allow_cid'])
3004                 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3005                 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3006                 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3007                 return true;
3008
3009         // This is harder. Parse all the permissions and compare the resulting set.
3010
3011         $recipients1 = enumerate_permissions($obj1);
3012         $recipients2 = enumerate_permissions($obj2);
3013         sort($recipients1);
3014         sort($recipients2);
3015         if($recipients1 == $recipients2)
3016                 return true;
3017         return false;
3018 }
3019
3020 // returns an array of contact-ids that are allowed to see this object
3021
3022 function enumerate_permissions($obj) {
3023         require_once('include/group.php');
3024         $allow_people = expand_acl($obj['allow_cid']);
3025         $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3026         $deny_people  = expand_acl($obj['deny_cid']);
3027         $deny_groups  = expand_groups(expand_acl($obj['deny_gid']));
3028         $recipients   = array_unique(array_merge($allow_people,$allow_groups));
3029         $deny         = array_unique(array_merge($deny_people,$deny_groups));
3030         $recipients   = array_diff($recipients,$deny);
3031         return $recipients;
3032 }
3033
3034 function item_getfeedtags($item) {
3035         $ret = array();
3036         $matches = false;
3037         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3038         if($cnt) {
3039                 for($x = 0; $x < $cnt; $x ++) {
3040                         if($matches[1][$x])
3041                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3042                 }
3043         }
3044         $matches = false; 
3045         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3046         if($cnt) {
3047                 for($x = 0; $x < $cnt; $x ++) {
3048                         if($matches[1][$x])
3049                                 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3050                 }
3051         } 
3052         return $ret;
3053 }
3054
3055 function item_getfeedattach($item) {
3056         $ret = '';
3057         $arr = explode(',',$item['attach']);
3058         if(count($arr)) {
3059                 foreach($arr as $r) {
3060                         $matches = false;
3061                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3062                         if($cnt) {
3063                                 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3064                                 if(intval($matches[2]))
3065                                         $ret .= 'length="' . intval($matches[2]) . '" ';
3066                                 if($matches[4] !== ' ')
3067                                         $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3068                                 $ret .= ' />' . "\r\n";
3069                         }
3070                 }
3071         }
3072         return $ret;
3073 }
3074
3075
3076         
3077 function item_expire($uid,$days) {
3078
3079         if((! $uid) || ($days < 1))
3080                 return;
3081
3082         // $expire_network_only = save your own wall posts
3083         // and just expire conversations started by others
3084
3085         $expire_network_only = get_pconfig($uid,'expire','network_only');
3086         $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3087
3088         $r = q("SELECT * FROM `item` 
3089                 WHERE `uid` = %d 
3090                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
3091                 AND `id` = `parent` 
3092                 $sql_extra
3093                 AND `deleted` = 0",
3094                 intval($uid),
3095                 intval($days)
3096         );
3097
3098         if(! count($r))
3099                 return;
3100
3101         $expire_items = get_pconfig($uid, 'expire','items');
3102         $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3103         
3104         $expire_notes = get_pconfig($uid, 'expire','notes');
3105         $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3106
3107         $expire_starred = get_pconfig($uid, 'expire','starred');
3108         $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3109         
3110         $expire_photos = get_pconfig($uid, 'expire','photos');
3111         $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3112  
3113         logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3114
3115         foreach($r as $item) {
3116
3117                 // don't expire filed items
3118
3119                 if(strpos($item['file'],'[') !== false)
3120                         continue;
3121
3122                 // Only expire posts, not photos and photo comments
3123
3124                 if($expire_photos==0 && strlen($item['resource-id']))
3125                         continue;
3126                 if($expire_starred==0 && intval($item['starred']))
3127                         continue;
3128                 if($expire_notes==0 && $item['type']=='note')
3129                         continue;
3130                 if($expire_items==0 && $item['type']!='note')
3131                         continue;
3132
3133                 drop_item($item['id'],false);
3134         }
3135
3136         proc_run('php',"include/notifier.php","expire","$uid");
3137         
3138 }
3139
3140
3141 function drop_items($items) {
3142         $uid = 0;
3143
3144         if(! local_user() && ! remote_user())
3145                 return;
3146
3147         if(count($items)) {
3148                 foreach($items as $item) {
3149                         $owner = drop_item($item,false);
3150                         if($owner && ! $uid)
3151                                 $uid = $owner;
3152                 }
3153         }
3154
3155         // multiple threads may have been deleted, send an expire notification
3156
3157         if($uid)
3158                 proc_run('php',"include/notifier.php","expire","$uid");
3159 }
3160
3161
3162 function drop_item($id,$interactive = true) {
3163
3164         $a = get_app();
3165
3166         // locate item to be deleted
3167
3168         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3169                 intval($id)
3170         );
3171
3172         if(! count($r)) {
3173                 if(! $interactive)
3174                         return 0;
3175                 notice( t('Item not found.') . EOL);
3176                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3177         }
3178
3179         $item = $r[0];
3180
3181         $owner = $item['uid'];
3182
3183         // check if logged in user is either the author or owner of this item
3184
3185         if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3186
3187                 // delete the item
3188
3189                 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3190                         dbesc(datetime_convert()),
3191                         dbesc(datetime_convert()),
3192                         intval($item['id'])
3193                 );
3194
3195                 // clean up categories and tags so they don't end up as orphans
3196
3197                 $matches = false;
3198                 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3199                 if($cnt) {
3200                         foreach($matches as $mtch) {
3201                                 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3202                         }
3203                 }
3204
3205                 $matches = false;
3206
3207                 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3208                 if($cnt) {
3209                         foreach($matches as $mtch) {
3210                                 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3211                         }
3212                 }
3213
3214                 // If item is a link to a photo resource, nuke all the associated photos 
3215                 // (visitors will not have photo resources)
3216                 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3217                 // generate a resource-id and therefore aren't intimately linked to the item. 
3218
3219                 if(strlen($item['resource-id'])) {
3220                         q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3221                                 dbesc($item['resource-id']),
3222                                 intval($item['uid'])
3223                         );
3224                         // ignore the result
3225                 }
3226
3227                 // If item is a link to an event, nuke the event record.
3228
3229                 if(intval($item['event-id'])) {
3230                         q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3231                                 intval($item['event-id']),
3232                                 intval($item['uid'])
3233                         );
3234                         // ignore the result
3235                 }
3236
3237                 // clean up item_id and sign meta-data tables
3238
3239                 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3240                         intval($item['id']),
3241                         intval($item['uid'])
3242                 );
3243
3244                 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3245                         intval($item['id']),
3246                         intval($item['uid'])
3247                 );
3248
3249                 // If it's the parent of a comment thread, kill all the kids
3250
3251                 if($item['uri'] == $item['parent-uri']) {
3252                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3253                                 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3254                                 dbesc(datetime_convert()),
3255                                 dbesc(datetime_convert()),
3256                                 dbesc($item['parent-uri']),
3257                                 intval($item['uid'])
3258                         );
3259                         // ignore the result
3260                 }
3261                 else {
3262                         // ensure that last-child is set in case the comment that had it just got wiped.
3263                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3264                                 dbesc(datetime_convert()),
3265                                 dbesc($item['parent-uri']),
3266                                 intval($item['uid'])
3267                         );
3268                         // who is the last child now? 
3269                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d ORDER BY `edited` DESC LIMIT 1",
3270                                 dbesc($item['parent-uri']),
3271                                 intval($item['uid'])
3272                         );
3273                         if(count($r)) {
3274                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3275                                         intval($r[0]['id'])
3276                                 );
3277                         }       
3278                 }
3279                 $drop_id = intval($item['id']);
3280
3281                 // send the notification upstream/downstream as the case may be
3282
3283                 if(! $interactive)
3284                         return $owner;
3285
3286                 proc_run('php',"include/notifier.php","drop","$drop_id");
3287                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3288                 //NOTREACHED
3289         }
3290         else {
3291                 if(! $interactive)
3292                         return 0;
3293                 notice( t('Permission denied.') . EOL);
3294                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3295                 //NOTREACHED
3296         }
3297         
3298 }