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