]> git.mxchange.org Git - friendica.git/blob - include/items.php
prevent runaway notifications when parent=0 due to race condition
[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,$force_parent = false) {
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                         $parent_deleted = $r[0]['deleted'];
693                         $allow_cid      = $r[0]['allow_cid'];
694                         $allow_gid      = $r[0]['allow_gid'];
695                         $deny_cid       = $r[0]['deny_cid'];
696                         $deny_gid       = $r[0]['deny_gid'];
697                 }
698                 else {
699
700                         // Allow one to see reply tweets from status.net even when
701                         // we don't have or can't see the original post.
702
703                         if($force_parent) {
704                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
705                                 $parent_id = 0;
706                                 $arr['thr-parent'] = $arr['parent-uri'];
707                                 $arr['parent-uri'] = $arr['uri'];
708                         }
709                         else {
710                                 logger('item_store: item parent was not found - ignoring item');
711                                 return 0;
712                         }
713                 }
714         }
715
716         call_hooks('post_remote',$arr);
717
718         dbesc_array($arr);
719
720         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
721
722         $r = dbq("INSERT INTO `item` (`" 
723                         . implode("`, `", array_keys($arr)) 
724                         . "`) VALUES ('" 
725                         . implode("', '", array_values($arr)) 
726                         . "')" );
727
728         // find the item we just created
729
730         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
731                 $arr['uri'],           // already dbesc'd
732                 intval($arr['uid'])
733         );
734         if(count($r)) {
735                 $current_post = $r[0]['id'];
736                 logger('item_store: created item ' . $current_post);
737         }
738         else {
739                 logger('item_store: could not locate created item');
740                 return 0;
741         }
742
743         if($arr['parent-uri'] === $arr['uri'])
744                 $parent_id = $current_post;
745  
746         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
747                 $private = 1;
748         else
749                 $private = $arr['private']; 
750
751         // Set parent id - and also make sure to inherit the parent's ACL's.
752
753         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
754                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = $d WHERE `id` = %d LIMIT 1",
755                 intval($parent_id),
756                 dbesc($allow_cid),
757                 dbesc($allow_gid),
758                 dbesc($deny_cid),
759                 dbesc($deny_gid),
760                 intval($private),
761                 intval($parent_deleted),
762                 intval($current_post)
763         );
764
765         return $current_post;
766 }
767
768 function get_item_contact($item,$contacts) {
769         if(! count($contacts) || (! is_array($item)))
770                 return false;
771         foreach($contacts as $contact) {
772                 if($contact['id'] == $item['contact-id']) {
773                         return $contact;
774                         break; // NOTREACHED
775                 }
776         }
777         return false;
778 }
779
780
781 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
782
783         $a = get_app();
784
785         if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
786                 return 3;
787
788         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
789
790         if($contact['duplex'] && $contact['dfrn-id'])
791                 $idtosend = '0:' . $orig_id;
792         if($contact['duplex'] && $contact['issued-id'])
793                 $idtosend = '1:' . $orig_id;            
794
795         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
796
797         $rino_enable = get_config('system','rino_encrypt');
798
799         if(! $rino_enable)
800                 $rino = 0;
801
802         $url = $contact['notify'] . '?dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
803
804         logger('dfrn_deliver: ' . $url);
805
806         $xml = fetch_url($url);
807
808         $curl_stat = $a->get_curl_code();
809         if(! $curl_stat)
810                 return(-1); // timed out
811
812         logger('dfrn_deliver: ' . $xml);
813
814         if(! $xml)
815                 return 3;
816
817         if(strpos($xml,'<?xml') === false) {
818                 logger('dfrn_deliver: no valid XML returned');
819                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
820                 return 3;
821         }
822
823         $res = simplexml_load_string($xml);
824
825         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
826                 return (($res->status) ? $res->status : 3);
827
828         $postvars     = array();
829         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
830         $challenge    = hex2bin((string) $res->challenge);
831         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
832         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
833
834         $final_dfrn_id = '';
835
836
837         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
838                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
839                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
840         }
841         else {
842                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
843                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
844         }
845
846         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
847
848         if(strpos($final_dfrn_id,':') == 1)
849                 $final_dfrn_id = substr($final_dfrn_id,2);
850
851         if($final_dfrn_id != $orig_id) {
852                 logger('dfrn_deliver: wrong dfrn_id.');
853                 // did not decode properly - cannot trust this site 
854                 return 3;
855         }
856
857         $postvars['dfrn_id']      = $idtosend;
858         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
859         if($dissolve)
860                 $postvars['dissolve'] = '1';
861
862         if(($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked']) && (! $contact['readonly'])) {
863                 $postvars['data'] = $atom;
864         }
865         elseif($owner['page-flags'] == PAGE_COMMUNITY) {
866                 $postvars['data'] = $atom;
867         }
868         else {
869                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
870         }
871
872         if($rino && $rino_allowed && (! $dissolve)) {
873                 $key = substr(random_string(),0,16);
874                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
875                 $postvars['data'] = $data;
876                 logger('rino: sent key = ' . $key);     
877
878
879                 if($dfrn_version >= 2.1) {      
880                         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
881                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
882                         }
883                         else {
884                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
885                         }
886                 }
887                 else {
888                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
889                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
890                         }
891                         else {
892                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
893                         }
894                 }
895
896                 logger('md5 rawkey ' . md5($postvars['key']));
897
898                 $postvars['key'] = bin2hex($postvars['key']);
899         }
900
901         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
902
903         $xml = post_url($contact['notify'],$postvars);
904
905         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
906
907         $curl_stat = $a->get_curl_code();
908         if((! $curl_stat) || (! strlen($xml)))
909                 return(-1); // timed out
910
911
912         if(strpos($xml,'<?xml') === false) {
913                 logger('dfrn_deliver: phase 2: no valid XML returned');
914                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
915                 return 3;
916         }
917
918         $res = simplexml_load_string($xml);
919
920         return $res->status;
921  
922 }
923
924
925 /*
926  *
927  * consume_feed - process atom feed and update anything/everything we might need to update
928  *
929  * $xml = the (atom) feed to consume - no RSS spoken here, it might partially work since simplepie 
930  *        handles both, but we don't claim it will work well, and are reasonably certain it won't.
931  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
932  *             It is this person's stuff that is going to be updated.
933  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
934  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
935  *             have a contact record.
936  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
937  *        might not) try and subscribe to it.
938  *
939  */
940
941 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0) {
942
943         require_once('simplepie/simplepie.inc');
944
945         $feed = new SimplePie();
946         $feed->set_raw_data($xml);
947         if($datedir)
948                 $feed->enable_order_by_date(true);
949         else
950                 $feed->enable_order_by_date(false);
951         $feed->init();
952
953         if($feed->error())
954                 logger('consume_feed: Error parsing XML: ' . $feed->error());
955
956
957         // Check at the feed level for updated contact name and/or photo
958
959         $name_updated  = '';
960         $new_name = '';
961         $photo_timestamp = '';
962         $photo_url = '';
963         $birthday = '';
964
965         $hubs = $feed->get_links('hub');
966
967         if(count($hubs))
968                 $hub = implode(',', $hubs);
969
970         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
971         if($rawtags) {
972                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
973                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
974                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
975                         $new_name = $elems['name'][0]['data'];
976                 } 
977                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
978                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
979                         $photo_url = $elems['link'][0]['attribs']['']['href'];
980                 }
981
982                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
983                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
984                 }
985         }
986
987         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
988                 logger('consume_feed: Updating photo for ' . $contact['name']);
989                 require_once("Photo.php");
990                 $photo_failure = false;
991                 $have_photo = false;
992
993                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
994                         intval($contact['id']),
995                         intval($contact['uid'])
996                 );
997                 if(count($r)) {
998                         $resource_id = $r[0]['resource-id'];
999                         $have_photo = true;
1000                 }
1001                 else {
1002                         $resource_id = photo_new_resource();
1003                 }
1004                         
1005                 $img_str = fetch_url($photo_url,true);
1006                 $img = new Photo($img_str);
1007                 if($img->is_valid()) {
1008                         if($have_photo) {
1009                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1010                                         dbesc($resource_id),
1011                                         intval($contact['id']),
1012                                         intval($contact['uid'])
1013                                 );
1014                         }
1015                                 
1016                         $img->scaleImageSquare(175);
1017                                 
1018                         $hash = $resource_id;
1019                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
1020                                 
1021                         $img->scaleImage(80);
1022                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
1023
1024                         $img->scaleImage(48);
1025                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 6);
1026
1027                         $a = get_app();
1028
1029                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
1030                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1031                                 dbesc(datetime_convert()),
1032                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1033                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1034                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1035                                 intval($contact['uid']),
1036                                 intval($contact['id'])
1037                         );
1038                 }
1039         }
1040
1041         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1042                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1043                         dbesc(notags(trim($new_name))),
1044                         dbesc(datetime_convert()),
1045                         intval($contact['uid']),
1046                         intval($contact['id'])
1047                 );
1048         }
1049
1050         if(strlen($birthday)) {
1051                 if(substr($birthday,0,4) != $contact['bdyear']) {
1052                         logger('consume_feed: updating birthday: ' . $birthday);
1053
1054                         /**
1055                          *
1056                          * Add new birthday event for this person
1057                          *
1058                          * $bdtext is just a readable placeholder in case the event is shared
1059                          * with others. We will replace it during presentation to our $importer
1060                          * to contain a sparkle link and perhaps a photo. 
1061                          *
1062                          */
1063                          
1064                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1065
1066
1067                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1068                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1069                                 intval($contact['uid']),
1070                                 intval($contact['id']),
1071                                 dbesc(datetime_convert()),
1072                                 dbesc(datetime_convert()),
1073                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1074                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1075                                 dbesc($bdtext),
1076                                 dbesc('birthday')
1077                         );
1078                         
1079
1080                         // update bdyear
1081
1082                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1083                                 dbesc(substr($birthday,0,4)),
1084                                 intval($contact['uid']),
1085                                 intval($contact['id'])
1086                         );
1087
1088                         // This function is called twice without reloading the contact
1089                         // Make sure we only create one event. This is why &$contact 
1090                         // is a reference var in this function
1091
1092                         $contact['bdyear'] = substr($birthday,0,4);
1093                 }
1094
1095         }
1096
1097         // Now process the feed
1098         if($feed->get_item_quantity()) {                
1099
1100         // in inverse date order
1101                 if ($datedir)
1102                         $items = array_reverse($feed->get_items());
1103                 else
1104                         $items = $feed->get_items();
1105
1106                 foreach($items as $item) {
1107
1108                         $deleted = false;
1109
1110                         $rawdelete = $item->get_item_tags( NAMESPACE_TOMB, 'deleted-entry');
1111                         if(isset($rawdelete[0]['attribs']['']['ref'])) {
1112                                 $uri = $rawthread[0]['attribs']['']['ref'];
1113                                 $deleted = true;
1114                                 if(isset($rawdelete[0]['attribs']['']['when'])) {
1115                                         $when = $rawthread[0]['attribs']['']['when'];
1116                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1117                                 }
1118                                 else
1119                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1120                         }
1121                         if($deleted && is_array($contact)) {
1122                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1123                                         dbesc($uri),
1124                                         intval($importer['uid']),
1125                                         intval($contact['id'])
1126                                 );
1127                                 if(count($r)) {
1128                                         $item = $r[0];
1129                                         if($item['uri'] == $item['parent-uri']) {
1130                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1131                                                         `body` = '', `title` = ''
1132                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1133                                                         dbesc($when),
1134                                                         dbesc(datetime_convert()),
1135                                                         dbesc($item['uri']),
1136                                                         intval($importer['uid'])
1137                                                 );
1138                                         }
1139                                         else {
1140                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1141                                                         `body` = '', `title` = '' 
1142                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1143                                                         dbesc($when),
1144                                                         dbesc(datetime_convert()),
1145                                                         dbesc($uri),
1146                                                         intval($importer['uid'])
1147                                                 );
1148                                                 if($item['last-child']) {
1149                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1150                                                         $q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1151                                                                 dbesc(datetime_convert()),
1152                                                                 dbesc($item['parent-uri']),
1153                                                                 intval($item['uid'])
1154                                                         );
1155                                                         // who is the last child now? 
1156                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1157                                                                 ORDER BY `created` DESC LIMIT 1",
1158                                                                         dbesc($item['parent-uri']),
1159                                                                         intval($importer['uid'])
1160                                                         );
1161                                                         if(count($r)) {
1162                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1163                                                                         intval($r[0]['id'])
1164                                                                 );
1165                                                         }
1166                                                 }       
1167                                         }
1168                                 }       
1169                                 continue;
1170                         }
1171
1172
1173                         $is_reply = false;              
1174                         $item_id = $item->get_id();
1175                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1176                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1177                                 $is_reply = true;
1178                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1179                         }
1180
1181
1182                         if(($is_reply) && is_array($contact)) {
1183         
1184                                 // Have we seen it? If not, import it.
1185         
1186                                 $item_id = $item->get_id();
1187         
1188                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1189                                         dbesc($item_id),
1190                                         intval($importer['uid'])
1191                                 );
1192                                 // FIXME update content if 'updated' changes
1193                                 if(count($r)) {
1194                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1195                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1196                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1197                                                         dbesc(datetime_convert()),
1198                                                         dbesc($parent_uri),
1199                                                         intval($importer['uid'])
1200                                                 );
1201                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1202                                                         intval($allow[0]['data']),
1203                                                         dbesc(datetime_convert()),
1204                                                         dbesc($item_id),
1205                                                         intval($importer['uid'])
1206                                                 );
1207                                         }
1208                                         continue;
1209                                 }
1210                                 $datarray = get_atom_elements($feed,$item);
1211                                 $force_parent = false;
1212                                 if($contact['network'] === 'stat') {
1213                                         $force_parent = true;
1214                                         if(strlen($datarray['title']))
1215                                                 unset($datarray['title']);
1216                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1217                                                 dbesc(datetime_convert()),
1218                                                 dbesc($parent_uri),
1219                                                 intval($importer['uid'])
1220                                         );
1221                                         $datarray['last-child'] = 1;
1222                                 }
1223
1224                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1225                                         // one way feed - no remote comment ability
1226                                         $datarray['last-child'] = 0;
1227                                 }
1228                                 $datarray['parent-uri'] = $parent_uri;
1229                                 $datarray['uid'] = $importer['uid'];
1230                                 $datarray['contact-id'] = $contact['id'];
1231                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1232                                         $datarray['type'] = 'activity';
1233                                         $datarray['gravity'] = GRAVITY_LIKE;
1234                                 }
1235
1236                                 $r = item_store($datarray,$force_parent);
1237                                 continue;
1238                         }
1239
1240                         else {
1241                                 // Head post of a conversation. Have we seen it? If not, import it.
1242
1243                                 $item_id = $item->get_id();
1244                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1245                                         dbesc($item_id),
1246                                         intval($importer['uid'])
1247                                 );
1248                                 if(count($r)) {
1249                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1250                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1251                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1252                                                         intval($allow[0]['data']),
1253                                                         dbesc(datetime_convert()),
1254                                                         dbesc($item_id),
1255                                                         intval($importer['uid'])
1256                                                 );
1257                                         }
1258                                         continue;
1259                                 }
1260                                 $datarray = get_atom_elements($feed,$item);
1261
1262                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1263                                         logger('consume-feed: New follower');
1264                                         new_follower($importer,$contact,$datarray,$item);
1265                                         return;
1266                                 }
1267                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1268                                         lose_follower($importer,$contact,$datarray,$item);
1269                                         return;
1270                                 }
1271                                 if(! is_array($contact))
1272                                         return;
1273
1274                                 if($contact['network'] === 'stat') {
1275                                         if(strlen($datarray['title']))
1276                                                 unset($datarray['title']);
1277                                         $datarray['last-child'] = 1;
1278                                 }
1279
1280                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1281                                         // one way feed - no remote comment ability
1282                                         $datarray['last-child'] = 0;
1283                                 }
1284
1285                                 $datarray['parent-uri'] = $item_id;
1286                                 $datarray['uid'] = $importer['uid'];
1287                                 $datarray['contact-id'] = $contact['id'];
1288                                 $r = item_store($datarray);
1289                                 continue;
1290
1291                         }
1292                 }
1293         }
1294 }
1295
1296 function new_follower($importer,$contact,$datarray,$item) {
1297         $url = notags(trim($datarray['author-link']));
1298         $name = notags(trim($datarray['author-name']));
1299         $photo = notags(trim($datarray['author-avatar']));
1300
1301         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1302         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1303                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1304
1305         if(is_array($contact)) {
1306                 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
1307                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1308                                 intval(REL_BUD),
1309                                 intval($contact['id']),
1310                                 intval($importer['uid'])
1311                         );
1312                 }
1313
1314                 // send email notification to owner?
1315         }
1316         else {
1317         
1318                 // create contact record - set to readonly
1319
1320                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
1321                         `blocked`, `readonly`, `pending` )
1322                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1 ) ",
1323                         intval($importer['uid']),
1324                         dbesc(datetime_convert()),
1325                         dbesc($url),
1326                         dbesc($name),
1327                         dbesc($nick),
1328                         dbesc($photo),
1329                         dbesc('stat'),
1330                         intval(REL_VIP)
1331                 );
1332                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1333                                 intval($importer['uid']),
1334                                 dbesc($url),
1335                                 intval(REL_VIP)
1336                 );
1337                 if(count($r))
1338                                 $contact_record = $r[0];
1339
1340                 // create notification  
1341                 $hash = random_string();
1342
1343                 if(is_array($contact_record)) {
1344                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1345                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1346                                 intval($importer['uid']),
1347                                 intval($contact_record['id']),
1348                                 dbesc($hash),
1349                                 dbesc(datetime_convert())
1350                         );
1351                 }
1352                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1353                         intval($importer['uid'])
1354                 );
1355                 $a = get_app();
1356                 if(count($r)) {
1357                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1358                                 $email_tpl = load_view_file('view/follow_notify_eml.tpl');
1359                                 $email = replace_macros($email_tpl, array(
1360                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1361                                         '$url' => $url,
1362                                         '$myname' => $r[0]['username'],
1363                                         '$siteurl' => $a->get_baseurl(),
1364                                         '$sitename' => $a->config['sitename']
1365                                 ));
1366                                 $res = mail($r[0]['email'], 
1367                                         t("You have a new follower at ") . $a->config['sitename'],
1368                                         $email,
1369                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
1370                         
1371                         }
1372                 }
1373         }
1374 }
1375
1376 function lose_follower($importer,$contact,$datarray,$item) {
1377
1378         if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1379                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1380                         intval(REL_FAN),
1381                         intval($contact['id'])
1382                 );
1383         }
1384         else {
1385                 contact_remove($contact['id']);
1386         }
1387 }
1388
1389
1390 function subscribe_to_hub($url,$importer,$contact) {
1391
1392         if(is_array($importer)) {
1393                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1394                         intval($importer['uid'])
1395                 );
1396         }
1397         if(! count($r))
1398                 return;
1399
1400         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1401
1402         // Use a single verify token, even if multiple hubs
1403
1404         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1405
1406         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1407
1408         logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1409
1410         if(! strlen($contact['hub-verify'])) {
1411                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1412                         dbesc($verify_token),
1413                         intval($contact['id'])
1414                 );
1415         }
1416
1417         post_url($url,$params);                 
1418         return;
1419
1420 }
1421
1422
1423 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1424         $o = '';
1425         if(! $tag)
1426                 return $o;
1427         $name = xmlify($name);
1428         $uri = xmlify($uri);
1429         $h = intval($h);
1430         $w = intval($w);
1431         $photo = xmlify($photo);
1432
1433
1434         $o .= "<$tag>\r\n";
1435         $o .= "<name>$name</name>\r\n";
1436         $o .= "<uri>$uri</uri>\r\n";
1437         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1438         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1439
1440         call_hooks('atom_author', $o);
1441
1442         $o .= "</$tag>\r\n";
1443         return $o;
1444 }
1445
1446 function atom_entry($item,$type,$author,$owner,$comment = false) {
1447
1448         if($item['deleted'])
1449                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1450
1451         $a = get_app();
1452
1453         $o = "\r\n\r\n<entry>\r\n";
1454
1455         if(is_array($author))
1456                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1457         else
1458                 $o .= atom_author('author',$item['name'],$item['url'],80,80,$item['thumb']);
1459         if(strlen($item['owner-name']))
1460                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1461
1462         if($item['parent'] != $item['id'])
1463                 $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";
1464
1465         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1466         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1467         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1468         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1469         $o .= '<dfrn:env>' . base64url_encode($item['body'], true) . '</dfrn:env>' . "\r\n";
1470         $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($item['body']) : $item['body']) . '</content>' . "\r\n";
1471         $o .= '<link rel="alternate" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1472         if($comment)
1473                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1474
1475         if($item['location']) {
1476                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1477                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1478         }
1479
1480         if($item['coord'])
1481                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1482
1483         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1484                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1485
1486         $verb = construct_verb($item);
1487         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1488         $actobj = construct_activity_object($item);
1489         if(strlen($actobj))
1490                 $o .= $actobj;
1491         $actarg = construct_activity_target($item);
1492         if(strlen($actarg))
1493                 $o .= $actarg;
1494
1495         $mentioned = get_mentions($item);
1496         if($mentioned)
1497                 $o .= $mentioned;
1498         
1499         call_hooks('atom_entry', $o);
1500
1501         $o .= '</entry>' . "\r\n";
1502         
1503         return $o;
1504 }
1505