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