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