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