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