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