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