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