]> git.mxchange.org Git - friendica.git/blob - include/items.php
missing $submit
[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                         // Edge case. We host a public forum that was originally posted to privately.
818                         // The original author commented, but as this is a comment, the permissions
819                         // weren't fixed up so it will still show the comment as private unless we fix it here. 
820
821                         if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
822                                 $arr['private'] = 0;
823                 }
824                 else {
825
826                         // Allow one to see reply tweets from status.net even when
827                         // we don't have or can't see the original post.
828
829                         if($force_parent) {
830                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
831                                 $parent_id = 0;
832                                 $arr['thr-parent'] = $arr['parent-uri'];
833                                 $arr['parent-uri'] = $arr['uri'];
834                                 $arr['gravity'] = 0;
835                         }
836                         else {
837                                 logger('item_store: item parent was not found - ignoring item');
838                                 return 0;
839                         }
840                         
841                         $parent_deleted = 0;
842                 }
843         }
844
845         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
846                 dbesc($arr['uri']),
847                 intval($arr['uid'])
848         );
849         if($r && count($r)) {
850                 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
851                 return 0;
852         }
853
854         call_hooks('post_remote',$arr);
855
856         if(x($arr,'cancel')) {
857                 logger('item_store: post cancelled by plugin.');
858                 return 0;
859         }
860
861         dbesc_array($arr);
862
863         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
864
865         $r = dbq("INSERT INTO `item` (`" 
866                         . implode("`, `", array_keys($arr)) 
867                         . "`) VALUES ('" 
868                         . implode("', '", array_values($arr)) 
869                         . "')" );
870
871         // find the item we just created
872
873         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
874                 $arr['uri'],           // already dbesc'd
875                 intval($arr['uid'])
876         );
877
878         if(count($r)) {
879                 $current_post = $r[0]['id'];
880                 logger('item_store: created item ' . $current_post);
881         }
882         else {
883                 logger('item_store: could not locate created item');
884                 return 0;
885         }
886         if(count($r) > 1) {
887                 logger('item_store: duplicated post occurred. Removing duplicates.');
888                 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
889                         $arr['uri'],
890                         intval($arr['uid']),
891                         intval($current_post)
892                 );
893         }
894
895         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
896                 $parent_id = $current_post;
897
898         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
899                 $private = 1;
900         else
901                 $private = $arr['private']; 
902
903         // Set parent id - and also make sure to inherit the parent's ACL's.
904
905         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
906                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
907                 intval($parent_id),
908                 dbesc($allow_cid),
909                 dbesc($allow_gid),
910                 dbesc($deny_cid),
911                 dbesc($deny_gid),
912                 intval($private),
913                 intval($parent_deleted),
914                 intval($current_post)
915         );
916
917         $arr['id'] = $current_post;
918         $arr['parent'] = $parent_id;
919         $arr['allow_cid'] = $allow_cid;
920         $arr['allow_gid'] = $allow_gid;
921         $arr['deny_cid'] = $deny_cid;
922         $arr['deny_gid'] = $deny_gid;
923         $arr['private'] = $private;
924         $arr['deleted'] = $parent_deleted;
925         call_hooks('post_remote_end',$arr);
926
927         // update the commented timestamp on the parent
928
929         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
930                 dbesc(datetime_convert()),
931                 dbesc(datetime_convert()),
932                 intval($parent_id)
933         );
934
935         if($dsprsig) {
936                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
937                         intval($current_post),
938                         dbesc($dsprsig->signed_text),
939                         dbesc($dsprsig->signature),
940                         dbesc($dsprsig->signer)
941                 );
942         }
943
944
945         /**
946          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
947          */
948
949         if($arr['last-child']) {
950                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
951                         dbesc($arr['uri']),
952                         intval($arr['uid']),
953                         intval($current_post)
954                 );
955         }
956
957         tag_deliver($arr['uid'],$current_post);
958
959         return $current_post;
960 }
961
962 function get_item_contact($item,$contacts) {
963         if(! count($contacts) || (! is_array($item)))
964                 return false;
965         foreach($contacts as $contact) {
966                 if($contact['id'] == $item['contact-id']) {
967                         return $contact;
968                         break; // NOTREACHED
969                 }
970         }
971         return false;
972 }
973
974
975 function tag_deliver($uid,$item_id) {
976
977         // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
978
979         $a = get_app();
980
981         $mention = false;
982
983         $u = q("select * from user where uid = %d limit 1",
984                 intval($uid)
985         );
986         if(! count($u))
987                 return;
988
989         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
990         $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
991
992
993         $i = q("select * from item where id = %d and uid = %d limit 1",
994                 intval($item_id),
995                 intval($uid)
996         );
997         if(! count($i))
998                 return;
999
1000         $item = $i[0];
1001
1002         $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1003
1004         // Diaspora uses their own hardwired link URL in @-tags
1005         // instead of the one we supply with webfinger
1006
1007         $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1008
1009         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1010         if($cnt) {
1011                 foreach($matches as $mtch) {
1012                         if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1013                                 $mention = true;
1014                                 logger('tag_deliver: mention found: ' . $mtch[2]);
1015                         }
1016                 }
1017         }
1018
1019         if(! $mention)
1020                 return;
1021
1022         // send a notification
1023
1024         require_once('include/enotify.php');
1025         notification(array(
1026                 'type'         => NOTIFY_TAGSELF,
1027                 'notify_flags' => $u[0]['notify-flags'],
1028                 'language'     => $u[0]['language'],
1029                 'to_name'      => $u[0]['username'],
1030                 'to_email'     => $u[0]['email'],
1031                 'uid'          => $u[0]['uid'],
1032                 'item'         => $item,
1033                 'link'         => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1034                 'source_name'  => $item['author-name'],
1035                 'source_link'  => $item['author-link'],
1036                 'source_photo' => $item['author-avatar'],
1037                 'verb'         => ACTIVITY_TAG,
1038                 'otype'        => 'item'
1039         ));
1040
1041         if((! $community_page) && (! $prvgroup))
1042                 return;
1043
1044
1045         // tgroup delivery - setup a second delivery chain
1046         // prevent delivery looping - only proceed
1047         // if the message originated elsewhere and is a top-level post
1048
1049         if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1050                 return;
1051
1052         // now change this copy of the post to a forum head message and deliver to all the tgroup members
1053
1054
1055         $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1056                 intval($u[0]['uid'])
1057         );
1058         if(! count($c))
1059                 return;
1060
1061         // also reset all the privacy bits to the forum default permissions
1062
1063         $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1064
1065         $forum_mode = (($prvgroup) ? 2 : 1);
1066
1067         q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s', 
1068                 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'  where id = %d limit 1",
1069                 intval($forum_mode),
1070                 dbesc($c[0]['name']),
1071                 dbesc($c[0]['url']),
1072                 dbesc($c[0]['thumb']),
1073                 intval($private),
1074                 dbesc($u[0]['allow_cid']),
1075                 dbesc($u[0]['allow_gid']),
1076                 dbesc($u[0]['deny_cid']),
1077                 dbesc($u[0]['deny_gid']),
1078                 intval($item_id)
1079         );
1080
1081         proc_run('php','include/notifier.php','tgroup',$item_id);                       
1082
1083 }
1084
1085
1086
1087
1088
1089
1090 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1091
1092         $a = get_app();
1093
1094         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1095
1096         if($contact['duplex'] && $contact['dfrn-id'])
1097                 $idtosend = '0:' . $orig_id;
1098         if($contact['duplex'] && $contact['issued-id'])
1099                 $idtosend = '1:' . $orig_id;            
1100
1101         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1102
1103         $rino_enable = get_config('system','rino_encrypt');
1104
1105         if(! $rino_enable)
1106                 $rino = 0;
1107
1108         $ssl_val = intval(get_config('system','ssl_policy'));
1109         $ssl_policy = '';
1110
1111         switch($ssl_val){
1112                 case SSL_POLICY_FULL:
1113                         $ssl_policy = 'full';
1114                         break;
1115                 case SSL_POLICY_SELFSIGN:
1116                         $ssl_policy = 'self';
1117                         break;                  
1118                 case SSL_POLICY_NONE:
1119                 default:
1120                         $ssl_policy = 'none';
1121                         break;
1122         }
1123
1124         $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1125
1126         logger('dfrn_deliver: ' . $url);
1127
1128         $xml = fetch_url($url);
1129
1130         $curl_stat = $a->get_curl_code();
1131         if(! $curl_stat)
1132                 return(-1); // timed out
1133
1134         logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1135
1136         if(! $xml)
1137                 return 3;
1138
1139         if(strpos($xml,'<?xml') === false) {
1140                 logger('dfrn_deliver: no valid XML returned');
1141                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1142                 return 3;
1143         }
1144
1145         $res = parse_xml_string($xml);
1146
1147         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1148                 return (($res->status) ? $res->status : 3);
1149
1150         $postvars     = array();
1151         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1152         $challenge    = hex2bin((string) $res->challenge);
1153         $perm         = (($res->perm) ? $res->perm : null);
1154         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1155         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1156         $page         = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1157
1158         if($owner['page-flags'] == PAGE_PRVGROUP)
1159                 $page = 2;
1160
1161         $final_dfrn_id = '';
1162
1163         if($perm) {
1164                 if((($perm == 'rw') && (! intval($contact['writable']))) 
1165                 || (($perm == 'r') && (intval($contact['writable'])))) {
1166                         q("update contact set writable = %d where id = %d limit 1",
1167                                 intval(($perm == 'rw') ? 1 : 0),
1168                                 intval($contact['id'])
1169                         );
1170                         $contact['writable'] = (string) 1 - intval($contact['writable']);                       
1171                 }
1172         }
1173
1174         if(($contact['duplex'] && strlen($contact['pubkey'])) 
1175                 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1176                 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1177                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1178                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1179         }
1180         else {
1181                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1182                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1183         }
1184
1185         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1186
1187         if(strpos($final_dfrn_id,':') == 1)
1188                 $final_dfrn_id = substr($final_dfrn_id,2);
1189
1190         if($final_dfrn_id != $orig_id) {
1191                 logger('dfrn_deliver: wrong dfrn_id.');
1192                 // did not decode properly - cannot trust this site 
1193                 return 3;
1194         }
1195
1196         $postvars['dfrn_id']      = $idtosend;
1197         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1198         if($dissolve)
1199                 $postvars['dissolve'] = '1';
1200
1201
1202         if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1203                 $postvars['data'] = $atom;
1204                 $postvars['perm'] = 'rw';
1205         }
1206         else {
1207                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1208                 $postvars['perm'] = 'r';
1209         }
1210
1211         $postvars['ssl_policy'] = $ssl_policy;
1212
1213         if($page)
1214                 $postvars['page'] = $page;
1215         
1216         if($rino && $rino_allowed && (! $dissolve)) {
1217                 $key = substr(random_string(),0,16);
1218                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1219                 $postvars['data'] = $data;
1220                 logger('rino: sent key = ' . $key, LOGGER_DEBUG);       
1221
1222
1223                 if($dfrn_version >= 2.1) {      
1224                         if(($contact['duplex'] && strlen($contact['pubkey'])) 
1225                                 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1226                                 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1227
1228                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1229                         }
1230                         else {
1231                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1232                         }
1233                 }
1234                 else {
1235                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1236                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1237                         }
1238                         else {
1239                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1240                         }
1241                 }
1242
1243                 logger('md5 rawkey ' . md5($postvars['key']));
1244
1245                 $postvars['key'] = bin2hex($postvars['key']);
1246         }
1247
1248         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1249
1250         $xml = post_url($contact['notify'],$postvars);
1251
1252         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1253
1254         $curl_stat = $a->get_curl_code();
1255         if((! $curl_stat) || (! strlen($xml)))
1256                 return(-1); // timed out
1257
1258         if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1259                 return(-1);
1260
1261         if(strpos($xml,'<?xml') === false) {
1262                 logger('dfrn_deliver: phase 2: no valid XML returned');
1263                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1264                 return 3;
1265         }
1266
1267         $res = parse_xml_string($xml);
1268
1269         return $res->status; 
1270 }
1271
1272
1273 /**
1274  *
1275  * consume_feed - process atom feed and update anything/everything we might need to update
1276  *
1277  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1278  *
1279  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1280  *             It is this person's stuff that is going to be updated.
1281  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1282  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
1283  *             have a contact record.
1284  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
1285  *        might not) try and subscribe to it.
1286  * $datedir sorts in reverse order
1287  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been 
1288  *      imported prior to its children being seen in the stream unless we are certain
1289  *      of how the feed is arranged/ordered.
1290  * With $pass = 1, we only pull parent items out of the stream.
1291  * With $pass = 2, we only pull children (comments/likes).
1292  *
1293  * So running this twice, first with pass 1 and then with pass 2 will do the right
1294  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1295  * model where comments can have sub-threads. That would require some massive sorting
1296  * to get all the feed items into a mostly linear ordering, and might still require
1297  * recursion.  
1298  */
1299
1300 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1301
1302         require_once('library/simplepie/simplepie.inc');
1303
1304         if(! strlen($xml)) {
1305                 logger('consume_feed: empty input');
1306                 return;
1307         }
1308                 
1309         $feed = new SimplePie();
1310         $feed->set_raw_data($xml);
1311         if($datedir)
1312                 $feed->enable_order_by_date(true);
1313         else
1314                 $feed->enable_order_by_date(false);
1315         $feed->init();
1316
1317         if($feed->error())
1318                 logger('consume_feed: Error parsing XML: ' . $feed->error());
1319
1320         $permalink = $feed->get_permalink();
1321
1322         // Check at the feed level for updated contact name and/or photo
1323
1324         $name_updated  = '';
1325         $new_name = '';
1326         $photo_timestamp = '';
1327         $photo_url = '';
1328         $birthday = '';
1329
1330         $hubs = $feed->get_links('hub');
1331         logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1332
1333         if(count($hubs))
1334                 $hub = implode(',', $hubs);
1335
1336         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1337         if(! $rawtags)
1338                 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1339         if($rawtags) {
1340                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1341                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1342                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1343                         $new_name = $elems['name'][0]['data'];
1344                 } 
1345                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1346                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1347                         $photo_url = $elems['link'][0]['attribs']['']['href'];
1348                 }
1349
1350                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1351                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1352                 }
1353         }
1354
1355         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1356                 logger('consume_feed: Updating photo for ' . $contact['name']);
1357                 require_once("Photo.php");
1358                 $photo_failure = false;
1359                 $have_photo = false;
1360
1361                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1362                         intval($contact['id']),
1363                         intval($contact['uid'])
1364                 );
1365                 if(count($r)) {
1366                         $resource_id = $r[0]['resource-id'];
1367                         $have_photo = true;
1368                 }
1369                 else {
1370                         $resource_id = photo_new_resource();
1371                 }
1372                         
1373                 $img_str = fetch_url($photo_url,true);
1374                 // guess mimetype from headers or filename
1375                 $type = guess_image_type($photo_url,true);
1376                 
1377                 
1378                 $img = new Photo($img_str, $type);
1379                 if($img->is_valid()) {
1380                         if($have_photo) {
1381                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1382                                         dbesc($resource_id),
1383                                         intval($contact['id']),
1384                                         intval($contact['uid'])
1385                                 );
1386                         }
1387                                 
1388                         $img->scaleImageSquare(175);
1389                                 
1390                         $hash = $resource_id;
1391                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1392                                 
1393                         $img->scaleImage(80);
1394                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1395
1396                         $img->scaleImage(48);
1397                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1398
1399                         $a = get_app();
1400
1401                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
1402                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1403                                 dbesc(datetime_convert()),
1404                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1405                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1406                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1407                                 intval($contact['uid']),
1408                                 intval($contact['id'])
1409                         );
1410                 }
1411         }
1412
1413         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1414                 $r = q("select * from contact where uid = %d and id = %d limit 1",
1415                         intval($contact['uid']),
1416                         intval($contact['id'])
1417                 );
1418
1419                 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1420                         dbesc(notags(trim($new_name))),
1421                         dbesc(datetime_convert()),
1422                         intval($contact['uid']),
1423                         intval($contact['id'])
1424                 );
1425
1426                 // do our best to update the name on content items
1427
1428                 if(count($r)) {
1429                         q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1430                                 dbesc(notags(trim($new_name))),
1431                                 dbesc($r[0]['name']),
1432                                 dbesc($r[0]['url']),
1433                                 intval($contact['uid'])
1434                         );
1435                 }
1436         }
1437
1438         if(strlen($birthday)) {
1439                 if(substr($birthday,0,4) != $contact['bdyear']) {
1440                         logger('consume_feed: updating birthday: ' . $birthday);
1441
1442                         /**
1443                          *
1444                          * Add new birthday event for this person
1445                          *
1446                          * $bdtext is just a readable placeholder in case the event is shared
1447                          * with others. We will replace it during presentation to our $importer
1448                          * to contain a sparkle link and perhaps a photo. 
1449                          *
1450                          */
1451                          
1452                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1453
1454
1455                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1456                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1457                                 intval($contact['uid']),
1458                                 intval($contact['id']),
1459                                 dbesc(datetime_convert()),
1460                                 dbesc(datetime_convert()),
1461                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1462                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1463                                 dbesc($bdtext),
1464                                 dbesc('birthday')
1465                         );
1466                         
1467
1468                         // update bdyear
1469
1470                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1471                                 dbesc(substr($birthday,0,4)),
1472                                 intval($contact['uid']),
1473                                 intval($contact['id'])
1474                         );
1475
1476                         // This function is called twice without reloading the contact
1477                         // Make sure we only create one event. This is why &$contact 
1478                         // is a reference var in this function
1479
1480                         $contact['bdyear'] = substr($birthday,0,4);
1481                 }
1482
1483         }
1484
1485         $community_page = 0;
1486         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1487         if($rawtags) {
1488                 $community_page = intval($rawtags[0]['data']);
1489         }
1490         if(is_array($contact) && intval($contact['forum']) != $community_page) {
1491                 q("update contact set forum = %d where id = %d limit 1",
1492                         intval($community_page),
1493                         intval($contact['id'])
1494                 );
1495                 $contact['forum'] = (string) $community_page;
1496         }
1497
1498
1499         // process any deleted entries
1500
1501         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1502         if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1503                 foreach($del_entries as $dentry) {
1504                         $deleted = false;
1505                         if(isset($dentry['attribs']['']['ref'])) {
1506                                 $uri = $dentry['attribs']['']['ref'];
1507                                 $deleted = true;
1508                                 if(isset($dentry['attribs']['']['when'])) {
1509                                         $when = $dentry['attribs']['']['when'];
1510                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1511                                 }
1512                                 else
1513                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1514                         }
1515                         if($deleted && is_array($contact)) {
1516                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id` 
1517                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1518                                         dbesc($uri),
1519                                         intval($importer['uid']),
1520                                         intval($contact['id'])
1521                                 );
1522                                 if(count($r)) {
1523                                         $item = $r[0];
1524
1525                                         if(! $item['deleted'])
1526                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1527
1528                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1529                                                 $xo = parse_xml_string($item['object'],false);
1530                                                 $xt = parse_xml_string($item['target'],false);
1531                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
1532                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1533                                                                 dbesc($xt->id),
1534                                                                 intval($importer['importer_uid'])
1535                                                         );
1536                                                         if(count($i)) {
1537
1538                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
1539
1540                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1541                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1542                                                                 $author_copy = (($item['origin']) ? true : false);
1543
1544                                                                 if($owner_remove && $author_copy)
1545                                                                         continue;
1546                                                                 if($author_remove || $owner_remove) {
1547                                                                         $tags = explode(',',$i[0]['tag']);
1548                                                                         $newtags = array();
1549                                                                         if(count($tags)) {
1550                                                                                 foreach($tags as $tag)
1551                                                                                         if(trim($tag) !== trim($xo->body))
1552                                                                                                 $newtags[] = trim($tag);
1553                                                                         }
1554                                                                         q("update item set tag = '%s' where id = %d limit 1",
1555                                                                                 dbesc(implode(',',$newtags)),
1556                                                                                 intval($i[0]['id'])
1557                                                                         );
1558                                                                 }
1559                                                         }
1560                                                 }
1561                                         }
1562
1563                                         if($item['uri'] == $item['parent-uri']) {
1564                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1565                                                         `body` = '', `title` = ''
1566                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1567                                                         dbesc($when),
1568                                                         dbesc(datetime_convert()),
1569                                                         dbesc($item['uri']),
1570                                                         intval($importer['uid'])
1571                                                 );
1572                                         }
1573                                         else {
1574                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1575                                                         `body` = '', `title` = '' 
1576                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1577                                                         dbesc($when),
1578                                                         dbesc(datetime_convert()),
1579                                                         dbesc($uri),
1580                                                         intval($importer['uid'])
1581                                                 );
1582                                                 if($item['last-child']) {
1583                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1584                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1585                                                                 dbesc(datetime_convert()),
1586                                                                 dbesc($item['parent-uri']),
1587                                                                 intval($item['uid'])
1588                                                         );
1589                                                         // who is the last child now? 
1590                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d 
1591                                                                 ORDER BY `created` DESC LIMIT 1",
1592                                                                         dbesc($item['parent-uri']),
1593                                                                         intval($importer['uid'])
1594                                                         );
1595                                                         if(count($r)) {
1596                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1597                                                                         intval($r[0]['id'])
1598                                                                 );
1599                                                         }
1600                                                 }       
1601                                         }
1602                                 }       
1603                         }
1604                 }
1605         }
1606
1607         // Now process the feed
1608
1609         if($feed->get_item_quantity()) {                
1610
1611                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1612
1613         // in inverse date order
1614                 if ($datedir)
1615                         $items = array_reverse($feed->get_items());
1616                 else
1617                         $items = $feed->get_items();
1618
1619
1620                 foreach($items as $item) {
1621
1622                         $is_reply = false;              
1623                         $item_id = $item->get_id();
1624                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1625                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1626                                 $is_reply = true;
1627                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1628                         }
1629
1630                         if(($is_reply) && is_array($contact)) {
1631
1632                                 if($pass == 1)
1633                                         continue;
1634
1635                                 // Have we seen it? If not, import it.
1636         
1637                                 $item_id  = $item->get_id();
1638                                 $datarray = get_atom_elements($feed,$item);
1639
1640
1641                                 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1642                                         $datarray['author-name'] = $contact['name'];
1643                                 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1644                                         $datarray['author-link'] = $contact['url'];
1645                                 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1646                                         $datarray['author-avatar'] = $contact['thumb'];
1647
1648                                 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1649                                         logger('consume_feed: no author information! ' . print_r($datarray,true));
1650                                         continue;
1651                                 }
1652
1653                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1654                                         dbesc($item_id),
1655                                         intval($importer['uid'])
1656                                 );
1657
1658                                 // Update content if 'updated' changes
1659
1660                                 if(count($r)) {
1661                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1662
1663                                                 // do not accept (ignore) an earlier edit than one we currently have.
1664                                                 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1665                                                         continue;
1666
1667                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1668                                                         dbesc($datarray['title']),
1669                                                         dbesc($datarray['body']),
1670                                                         dbesc($datarray['tag']),
1671                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1672                                                         dbesc($item_id),
1673                                                         intval($importer['uid'])
1674                                                 );
1675                                         }
1676
1677                                         // update last-child if it changes
1678
1679                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1680                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1681                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1682                                                         dbesc(datetime_convert()),
1683                                                         dbesc($parent_uri),
1684                                                         intval($importer['uid'])
1685                                                 );
1686                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1687                                                         intval($allow[0]['data']),
1688                                                         dbesc(datetime_convert()),
1689                                                         dbesc($item_id),
1690                                                         intval($importer['uid'])
1691                                                 );
1692                                         }
1693                                         continue;
1694                                 }
1695
1696                                 $force_parent = false;
1697                                 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1698                                         if($contact['network'] === NETWORK_OSTATUS)
1699                                                 $force_parent = true;
1700                                         if(strlen($datarray['title']))
1701                                                 unset($datarray['title']);
1702                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1703                                                 dbesc(datetime_convert()),
1704                                                 dbesc($parent_uri),
1705                                                 intval($importer['uid'])
1706                                         );
1707                                         $datarray['last-child'] = 1;
1708                                 }
1709
1710                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1711                                         // one way feed - no remote comment ability
1712                                         $datarray['last-child'] = 0;
1713                                 }
1714                                 $datarray['parent-uri'] = $parent_uri;
1715                                 $datarray['uid'] = $importer['uid'];
1716                                 $datarray['contact-id'] = $contact['id'];
1717                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1718                                         $datarray['type'] = 'activity';
1719                                         $datarray['gravity'] = GRAVITY_LIKE;
1720                                         // only one like or dislike per person
1721                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
1722                                                 intval($datarray['uid']),
1723                                                 intval($datarray['contact-id']),
1724                                                 dbesc($datarray['verb'])
1725                                         );
1726                                         if($r && count($r))
1727                                                 continue; 
1728                                 }
1729
1730                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1731                                         $xo = parse_xml_string($datarray['object'],false);
1732                                         $xt = parse_xml_string($datarray['target'],false);
1733
1734                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
1735                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1736                                                         dbesc($xt->id),
1737                                                         intval($importer['importer_uid'])
1738                                                 );
1739                                                 if(! count($r))
1740                                                         continue;
1741
1742                                                 // extract tag, if not duplicate, add to parent item
1743                                                 if($xo->id && $xo->content) {
1744                                                         $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1745                                                         if(! (stristr($r[0]['tag'],$newtag))) {
1746                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1747                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1748                                                                         intval($r[0]['id'])
1749                                                                 );
1750                                                         }
1751                                                 }
1752                                         }
1753                                 }
1754
1755                                 $r = item_store($datarray,$force_parent);
1756                                 continue;
1757                         }
1758
1759                         else {
1760
1761                                 // Head post of a conversation. Have we seen it? If not, import it.
1762
1763                                 $item_id  = $item->get_id();
1764
1765                                 $datarray = get_atom_elements($feed,$item);
1766
1767                                 if(is_array($contact)) {
1768                                         if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1769                                                 $datarray['author-name'] = $contact['name'];
1770                                         if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1771                                                 $datarray['author-link'] = $contact['url'];
1772                                         if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1773                                                 $datarray['author-avatar'] = $contact['thumb'];
1774                                 }
1775
1776                                 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1777                                         logger('consume_feed: no author information! ' . print_r($datarray,true));
1778                                         continue;
1779                                 }
1780
1781                                 // special handling for events
1782
1783                                 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1784                                         $ev = bbtoevent($datarray['body']);
1785                                         if(x($ev,'desc') && x($ev,'start')) {
1786                                                 $ev['uid'] = $importer['uid'];
1787                                                 $ev['uri'] = $item_id;
1788                                                 $ev['edited'] = $datarray['edited'];
1789                                                 $ev['private'] = $datarray['private'];
1790
1791                                                 if(is_array($contact))
1792                                                         $ev['cid'] = $contact['id'];
1793                                                 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1794                                                         dbesc($item_id),
1795                                                         intval($importer['uid'])
1796                                                 );
1797                                                 if(count($r))
1798                                                         $ev['id'] = $r[0]['id'];
1799                                                 $xyz = event_store($ev);
1800                                                 continue;
1801                                         }
1802                                 }
1803
1804                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1805                                         dbesc($item_id),
1806                                         intval($importer['uid'])
1807                                 );
1808
1809                                 // Update content if 'updated' changes
1810
1811                                 if(count($r)) {
1812                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1813
1814                                                 // do not accept (ignore) an earlier edit than one we currently have.
1815                                                 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1816                                                         continue;
1817
1818                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1819                                                         dbesc($datarray['title']),
1820                                                         dbesc($datarray['body']),
1821                                                         dbesc($datarray['tag']),
1822                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1823                                                         dbesc($item_id),
1824                                                         intval($importer['uid'])
1825                                                 );
1826                                         }
1827
1828                                         // update last-child if it changes
1829
1830                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1831                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1832                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1833                                                         intval($allow[0]['data']),
1834                                                         dbesc(datetime_convert()),
1835                                                         dbesc($item_id),
1836                                                         intval($importer['uid'])
1837                                                 );
1838                                         }
1839                                         continue;
1840                                 }
1841
1842                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1843                                         logger('consume-feed: New follower');
1844                                         new_follower($importer,$contact,$datarray,$item);
1845                                         return;
1846                                 }
1847                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1848                                         lose_follower($importer,$contact,$datarray,$item);
1849                                         return;
1850                                 }
1851
1852                                 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1853                                         logger('consume-feed: New friend request');
1854                                         new_follower($importer,$contact,$datarray,$item,true);
1855                                         return;
1856                                 }
1857                                 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND))  {
1858                                         lose_sharer($importer,$contact,$datarray,$item);
1859                                         return;
1860                                 }
1861
1862
1863                                 if(! is_array($contact))
1864                                         return;
1865
1866                                 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1867                                         if(strlen($datarray['title']))
1868                                                 unset($datarray['title']);
1869                                         $datarray['last-child'] = 1;
1870                                 }
1871
1872                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1873                                                 // one way feed - no remote comment ability
1874                                                 $datarray['last-child'] = 0;
1875                                 }
1876                                 if($contact['network'] === NETWORK_FEED)
1877                                         $datarray['private'] = 1;
1878
1879                                 // This is my contact on another system, but it's really me.
1880                                 // Turn this into a wall post.
1881
1882                                 if($contact['remote_self'])
1883                                         $datarray['wall'] = 1;
1884
1885                                 $datarray['parent-uri'] = $item_id;
1886                                 $datarray['uid'] = $importer['uid'];
1887                                 $datarray['contact-id'] = $contact['id'];
1888
1889                                 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1890                                         // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery, 
1891                                         // but otherwise there's a possible data mixup on the sender's system.
1892                                         // the tgroup delivery code called from item_store will correct it if it's a forum,
1893                                         // but we're going to unconditionally correct it here so that the post will always be owned by our contact. 
1894                                         logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
1895                                         $datarray['owner-name']   = $contact['name'];
1896                                         $datarray['owner-link']   = $contact['url'];
1897                                         $datarray['owner-avatar'] = $contact['thumb'];
1898                                 }
1899
1900                                 $r = item_store($datarray);
1901                                 continue;
1902
1903                         }
1904                 }
1905         }
1906 }
1907
1908 function local_delivery($importer,$data) {
1909
1910         $a = get_app();
1911
1912         if($importer['readonly']) {
1913                 // We aren't receiving stuff from this person. But we will quietly ignore them
1914                 // rather than a blatant "go away" message.
1915                 logger('local_delivery: ignoring');
1916                 return 0;
1917                 //NOTREACHED
1918         }
1919
1920         // Consume notification feed. This may differ from consuming a public feed in several ways
1921         // - might contain email or friend suggestions
1922         // - might contain remote followup to our message
1923         //              - in which case we need to accept it and then notify other conversants
1924         // - we may need to send various email notifications
1925
1926         $feed = new SimplePie();
1927         $feed->set_raw_data($data);
1928         $feed->enable_order_by_date(false);
1929         $feed->init();
1930
1931 /*
1932         // Currently unsupported - needs a lot of work
1933         $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1934         if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1935                 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1936                 $newloc = array();
1937                 $newloc['uid'] = $importer['importer_uid'];
1938                 $newloc['cid'] = $importer['id'];
1939                 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1940                 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1941                 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1942                 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1943                 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1944                 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1945                 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1946                 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1947                 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1948                 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1949                 
1950                 // TODO
1951                 // merge with current record, current contents have priority
1952                 // update record, set url-updated
1953                 // update profile photos
1954                 // schedule a scan?
1955
1956         }
1957 */
1958
1959         // handle friend suggestion notification
1960
1961         $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1962         if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1963                 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1964                 $fsugg = array();
1965                 $fsugg['uid'] = $importer['importer_uid'];
1966                 $fsugg['cid'] = $importer['id'];
1967                 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1968                 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1969                 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1970                 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1971                 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1972
1973                 // Does our member already have a friend matching this description?
1974
1975                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1976                         dbesc($fsugg['name']),
1977                         dbesc(normalise_link($fsugg['url'])),
1978                         intval($fsugg['uid'])
1979                 );
1980                 if(count($r))
1981                         return 0;
1982
1983                 // Do we already have an fcontact record for this person?
1984
1985                 $fid = 0;
1986                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1987                         dbesc($fsugg['url']),
1988                         dbesc($fsugg['name']),
1989                         dbesc($fsugg['request'])
1990                 );
1991                 if(count($r)) {
1992                         $fid = $r[0]['id'];
1993
1994                         // OK, we do. Do we already have an introduction for this person ?
1995                         $r = q("select id from intro where uid = %d and fid = %d limit 1",
1996                                 intval($fsugg['uid']),
1997                                 intval($fid)
1998                         );
1999                         if(count($r))
2000                                 return 0;
2001                 }
2002                 if(! $fid)
2003                         $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2004                         dbesc($fsugg['name']),
2005                         dbesc($fsugg['url']),
2006                         dbesc($fsugg['photo']),
2007                         dbesc($fsugg['request'])
2008                 );
2009                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2010                         dbesc($fsugg['url']),
2011                         dbesc($fsugg['name']),
2012                         dbesc($fsugg['request'])
2013                 );
2014                 if(count($r)) {
2015                         $fid = $r[0]['id'];
2016                 }
2017                 // database record did not get created. Quietly give up.
2018                 else
2019                         return 0;
2020
2021
2022                 $hash = random_string();
2023  
2024                 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2025                         VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2026                         intval($fsugg['uid']),
2027                         intval($fid),
2028                         intval($fsugg['cid']),
2029                         dbesc($fsugg['body']),
2030                         dbesc($hash),
2031                         dbesc(datetime_convert()),
2032                         intval(0)
2033                 );
2034
2035                 notification(array(
2036                         'type'         => NOTIFY_SUGGEST,
2037                         'notify_flags' => $importer['notify-flags'],
2038                         'language'     => $importer['language'],
2039                         'to_name'      => $importer['username'],
2040                         'to_email'     => $importer['email'],
2041                         'uid'          => $importer['importer_uid'],
2042                         'item'         => $fsugg,
2043                         'link'         => $a->get_baseurl() . '/notifications/intros',
2044                         'source_name'  => $importer['name'],
2045                         'source_link'  => $importer['url'],
2046                         'source_photo' => $importer['photo'],
2047                         'verb'         => ACTIVITY_REQ_FRIEND,
2048                         'otype'        => 'intro'
2049                 ));
2050
2051                 return 0;
2052         }
2053
2054         $ismail = false;
2055
2056         $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2057         if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2058
2059                 logger('local_delivery: private message received');
2060
2061                 $ismail = true;
2062                 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2063
2064                 $msg = array();
2065                 $msg['uid'] = $importer['importer_uid'];
2066                 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2067                 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2068                 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2069                 $msg['contact-id'] = $importer['id'];
2070                 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2071                 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2072                 $msg['seen'] = 0;
2073                 $msg['replied'] = 0;
2074                 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2075                 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2076                 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2077                 
2078                 dbesc_array($msg);
2079
2080                 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) 
2081                         . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2082
2083                 // send notifications.
2084
2085                 require_once('include/enotify.php');
2086
2087                 $notif_params = array(
2088                         'type' => NOTIFY_MAIL,
2089                         'notify_flags' => $importer['notify-flags'],
2090                         'language' => $importer['language'],
2091                         'to_name' => $importer['username'],
2092                         'to_email' => $importer['email'],
2093                         'uid' => $importer['importer_uid'],
2094                         'item' => $msg,
2095                         'source_name' => $msg['from-name'],
2096                         'source_link' => $importer['url'],
2097                         'source_photo' => $importer['thumb'],
2098                         'verb' => ACTIVITY_POST,
2099                         'otype' => 'mail'
2100                 );
2101                         
2102                 notification($notif_params);
2103                 return 0;
2104
2105                 // NOTREACHED
2106         }       
2107
2108         $community_page = 0;
2109         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2110         if($rawtags) {
2111                 $community_page = intval($rawtags[0]['data']);
2112         }
2113         if(intval($importer['forum']) != $community_page) {
2114                 q("update contact set forum = %d where id = %d limit 1",
2115                         intval($community_page),
2116                         intval($importer['id'])
2117                 );
2118                 $importer['forum'] = (string) $community_page;
2119         }
2120         
2121         logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2122
2123         // process any deleted entries
2124
2125         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2126         if(is_array($del_entries) && count($del_entries)) {
2127                 foreach($del_entries as $dentry) {
2128                         $deleted = false;
2129                         if(isset($dentry['attribs']['']['ref'])) {
2130                                 $uri = $dentry['attribs']['']['ref'];
2131                                 $deleted = true;
2132                                 if(isset($dentry['attribs']['']['when'])) {
2133                                         $when = $dentry['attribs']['']['when'];
2134                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2135                                 }
2136                                 else
2137                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2138                         }
2139                         if($deleted) {
2140
2141                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2142                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2143                                         dbesc($uri),
2144                                         intval($importer['importer_uid']),
2145                                         intval($importer['id'])
2146                                 );
2147
2148                                 if(count($r)) {
2149                                         $item = $r[0];
2150
2151                                         if($item['deleted'])
2152                                                 continue;
2153
2154                                         logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2155
2156                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2157                                                 $xo = parse_xml_string($item['object'],false);
2158                                                 $xt = parse_xml_string($item['target'],false);
2159
2160                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
2161                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2162                                                                 dbesc($xt->id),
2163                                                                 intval($importer['importer_uid'])
2164                                                         );
2165                                                         if(count($i)) {
2166
2167                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2168                                                                 
2169                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2170                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2171                                                                 $author_copy = (($item['origin']) ? true : false); 
2172
2173                                                                 if($owner_remove && $author_copy)
2174                                                                         continue;
2175                                                                 if($author_remove || $owner_remove) {                                                           
2176                                                                         $tags = explode(',',$i[0]['tag']);
2177                                                                         $newtags = array();
2178                                                                         if(count($tags)) {
2179                                                                                 foreach($tags as $tag)
2180                                                                                         if(trim($tag) !== trim($xo->body))
2181                                                                                                 $newtags[] = trim($tag);
2182                                                                         }
2183                                                                         q("update item set tag = '%s' where id = %d limit 1",
2184                                                                                 dbesc(implode(',',$newtags)),
2185                                                                                 intval($i[0]['id'])
2186                                                                         );
2187                                                                 }
2188                                                         }
2189                                                 }
2190                                         }
2191
2192                                         if($item['uri'] == $item['parent-uri']) {
2193                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2194                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
2195                                                         dbesc($when),
2196                                                         dbesc(datetime_convert()),
2197                                                         dbesc($item['uri']),
2198                                                         intval($importer['importer_uid'])
2199                                                 );
2200                                         }
2201                                         else {
2202                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
2203                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2204                                                         dbesc($when),
2205                                                         dbesc(datetime_convert()),
2206                                                         dbesc($uri),
2207                                                         intval($importer['importer_uid'])
2208                                                 );
2209                                                 if($item['last-child']) {
2210                                                         // ensure that last-child is set in case the comment that had it just got wiped.
2211                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2212                                                                 dbesc(datetime_convert()),
2213                                                                 dbesc($item['parent-uri']),
2214                                                                 intval($item['uid'])
2215                                                         );
2216                                                         // who is the last child now? 
2217                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2218                                                                 ORDER BY `created` DESC LIMIT 1",
2219                                                                         dbesc($item['parent-uri']),
2220                                                                         intval($importer['importer_uid'])
2221                                                         );
2222                                                         if(count($r)) {
2223                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2224                                                                         intval($r[0]['id'])
2225                                                                 );
2226                                                         }       
2227                                                 }
2228                                         }       
2229                                 }
2230                         }
2231                 }
2232         }
2233
2234
2235         foreach($feed->get_items() as $item) {
2236
2237                 $is_reply = false;              
2238                 $item_id = $item->get_id();
2239                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2240                 if(isset($rawthread[0]['attribs']['']['ref'])) {
2241                         $is_reply = true;
2242                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
2243                 }
2244
2245                 if($is_reply) {
2246                         $community = false;
2247
2248                         if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2249                                 $sql_extra = '';
2250                                 $community = true;
2251                                 logger('local_delivery: possible community reply');
2252                         }
2253                         else
2254                                 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2255  
2256                         // was the top-level post for this reply written by somebody on this site? 
2257                         // Specifically, the recipient? 
2258
2259                         $is_a_remote_comment = false;
2260
2261                         $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`, 
2262                                 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` 
2263                                 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` 
2264                                 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2265                                 AND `item`.`uid` = %d 
2266                                 $sql_extra
2267                                 LIMIT 1",
2268                                 dbesc($parent_uri),
2269                                 dbesc($parent_uri),
2270                                 intval($importer['importer_uid'])
2271                         );
2272                         if($r && count($r))
2273                                 $is_a_remote_comment = true;                    
2274
2275                         // Does this have the characteristics of a community or private group comment?
2276                         // If it's a reply to a wall post on a community/prvgroup page it's a 
2277                         // valid community comment. Also forum_mode makes it valid for sure. 
2278                         // If neither, it's not.
2279
2280                         if($is_a_remote_comment && $community) {
2281                                 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2282                                         $is_a_remote_comment = false;
2283                                         logger('local_delivery: not a community reply');
2284                                 }
2285                         }
2286
2287                         if($is_a_remote_comment) {
2288                                 logger('local_delivery: received remote comment');
2289                                 $is_like = false;
2290                                 // remote reply to our post. Import and then notify everybody else.
2291
2292                                 $datarray = get_atom_elements($feed,$item);
2293
2294                                 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body`  FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2295                                         dbesc($item_id),
2296                                         intval($importer['importer_uid'])
2297                                 );
2298
2299                                 // Update content if 'updated' changes
2300
2301                                 if(count($r)) {
2302                                         $iid = $r[0]['id'];
2303                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2304                                         
2305                                                 // do not accept (ignore) an earlier edit than one we currently have.
2306                                                 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2307                                                         continue;
2308   
2309                                                 logger('received updated comment' , LOGGER_DEBUG);
2310                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2311                                                         dbesc($datarray['title']),
2312                                                         dbesc($datarray['body']),
2313                                                         dbesc($datarray['tag']),
2314                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2315                                                         dbesc($item_id),
2316                                                         intval($importer['importer_uid'])
2317                                                 );
2318
2319                                                 proc_run('php',"include/notifier.php","comment-import",$iid);
2320
2321                                         }
2322
2323                                         continue;
2324                                 }
2325
2326
2327                                 // TODO: make this next part work against both delivery threads of a community post
2328
2329 //                              if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2330 //                                      logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] ); 
2331                                         // they won't know what to do so don't report an error. Just quietly die.
2332 //                                      return 0;
2333 //                              }                                       
2334
2335                                 // our user with $importer['importer_uid'] is the owner
2336
2337                                 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2338                                         intval($importer['importer_uid'])
2339                                 );
2340
2341
2342                                 $datarray['type'] = 'remote-comment';
2343                                 $datarray['wall'] = 1;
2344                                 $datarray['parent-uri'] = $parent_uri;
2345                                 $datarray['uid'] = $importer['importer_uid'];
2346                                 $datarray['owner-name'] = $own[0]['name'];
2347                                 $datarray['owner-link'] = $own[0]['url'];
2348                                 $datarray['owner-avatar'] = $own[0]['thumb'];
2349                                 $datarray['contact-id'] = $importer['id'];
2350
2351                                 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2352                                         $is_like = true;
2353                                         $datarray['type'] = 'activity';
2354                                         $datarray['gravity'] = GRAVITY_LIKE;
2355                                         $datarray['last-child'] = 0;
2356                                         // only one like or dislike per person
2357                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2358                                                 intval($datarray['uid']),
2359                                                 intval($datarray['contact-id']),
2360                                                 dbesc($datarray['verb'])
2361                                         );
2362                                         if($r && count($r))
2363                                                 continue; 
2364                                 }
2365
2366                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2367                                         
2368                                         $xo = parse_xml_string($datarray['object'],false);
2369                                         $xt = parse_xml_string($datarray['target'],false);
2370
2371                                         if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2372
2373                                                 // fetch the parent item
2374
2375                                                 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2376                                                         dbesc($xt->id),
2377                                                         intval($importer['importer_uid'])
2378                                                 );
2379                                                 if(! count($tagp))
2380                                                         continue;       
2381
2382                                                 // extract tag, if not duplicate, and this user allows tags, add to parent item                                         
2383
2384                                                 if($xo->id && $xo->content) {
2385                                                         $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2386                                                         if(! (stristr($tagp[0]['tag'],$newtag))) {
2387                                                                 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2388                                                                         intval($importer['importer_uid'])
2389                                                                 );
2390                                                                 if(count($i) && ! intval($i[0]['blocktags'])) {
2391                                                                         q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2392                                                                                 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2393                                                                                 intval($tagp[0]['id']),
2394                                                                                 dbesc(datetime_convert())
2395                                                                         );
2396                                                                 }
2397                                                         }
2398                                                 }                                                                                                       
2399                                         }
2400                                 }
2401
2402 //                              if($community) {
2403 //                                      $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2404 //                                      if(! stristr($datarray['tag'],$newtag)) {
2405 //                                              if(strlen($datarray['tag']))
2406 //                                                      $datarray['tag'] .= ',';
2407 //                                              $datarray['tag'] .= $newtag;
2408 //                                      }
2409 //                              }
2410
2411
2412                                 $posted_id = item_store($datarray);
2413                                 $parent = 0;
2414
2415                                 if($posted_id) {
2416                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2417                                                 intval($posted_id),
2418                                                 intval($importer['importer_uid'])
2419                                         );
2420                                         if(count($r))
2421                                                 $parent = $r[0]['parent'];
2422                         
2423                                         if(! $is_like) {
2424                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2425                                                         dbesc(datetime_convert()),
2426                                                         intval($importer['importer_uid']),
2427                                                         intval($r[0]['parent'])
2428                                                 );
2429
2430                                                 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2431                                                         dbesc(datetime_convert()),
2432                                                         intval($importer['importer_uid']),
2433                                                         intval($posted_id)
2434                                                 );
2435                                         }
2436
2437                                         if($posted_id && $parent) {
2438                                 
2439                                                 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2440                                         
2441                                                 if((! $is_like) && (! $importer['self'])) {
2442
2443                                                         require_once('include/enotify.php');
2444
2445                                                         notification(array(
2446                                                                 'type'         => NOTIFY_COMMENT,
2447                                                                 'notify_flags' => $importer['notify-flags'],
2448                                                                 'language'     => $importer['language'],
2449                                                                 'to_name'      => $importer['username'],
2450                                                                 'to_email'     => $importer['email'],
2451                                                                 'uid'          => $importer['importer_uid'],
2452                                                                 'item'         => $datarray,
2453                                                                 'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2454                                                                 'source_name'  => stripslashes($datarray['author-name']),
2455                                                                 'source_link'  => $datarray['author-link'],
2456                                                                 'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
2457                                                                         ? $importer['thumb'] : $datarray['author-avatar']),
2458                                                                 'verb'         => ACTIVITY_POST,
2459                                                                 'otype'        => 'item',
2460                                                                 'parent'       => $parent,
2461
2462                                                         ));
2463
2464                                                 }
2465                                         }
2466
2467                                         return 0;
2468                                         // NOTREACHED
2469                                 }
2470                         }
2471                         else {
2472
2473                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2474
2475                                 $item_id  = $item->get_id();
2476                                 $datarray = get_atom_elements($feed,$item);
2477
2478                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2479                                         dbesc($item_id),
2480                                         intval($importer['importer_uid'])
2481                                 );
2482
2483                                 // Update content if 'updated' changes
2484
2485                                 if(count($r)) {
2486                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2487
2488                                                 // do not accept (ignore) an earlier edit than one we currently have.
2489                                                 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2490                                                         continue;
2491
2492                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2493                                                         dbesc($datarray['title']),
2494                                                         dbesc($datarray['body']),
2495                                                         dbesc($datarray['tag']),
2496                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2497                                                         dbesc($item_id),
2498                                                         intval($importer['importer_uid'])
2499                                                 );
2500                                         }
2501
2502                                         // update last-child if it changes
2503
2504                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2505                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2506                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2507                                                         dbesc(datetime_convert()),
2508                                                         dbesc($parent_uri),
2509                                                         intval($importer['importer_uid'])
2510                                                 );
2511                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2512                                                         intval($allow[0]['data']),
2513                                                         dbesc(datetime_convert()),
2514                                                         dbesc($item_id),
2515                                                         intval($importer['importer_uid'])
2516                                                 );
2517                                         }
2518                                         continue;
2519                                 }
2520
2521                                 $datarray['parent-uri'] = $parent_uri;
2522                                 $datarray['uid'] = $importer['importer_uid'];
2523                                 $datarray['contact-id'] = $importer['id'];
2524                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2525                                         $datarray['type'] = 'activity';
2526                                         $datarray['gravity'] = GRAVITY_LIKE;
2527                                         // only one like or dislike per person
2528                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2529                                                 intval($datarray['uid']),
2530                                                 intval($datarray['contact-id']),
2531                                                 dbesc($datarray['verb'])
2532                                         );
2533                                         if($r && count($r))
2534                                                 continue; 
2535
2536                                 }
2537
2538                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2539
2540                                         $xo = parse_xml_string($datarray['object'],false);
2541                                         $xt = parse_xml_string($datarray['target'],false);
2542
2543                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
2544                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2545                                                         dbesc($xt->id),
2546                                                         intval($importer['importer_uid'])
2547                                                 );
2548                                                 if(! count($r))
2549                                                         continue;                               
2550
2551                                                 // extract tag, if not duplicate, add to parent item                                            
2552                                                 if($xo->content) {
2553                                                         if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2554                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2555                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2556                                                                         intval($r[0]['id'])
2557                                                                 );
2558                                                         }
2559                                                 }                                                                                                       
2560                                         }
2561                                 }
2562
2563                                 $posted_id = item_store($datarray);
2564
2565                                 // find out if our user is involved in this conversation and wants to be notified.
2566                         
2567                                 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
2568
2569                                         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
2570                                                 dbesc($parent_uri),
2571                                                 intval($importer['importer_uid'])
2572                                         );
2573
2574                                         if(count($myconv)) {
2575                                                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2576
2577                                                 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2578                                                 if(! link_compare($datarray['author-link'],$importer_url)) {
2579
2580                                                         
2581                                                         foreach($myconv as $conv) {
2582
2583                                                                 // now if we find a match, it means we're in this conversation
2584         
2585                                                                 if(! link_compare($conv['author-link'],$importer_url))
2586                                                                         continue;
2587
2588                                                                 require_once('include/enotify.php');
2589                                                                 
2590                                                                 $conv_parent = $conv['parent'];
2591
2592                                                                 notification(array(
2593                                                                         'type'         => NOTIFY_COMMENT,
2594                                                                         'notify_flags' => $importer['notify-flags'],
2595                                                                         'language'     => $importer['language'],
2596                                                                         'to_name'      => $importer['username'],
2597                                                                         'to_email'     => $importer['email'],
2598                                                                         'uid'          => $importer['importer_uid'],
2599                                                                         'item'         => $datarray,
2600                                                                         'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2601                                                                         'source_name'  => stripslashes($datarray['author-name']),
2602                                                                         'source_link'  => $datarray['author-link'],
2603                                                                         'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
2604                                                                                 ? $importer['thumb'] : $datarray['author-avatar']),
2605                                                                         'verb'         => ACTIVITY_POST,
2606                                                                         'otype'        => 'item',
2607                                                                         'parent'       => $conv_parent,
2608
2609                                                                 ));
2610
2611                                                                 // only send one notification
2612                                                                 break;
2613                                                         }
2614                                                 }
2615                                         }
2616                                 }
2617                                 continue;
2618                         }
2619                 }
2620
2621                 else {
2622
2623                         // Head post of a conversation. Have we seen it? If not, import it.
2624
2625
2626                         $item_id  = $item->get_id();
2627                         $datarray = get_atom_elements($feed,$item);
2628
2629                         if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2630                                 $ev = bbtoevent($datarray['body']);
2631                                 if(x($ev,'desc') && x($ev,'start')) {
2632                                         $ev['cid'] = $importer['id'];
2633                                         $ev['uid'] = $importer['uid'];
2634                                         $ev['uri'] = $item_id;
2635                                         $ev['edited'] = $datarray['edited'];
2636                                         $ev['private'] = $datarray['private'];
2637
2638                                         $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2639                                                 dbesc($item_id),
2640                                                 intval($importer['uid'])
2641                                         );
2642                                         if(count($r))
2643                                                 $ev['id'] = $r[0]['id'];
2644                                         $xyz = event_store($ev);
2645                                         continue;
2646                                 }
2647                         }
2648
2649                         $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2650                                 dbesc($item_id),
2651                                 intval($importer['importer_uid'])
2652                         );
2653
2654                         // Update content if 'updated' changes
2655
2656                         if(count($r)) {
2657                                 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2658
2659                                         // do not accept (ignore) an earlier edit than one we currently have.
2660                                         if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2661                                                 continue;
2662
2663                                         $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2664                                                 dbesc($datarray['title']),
2665                                                 dbesc($datarray['body']),
2666                                                 dbesc($datarray['tag']),
2667                                                 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2668                                                 dbesc($item_id),
2669                                                 intval($importer['importer_uid'])
2670                                         );
2671                                 }
2672
2673                                 // update last-child if it changes
2674
2675                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2676                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2677                                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2678                                                 intval($allow[0]['data']),
2679                                                 dbesc(datetime_convert()),
2680                                                 dbesc($item_id),
2681                                                 intval($importer['importer_uid'])
2682                                         );
2683                                 }
2684                                 continue;
2685                         }
2686
2687                         // This is my contact on another system, but it's really me.
2688                         // Turn this into a wall post.
2689
2690                         if($importer['remote_self'])
2691                                 $datarray['wall'] = 1;
2692
2693                         $datarray['parent-uri'] = $item_id;
2694                         $datarray['uid'] = $importer['importer_uid'];
2695                         $datarray['contact-id'] = $importer['id'];
2696
2697                         if(! link_compare($datarray['owner-link'],$contact['url'])) {
2698                                 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery, 
2699                                 // but otherwise there's a possible data mixup on the sender's system.
2700                                 // the tgroup delivery code called from item_store will correct it if it's a forum,
2701                                 // but we're going to unconditionally correct it here so that the post will always be owned by our contact. 
2702                                 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2703                                 $datarray['owner-name']   = $importer['senderName'];
2704                                 $datarray['owner-link']   = $importer['url'];
2705                                 $datarray['owner-avatar'] = $importer['thumb'];
2706                         }
2707
2708                         $r = item_store($datarray);
2709                         continue;
2710                 }
2711         }
2712
2713         return 0;
2714         // NOTREACHED
2715
2716 }
2717
2718
2719 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2720         $url = notags(trim($datarray['author-link']));
2721         $name = notags(trim($datarray['author-name']));
2722         $photo = notags(trim($datarray['author-avatar']));
2723
2724         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2725         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2726                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2727
2728         if(is_array($contact)) {
2729                 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2730                         || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2731                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2732                                 intval(CONTACT_IS_FRIEND),
2733                                 intval($contact['id']),
2734                                 intval($importer['uid'])
2735                         );
2736                 }
2737                 // send email notification to owner?
2738         }
2739         else {
2740         
2741                 // create contact record
2742
2743                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`, 
2744                         `blocked`, `readonly`, `pending`, `writable` )
2745                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2746                         intval($importer['uid']),
2747                         dbesc(datetime_convert()),
2748                         dbesc($url),
2749                         dbesc(normalise_link($url)),
2750                         dbesc($name),
2751                         dbesc($nick),
2752                         dbesc($photo),
2753                         dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2754                         intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2755                 );
2756                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2757                                 intval($importer['uid']),
2758                                 dbesc($url)
2759                 );
2760                 if(count($r))
2761                                 $contact_record = $r[0];
2762
2763                 // create notification  
2764                 $hash = random_string();
2765
2766                 if(is_array($contact_record)) {
2767                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2768                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2769                                 intval($importer['uid']),
2770                                 intval($contact_record['id']),
2771                                 dbesc($hash),
2772                                 dbesc(datetime_convert())
2773                         );
2774                 }
2775                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2776                         intval($importer['uid'])
2777                 );
2778                 $a = get_app();
2779                 if(count($r)) {
2780
2781                         if(intval($r[0]['def_gid'])) {
2782                                 require_once('include/group.php');
2783                                 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
2784                         }
2785
2786                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2787                                 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2788                                 $email = replace_macros($email_tpl, array(
2789                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2790                                         '$url' => $url,
2791                                         '$myname' => $r[0]['username'],
2792                                         '$siteurl' => $a->get_baseurl(),
2793                                         '$sitename' => $a->config['sitename']
2794                                 ));
2795                                 $res = mail($r[0]['email'], 
2796                                         (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2797                                         $email,
2798                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2799                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
2800                                         . 'Content-transfer-encoding: 8bit' );
2801                         
2802                         }
2803                 }
2804         }
2805 }
2806
2807 function lose_follower($importer,$contact,$datarray,$item) {
2808
2809         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2810                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2811                         intval(CONTACT_IS_SHARING),
2812                         intval($contact['id'])
2813                 );
2814         }
2815         else {
2816                 contact_remove($contact['id']);
2817         }
2818 }
2819
2820 function lose_sharer($importer,$contact,$datarray,$item) {
2821
2822         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2823                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2824                         intval(CONTACT_IS_FOLLOWER),
2825                         intval($contact['id'])
2826                 );
2827         }
2828         else {
2829                 contact_remove($contact['id']);
2830         }
2831 }
2832
2833
2834 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2835
2836         $a = get_app();
2837
2838         if(is_array($importer)) {
2839                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2840                         intval($importer['uid'])
2841                 );
2842         }
2843
2844         // Diaspora has different message-ids in feeds than they do 
2845         // through the direct Diaspora protocol. If we try and use
2846         // the feed, we'll get duplicates. So don't.
2847
2848         if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2849                 return;
2850
2851         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2852
2853         // Use a single verify token, even if multiple hubs
2854
2855         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2856
2857         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2858
2859         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
2860
2861         if(! strlen($contact['hub-verify'])) {
2862                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2863                         dbesc($verify_token),
2864                         intval($contact['id'])
2865                 );
2866         }
2867
2868         post_url($url,$params);
2869
2870         logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
2871                         
2872         return;
2873
2874 }
2875
2876
2877 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2878         $o = '';
2879         if(! $tag)
2880                 return $o;
2881         $name = xmlify($name);
2882         $uri = xmlify($uri);
2883         $h = intval($h);
2884         $w = intval($w);
2885         $photo = xmlify($photo);
2886
2887
2888         $o .= "<$tag>\r\n";
2889         $o .= "<name>$name</name>\r\n";
2890         $o .= "<uri>$uri</uri>\r\n";
2891         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2892         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2893
2894         call_hooks('atom_author', $o);
2895
2896         $o .= "</$tag>\r\n";
2897         return $o;
2898 }
2899
2900 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
2901
2902         $a = get_app();
2903
2904         if(! $item['parent'])
2905                 return;
2906
2907         if($item['deleted'])
2908                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2909
2910
2911         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2912                 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
2913         else
2914                 $body = $item['body'];
2915
2916
2917         $o = "\r\n\r\n<entry>\r\n";
2918
2919         if(is_array($author))
2920                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2921         else
2922                 $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']));
2923         if(strlen($item['owner-name']))
2924                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2925
2926         if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2927                 $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";
2928
2929         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2930         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2931         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2932         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2933         $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2934         $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2935         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2936         if($comment)
2937                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2938
2939         if($item['location']) {
2940                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2941                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2942         }
2943
2944         if($item['coord'])
2945                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2946
2947         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2948                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2949
2950         if($item['extid'])
2951                 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2952         if($item['bookmark'])
2953                 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2954
2955         if($item['app'])
2956                 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2957
2958         if($item['guid'])
2959                 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2960
2961         if($item['signed_text']) {
2962                 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2963                 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2964         }
2965
2966         $verb = construct_verb($item);
2967         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2968         $actobj = construct_activity_object($item);
2969         if(strlen($actobj))
2970                 $o .= $actobj;
2971         $actarg = construct_activity_target($item);
2972         if(strlen($actarg))
2973                 $o .= $actarg;
2974
2975         $tags = item_getfeedtags($item);
2976         if(count($tags)) {
2977                 foreach($tags as $t) {
2978                         $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2979                 }
2980         }
2981
2982         $o .= item_getfeedattach($item);
2983
2984         $mentioned = get_mentions($item);
2985         if($mentioned)
2986                 $o .= $mentioned;
2987         
2988         call_hooks('atom_entry', $o);
2989
2990         $o .= '</entry>' . "\r\n";
2991         
2992         return $o;
2993 }
2994
2995 function fix_private_photos($s,$uid, $item = null, $cid = 0) {
2996         $a = get_app();
2997
2998         logger('fix_private_photos', LOGGER_DEBUG);
2999         $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3000
3001         if(preg_match("/\[img(.*?)\](.*?)\[\/img\]/is",$s,$matches)) {
3002                 $image = $matches[2];
3003                 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3004                 if(stristr($image , $site . '/photo/')) {
3005                         $replace = false;
3006                         $i = basename($image);
3007                         $i = str_replace(array('.jpg','.png'),array('',''),$i);
3008                         $x = strpos($i,'-');
3009                         if($x) {
3010                                 $res = substr($i,$x+1);
3011                                 $i = substr($i,0,$x);
3012                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3013                                         dbesc($i),
3014                                         intval($res),
3015                                         intval($uid)
3016                                 );
3017                                 if(count($r)) {
3018
3019                                         // Check to see if we should replace this photo link with an embedded image
3020                                         // 1. No need to do so if the photo is public
3021                                         // 2. If there's a contact-id provided, see if they're in the access list
3022                                         //    for the photo. If so, embed it. 
3023                                         // 3. Otherwise, if we have an item, see if the item permissions match the photo
3024                                         //    permissions, regardless of order but first check to see if they're an exact
3025                                         //    match to save some processing overhead.
3026                                 
3027                                         // Currently we only embed one private photo per message so as not to hit import 
3028                                         // size limits at the receiving end.
3029
3030                                         // To embed multiples, we would need to parse out the embedded photos on message
3031                                         // receipt and limit size based only on the text component. Would also need to
3032                                         // ignore all photos during bbcode translation and item localisation, as these
3033                                         // will hit internal regex backtrace limits.  
3034
3035                                         if(has_permissions($r[0])) {
3036                                                 if($cid) {
3037                                                         $recips = enumerate_permissions($r[0]);
3038                                                         if(in_array($cid, $recips)) {
3039                                                                 $replace = true;        
3040                                                         }
3041                                                 }
3042                                                 elseif($item) {
3043                                                         if(compare_permissions($item,$r[0]))
3044                                                                 $replace = true;
3045                                                 }
3046                                         }
3047                                         if($replace) {
3048                                                 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3049                                                 $s = str_replace($image, 'data:' . $r[0]['type'] . ';base64,' . base64_encode($r[0]['data']), $s);
3050                                                 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
3051                                         }
3052                                 }
3053                         }
3054                 }       
3055         }
3056         return($s);
3057 }
3058
3059
3060 function has_permissions($obj) {
3061         if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3062                 return true;
3063         return false;
3064 }
3065
3066 function compare_permissions($obj1,$obj2) {
3067         // first part is easy. Check that these are exactly the same. 
3068         if(($obj1['allow_cid'] == $obj2['allow_cid'])
3069                 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3070                 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3071                 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3072                 return true;
3073
3074         // This is harder. Parse all the permissions and compare the resulting set.
3075
3076         $recipients1 = enumerate_permissions($obj1);
3077         $recipients2 = enumerate_permissions($obj2);
3078         sort($recipients1);
3079         sort($recipients2);
3080         if($recipients1 == $recipients2)
3081                 return true;
3082         return false;
3083 }
3084
3085 // returns an array of contact-ids that are allowed to see this object
3086
3087 function enumerate_permissions($obj) {
3088         require_once('include/group.php');
3089         $allow_people = expand_acl($obj['allow_cid']);
3090         $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3091         $deny_people  = expand_acl($obj['deny_cid']);
3092         $deny_groups  = expand_groups(expand_acl($obj['deny_gid']));
3093         $recipients   = array_unique(array_merge($allow_people,$allow_groups));
3094         $deny         = array_unique(array_merge($deny_people,$deny_groups));
3095         $recipients   = array_diff($recipients,$deny);
3096         return $recipients;
3097 }
3098
3099 function item_getfeedtags($item) {
3100         $ret = array();
3101         $matches = false;
3102         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3103         if($cnt) {
3104                 for($x = 0; $x < $cnt; $x ++) {
3105                         if($matches[1][$x])
3106                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3107                 }
3108         }
3109         $matches = false; 
3110         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3111         if($cnt) {
3112                 for($x = 0; $x < $cnt; $x ++) {
3113                         if($matches[1][$x])
3114                                 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3115                 }
3116         } 
3117         return $ret;
3118 }
3119
3120 function item_getfeedattach($item) {
3121         $ret = '';
3122         $arr = explode(',',$item['attach']);
3123         if(count($arr)) {
3124                 foreach($arr as $r) {
3125                         $matches = false;
3126                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3127                         if($cnt) {
3128                                 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3129                                 if(intval($matches[2]))
3130                                         $ret .= 'length="' . intval($matches[2]) . '" ';
3131                                 if($matches[4] !== ' ')
3132                                         $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3133                                 $ret .= ' />' . "\r\n";
3134                         }
3135                 }
3136         }
3137         return $ret;
3138 }
3139
3140
3141         
3142 function item_expire($uid,$days) {
3143
3144         if((! $uid) || ($days < 1))
3145                 return;
3146
3147         // $expire_network_only = save your own wall posts
3148         // and just expire conversations started by others
3149
3150         $expire_network_only = get_pconfig($uid,'expire','network_only');
3151         $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3152
3153         $r = q("SELECT * FROM `item` 
3154                 WHERE `uid` = %d 
3155                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
3156                 AND `id` = `parent` 
3157                 $sql_extra
3158                 AND `deleted` = 0",
3159                 intval($uid),
3160                 intval($days)
3161         );
3162
3163         if(! count($r))
3164                 return;
3165
3166         $expire_items = get_pconfig($uid, 'expire','items');
3167         $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3168         
3169         $expire_notes = get_pconfig($uid, 'expire','notes');
3170         $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3171
3172         $expire_starred = get_pconfig($uid, 'expire','starred');
3173         $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3174         
3175         $expire_photos = get_pconfig($uid, 'expire','photos');
3176         $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3177  
3178         logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3179
3180         foreach($r as $item) {
3181
3182                 // don't expire filed items
3183
3184                 if(strpos($item['file'],'[') !== false)
3185                         continue;
3186
3187                 // Only expire posts, not photos and photo comments
3188
3189                 if($expire_photos==0 && strlen($item['resource-id']))
3190                         continue;
3191                 if($expire_starred==0 && intval($item['starred']))
3192                         continue;
3193                 if($expire_notes==0 && $item['type']=='note')
3194                         continue;
3195                 if($expire_items==0 && $item['type']!='note')
3196                         continue;
3197
3198                 drop_item($item['id'],false);
3199         }
3200
3201         proc_run('php',"include/notifier.php","expire","$uid");
3202         
3203 }
3204
3205
3206 function drop_items($items) {
3207         $uid = 0;
3208
3209         if(! local_user() && ! remote_user())
3210                 return;
3211
3212         if(count($items)) {
3213                 foreach($items as $item) {
3214                         $owner = drop_item($item,false);
3215                         if($owner && ! $uid)
3216                                 $uid = $owner;
3217                 }
3218         }
3219
3220         // multiple threads may have been deleted, send an expire notification
3221
3222         if($uid)
3223                 proc_run('php',"include/notifier.php","expire","$uid");
3224 }
3225
3226
3227 function drop_item($id,$interactive = true) {
3228
3229         $a = get_app();
3230
3231         // locate item to be deleted
3232
3233         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3234                 intval($id)
3235         );
3236
3237         if(! count($r)) {
3238                 if(! $interactive)
3239                         return 0;
3240                 notice( t('Item not found.') . EOL);
3241                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3242         }
3243
3244         $item = $r[0];
3245
3246         $owner = $item['uid'];
3247
3248         // check if logged in user is either the author or owner of this item
3249
3250         if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3251
3252                 // delete the item
3253
3254                 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3255                         dbesc(datetime_convert()),
3256                         dbesc(datetime_convert()),
3257                         intval($item['id'])
3258                 );
3259
3260                 // clean up categories and tags so they don't end up as orphans
3261
3262                 $matches = false;
3263                 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3264                 if($cnt) {
3265                         foreach($matches as $mtch) {
3266                                 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3267                         }
3268                 }
3269
3270                 $matches = false;
3271
3272                 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3273                 if($cnt) {
3274                         foreach($matches as $mtch) {
3275                                 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3276                         }
3277                 }
3278
3279                 // If item is a link to a photo resource, nuke all the associated photos 
3280                 // (visitors will not have photo resources)
3281                 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3282                 // generate a resource-id and therefore aren't intimately linked to the item. 
3283
3284                 if(strlen($item['resource-id'])) {
3285                         q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3286                                 dbesc($item['resource-id']),
3287                                 intval($item['uid'])
3288                         );
3289                         // ignore the result
3290                 }
3291
3292                 // If item is a link to an event, nuke the event record.
3293
3294                 if(intval($item['event-id'])) {
3295                         q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3296                                 intval($item['event-id']),
3297                                 intval($item['uid'])
3298                         );
3299                         // ignore the result
3300                 }
3301
3302                 // clean up item_id and sign meta-data tables
3303
3304                 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3305                         intval($item['id']),
3306                         intval($item['uid'])
3307                 );
3308
3309                 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3310                         intval($item['id']),
3311                         intval($item['uid'])
3312                 );
3313
3314                 // If it's the parent of a comment thread, kill all the kids
3315
3316                 if($item['uri'] == $item['parent-uri']) {
3317                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3318                                 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3319                                 dbesc(datetime_convert()),
3320                                 dbesc(datetime_convert()),
3321                                 dbesc($item['parent-uri']),
3322                                 intval($item['uid'])
3323                         );
3324                         // ignore the result
3325                 }
3326                 else {
3327                         // ensure that last-child is set in case the comment that had it just got wiped.
3328                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3329                                 dbesc(datetime_convert()),
3330                                 dbesc($item['parent-uri']),
3331                                 intval($item['uid'])
3332                         );
3333                         // who is the last child now? 
3334                         $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",
3335                                 dbesc($item['parent-uri']),
3336                                 intval($item['uid'])
3337                         );
3338                         if(count($r)) {
3339                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3340                                         intval($r[0]['id'])
3341                                 );
3342                         }
3343
3344                         // Add a relayable_retraction signature for Diaspora. Note that we can't add a target_author_signature
3345                         // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
3346                         // the comment, that means we're the home of the post, and Diaspora will only
3347                         // check the parent_author_signature of retractions that it doesn't have to relay further
3348                         //
3349                         // I don't think this function gets called for an "unlike," but I'll check anyway
3350                         $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
3351
3352                         if(local_user() == $item['uid']) {
3353
3354                                 $handle = $a->user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
3355                                 $authorsig = base64_encode(rsa_sign($signed_text,$a->user['prvkey'],'sha256'));
3356                         }
3357                         else {
3358                                 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
3359                                         $item['contact-id']
3360                                 );
3361                                 if(count($r)) {
3362                                         // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
3363                                         // only handles DFRN deletes
3364                                         $handle_baseurl_start = strpos($r['url'],'://') + 3;
3365                                         $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
3366                                         $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
3367                                         $authorsig = '';
3368                                 }
3369                         }
3370
3371                         if(isset($handle))
3372                                 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
3373                                         intval($item['id']),
3374                                         dbesc($signed_text),
3375                                         dbesc($authorsig),
3376                                         dbesc($handle)
3377                                 );
3378                 }
3379                 $drop_id = intval($item['id']);
3380
3381                 // send the notification upstream/downstream as the case may be
3382
3383                 if(! $interactive)
3384                         return $owner;
3385
3386                 proc_run('php',"include/notifier.php","drop","$drop_id");
3387                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3388                 //NOTREACHED
3389         }
3390         else {
3391                 if(! $interactive)
3392                         return 0;
3393                 notice( t('Permission denied.') . EOL);
3394                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3395                 //NOTREACHED
3396         }
3397         
3398 }
3399
3400
3401 function first_post_date($uid,$wall = false) {
3402         $r = q("select id, created from item 
3403                 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0 
3404                 and id = parent
3405                 order by created asc limit 1",
3406                 intval($uid),
3407                 intval($wall ? 1 : 0)
3408         );
3409         if(count($r)) {
3410 //              logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
3411                 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
3412         }
3413         return false;
3414 }
3415
3416 function posted_dates($uid,$wall) {
3417         $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
3418
3419         $dthen = first_post_date($uid,$wall);
3420         if(! $dthen)
3421                 return array();
3422
3423         // If it's near the end of a long month, backup to the 28th so that in 
3424         // consecutive loops we'll always get a whole month difference.
3425
3426         if(intval(substr($dnow,8)) > 28)
3427                 $dnow = substr($dnow,0,8) . '28';
3428         if(intval(substr($dthen,8)) > 28)
3429                 $dnow = substr($dthen,0,8) . '28';
3430
3431         $ret = array();
3432         while($dnow >= $dthen) {
3433                 $dstart = substr($dnow,0,8) . '01';
3434                 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
3435                 $start_month = datetime_convert('','',$dstart,'Y-m-d');
3436                 $end_month = datetime_convert('','',$dend,'Y-m-d');
3437                 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
3438                 $ret[] = array($str,$end_month,$start_month);
3439                 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
3440         }
3441         return $ret;
3442 }
3443
3444
3445 function posted_date_widget($url,$uid,$wall) {
3446         $o = '';
3447
3448         // For former Facebook folks that left because of "timeline"
3449
3450         if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
3451                 return $o;
3452
3453         $ret = posted_dates($uid,$wall);
3454         if(! count($ret))
3455                 return $o;
3456
3457         $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
3458                 '$title' => t('Archives'),
3459                 '$size' => ((count($ret) > 6) ? 6 : count($ret)),
3460                 '$url' => $url,
3461                 '$dates' => $ret
3462         ));
3463         return $o;
3464 }