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