]> git.mxchange.org Git - friendica.git/blob - include/items.php
truncate names in acl selector
[friendica.git] / include / items.php
1 <?php
2
3 require_once('bbcode.php');
4 require_once('oembed.php');
5
6 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
7
8
9         // default permissions - anonymous user
10
11         $sql_extra = " 
12                 AND `allow_cid` = '' 
13                 AND `allow_gid` = '' 
14                 AND `deny_cid`  = '' 
15                 AND `deny_gid`  = '' 
16         ";
17
18         if(strlen($owner_nick) && ! intval($owner_nick)) {
19                 $r = q("SELECT `uid`, `nickname`, `timezone` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
20                         dbesc($owner_nick)
21                 );
22                 if(count($r)) {
23                         $owner_id = $r[0]['uid'];
24                         $owner_nick = $r[0]['nickname'];
25                         $owner_tz = $r[0]['timezone'];
26                 }
27         }
28
29         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
30                 intval($owner_id)
31         );
32         if(count($r)) {
33                 $owner = $r[0];
34                 $owner['nickname'] = $owner_nick;
35         }
36         else
37                 killme();
38
39
40         /**
41          *
42          * Determine the next birthday, but only if the birthday is published
43          * in the default profile. We _could_ also look for a private profile that the
44          * recipient can see, but somebody could get mad at us if they start getting
45          * public birthday greetings when they haven't made this info public. 
46          *
47          * Assuming we are able to publish this info, we are then going to convert
48          * the start time from the owner's timezone to UTC. 
49          *
50          * This will potentially solve the problem found with some social networks
51          * where birthdays are converted to the viewer's timezone and salutations from
52          * elsewhere in the world show up on the wrong day. We will convert it to the
53          * viewer's timezone also, but first we are going to convert it from the birthday
54          * person's timezone to GMT - so the viewer may find the birthday starting at
55          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
56          *
57          */
58
59         $birthday = '';
60
61         $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
62                 intval($owner_id)
63         );
64
65         if($p && count($p)) {
66                 $tmp_dob = substr($p[0]['dob'],5);
67                 if(intval($tmp_dob)) {
68                         $y = datetime_convert($owner_tz,$owner_tz,'now','Y');
69                         $bd = $y . '-' . $tmp_dob . ' 00:00';
70                         $t_dob = strtotime($bd);
71                         $now = strtotime(datetime_convert($owner_tz,$owner_tz,'now'));
72                         if($t_dob < $now)
73                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
74                         $birthday = datetime_convert($owner_tz,'UTC',$bd,ATOM_TIME); 
75                 }
76         }
77
78         if($dfrn_id && $dfrn_id != '*') {
79
80                 $sql_extra = '';
81                 switch($direction) {
82                         case (-1):
83                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
84                                 $my_id = $dfrn_id;
85                                 break;
86                         case 0:
87                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
88                                 $my_id = '1:' . $dfrn_id;
89                                 break;
90                         case 1:
91                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
92                                 $my_id = '0:' . $dfrn_id;
93                                 break;
94                         default:
95                                 return false;
96                                 break; // NOTREACHED
97                 }
98
99                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
100                         intval($owner_id)
101                 );
102
103                 if(! count($r))
104                         return false;
105
106                 $contact = $r[0];
107                 $groups = init_groups_visitor($contact['id']);
108
109                 if(count($groups)) {
110                         for($x = 0; $x < count($groups); $x ++) 
111                                 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
112                         $gs = implode('|', $groups);
113                 }
114                 else
115                         $gs = '<<>>' ; // Impossible to match 
116
117                 $sql_extra = sprintf(" 
118                         AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' ) 
119                         AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' ) 
120                         AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
121                         AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s') 
122                 ",
123                         intval($contact['id']),
124                         intval($contact['id']),
125                         dbesc($gs),
126                         dbesc($gs)
127                 );
128         }
129
130         if($dfrn_id === '' || $dfrn_id === '*')
131                 $sort = 'DESC';
132         else
133                 $sort = 'ASC';
134
135         if(! strlen($last_update))
136                 $last_update = 'now -30 days';
137
138         $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
139
140         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
141                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, 
142                 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
143                 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, 
144                 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`
145                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
146                 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 
147                 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
148                 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
149                 $sql_extra
150                 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
151                 intval($owner_id),
152                 dbesc($check_date),
153                 dbesc($check_date),
154                 dbesc($sort)
155         );
156
157         // Will check further below if this actually returned results.
158         // We will provide an empty feed in any case.
159
160         $items = $r;
161
162         $feed_template = load_view_file('view/atom_feed.tpl');
163
164         $atom = '';
165
166         $hub = get_config('system','huburl');
167
168         $hubxml = '';
169         if(strlen($hub)) {
170                 $hubs = explode(',', $hub);
171                 if(count($hubs)) {
172                         foreach($hubs as $h) {
173                                 $h = trim($h);
174                                 if(! strlen($h))
175                                         continue;
176                                 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
177                         }
178                 }
179         }
180
181         $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $owner_nick) . '" />' . "\n" ; 
182         $salmon .= '<link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $owner_nick) . '" />' . "\n" ; 
183         $salmon .= '<link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $owner_nick) . '" />' . "\n" ; 
184
185
186         $atom .= replace_macros($feed_template, array(
187                 '$version'      => xmlify(FRIENDIKA_VERSION),
188                 '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
189                 '$feed_title'   => xmlify($owner['name']),
190                 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
191                 '$hub'          => $hubxml,
192                 '$salmon'       => $salmon,
193                 '$name'         => xmlify($owner['name']),
194                 '$profile_page' => xmlify($owner['url']),
195                 '$photo'        => xmlify($owner['photo']),
196                 '$thumb'        => xmlify($owner['thumb']),
197                 '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
198                 '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
199                 '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) , 
200                 '$birthday'     => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
201         ));
202
203         call_hooks('atom_feed', $atom);
204
205         if(! count($items)) {
206
207                 call_hooks('atom_feed_end', $atom);
208
209                 $atom .= '</feed>' . "\r\n";
210                 return $atom;
211         }
212
213         foreach($items as $item) {
214
215                 // public feeds get html, our own nodes use bbcode
216
217                 if($dfrn_id === '*') {
218                         $type = 'html';
219                 }
220                 else {
221                         $type = 'text';
222                 }
223
224                 $atom .= atom_entry($item,$type,null,$owner,true);
225         }
226
227         call_hooks('atom_feed_end', $atom);
228
229         $atom .= '</feed>' . "\r\n";
230
231         return $atom;
232 }
233
234
235 function construct_verb($item) {
236         if($item['verb'])
237                 return $item['verb'];
238         return ACTIVITY_POST;
239 }
240
241 function construct_activity_object($item) {
242
243         if($item['object']) {
244                 $o = '<as:object>' . "\r\n";
245                 $r = @simplexml_load_string($item['object']);
246                 if($r->type)
247                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
248                 if($r->id)
249                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
250                 if($r->title)
251                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
252                 if($r->link) {
253                         if(substr($r->link,0,1) === '<') 
254                                 $o .= $r->link;
255                         else
256                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
257                 }
258                 if($r->content)
259                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
260                 $o .= '</as:object>' . "\r\n";
261                 return $o;
262         }
263
264         return '';
265
266
267 function construct_activity_target($item) {
268
269         if($item['target']) {
270                 $o = '<as:target>' . "\r\n";
271                 $r = @simplexml_load_string($item['target']);
272                 if($r->type)
273                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
274                 if($r->id)
275                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
276                 if($r->title)
277                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
278                 if($r->link) {
279                         if(substr($r->link,0,1) === '<') 
280                                 $o .= $r->link;
281                         else
282                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
283                 }
284                 if($r->content)
285                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
286                 $o .= '</as:target>' . "\r\n";
287                 return $o;
288         }
289
290         return '';
291
292
293
294
295
296 function get_atom_elements($feed,$item) {
297
298         require_once('library/HTMLPurifier.auto.php');
299         require_once('include/html2bbcode.php');
300
301         $best_photo = array();
302
303         $res = array();
304
305         $author = $item->get_author();
306         $res['author-name'] = unxmlify($author->get_name());
307         $res['author-link'] = unxmlify($author->get_link());
308         $res['uri'] = unxmlify($item->get_id());
309         $res['title'] = unxmlify($item->get_title());
310         $res['body'] = unxmlify($item->get_content());
311
312
313         // look for a photo. We should check media size and find the best one,
314         // but for now let's just find any author photo
315
316         $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
317
318         if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
319                 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
320                 foreach($base as $link) {
321                         if(! $res['author-avatar']) {
322                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
323                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
324                         }
325                 }
326         }                       
327
328         $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
329
330         if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
331                 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
332                 if($base && count($base)) {
333                         foreach($base as $link) {
334                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
335                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
336                                 if(! $res['author-avatar']) {
337                                         if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
338                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
339                                 }
340                         }
341                 }
342         }
343
344         // No photo/profile-link on the item - look at the feed level
345
346         if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
347                 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
348                 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
349                         $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
350                         foreach($base as $link) {
351                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
352                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
353                                 if(! $res['author-avatar']) {
354                                         if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
355                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
356                                 }
357                         }
358                 }                       
359
360                 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
361
362                 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
363                         $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
364
365                         if($base && count($base)) {
366                                 foreach($base as $link) {
367                                         if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
368                                                 $res['author-link'] = unxmlify($link['attribs']['']['href']);
369                                         if(! (x($res,'author-avatar'))) {
370                                                 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
371                                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
372                                         }
373                                 }
374                         }
375                 }
376         }
377
378
379         $maxlen = get_max_import_size();
380         if($maxlen && (strlen($res['body']) > $maxlen))
381                 $res['body'] = substr($res['body'],0, $maxlen);
382
383         // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust 
384         // the content type. Our own network only emits text normally, though it might have been converted to 
385         // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
386         // have to assume it is all html and needs to be purified.
387
388         // It doesn't matter all that much security wise - because before this content is used anywhere, we are 
389         // going to escape any tags we find regardless, but this lets us import a limited subset of html from 
390         // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining 
391         // html.
392
393
394         if((strpos($res['body'],'<')) || (strpos($res['body'],'>'))) {
395
396                 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
397                         '[youtube]$1[/youtube]', $res['body']);
398
399                 $res['body'] = oembed_html2bbcode($res['body']);
400         
401                 $config = HTMLPurifier_Config::createDefault();
402                 $config->set('Cache.DefinitionImpl', null);
403
404                 // we shouldn't need a whitelist, because the bbcode converter
405                 // will strip out any unsupported tags.
406                 // $config->set('HTML.Allowed', 'p,b,a[href],i'); 
407
408                 $purifier = new HTMLPurifier($config);
409                 $res['body'] = $purifier->purify($res['body']);
410
411                 $res['body'] = html2bbcode($res['body']);
412         }
413         else
414                 $res['body'] = escape_tags($res['body']);
415         
416
417         $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
418         if($allow && $allow[0]['data'] == 1)
419                 $res['last-child'] = 1;
420         else
421                 $res['last-child'] = 0;
422
423         $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
424         if($private && $private[0]['data'] == 1)
425                 $res['private'] = 1;
426         else
427                 $res['private'] = 0;
428
429
430         $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
431         if($rawlocation)
432                 $res['location'] = unxmlify($rawlocation[0]['data']);
433
434
435         $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
436         if($rawcreated)
437                 $res['created'] = unxmlify($rawcreated[0]['data']);
438
439
440         $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
441         if($rawedited)
442                 $res['edited'] = unxmlify($rawcreated[0]['data']);
443
444
445         if(! $res['created'])
446                 $res['created'] = $item->get_date();
447
448         if(! $res['edited'])
449                 $res['edited'] = $item->get_date();
450
451
452         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
453         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
454                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
455         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
456                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
457         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
458                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
459         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
460                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
461
462         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
463                 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
464
465                 foreach($base as $link) {
466                         if(! $res['owner-avatar']) {
467                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')                 
468                                         $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
469                         }
470                 }
471         }
472
473         $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
474         if($rawgeo)
475                 $res['coord'] = unxmlify($rawgeo[0]['data']);
476
477
478         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
479
480         // select between supported verbs
481
482         if($rawverb) {
483                 $res['verb'] = unxmlify($rawverb[0]['data']);
484         }
485
486         // translate OStatus unfollow to activity streams if it happened to get selected
487                 
488         if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
489                 $res['verb'] = ACTIVITY_UNFOLLOW;
490
491                 
492
493         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
494
495         if($rawobj) {
496                 $res['object'] = '<object>' . "\n";
497                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
498                         $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
499                         $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
500                 }       
501                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
502                         $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
503                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
504                         $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
505                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
506                         $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
507                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
508                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
509                         if(! $body)
510                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
511                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
512                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
513                         if((strpos($body,'<')) || (strpos($body,'>'))) {
514
515                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
516                                         '[youtube]$1[/youtube]', $body);
517
518                                 $config = HTMLPurifier_Config::createDefault();
519                                 $config->set('Cache.DefinitionImpl', null);
520
521                                 $purifier = new HTMLPurifier($config);
522                                 $body = $purifier->purify($body);
523                                 $body = html2bbcode($body);
524                         }
525                         else
526                                 $body = escape_tags($body);
527
528                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
529                 }
530
531                 $res['object'] .= '</object>' . "\n";
532         }
533
534         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
535
536         if($rawobj) {
537                 $res['target'] = '<target>' . "\n";
538                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
539                         $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
540                 }       
541                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
542                         $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
543
544                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
545                         $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
546                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
547                         $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
548                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
549                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
550                         if(! $body)
551                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
552                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
553                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
554                         if((strpos($body,'<')) || (strpos($body,'>'))) {
555
556                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
557                                         '[youtube]$1[/youtube]', $body);
558
559                                 $config = HTMLPurifier_Config::createDefault();
560                                 $config->set('Cache.DefinitionImpl', null);
561
562                                 $purifier = new HTMLPurifier($config);
563                                 $body = $purifier->purify($body);
564                                 $body = html2bbcode($body);
565                         }
566                         else
567                                 $body = escape_tags($body);
568
569                         $res['target'] .= '<content>' . $body . '</content>' . "\n";
570                 }
571
572                 $res['target'] .= '</target>' . "\n";
573         }
574
575         $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
576
577         call_hooks('parse_atom', $arr);
578
579         return $res;
580 }
581
582 function encode_rel_links($links) {
583         $o = '';
584         if(! ((is_array($links)) && (count($links))))
585                 return $o;
586         foreach($links as $link) {
587                 $o .= '<link ';
588                 if($link['attribs']['']['rel'])
589                         $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
590                 if($link['attribs']['']['type'])
591                         $o .= 'type="' . $link['attribs']['']['type'] . '" ';
592                 if($link['attribs']['']['href'])
593                         $o .= 'href="' . $link['attribs']['']['href'] . '" ';
594                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
595                         $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
596                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
597                         $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
598                 $o .= ' />' . "\n" ;
599         }
600         return xmlify($o);
601 }
602
603 function item_store($arr) {
604
605         if($arr['gravity'])
606                 $arr['gravity'] = intval($arr['gravity']);
607         elseif($arr['parent-uri'] == $arr['uri'])
608                 $arr['gravity'] = 0;
609         elseif(activity_match($arr['verb'],ACTIVITY_POST))
610                 $arr['gravity'] = 6;
611         else      
612                 $arr['gravity'] = 6;   // extensible catchall
613
614         if(! x($arr,'type'))
615                 $arr['type']      = 'remote';
616         $arr['wall']          = ((x($arr,'wall'))          ? intval($arr['wall'])                : 0);
617         $arr['uri']           = ((x($arr,'uri'))           ? notags(trim($arr['uri']))           : random_string());
618         $arr['author-name']   = ((x($arr,'author-name'))   ? notags(trim($arr['author-name']))   : '');
619         $arr['author-link']   = ((x($arr,'author-link'))   ? notags(trim($arr['author-link']))   : '');
620         $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
621         $arr['owner-name']    = ((x($arr,'owner-name'))    ? notags(trim($arr['owner-name']))    : '');
622         $arr['owner-link']    = ((x($arr,'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
623         $arr['owner-avatar']  = ((x($arr,'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
624         $arr['created']       = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
625         $arr['edited']        = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
626         $arr['changed']       = datetime_convert();
627         $arr['title']         = ((x($arr,'title'))         ? notags(trim($arr['title']))         : '');
628         $arr['location']      = ((x($arr,'location'))      ? notags(trim($arr['location']))      : '');
629         $arr['coord']         = ((x($arr,'coord'))         ? notags(trim($arr['coord']))         : '');
630         $arr['last-child']    = ((x($arr,'last-child'))    ? intval($arr['last-child'])          : 0 );
631         $arr['visible']       = ((x($arr,'visible') !== false) ? intval($arr['visible'])         : 1 );
632         $arr['deleted']       = 0;
633         $arr['parent-uri']    = ((x($arr,'parent-uri'))    ? notags(trim($arr['parent-uri']))    : '');
634         $arr['verb']          = ((x($arr,'verb'))          ? notags(trim($arr['verb']))          : '');
635         $arr['object-type']   = ((x($arr,'object-type'))   ? notags(trim($arr['object-type']))   : '');
636         $arr['object']        = ((x($arr,'object'))        ? trim($arr['object'])                : '');
637         $arr['target-type']   = ((x($arr,'target-type'))   ? notags(trim($arr['target-type']))   : '');
638         $arr['target']        = ((x($arr,'target'))        ? trim($arr['target'])                : '');
639         $arr['allow_cid']     = ((x($arr,'allow_cid'))     ? trim($arr['allow_cid'])             : '');
640         $arr['allow_gid']     = ((x($arr,'allow_gid'))     ? trim($arr['allow_gid'])             : '');
641         $arr['deny_cid']      = ((x($arr,'deny_cid'))      ? trim($arr['deny_cid'])              : '');
642         $arr['deny_gid']      = ((x($arr,'deny_gid'))      ? trim($arr['deny_gid'])              : '');
643         $arr['private']       = ((x($arr,'private'))       ? intval($arr['private'])             : 0 );
644         $arr['body']          = ((x($arr,'body'))          ? escape_tags(trim($arr['body']))     : '');
645
646         // The content body has been through a lot of filtering and transport escaping by now. 
647         // We don't want to skip any filters, however a side effect of all this filtering 
648         // is that ampersands and <> may have been double encoded, depending on which filter chain
649         // they came through. 
650
651         $arr['body']          = str_replace(
652                                                                 array('&amp;amp;', '&amp;gt;', '&amp;lt;', '&amp;quot;'),
653                                                                 array('&amp;'    , '&gt;'    , '&lt;',     '&quot;'),
654                                                                 $arr['body']
655                                                         );
656
657
658
659         if($arr['parent-uri'] === $arr['uri']) {
660                 $parent_id = 0;
661                 $allow_cid = $arr['allow_cid'];
662                 $allow_gid = $arr['allow_gid'];
663                 $deny_cid  = $arr['deny_cid'];
664                 $deny_gid  = $arr['deny_gid'];
665         }
666         else { 
667
668                 // find the parent and snarf the item id and ACL's
669
670                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
671                         dbesc($arr['parent-uri']),
672                         intval($arr['uid'])
673                 );
674
675                 if(count($r)) {
676
677                         // is the new message multi-level threaded?
678                         // even though we don't support it now, preserve the info
679                         // and re-attach to the conversation parent.
680
681                         if($r[0]['uri'] != $r[0]['parent-uri']) {
682                                 $arr['thr-parent'] = $arr['parent-uri'];
683                                 $arr['parent-uri'] = $r[0]['parent-uri'];
684                         }
685
686                         $parent_id = $r[0]['id'];
687                         $allow_cid = $r[0]['allow_cid'];
688                         $allow_gid = $r[0]['allow_gid'];
689                         $deny_cid  = $r[0]['deny_cid'];
690                         $deny_gid  = $r[0]['deny_gid'];
691                 }
692                 else {
693                         logger('item_store: item parent was not found - ignoring item');
694                         return 0;
695                 }
696         }
697
698         call_hooks('post_remote',$arr);
699
700         dbesc_array($arr);
701
702         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
703
704         $r = dbq("INSERT INTO `item` (`" 
705                         . implode("`, `", array_keys($arr)) 
706                         . "`) VALUES ('" 
707                         . implode("', '", array_values($arr)) 
708                         . "')" );
709
710         // find the item we just created
711
712         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
713                 $arr['uri'],           // already dbesc'd
714                 intval($arr['uid'])
715         );
716         if(count($r)) {
717                 $current_post = $r[0]['id'];
718                 logger('item_store: created item ' . $current_post);
719         }
720         else {
721                 logger('item_store: could not locate created item');
722                 return 0;
723         }
724
725         if($arr['parent-uri'] === $arr['uri'])
726                 $parent_id = $current_post;
727  
728         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
729                 $private = 1;
730         else
731                 $private = $arr['private']; 
732
733         // Set parent id - and also make sure to inherit the parent's ACL's.
734
735         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
736                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d WHERE `id` = %d LIMIT 1",
737                 intval($parent_id),
738                 dbesc($allow_cid),
739                 dbesc($allow_gid),
740                 dbesc($deny_cid),
741                 dbesc($deny_gid),
742                 intval($private),
743                 intval($current_post)
744         );
745
746         return $current_post;
747 }
748
749 function get_item_contact($item,$contacts) {
750         if(! count($contacts) || (! is_array($item)))
751                 return false;
752         foreach($contacts as $contact) {
753                 if($contact['id'] == $item['contact-id']) {
754                         return $contact;
755                         break; // NOTREACHED
756                 }
757         }
758         return false;
759 }
760
761
762 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
763
764         $a = get_app();
765
766         if((! strlen($contact['dfrn-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
767                 return 3;
768
769         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
770
771         if($contact['duplex'] && $contact['dfrn-id'])
772                 $idtosend = '0:' . $orig_id;
773         if($contact['duplex'] && $contact['issued-id'])
774                 $idtosend = '1:' . $orig_id;            
775
776         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
777
778         $rino_enable = get_config('system','rino_encrypt');
779
780         if(! $rino_enable)
781                 $rino = 0;
782
783         $url = $contact['notify'] . '?dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
784
785         logger('dfrn_deliver: ' . $url);
786
787         $xml = fetch_url($url);
788
789         $curl_stat = $a->get_curl_code();
790         if(! $curl_stat)
791                 return(-1); // timed out
792
793         logger('dfrn_deliver: ' . $xml);
794
795         if(! $xml)
796                 return 3;
797
798         $res = simplexml_load_string($xml);
799
800         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
801                 return (($res->status) ? $res->status : 3);
802
803         $postvars     = array();
804         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
805         $challenge    = hex2bin((string) $res->challenge);
806         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
807
808         $final_dfrn_id = '';
809
810
811         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
812                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
813                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
814         }
815         else {
816                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
817                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
818         }
819
820         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
821
822         if(strpos($final_dfrn_id,':') == 1)
823                 $final_dfrn_id = substr($final_dfrn_id,2);
824
825         if($final_dfrn_id != $orig_id) {
826                 logger('dfrn_deliver: wrong dfrn_id.');
827                 // did not decode properly - cannot trust this site 
828                 return 3;
829         }
830
831         $postvars['dfrn_id']      = $idtosend;
832         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
833         if($dissolve)
834                 $postvars['dissolve'] = '1';
835
836         if(($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked']) && (! $contact['readonly'])) {
837                 $postvars['data'] = $atom;
838         }
839         elseif($owner['page-flags'] == PAGE_COMMUNITY) {
840                 $postvars['data'] = $atom;
841         }
842         else {
843                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
844         }
845
846         if($rino && $rino_allowed && (! $dissolve)) {
847                 $key = substr(random_string(),0,16);
848                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
849                 $postvars['data'] = $data;
850                 logger('rino: sent key = ' . $key);     
851
852                 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
853                         openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
854                 }
855                 else {
856                         openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
857                 }
858
859                 logger('md5 rawkey ' . md5($postvars['key']));
860
861                 $postvars['key'] = bin2hex($postvars['key']);
862         }
863
864         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
865
866         $xml = post_url($contact['notify'],$postvars);
867
868         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
869
870         $curl_stat = $a->get_curl_code();
871         if((! $curl_stat) || (! strlen($xml)))
872                 return(-1); // timed out
873
874         $res = simplexml_load_string($xml);
875
876         return $res->status;
877  
878 }
879
880
881 /*
882  *
883  * consume_feed - process atom feed and update anything/everything we might need to update
884  *
885  * $xml = the (atom) feed to consume - no RSS spoken here, it might partially work since simplepie 
886  *        handles both, but we don't claim it will work well, and are reasonably certain it won't.
887  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
888  *             It is this person's stuff that is going to be updated.
889  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
890  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
891  *             have a contact record.
892  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
893  *        might not) try and subscribe to it.
894  *
895  */
896
897 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0) {
898
899         require_once('simplepie/simplepie.inc');
900
901         $feed = new SimplePie();
902         $feed->set_raw_data($xml);
903         if($datedir)
904                 $feed->enable_order_by_date(true);
905         else
906                 $feed->enable_order_by_date(false);
907         $feed->init();
908
909         if($feed->error())
910                 logger('consume_feed: Error parsing XML: ' . $feed->error());
911
912
913         // Check at the feed level for updated contact name and/or photo
914
915         $name_updated  = '';
916         $new_name = '';
917         $photo_timestamp = '';
918         $photo_url = '';
919         $birthday = '';
920
921         $hubs = $feed->get_links('hub');
922
923         if(count($hubs))
924                 $hub = implode(',', $hubs);
925
926         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
927         if($rawtags) {
928                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
929                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
930                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
931                         $new_name = $elems['name'][0]['data'];
932                 } 
933                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
934                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
935                         $photo_url = $elems['link'][0]['attribs']['']['href'];
936                 }
937
938                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
939                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
940                 }
941         }
942
943         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
944                 logger('consume_feed: Updating photo for ' . $contact['name']);
945                 require_once("Photo.php");
946                 $photo_failure = false;
947                 $have_photo = false;
948
949                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
950                         intval($contact['id']),
951                         intval($contact['uid'])
952                 );
953                 if(count($r)) {
954                         $resource_id = $r[0]['resource-id'];
955                         $have_photo = true;
956                 }
957                 else {
958                         $resource_id = photo_new_resource();
959                 }
960                         
961                 $img_str = fetch_url($photo_url,true);
962                 $img = new Photo($img_str);
963                 if($img->is_valid()) {
964                         if($have_photo) {
965                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
966                                         dbesc($resource_id),
967                                         intval($contact['id']),
968                                         intval($contact['uid'])
969                                 );
970                         }
971                                 
972                         $img->scaleImageSquare(175);
973                                 
974                         $hash = $resource_id;
975                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
976                                 
977                         $img->scaleImage(80);
978                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
979
980                         $img->scaleImage(48);
981                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 6);
982
983                         $a = get_app();
984
985                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
986                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
987                                 dbesc(datetime_convert()),
988                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
989                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
990                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
991                                 intval($contact['uid']),
992                                 intval($contact['id'])
993                         );
994                 }
995         }
996
997         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
998                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
999                         dbesc(notags(trim($new_name))),
1000                         dbesc(datetime_convert()),
1001                         intval($contact['uid']),
1002                         intval($contact['id'])
1003                 );
1004         }
1005
1006         if(strlen($birthday)) {
1007                 if(substr($birthday,0,4) != $contact['bdyear']) {
1008                         logger('consume_feed: updating birthday: ' . $birthday);
1009
1010                         /**
1011                          *
1012                          * Add new birthday event for this person
1013                          *
1014                          * $bdtext is just a readable placeholder in case the event is shared
1015                          * with others. We will replace it during presentation to our $importer
1016                          * to contain a sparkle link and perhaps a photo. 
1017                          *
1018                          */
1019                          
1020                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1021
1022
1023                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1024                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1025                                 intval($contact['uid']),
1026                                 intval($contact['id']),
1027                                 dbesc(datetime_convert()),
1028                                 dbesc(datetime_convert()),
1029                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1030                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1031                                 dbesc($bdtext),
1032                                 dbesc('birthday')
1033                         );
1034                         
1035
1036                         // update bdyear
1037
1038                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1039                                 dbesc(substr($birthday,0,4)),
1040                                 intval($contact['uid']),
1041                                 intval($contact['id'])
1042                         );
1043
1044                         // This function is called twice without reloading the contact
1045                         // Make sure we only create one event. This is why &$contact 
1046                         // is a reference var in this function
1047
1048                         $contact['bdyear'] = substr($birthday,0,4);
1049                 }
1050
1051         }
1052
1053         // Now process the feed
1054         if($feed->get_item_quantity()) {                
1055
1056         // in inverse date order
1057                 if ($datedir)
1058                         $items = array_reverse($feed->get_items());
1059                 else
1060                         $items = $feed->get_items();
1061
1062                 foreach($items as $item) {
1063
1064                         $deleted = false;
1065
1066                         $rawdelete = $item->get_item_tags( NAMESPACE_TOMB, 'deleted-entry');
1067                         if(isset($rawdelete[0]['attribs']['']['ref'])) {
1068                                 $uri = $rawthread[0]['attribs']['']['ref'];
1069                                 $deleted = true;
1070                                 if(isset($rawdelete[0]['attribs']['']['when'])) {
1071                                         $when = $rawthread[0]['attribs']['']['when'];
1072                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1073                                 }
1074                                 else
1075                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1076                         }
1077                         if($deleted && is_array($contact)) {
1078                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1079                                         dbesc($uri),
1080                                         intval($importer['uid']),
1081                                         intval($contact['id'])
1082                                 );
1083                                 if(count($r)) {
1084                                         $item = $r[0];
1085                                         if($item['uri'] == $item['parent-uri']) {
1086                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1087                                                         `body` = '', `title` = ''
1088                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1089                                                         dbesc($when),
1090                                                         dbesc(datetime_convert()),
1091                                                         dbesc($item['uri']),
1092                                                         intval($importer['uid'])
1093                                                 );
1094                                         }
1095                                         else {
1096                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1097                                                         `body` = '', `title` = '' 
1098                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1099                                                         dbesc($when),
1100                                                         dbesc(datetime_convert()),
1101                                                         dbesc($uri),
1102                                                         intval($importer['uid'])
1103                                                 );
1104                                                 if($item['last-child']) {
1105                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1106                                                         $q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1107                                                                 dbesc(datetime_convert()),
1108                                                                 dbesc($item['parent-uri']),
1109                                                                 intval($item['uid'])
1110                                                         );
1111                                                         // who is the last child now? 
1112                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1113                                                                 ORDER BY `created` DESC LIMIT 1",
1114                                                                         dbesc($item['parent-uri']),
1115                                                                         intval($importer['uid'])
1116                                                         );
1117                                                         if(count($r)) {
1118                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1119                                                                         intval($r[0]['id'])
1120                                                                 );
1121                                                         }
1122                                                 }       
1123                                         }
1124                                 }       
1125                                 continue;
1126                         }
1127
1128
1129                         $is_reply = false;              
1130                         $item_id = $item->get_id();
1131                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1132                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1133                                 $is_reply = true;
1134                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1135                         }
1136
1137
1138                         if(($is_reply) && is_array($contact)) {
1139         
1140                                 // Have we seen it? If not, import it.
1141         
1142                                 $item_id = $item->get_id();
1143         
1144                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1145                                         dbesc($item_id),
1146                                         intval($importer['uid'])
1147                                 );
1148                                 // FIXME update content if 'updated' changes
1149                                 if(count($r)) {
1150                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1151                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1152                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1153                                                         dbesc(datetime_convert()),
1154                                                         dbesc($parent_uri),
1155                                                         intval($importer['uid'])
1156                                                 );
1157                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1158                                                         intval($allow[0]['data']),
1159                                                         dbesc(datetime_convert()),
1160                                                         dbesc($item_id),
1161                                                         intval($importer['uid'])
1162                                                 );
1163                                         }
1164                                         continue;
1165                                 }
1166                                 $datarray = get_atom_elements($feed,$item);
1167
1168                                 if($contact['network'] === 'stat') {
1169                                         if(strlen($datarray['title']))
1170                                                 unset($datarray['title']);
1171                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1172                                                 dbesc(datetime_convert()),
1173                                                 dbesc($parent_uri),
1174                                                 intval($importer['uid'])
1175                                         );
1176                                         $datarray['last-child'] = 1;
1177                                 }
1178
1179                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1180                                         // one way feed - no remote comment ability
1181                                         $datarray['last-child'] = 0;
1182                                 }
1183                                 $datarray['parent-uri'] = $parent_uri;
1184                                 $datarray['uid'] = $importer['uid'];
1185                                 $datarray['contact-id'] = $contact['id'];
1186                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1187                                         $datarray['type'] = 'activity';
1188                                         $datarray['gravity'] = GRAVITY_LIKE;
1189                                 }
1190
1191                                 $r = item_store($datarray);
1192                                 continue;
1193                         }
1194
1195                         else {
1196                                 // Head post of a conversation. Have we seen it? If not, import it.
1197
1198                                 $item_id = $item->get_id();
1199                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1200                                         dbesc($item_id),
1201                                         intval($importer['uid'])
1202                                 );
1203                                 if(count($r)) {
1204                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1205                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1206                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1207                                                         intval($allow[0]['data']),
1208                                                         dbesc(datetime_convert()),
1209                                                         dbesc($item_id),
1210                                                         intval($importer['uid'])
1211                                                 );
1212                                         }
1213                                         continue;
1214                                 }
1215                                 $datarray = get_atom_elements($feed,$item);
1216
1217                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1218                                         logger('consume-feed: New follower');
1219                                         new_follower($importer,$contact,$datarray,$item);
1220                                         return;
1221                                 }
1222                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1223                                         lose_follower($importer,$contact,$datarray,$item);
1224                                         return;
1225                                 }
1226                                 if(! is_array($contact))
1227                                         return;
1228
1229                                 if($contact['network'] === 'stat') {
1230                                         if(strlen($datarray['title']))
1231                                                 unset($datarray['title']);
1232                                         $datarray['last-child'] = 1;
1233                                 }
1234
1235                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1236                                         // one way feed - no remote comment ability
1237                                         $datarray['last-child'] = 0;
1238                                 }
1239
1240                                 $datarray['parent-uri'] = $item_id;
1241                                 $datarray['uid'] = $importer['uid'];
1242                                 $datarray['contact-id'] = $contact['id'];
1243                                 $r = item_store($datarray);
1244                                 continue;
1245
1246                         }
1247                 }
1248         }
1249 }
1250
1251 function new_follower($importer,$contact,$datarray,$item) {
1252         $url = notags(trim($datarray['author-link']));
1253         $name = notags(trim($datarray['author-name']));
1254         $photo = notags(trim($datarray['author-avatar']));
1255
1256         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1257         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1258                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1259
1260         if(is_array($contact)) {
1261                 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
1262                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1263                                 intval(REL_BUD),
1264                                 intval($contact['id']),
1265                                 intval($importer['uid'])
1266                         );
1267                 }
1268
1269                 // send email notification to owner?
1270         }
1271         else {
1272         
1273                 // create contact record - set to readonly
1274
1275                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
1276                         `blocked`, `readonly`, `pending` )
1277                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1 ) ",
1278                         intval($importer['uid']),
1279                         dbesc(datetime_convert()),
1280                         dbesc($url),
1281                         dbesc($name),
1282                         dbesc($nick),
1283                         dbesc($photo),
1284                         dbesc('stat'),
1285                         intval(REL_VIP)
1286                 );
1287                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1288                                 intval($importer['uid']),
1289                                 dbesc($url),
1290                                 intval(REL_VIP)
1291                 );
1292                 if(count($r))
1293                                 $contact_record = $r[0];
1294
1295                 // create notification  
1296                 $hash = random_string();
1297
1298                 if(is_array($contact_record)) {
1299                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1300                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1301                                 intval($importer['uid']),
1302                                 intval($contact_record['id']),
1303                                 dbesc($hash),
1304                                 dbesc(datetime_convert())
1305                         );
1306                 }
1307                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1308                         intval($importer['uid'])
1309                 );
1310                 $a = get_app();
1311                 if(count($r)) {
1312                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1313                                 $email_tpl = load_view_file('view/follow_notify_eml.tpl');
1314                                 $email = replace_macros($email_tpl, array(
1315                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1316                                         '$url' => $url,
1317                                         '$myname' => $r[0]['username'],
1318                                         '$siteurl' => $a->get_baseurl(),
1319                                         '$sitename' => $a->config['sitename']
1320                                 ));
1321                                 $res = mail($r[0]['email'], 
1322                                         t("You have a new follower at ") . $a->config['sitename'],
1323                                         $email,
1324                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
1325                         
1326                         }
1327                 }
1328         }
1329 }
1330
1331 function lose_follower($importer,$contact,$datarray,$item) {
1332
1333         if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1334                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1335                         intval(REL_FAN),
1336                         intval($contact['id'])
1337                 );
1338         }
1339         else {
1340                 contact_remove($contact['id']);
1341         }
1342 }
1343
1344
1345 function subscribe_to_hub($url,$importer,$contact) {
1346
1347         if(is_array($importer)) {
1348                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1349                         intval($importer['uid'])
1350                 );
1351         }
1352         if(! count($r))
1353                 return;
1354
1355         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1356
1357         // Use a single verify token, even if multiple hubs
1358
1359         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1360
1361         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1362
1363         logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1364
1365         if(! strlen($contact['hub-verify'])) {
1366                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1367                         dbesc($verify_token),
1368                         intval($contact['id'])
1369                 );
1370         }
1371
1372         post_url($url,$params);                 
1373         return;
1374
1375 }
1376
1377
1378 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1379         $o = '';
1380         if(! $tag)
1381                 return $o;
1382         $name = xmlify($name);
1383         $uri = xmlify($uri);
1384         $h = intval($h);
1385         $w = intval($w);
1386         $photo = xmlify($photo);
1387
1388
1389         $o .= "<$tag>\r\n";
1390         $o .= "<name>$name</name>\r\n";
1391         $o .= "<uri>$uri</uri>\r\n";
1392         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1393         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1394
1395         call_hooks('atom_author', $o);
1396
1397         $o .= "</$tag>\r\n";
1398         return $o;
1399 }
1400
1401 function atom_entry($item,$type,$author,$owner,$comment = false) {
1402
1403         if($item['deleted'])
1404                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1405
1406         $a = get_app();
1407
1408         $o = "\r\n\r\n<entry>\r\n";
1409
1410         if(is_array($author))
1411                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1412         else
1413                 $o .= atom_author('author',$item['name'],$item['url'],80,80,$item['thumb']);
1414         if(strlen($item['owner-name']))
1415                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1416
1417         if($item['parent'] != $item['id'])
1418                 $o .= '<thr:in-reply-to ref="' . xmlify($item['parent-uri']) . '" type="text/html" href="' .  xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1419
1420         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1421         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1422         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1423         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1424         $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($item['body']) : $item['body']) . '</content>' . "\r\n";
1425         $o .= '<link rel="alternate" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1426         if($comment)
1427                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1428
1429         if($item['location']) {
1430                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1431                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1432         }
1433
1434         if($item['coord'])
1435                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1436
1437         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1438                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1439
1440         $verb = construct_verb($item);
1441         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1442         $actobj = construct_activity_object($item);
1443         if(strlen($actobj))
1444                 $o .= $actobj;
1445         $actarg = construct_activity_target($item);
1446         if(strlen($actarg))
1447                 $o .= $actarg;
1448
1449         $mentioned = get_mentions($item);
1450         if($mentioned)
1451                 $o .= $mentioned;
1452         
1453         call_hooks('atom_entry', $o);
1454
1455         $o .= '</entry>' . "\r\n";
1456         
1457         return $o;
1458 }
1459