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