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