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