]> git.mxchange.org Git - friendica.git/blob - include/items.php
55b17158a3e9d6e1cf99de0ffa8faba35fc6c2e8
[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
388         $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
389         if($rawlocation)
390                 $res['location'] = unxmlify($rawlocation[0]['data']);
391
392
393         $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
394         if($rawcreated)
395                 $res['created'] = unxmlify($rawcreated[0]['data']);
396
397
398         $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
399         if($rawedited)
400                 $res['edited'] = unxmlify($rawedited[0]['data']);
401
402         if((x($res,'edited')) && (! (x($res,'created'))))
403                 $res['created'] = $res['edited']; 
404
405         if(! $res['created'])
406                 $res['created'] = $item->get_date('c');
407
408         if(! $res['edited'])
409                 $res['edited'] = $item->get_date('c');
410
411
412         // Disallow time travelling posts
413
414         $d1 = strtotime($res['created']);
415         $d2 = strtotime($res['edited']);
416         $d3 = strtotime('now');
417
418         if($d1 > $d3)
419                 $res['created'] = datetime_convert();
420         if($d2 > $d3)
421                 $res['edited'] = datetime_convert();
422
423         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
424         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
425                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
426         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
427                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
428         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
429                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
430         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
431                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
432
433         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
434                 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
435
436                 foreach($base as $link) {
437                         if(! $res['owner-avatar']) {
438                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')                 
439                                         $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
440                         }
441                 }
442         }
443
444         $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
445         if($rawgeo)
446                 $res['coord'] = unxmlify($rawgeo[0]['data']);
447
448
449         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
450
451         // select between supported verbs
452
453         if($rawverb) {
454                 $res['verb'] = unxmlify($rawverb[0]['data']);
455         }
456
457         // translate OStatus unfollow to activity streams if it happened to get selected
458                 
459         if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
460                 $res['verb'] = ACTIVITY_UNFOLLOW;
461
462
463         $cats = $item->get_categories();
464         if($cats) {
465                 $tag_arr = array();
466                 foreach($cats as $cat) {
467                         $term = $cat->get_term();
468                         if(! $term)
469                                 $term = $cat->get_label();
470                         $scheme = $cat->get_scheme();
471                         if($scheme && $term && stristr($scheme,'X-DFRN:'))
472                                 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
473                         elseif($term)
474                                 $tag_arr[] = notags(trim($term));
475                 }
476                 $res['tag'] =  implode(',', $tag_arr);
477         }
478
479         $attach = $item->get_enclosures();
480         if($attach) {
481                 $att_arr = array();
482                 foreach($attach as $att) {
483                         $len   = intval($att->get_length());
484                         $link  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
485                         $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
486                         $type  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
487                         if(strpos($type,';'))
488                                 $type = substr($type,0,strpos($type,';'));
489                         if((! $link) || (strpos($link,'http') !== 0))
490                                 continue;
491
492                         if(! $title)
493                                 $title = ' ';
494                         if(! $type)
495                                 $type = 'application/octet-stream';
496
497                         $att_arr[] = '[attach]href="' . $link . '" size="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]'; 
498                 }
499                 $res['attach'] = implode(',', $att_arr);
500         }
501
502         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
503
504         if($rawobj) {
505                 $res['object'] = '<object>' . "\n";
506                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
507                         $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
508                         $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
509                 }       
510                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
511                         $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
512                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
513                         $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
514                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
515                         $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
516                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
517                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
518                         if(! $body)
519                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
520                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
521                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
522                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
523
524                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
525                                         '[youtube]$1[/youtube]', $body);
526
527                 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
528                         '[youtube]$1[/youtube]', $res['body']);
529
530
531                                 $config = HTMLPurifier_Config::createDefault();
532                                 $config->set('Cache.DefinitionImpl', null);
533
534                                 $purifier = new HTMLPurifier($config);
535                                 $body = $purifier->purify($body);
536                                 $body = html2bbcode($body);
537                         }
538
539                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
540                 }
541
542                 $res['object'] .= '</object>' . "\n";
543         }
544
545         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
546
547         if($rawobj) {
548                 $res['target'] = '<target>' . "\n";
549                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
550                         $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
551                 }       
552                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
553                         $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
554
555                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
556                         $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
557                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
558                         $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
559                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
560                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
561                         if(! $body)
562                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
563                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
564                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
565                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
566
567                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
568                                         '[youtube]$1[/youtube]', $body);
569
570                 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
571                         '[youtube]$1[/youtube]', $res['body']);
572
573                                 $config = HTMLPurifier_Config::createDefault();
574                                 $config->set('Cache.DefinitionImpl', null);
575
576                                 $purifier = new HTMLPurifier($config);
577                                 $body = $purifier->purify($body);
578                                 $body = html2bbcode($body);
579                         }
580
581                         $res['target'] .= '<content>' . $body . '</content>' . "\n";
582                 }
583
584                 $res['target'] .= '</target>' . "\n";
585         }
586
587         $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
588
589         call_hooks('parse_atom', $arr);
590
591         return $res;
592 }
593
594 function encode_rel_links($links) {
595         $o = '';
596         if(! ((is_array($links)) && (count($links))))
597                 return $o;
598         foreach($links as $link) {
599                 $o .= '<link ';
600                 if($link['attribs']['']['rel'])
601                         $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
602                 if($link['attribs']['']['type'])
603                         $o .= 'type="' . $link['attribs']['']['type'] . '" ';
604                 if($link['attribs']['']['href'])
605                         $o .= 'href="' . $link['attribs']['']['href'] . '" ';
606                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
607                         $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
608                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
609                         $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
610                 $o .= ' />' . "\n" ;
611         }
612         return xmlify($o);
613 }
614
615 function item_store($arr,$force_parent = false) {
616
617         if($arr['gravity'])
618                 $arr['gravity'] = intval($arr['gravity']);
619         elseif($arr['parent-uri'] == $arr['uri'])
620                 $arr['gravity'] = 0;
621         elseif(activity_match($arr['verb'],ACTIVITY_POST))
622                 $arr['gravity'] = 6;
623         else      
624                 $arr['gravity'] = 6;   // extensible catchall
625
626         if(! x($arr,'type'))
627                 $arr['type']      = 'remote';
628
629         // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
630
631         if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false)) 
632                 $arr['body'] = strip_tags($arr['body']);
633
634
635         $arr['wall']          = ((x($arr,'wall'))          ? intval($arr['wall'])                : 0);
636         $arr['uri']           = ((x($arr,'uri'))           ? notags(trim($arr['uri']))           : random_string());
637         $arr['author-name']   = ((x($arr,'author-name'))   ? notags(trim($arr['author-name']))   : '');
638         $arr['author-link']   = ((x($arr,'author-link'))   ? notags(trim($arr['author-link']))   : '');
639         $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
640         $arr['owner-name']    = ((x($arr,'owner-name'))    ? notags(trim($arr['owner-name']))    : '');
641         $arr['owner-link']    = ((x($arr,'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
642         $arr['owner-avatar']  = ((x($arr,'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
643         $arr['created']       = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
644         $arr['edited']        = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
645         $arr['changed']       = datetime_convert();
646         $arr['title']         = ((x($arr,'title'))         ? notags(trim($arr['title']))         : '');
647         $arr['location']      = ((x($arr,'location'))      ? notags(trim($arr['location']))      : '');
648         $arr['coord']         = ((x($arr,'coord'))         ? notags(trim($arr['coord']))         : '');
649         $arr['last-child']    = ((x($arr,'last-child'))    ? intval($arr['last-child'])          : 0 );
650         $arr['visible']       = ((x($arr,'visible') !== false) ? intval($arr['visible'])         : 1 );
651         $arr['deleted']       = 0;
652         $arr['parent-uri']    = ((x($arr,'parent-uri'))    ? notags(trim($arr['parent-uri']))    : '');
653         $arr['verb']          = ((x($arr,'verb'))          ? notags(trim($arr['verb']))          : '');
654         $arr['object-type']   = ((x($arr,'object-type'))   ? notags(trim($arr['object-type']))   : '');
655         $arr['object']        = ((x($arr,'object'))        ? trim($arr['object'])                : '');
656         $arr['target-type']   = ((x($arr,'target-type'))   ? notags(trim($arr['target-type']))   : '');
657         $arr['target']        = ((x($arr,'target'))        ? trim($arr['target'])                : '');
658         $arr['plink']         = ((x($arr,'plink'))         ? notags(trim($arr['plink']))         : '');
659         $arr['allow_cid']     = ((x($arr,'allow_cid'))     ? trim($arr['allow_cid'])             : '');
660         $arr['allow_gid']     = ((x($arr,'allow_gid'))     ? trim($arr['allow_gid'])             : '');
661         $arr['deny_cid']      = ((x($arr,'deny_cid'))      ? trim($arr['deny_cid'])              : '');
662         $arr['deny_gid']      = ((x($arr,'deny_gid'))      ? trim($arr['deny_gid'])              : '');
663         $arr['private']       = ((x($arr,'private'))       ? intval($arr['private'])             : 0 );
664         $arr['body']          = ((x($arr,'body'))          ? trim($arr['body'])                  : '');
665         $arr['tag']           = ((x($arr,'tag'))           ? notags(trim($arr['tag']))           : '');
666         $arr['attach']        = ((x($arr,'attach'))        ? notags(trim($arr['attach']))        : '');
667
668         if($arr['parent-uri'] === $arr['uri']) {
669                 $parent_id = 0;
670                 $allow_cid = $arr['allow_cid'];
671                 $allow_gid = $arr['allow_gid'];
672                 $deny_cid  = $arr['deny_cid'];
673                 $deny_gid  = $arr['deny_gid'];
674         }
675         else { 
676
677                 // find the parent and snarf the item id and ACL's
678                 // and anything else we need to inherit
679
680                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
681                         dbesc($arr['parent-uri']),
682                         intval($arr['uid'])
683                 );
684
685                 if(count($r)) {
686
687                         // is the new message multi-level threaded?
688                         // even though we don't support it now, preserve the info
689                         // and re-attach to the conversation parent.
690
691                         if($r[0]['uri'] != $r[0]['parent-uri']) {
692                                 $arr['thr-parent'] = $arr['parent-uri'];
693                                 $arr['parent-uri'] = $r[0]['parent-uri'];
694                         }
695
696                         $parent_id      = $r[0]['id'];
697                         $parent_deleted = $r[0]['deleted'];
698                         $allow_cid      = $r[0]['allow_cid'];
699                         $allow_gid      = $r[0]['allow_gid'];
700                         $deny_cid       = $r[0]['deny_cid'];
701                         $deny_gid       = $r[0]['deny_gid'];
702                         $arr['wall']    = $r[0]['wall'];
703                 }
704                 else {
705
706                         // Allow one to see reply tweets from status.net even when
707                         // we don't have or can't see the original post.
708
709                         if($force_parent) {
710                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
711                                 $parent_id = 0;
712                                 $arr['thr-parent'] = $arr['parent-uri'];
713                                 $arr['parent-uri'] = $arr['uri'];
714                                 $arr['gravity'] = 0;
715                         }
716                         else {
717                                 logger('item_store: item parent was not found - ignoring item');
718                                 return 0;
719                         }
720                 }
721         }
722
723         call_hooks('post_remote',$arr);
724
725         dbesc_array($arr);
726
727         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
728
729         $r = dbq("INSERT INTO `item` (`" 
730                         . implode("`, `", array_keys($arr)) 
731                         . "`) VALUES ('" 
732                         . implode("', '", array_values($arr)) 
733                         . "')" );
734
735         // find the item we just created
736
737         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
738                 $arr['uri'],           // already dbesc'd
739                 intval($arr['uid'])
740         );
741         if(count($r)) {
742                 $current_post = $r[0]['id'];
743                 logger('item_store: created item ' . $current_post);
744         }
745         else {
746                 logger('item_store: could not locate created item');
747                 return 0;
748         }
749
750         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
751                 $parent_id = $current_post;
752
753         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
754                 $private = 1;
755         else
756                 $private = $arr['private']; 
757
758         // Set parent id - and also make sure to inherit the parent's ACL's.
759
760         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
761                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
762                 intval($parent_id),
763                 dbesc($allow_cid),
764                 dbesc($allow_gid),
765                 dbesc($deny_cid),
766                 dbesc($deny_gid),
767                 intval($private),
768                 intval($parent_deleted),
769                 intval($current_post)
770         );
771
772         /**
773          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
774          */
775
776         if($arr['last-child']) {
777                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
778                         dbesc($arr['uri']),
779                         intval($arr['uid']),
780                         intval($current_post)
781                 );
782         }
783
784         return $current_post;
785 }
786
787 function get_item_contact($item,$contacts) {
788         if(! count($contacts) || (! is_array($item)))
789                 return false;
790         foreach($contacts as $contact) {
791                 if($contact['id'] == $item['contact-id']) {
792                         return $contact;
793                         break; // NOTREACHED
794                 }
795         }
796         return false;
797 }
798
799
800 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
801
802         $a = get_app();
803
804         if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
805                 return 3;
806
807         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
808
809         if($contact['duplex'] && $contact['dfrn-id'])
810                 $idtosend = '0:' . $orig_id;
811         if($contact['duplex'] && $contact['issued-id'])
812                 $idtosend = '1:' . $orig_id;            
813
814         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
815
816         $rino_enable = get_config('system','rino_encrypt');
817
818         if(! $rino_enable)
819                 $rino = 0;
820
821         $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
822
823         logger('dfrn_deliver: ' . $url);
824
825         $xml = fetch_url($url);
826
827         $curl_stat = $a->get_curl_code();
828         if(! $curl_stat)
829                 return(-1); // timed out
830
831         logger('dfrn_deliver: ' . $xml);
832
833         if(! $xml)
834                 return 3;
835
836         if(strpos($xml,'<?xml') === false) {
837                 logger('dfrn_deliver: no valid XML returned');
838                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
839                 return 3;
840         }
841
842         $res = parse_xml_string($xml);
843
844         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
845                 return (($res->status) ? $res->status : 3);
846
847         $postvars     = array();
848         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
849         $challenge    = hex2bin((string) $res->challenge);
850         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
851         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
852
853         $final_dfrn_id = '';
854
855
856         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
857                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
858                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
859         }
860         else {
861                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
862                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
863         }
864
865         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
866
867         if(strpos($final_dfrn_id,':') == 1)
868                 $final_dfrn_id = substr($final_dfrn_id,2);
869
870         if($final_dfrn_id != $orig_id) {
871                 logger('dfrn_deliver: wrong dfrn_id.');
872                 // did not decode properly - cannot trust this site 
873                 return 3;
874         }
875
876         $postvars['dfrn_id']      = $idtosend;
877         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
878         if($dissolve)
879                 $postvars['dissolve'] = '1';
880
881
882         if((($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
883                 $postvars['data'] = $atom;
884                 $postvars['perm'] = 'rw';
885         }
886         else {
887                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
888                 $postvars['perm'] = 'r';
889         }
890
891         if($rino && $rino_allowed && (! $dissolve)) {
892                 $key = substr(random_string(),0,16);
893                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
894                 $postvars['data'] = $data;
895                 logger('rino: sent key = ' . $key);     
896
897
898                 if($dfrn_version >= 2.1) {      
899                         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
900                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
901                         }
902                         else {
903                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
904                         }
905                 }
906                 else {
907                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
908                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
909                         }
910                         else {
911                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
912                         }
913                 }
914
915                 logger('md5 rawkey ' . md5($postvars['key']));
916
917                 $postvars['key'] = bin2hex($postvars['key']);
918         }
919
920         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
921
922         $xml = post_url($contact['notify'],$postvars);
923
924         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
925
926         $curl_stat = $a->get_curl_code();
927         if((! $curl_stat) || (! strlen($xml)))
928                 return(-1); // timed out
929
930         if(strpos($xml,'<?xml') === false) {
931                 logger('dfrn_deliver: phase 2: no valid XML returned');
932                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
933                 return 3;
934         }
935
936         $res = parse_xml_string($xml);
937
938         return $res->status; 
939 }
940
941
942 /**
943  *
944  * consume_feed - process atom feed and update anything/everything we might need to update
945  *
946  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
947  *
948  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
949  *             It is this person's stuff that is going to be updated.
950  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
951  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
952  *             have a contact record.
953  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
954  *        might not) try and subscribe to it.
955  *
956  */
957
958 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $secure_feed = false) {
959
960         require_once('simplepie/simplepie.inc');
961
962         $feed = new SimplePie();
963         $feed->set_raw_data($xml);
964         if($datedir)
965                 $feed->enable_order_by_date(true);
966         else
967                 $feed->enable_order_by_date(false);
968         $feed->init();
969
970         if($feed->error())
971                 logger('consume_feed: Error parsing XML: ' . $feed->error());
972
973         $permalink = $feed->get_permalink();
974
975         // Check at the feed level for updated contact name and/or photo
976
977         $name_updated  = '';
978         $new_name = '';
979         $photo_timestamp = '';
980         $photo_url = '';
981         $birthday = '';
982
983         $hubs = $feed->get_links('hub');
984
985         if(count($hubs))
986                 $hub = implode(',', $hubs);
987
988         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
989         if($rawtags) {
990                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
991                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
992                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
993                         $new_name = $elems['name'][0]['data'];
994                 } 
995                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
996                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
997                         $photo_url = $elems['link'][0]['attribs']['']['href'];
998                 }
999
1000                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1001                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1002                 }
1003         }
1004
1005         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1006                 logger('consume_feed: Updating photo for ' . $contact['name']);
1007                 require_once("Photo.php");
1008                 $photo_failure = false;
1009                 $have_photo = false;
1010
1011                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1012                         intval($contact['id']),
1013                         intval($contact['uid'])
1014                 );
1015                 if(count($r)) {
1016                         $resource_id = $r[0]['resource-id'];
1017                         $have_photo = true;
1018                 }
1019                 else {
1020                         $resource_id = photo_new_resource();
1021                 }
1022                         
1023                 $img_str = fetch_url($photo_url,true);
1024                 $img = new Photo($img_str);
1025                 if($img->is_valid()) {
1026                         if($have_photo) {
1027                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1028                                         dbesc($resource_id),
1029                                         intval($contact['id']),
1030                                         intval($contact['uid'])
1031                                 );
1032                         }
1033                                 
1034                         $img->scaleImageSquare(175);
1035                                 
1036                         $hash = $resource_id;
1037                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
1038                                 
1039                         $img->scaleImage(80);
1040                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
1041
1042                         $img->scaleImage(48);
1043                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 6);
1044
1045                         $a = get_app();
1046
1047                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
1048                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1049                                 dbesc(datetime_convert()),
1050                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1051                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1052                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1053                                 intval($contact['uid']),
1054                                 intval($contact['id'])
1055                         );
1056                 }
1057         }
1058
1059         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1060                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1061                         dbesc(notags(trim($new_name))),
1062                         dbesc(datetime_convert()),
1063                         intval($contact['uid']),
1064                         intval($contact['id'])
1065                 );
1066         }
1067
1068         if(strlen($birthday)) {
1069                 if(substr($birthday,0,4) != $contact['bdyear']) {
1070                         logger('consume_feed: updating birthday: ' . $birthday);
1071
1072                         /**
1073                          *
1074                          * Add new birthday event for this person
1075                          *
1076                          * $bdtext is just a readable placeholder in case the event is shared
1077                          * with others. We will replace it during presentation to our $importer
1078                          * to contain a sparkle link and perhaps a photo. 
1079                          *
1080                          */
1081                          
1082                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1083
1084
1085                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1086                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1087                                 intval($contact['uid']),
1088                                 intval($contact['id']),
1089                                 dbesc(datetime_convert()),
1090                                 dbesc(datetime_convert()),
1091                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1092                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1093                                 dbesc($bdtext),
1094                                 dbesc('birthday')
1095                         );
1096                         
1097
1098                         // update bdyear
1099
1100                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1101                                 dbesc(substr($birthday,0,4)),
1102                                 intval($contact['uid']),
1103                                 intval($contact['id'])
1104                         );
1105
1106                         // This function is called twice without reloading the contact
1107                         // Make sure we only create one event. This is why &$contact 
1108                         // is a reference var in this function
1109
1110                         $contact['bdyear'] = substr($birthday,0,4);
1111                 }
1112
1113         }
1114
1115
1116         // process any deleted entries
1117
1118         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1119         if(is_array($del_entries) && count($del_entries)) {
1120                 foreach($del_entries as $dentry) {
1121                         $deleted = false;
1122                         if(isset($dentry['attribs']['']['ref'])) {
1123                                 $uri = $dentry['attribs']['']['ref'];
1124                                 $deleted = true;
1125                                 if(isset($dentry['attribs']['']['when'])) {
1126                                         $when = $dentry['attribs']['']['when'];
1127                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1128                                 }
1129                                 else
1130                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1131                         }
1132                         if($deleted && is_array($contact)) {
1133                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1134                                         dbesc($uri),
1135                                         intval($importer['uid']),
1136                                         intval($contact['id'])
1137                                 );
1138                                 if(count($r)) {
1139                                         $item = $r[0];
1140
1141                                         if(! $item['deleted'])
1142                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1143
1144                                         if($item['uri'] == $item['parent-uri']) {
1145                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1146                                                         `body` = '', `title` = ''
1147                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1148                                                         dbesc($when),
1149                                                         dbesc(datetime_convert()),
1150                                                         dbesc($item['uri']),
1151                                                         intval($importer['uid'])
1152                                                 );
1153                                         }
1154                                         else {
1155                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1156                                                         `body` = '', `title` = '' 
1157                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1158                                                         dbesc($when),
1159                                                         dbesc(datetime_convert()),
1160                                                         dbesc($uri),
1161                                                         intval($importer['uid'])
1162                                                 );
1163                                                 if($item['last-child']) {
1164                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1165                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1166                                                                 dbesc(datetime_convert()),
1167                                                                 dbesc($item['parent-uri']),
1168                                                                 intval($item['uid'])
1169                                                         );
1170                                                         // who is the last child now? 
1171                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1172                                                                 ORDER BY `created` DESC LIMIT 1",
1173                                                                         dbesc($item['parent-uri']),
1174                                                                         intval($importer['uid'])
1175                                                         );
1176                                                         if(count($r)) {
1177                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1178                                                                         intval($r[0]['id'])
1179                                                                 );
1180                                                         }
1181                                                 }       
1182                                         }
1183                                 }       
1184                         }
1185                 }
1186         }
1187
1188         // Now process the feed
1189
1190         if($feed->get_item_quantity()) {                
1191
1192                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1193
1194         // in inverse date order
1195                 if ($datedir)
1196                         $items = array_reverse($feed->get_items());
1197                 else
1198                         $items = $feed->get_items();
1199
1200
1201                 foreach($items as $item) {
1202
1203                         $is_reply = false;              
1204                         $item_id = $item->get_id();
1205                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1206                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1207                                 $is_reply = true;
1208                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1209                         }
1210
1211                         if(($is_reply) && is_array($contact)) {
1212
1213                                 // Have we seen it? If not, import it.
1214         
1215                                 $item_id  = $item->get_id();
1216                                 $datarray = get_atom_elements($feed,$item);
1217
1218                                 if(! x($datarray,'author-name'))
1219                                         $datarray['author-name'] = $contact['name'];
1220                                 if(! x($datarray,'author-link'))
1221                                         $datarray['author-link'] = $contact['url'];
1222                                 if(! x($datarray,'author-avatar'))
1223                                         $datarray['author-avatar'] = $contact['thumb'];
1224
1225                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1226                                         dbesc($item_id),
1227                                         intval($importer['uid'])
1228                                 );
1229
1230                                 // Update content if 'updated' changes
1231
1232                                 if(count($r)) {
1233                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1234                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1235                                                         dbesc($datarray['body']),
1236                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1237                                                         dbesc($item_id),
1238                                                         intval($importer['uid'])
1239                                                 );
1240                                         }
1241
1242                                         // update last-child if it changes
1243
1244                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1245                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1246                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1247                                                         dbesc(datetime_convert()),
1248                                                         dbesc($parent_uri),
1249                                                         intval($importer['uid'])
1250                                                 );
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
1261                                 $force_parent = false;
1262                                 if($contact['network'] === 'stat') {
1263                                         $force_parent = true;
1264                                         if(strlen($datarray['title']))
1265                                                 unset($datarray['title']);
1266                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1267                                                 dbesc(datetime_convert()),
1268                                                 dbesc($parent_uri),
1269                                                 intval($importer['uid'])
1270                                         );
1271                                         $datarray['last-child'] = 1;
1272                                 }
1273
1274                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1275                                         // one way feed - no remote comment ability
1276                                         $datarray['last-child'] = 0;
1277                                 }
1278                                 $datarray['parent-uri'] = $parent_uri;
1279                                 $datarray['uid'] = $importer['uid'];
1280                                 $datarray['contact-id'] = $contact['id'];
1281                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1282                                         $datarray['type'] = 'activity';
1283                                         $datarray['gravity'] = GRAVITY_LIKE;
1284                                 }
1285
1286                                 $r = item_store($datarray,$force_parent);
1287                                 continue;
1288                         }
1289
1290                         else {
1291
1292                                 // Head post of a conversation. Have we seen it? If not, import it.
1293
1294                                 $item_id  = $item->get_id();
1295
1296                                 $datarray = get_atom_elements($feed,$item);
1297
1298                                 if(is_array($contact)) {
1299                                         if(! x($datarray,'author-name'))
1300                                                 $datarray['author-name'] = $contact['name'];
1301                                         if(! x($datarray,'author-link'))
1302                                                 $datarray['author-link'] = $contact['url'];
1303                                         if(! x($datarray,'author-avatar'))
1304                                                 $datarray['author-avatar'] = $contact['thumb'];
1305                                 }
1306
1307                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1308                                         dbesc($item_id),
1309                                         intval($importer['uid'])
1310                                 );
1311
1312                                 // Update content if 'updated' changes
1313
1314                                 if(count($r)) {
1315                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1316                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1317                                                         dbesc($datarray['body']),
1318                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1319                                                         dbesc($item_id),
1320                                                         intval($importer['uid'])
1321                                                 );
1322                                         }
1323
1324                                         // update last-child if it changes
1325
1326                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1327                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1328                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1329                                                         intval($allow[0]['data']),
1330                                                         dbesc(datetime_convert()),
1331                                                         dbesc($item_id),
1332                                                         intval($importer['uid'])
1333                                                 );
1334                                         }
1335                                         continue;
1336                                 }
1337
1338                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1339                                         logger('consume-feed: New follower');
1340                                         new_follower($importer,$contact,$datarray,$item);
1341                                         return;
1342                                 }
1343                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1344                                         lose_follower($importer,$contact,$datarray,$item);
1345                                         return;
1346                                 }
1347                                 if(! is_array($contact))
1348                                         return;
1349
1350                                 if($contact['network'] === 'stat' || stristr($permalink,'twitter.com')) {
1351                                         if(strlen($datarray['title']))
1352                                                 unset($datarray['title']);
1353                                         $datarray['last-child'] = 1;
1354                                 }
1355
1356                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1357                                         // one way feed - no remote comment ability
1358                                         $datarray['last-child'] = 0;
1359                                 }
1360
1361                                 $datarray['parent-uri'] = $item_id;
1362                                 $datarray['uid'] = $importer['uid'];
1363                                 $datarray['contact-id'] = $contact['id'];
1364                                 $r = item_store($datarray);
1365                                 continue;
1366
1367                         }
1368                 }
1369         }
1370 }
1371
1372 function new_follower($importer,$contact,$datarray,$item) {
1373         $url = notags(trim($datarray['author-link']));
1374         $name = notags(trim($datarray['author-name']));
1375         $photo = notags(trim($datarray['author-avatar']));
1376
1377         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1378         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1379                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1380
1381         if(is_array($contact)) {
1382                 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
1383                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1384                                 intval(REL_BUD),
1385                                 intval($contact['id']),
1386                                 intval($importer['uid'])
1387                         );
1388                 }
1389
1390                 // send email notification to owner?
1391         }
1392         else {
1393         
1394                 // create contact record - set to readonly
1395
1396                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
1397                         `blocked`, `readonly`, `pending`, `writable` )
1398                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1, 1 ) ",
1399                         intval($importer['uid']),
1400                         dbesc(datetime_convert()),
1401                         dbesc($url),
1402                         dbesc($name),
1403                         dbesc($nick),
1404                         dbesc($photo),
1405                         dbesc('stat'),
1406                         intval(REL_VIP)
1407                 );
1408                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1409                                 intval($importer['uid']),
1410                                 dbesc($url),
1411                                 intval(REL_VIP)
1412                 );
1413                 if(count($r))
1414                                 $contact_record = $r[0];
1415
1416                 // create notification  
1417                 $hash = random_string();
1418
1419                 if(is_array($contact_record)) {
1420                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1421                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1422                                 intval($importer['uid']),
1423                                 intval($contact_record['id']),
1424                                 dbesc($hash),
1425                                 dbesc(datetime_convert())
1426                         );
1427                 }
1428                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1429                         intval($importer['uid'])
1430                 );
1431                 $a = get_app();
1432                 if(count($r)) {
1433                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1434                                 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
1435                                 $email = replace_macros($email_tpl, array(
1436                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1437                                         '$url' => $url,
1438                                         '$myname' => $r[0]['username'],
1439                                         '$siteurl' => $a->get_baseurl(),
1440                                         '$sitename' => $a->config['sitename']
1441                                 ));
1442                                 $res = mail($r[0]['email'], 
1443                                         t("You have a new follower at ") . $a->config['sitename'],
1444                                         $email,
1445                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
1446                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
1447                                         . 'Content-transfer-encoding: 8bit' );
1448                         
1449                         }
1450                 }
1451         }
1452 }
1453
1454 function lose_follower($importer,$contact,$datarray,$item) {
1455
1456         if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1457                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1458                         intval(REL_FAN),
1459                         intval($contact['id'])
1460                 );
1461         }
1462         else {
1463                 contact_remove($contact['id']);
1464         }
1465 }
1466
1467
1468 function subscribe_to_hub($url,$importer,$contact) {
1469
1470         if(is_array($importer)) {
1471                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1472                         intval($importer['uid'])
1473                 );
1474         }
1475         if(! count($r))
1476                 return;
1477
1478         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1479
1480         // Use a single verify token, even if multiple hubs
1481
1482         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1483
1484         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1485
1486         logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1487
1488         if(! strlen($contact['hub-verify'])) {
1489                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1490                         dbesc($verify_token),
1491                         intval($contact['id'])
1492                 );
1493         }
1494
1495         post_url($url,$params);                 
1496         return;
1497
1498 }
1499
1500
1501 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1502         $o = '';
1503         if(! $tag)
1504                 return $o;
1505         $name = xmlify($name);
1506         $uri = xmlify($uri);
1507         $h = intval($h);
1508         $w = intval($w);
1509         $photo = xmlify($photo);
1510
1511
1512         $o .= "<$tag>\r\n";
1513         $o .= "<name>$name</name>\r\n";
1514         $o .= "<uri>$uri</uri>\r\n";
1515         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1516         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1517
1518         call_hooks('atom_author', $o);
1519
1520         $o .= "</$tag>\r\n";
1521         return $o;
1522 }
1523
1524 function atom_entry($item,$type,$author,$owner,$comment = false) {
1525
1526         $a = get_app();
1527
1528         if($item['deleted'])
1529                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1530
1531
1532         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
1533                 $body = fix_private_photos($item['body'],$owner['uid']);
1534         else
1535                 $body = $item['body'];
1536
1537
1538         $o = "\r\n\r\n<entry>\r\n";
1539
1540         if(is_array($author))
1541                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1542         else
1543                 $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']));
1544         if(strlen($item['owner-name']))
1545                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1546
1547         if($item['parent'] != $item['id'])
1548                 $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";
1549
1550         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1551         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1552         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1553         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1554         $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
1555         $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($body) : $body) . '</content>' . "\r\n";
1556         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1557         if($comment)
1558                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1559
1560         if($item['location']) {
1561                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1562                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1563         }
1564
1565         if($item['coord'])
1566                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1567
1568         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1569                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1570
1571         $verb = construct_verb($item);
1572         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1573         $actobj = construct_activity_object($item);
1574         if(strlen($actobj))
1575                 $o .= $actobj;
1576         $actarg = construct_activity_target($item);
1577         if(strlen($actarg))
1578                 $o .= $actarg;
1579
1580         $tags = item_getfeedtags($item);
1581         if(count($tags)) {
1582                 foreach($tags as $t) {
1583                         $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
1584                 }
1585         }
1586
1587         $o .= item_getfeedattach($item);
1588
1589         $mentioned = get_mentions($item);
1590         if($mentioned)
1591                 $o .= $mentioned;
1592         
1593         call_hooks('atom_entry', $o);
1594
1595         $o .= '</entry>' . "\r\n";
1596         
1597         return $o;
1598 }
1599
1600 function fix_private_photos($s,$uid) {
1601         $a = get_app();
1602         logger('fix_private_photos');
1603
1604         if(preg_match("/\[img\](.+?)\[\/img\]/is",$s,$matches)) {
1605                 $image = $matches[1];
1606                 logger('fix_private_photos: found photo ' . $image);
1607                 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
1608                         $i = basename($image);
1609                         $i = str_replace('.jpg','',$i);
1610                         $x = strpos($i,'-');
1611                         if($x) {
1612                                 $res = substr($i,$x+1);
1613                                 $i = substr($i,0,$x);
1614                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1615                                         dbesc($i),
1616                                         intval($res),
1617                                         intval($uid)
1618                                 );
1619                                 if(count($r)) {
1620                                         logger('replacing photo');
1621                                         $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
1622                                 }
1623                         }
1624                         logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
1625                 }       
1626         }
1627         return($s);
1628 }
1629
1630
1631
1632 function item_getfeedtags($item) {
1633         $ret = array();
1634         $matches = false;
1635         $cnt = preg_match_all('|\#\[url\=(.+?)\](.+?)\[\/url\]|',$item['tag'],$matches);
1636         if($cnt) {
1637                 for($x = 0; $x < count($matches); $x ++) {
1638                         if($matches[1][$x])
1639                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1640                 }
1641         }
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         return $ret;
1651 }
1652
1653 function item_getfeedattach($item) {
1654         $ret = '';
1655         $arr = explode(',',$item['attach']);
1656         if(count($arr)) {
1657                 foreach($arr as $r) {
1658                         $matches = false;
1659                         $cnt = preg_match('|\[attach\]href=\"(.+?)\" size=\"(.+?)\" type=\"(.+?)\" title=\"(.+?)\"\[\/attach\]|',$r,$matches);
1660                         if($cnt) {
1661                                 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
1662                                 if(intval($matches[2]))
1663                                         $ret .= 'size="' . intval($matches[2]) . '" ';
1664                                 if($matches[4] !== ' ')
1665                                         $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
1666                                 $ret .= ' />' . "\r\n";
1667                         }
1668                 }
1669         }
1670         return $ret;
1671 }
1672
1673
1674         
1675 function item_expire($uid,$days) {
1676
1677         if((! $uid) || (! $days))
1678                 return;
1679
1680         $r = q("SELECT * FROM `item` 
1681                 WHERE `uid` = %d 
1682                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
1683                 AND `id` = `parent` 
1684                 AND `deleted` = 0",
1685                 intval($uid),
1686                 intval($days)
1687         );
1688
1689         if(! count($r))
1690                 return;
1691  
1692         logger('expire: # items=' . count($r) );
1693
1694         foreach($r as $item) {
1695
1696                 // Only expire posts, not photos and photo comments
1697
1698                 if(strlen($item['resource-id']))
1699                         continue;
1700
1701                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1702                         dbesc(datetime_convert()),
1703                         dbesc(datetime_convert()),
1704                         intval($item['id'])
1705                 );
1706
1707                 // kill the kids
1708
1709                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1710                         dbesc(datetime_convert()),
1711                         dbesc(datetime_convert()),
1712                         dbesc($item['parent-uri']),
1713                         intval($item['uid'])
1714                 );
1715
1716         }
1717
1718         proc_run('php',"include/notifier.php","expire","$uid");
1719
1720 }