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