]> git.mxchange.org Git - friendica.git/blob - include/items.php
50d7bd68c7439485af54b3b5dfe628441a5a2268
[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         // default permissions - anonymous user
10
11         if(! strlen($owner_nick))
12                 killme();
13
14         $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid`  = '' AND `deny_gid`  = '' ";
15
16         $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`
17                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
18                 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
19                 dbesc($owner_nick)
20         );
21
22         if(! count($r))
23                 killme();
24
25         $owner = $r[0];
26         $owner_id = $owner['user_uid'];
27         $owner_nick = $owner['nickname'];
28
29         $birthday = feed_birthday($owner_id,$owner['timezone']);
30
31         if(strlen($dfrn_id)) {
32
33                 $sql_extra = '';
34                 switch($direction) {
35                         case (-1):
36                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
37                                 $my_id = $dfrn_id;
38                                 break;
39                         case 0:
40                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
41                                 $my_id = '1:' . $dfrn_id;
42                                 break;
43                         case 1:
44                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
45                                 $my_id = '0:' . $dfrn_id;
46                                 break;
47                         default:
48                                 return false;
49                                 break; // NOTREACHED
50                 }
51
52                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
53                         intval($owner_id)
54                 );
55
56                 if(! count($r))
57                         killme();
58
59                 $contact = $r[0];
60                 $groups = init_groups_visitor($contact['id']);
61
62                 if(count($groups)) {
63                         for($x = 0; $x < count($groups); $x ++) 
64                                 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
65                         $gs = implode('|', $groups);
66                 }
67                 else
68                         $gs = '<<>>' ; // Impossible to match 
69
70                 $sql_extra = sprintf(" 
71                         AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' ) 
72                         AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' ) 
73                         AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
74                         AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s') 
75                 ",
76                         intval($contact['id']),
77                         intval($contact['id']),
78                         dbesc($gs),
79                         dbesc($gs)
80                 );
81         }
82
83         if($dfrn_id === '' || $dfrn_id === '*')
84                 $sort = 'DESC';
85         else
86                 $sort = 'ASC';
87
88         if(! strlen($last_update))
89                 $last_update = 'now -30 days';
90
91         $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
92
93         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
94                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, 
95                 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
96                 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, 
97                 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`
98                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
99                 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`parent` != 0 
100                 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
101                 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
102                 $sql_extra
103                 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
104                 intval($owner_id),
105                 dbesc($check_date),
106                 dbesc($check_date),
107                 dbesc($sort)
108         );
109
110         // Will check further below if this actually returned results.
111         // We will provide an empty feed if that is the case.
112
113         $items = $r;
114
115         $feed_template = get_markup_template('atom_feed.tpl');
116
117         $atom = '';
118
119         $hubxml = feed_hublinks();
120
121         $salmon = feed_salmonlinks($owner_nick);
122
123         $atom .= replace_macros($feed_template, array(
124                 '$version'      => xmlify(FRIENDIKA_VERSION),
125                 '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
126                 '$feed_title'   => xmlify($owner['name']),
127                 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
128                 '$hub'          => $hubxml,
129                 '$salmon'       => $salmon,
130                 '$name'         => xmlify($owner['name']),
131                 '$profile_page' => xmlify($owner['url']),
132                 '$photo'        => xmlify($owner['photo']),
133                 '$thumb'        => xmlify($owner['thumb']),
134                 '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
135                 '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
136                 '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) , 
137                 '$birthday'     => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
138         ));
139
140         call_hooks('atom_feed', $atom);
141
142         if(! count($items)) {
143
144                 call_hooks('atom_feed_end', $atom);
145
146                 $atom .= '</feed>' . "\r\n";
147                 return $atom;
148         }
149
150         foreach($items as $item) {
151
152                 // public feeds get html, our own nodes use bbcode
153
154                 if($dfrn_id === '') {
155                         $type = 'html';
156                 }
157                 else {
158                         $type = 'text';
159                 }
160
161                 $atom .= atom_entry($item,$type,null,$owner,true);
162         }
163
164         call_hooks('atom_feed_end', $atom);
165
166         $atom .= '</feed>' . "\r\n";
167
168         return $atom;
169 }
170
171
172 function construct_verb($item) {
173         if($item['verb'])
174                 return $item['verb'];
175         return ACTIVITY_POST;
176 }
177
178 function construct_activity_object($item) {
179
180         if($item['object']) {
181                 $o = '<as:object>' . "\r\n";
182                 $r = parse_xml_string($item['object'],false);
183
184
185                 if(! $r)
186                         return '';
187                 if($r->type)
188                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
189                 if($r->id)
190                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
191                 if($r->title)
192                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
193                 if($r->link) {
194                         if(substr($r->link,0,1) === '<') {
195                                 // patch up some facebook "like" activity objects that got stored incorrectly
196                                 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
197                                 // we can probably remove this hack here and in the following function in a few months time.
198                                 if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
199                                         $r->link = str_replace('&','&amp;', $r->link);
200                                 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
201                                 $o .= $r->link;
202                         }                                       
203                         else
204                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
205                 }
206                 if($r->content)
207                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
208                 $o .= '</as:object>' . "\r\n";
209                 return $o;
210         }
211
212         return '';
213
214
215 function construct_activity_target($item) {
216
217         if($item['target']) {
218                 $o = '<as:target>' . "\r\n";
219                 $r = parse_xml_string($item['target'],false);
220                 if(! $r)
221                         return '';
222                 if($r->type)
223                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
224                 if($r->id)
225                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
226                 if($r->title)
227                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
228                 if($r->link) {
229                         if(substr($r->link,0,1) === '<') {
230                                 if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
231                                         $r->link = str_replace('&','&amp;', $r->link);
232                                 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
233                                 $o .= $r->link;
234                         }                                       
235                         else
236                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
237                 }
238                 if($r->content)
239                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
240                 $o .= '</as:target>' . "\r\n";
241                 return $o;
242         }
243
244         return '';
245
246
247
248
249
250 function get_atom_elements($feed,$item) {
251
252         require_once('library/HTMLPurifier.auto.php');
253         require_once('include/html2bbcode.php');
254
255         $best_photo = array();
256
257         $res = array();
258
259         $author = $item->get_author();
260         if($author) { 
261                 $res['author-name'] = unxmlify($author->get_name());
262                 $res['author-link'] = unxmlify($author->get_link());
263         }
264         else {
265                 $res['author-name'] = unxmlify($feed->get_title());
266                 $res['author-link'] = unxmlify($feed->get_permalink());
267         }
268         $res['uri'] = unxmlify($item->get_id());
269         $res['title'] = unxmlify($item->get_title());
270         $res['body'] = unxmlify($item->get_content());
271         $res['plink'] = unxmlify($item->get_link(0));
272
273         // look for a photo. We should check media size and find the best one,
274         // but for now let's just find any author photo
275
276         $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
277
278         if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
279                 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
280                 foreach($base as $link) {
281                         if(! $res['author-avatar']) {
282                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
283                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
284                         }
285                 }
286         }                       
287
288         $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
289
290         if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
291                 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
292                 if($base && count($base)) {
293                         foreach($base as $link) {
294                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
295                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
296                                 if(! $res['author-avatar']) {
297                                         if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
298                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
299                                 }
300                         }
301                 }
302         }
303
304         // No photo/profile-link on the item - look at the feed level
305
306         if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
307                 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
308                 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
309                         $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
310                         foreach($base as $link) {
311                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
312                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
313                                 if(! $res['author-avatar']) {
314                                         if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
315                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
316                                 }
317                         }
318                 }                       
319
320                 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
321
322                 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
323                         $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
324
325                         if($base && count($base)) {
326                                 foreach($base as $link) {
327                                         if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
328                                                 $res['author-link'] = unxmlify($link['attribs']['']['href']);
329                                         if(! (x($res,'author-avatar'))) {
330                                                 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
331                                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
332                                         }
333                                 }
334                         }
335                 }
336         }
337
338         $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
339         if($apps && $apps[0]['attribs']['']['source']) {
340                 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
341                 if($res['app'] === 'web')
342                         $res['app'] = 'OStatus';
343         }                  
344
345         /**
346          * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
347          */
348
349         $have_real_body = false;
350
351         $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
352         if($rawenv) {
353                 $have_real_body = true;
354                 $res['body'] = $rawenv[0]['data'];
355                 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
356                 // make sure nobody is trying to sneak some html tags by us
357                 $res['body'] = notags(base64url_decode($res['body']));
358         }
359
360         $maxlen = get_max_import_size();
361         if($maxlen && (strlen($res['body']) > $maxlen))
362                 $res['body'] = substr($res['body'],0, $maxlen);
363
364         // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust 
365         // the content type. Our own network only emits text normally, though it might have been converted to 
366         // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
367         // have to assume it is all html and needs to be purified.
368
369         // It doesn't matter all that much security wise - because before this content is used anywhere, we are 
370         // going to escape any tags we find regardless, but this lets us import a limited subset of html from 
371         // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining 
372         // html.
373
374         if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
375
376                 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
377                         '[youtube]$1[/youtube]', $res['body']);
378
379                 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
380                         '[youtube]$1[/youtube]', $res['body']);
381
382                 $res['body'] = oembed_html2bbcode($res['body']);
383
384                 $config = HTMLPurifier_Config::createDefault();
385                 $config->set('Cache.DefinitionImpl', null);
386
387                 // we shouldn't need a whitelist, because the bbcode converter
388                 // will strip out any unsupported tags.
389                 // $config->set('HTML.Allowed', 'p,b,a[href],i'); 
390
391                 $purifier = new HTMLPurifier($config);
392                 $res['body'] = $purifier->purify($res['body']);
393
394                 $res['body'] = html2bbcode($res['body']);
395         }
396
397         $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
398         if($allow && $allow[0]['data'] == 1)
399                 $res['last-child'] = 1;
400         else
401                 $res['last-child'] = 0;
402
403         $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
404         if($private && $private[0]['data'] == 1)
405                 $res['private'] = 1;
406         else
407                 $res['private'] = 0;
408
409         $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
410         if($extid && $extid[0]['data'])
411                 $res['extid'] = $extid[0]['data'];
412
413         $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
414         if($rawlocation)
415                 $res['location'] = unxmlify($rawlocation[0]['data']);
416
417
418         $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
419         if($rawcreated)
420                 $res['created'] = unxmlify($rawcreated[0]['data']);
421
422
423         $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
424         if($rawedited)
425                 $res['edited'] = unxmlify($rawedited[0]['data']);
426
427         if((x($res,'edited')) && (! (x($res,'created'))))
428                 $res['created'] = $res['edited']; 
429
430         if(! $res['created'])
431                 $res['created'] = $item->get_date('c');
432
433         if(! $res['edited'])
434                 $res['edited'] = $item->get_date('c');
435
436
437         // Disallow time travelling posts
438
439         $d1 = strtotime($res['created']);
440         $d2 = strtotime($res['edited']);
441         $d3 = strtotime('now');
442
443         if($d1 > $d3)
444                 $res['created'] = datetime_convert();
445         if($d2 > $d3)
446                 $res['edited'] = datetime_convert();
447
448         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
449         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
450                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
451         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
452                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
453         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
454                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
455         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
456                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
457
458         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
459                 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
460
461                 foreach($base as $link) {
462                         if(! $res['owner-avatar']) {
463                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')                 
464                                         $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
465                         }
466                 }
467         }
468
469         $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
470         if($rawgeo)
471                 $res['coord'] = unxmlify($rawgeo[0]['data']);
472
473
474         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
475
476         // select between supported verbs
477
478         if($rawverb) {
479                 $res['verb'] = unxmlify($rawverb[0]['data']);
480         }
481
482         // translate OStatus unfollow to activity streams if it happened to get selected
483                 
484         if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
485                 $res['verb'] = ACTIVITY_UNFOLLOW;
486
487         $cats = $item->get_categories();
488         if($cats) {
489                 $tag_arr = array();
490                 foreach($cats as $cat) {
491                         $term = $cat->get_term();
492                         if(! $term)
493                                 $term = $cat->get_label();
494                         $scheme = $cat->get_scheme();
495                         if($scheme && $term && stristr($scheme,'X-DFRN:'))
496                                 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
497                         elseif($term)
498                                 $tag_arr[] = notags(trim($term));
499                 }
500                 $res['tag'] =  implode(',', $tag_arr);
501         }
502
503         $attach = $item->get_enclosures();
504         if($attach) {
505                 $att_arr = array();
506                 foreach($attach as $att) {
507                         $len   = intval($att->get_length());
508                         $link  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
509                         $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
510                         $type  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
511                         if(strpos($type,';'))
512                                 $type = substr($type,0,strpos($type,';'));
513                         if((! $link) || (strpos($link,'http') !== 0))
514                                 continue;
515
516                         if(! $title)
517                                 $title = ' ';
518                         if(! $type)
519                                 $type = 'application/octet-stream';
520
521                         $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]'; 
522                 }
523                 $res['attach'] = implode(',', $att_arr);
524         }
525
526         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
527
528         if($rawobj) {
529                 $res['object'] = '<object>' . "\n";
530                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
531                         $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
532                         $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
533                 }       
534                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
535                         $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
536                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
537                         $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
538                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
539                         $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
540                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
541                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
542                         if(! $body)
543                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
544                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
545                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
546                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
547
548                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
549                                         '[youtube]$1[/youtube]', $body);
550
551                 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
552                         '[youtube]$1[/youtube]', $res['body']);
553
554
555                                 $config = HTMLPurifier_Config::createDefault();
556                                 $config->set('Cache.DefinitionImpl', null);
557
558                                 $purifier = new HTMLPurifier($config);
559                                 $body = $purifier->purify($body);
560                                 $body = html2bbcode($body);
561                         }
562
563                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
564                 }
565
566                 $res['object'] .= '</object>' . "\n";
567         }
568
569         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
570
571         if($rawobj) {
572                 $res['target'] = '<target>' . "\n";
573                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
574                         $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
575                 }       
576                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
577                         $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
578
579                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
580                         $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
581                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
582                         $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
583                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
584                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
585                         if(! $body)
586                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
587                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
588                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
589                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
590
591                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
592                                         '[youtube]$1[/youtube]', $body);
593
594                 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
595                         '[youtube]$1[/youtube]', $res['body']);
596
597                                 $config = HTMLPurifier_Config::createDefault();
598                                 $config->set('Cache.DefinitionImpl', null);
599
600                                 $purifier = new HTMLPurifier($config);
601                                 $body = $purifier->purify($body);
602                                 $body = html2bbcode($body);
603                         }
604
605                         $res['target'] .= '<content>' . $body . '</content>' . "\n";
606                 }
607
608                 $res['target'] .= '</target>' . "\n";
609         }
610
611         $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
612
613         call_hooks('parse_atom', $arr);
614
615         return $res;
616 }
617
618 function encode_rel_links($links) {
619         $o = '';
620         if(! ((is_array($links)) && (count($links))))
621                 return $o;
622         foreach($links as $link) {
623                 $o .= '<link ';
624                 if($link['attribs']['']['rel'])
625                         $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
626                 if($link['attribs']['']['type'])
627                         $o .= 'type="' . $link['attribs']['']['type'] . '" ';
628                 if($link['attribs']['']['href'])
629                         $o .= 'href="' . $link['attribs']['']['href'] . '" ';
630                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
631                         $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
632                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
633                         $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
634                 $o .= ' />' . "\n" ;
635         }
636         return xmlify($o);
637 }
638
639 function item_store($arr,$force_parent = false) {
640
641         if($arr['gravity'])
642                 $arr['gravity'] = intval($arr['gravity']);
643         elseif($arr['parent-uri'] == $arr['uri'])
644                 $arr['gravity'] = 0;
645         elseif(activity_match($arr['verb'],ACTIVITY_POST))
646                 $arr['gravity'] = 6;
647         else      
648                 $arr['gravity'] = 6;   // extensible catchall
649
650         if(! x($arr,'type'))
651                 $arr['type']      = 'remote';
652
653         // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
654
655         if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false)) 
656                 $arr['body'] = strip_tags($arr['body']);
657
658
659         $arr['wall']          = ((x($arr,'wall'))          ? intval($arr['wall'])                : 0);
660         $arr['uri']           = ((x($arr,'uri'))           ? notags(trim($arr['uri']))           : random_string());
661         $arr['extid']         = ((x($arr,'extid'))         ? notags(trim($arr['extid']))         : '');
662         $arr['author-name']   = ((x($arr,'author-name'))   ? notags(trim($arr['author-name']))   : '');
663         $arr['author-link']   = ((x($arr,'author-link'))   ? notags(trim($arr['author-link']))   : '');
664         $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
665         $arr['owner-name']    = ((x($arr,'owner-name'))    ? notags(trim($arr['owner-name']))    : '');
666         $arr['owner-link']    = ((x($arr,'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
667         $arr['owner-avatar']  = ((x($arr,'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
668         $arr['created']       = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
669         $arr['edited']        = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
670         $arr['received']      = datetime_convert();
671         $arr['changed']       = datetime_convert();
672         $arr['title']         = ((x($arr,'title'))         ? notags(trim($arr['title']))         : '');
673         $arr['location']      = ((x($arr,'location'))      ? notags(trim($arr['location']))      : '');
674         $arr['coord']         = ((x($arr,'coord'))         ? notags(trim($arr['coord']))         : '');
675         $arr['last-child']    = ((x($arr,'last-child'))    ? intval($arr['last-child'])          : 0 );
676         $arr['visible']       = ((x($arr,'visible') !== false) ? intval($arr['visible'])         : 1 );
677         $arr['deleted']       = 0;
678         $arr['parent-uri']    = ((x($arr,'parent-uri'))    ? notags(trim($arr['parent-uri']))    : '');
679         $arr['verb']          = ((x($arr,'verb'))          ? notags(trim($arr['verb']))          : '');
680         $arr['object-type']   = ((x($arr,'object-type'))   ? notags(trim($arr['object-type']))   : '');
681         $arr['object']        = ((x($arr,'object'))        ? trim($arr['object'])                : '');
682         $arr['target-type']   = ((x($arr,'target-type'))   ? notags(trim($arr['target-type']))   : '');
683         $arr['target']        = ((x($arr,'target'))        ? trim($arr['target'])                : '');
684         $arr['plink']         = ((x($arr,'plink'))         ? notags(trim($arr['plink']))         : '');
685         $arr['allow_cid']     = ((x($arr,'allow_cid'))     ? trim($arr['allow_cid'])             : '');
686         $arr['allow_gid']     = ((x($arr,'allow_gid'))     ? trim($arr['allow_gid'])             : '');
687         $arr['deny_cid']      = ((x($arr,'deny_cid'))      ? trim($arr['deny_cid'])              : '');
688         $arr['deny_gid']      = ((x($arr,'deny_gid'))      ? trim($arr['deny_gid'])              : '');
689         $arr['private']       = ((x($arr,'private'))       ? intval($arr['private'])             : 0 );
690         $arr['body']          = ((x($arr,'body'))          ? trim($arr['body'])                  : '');
691         $arr['tag']           = ((x($arr,'tag'))           ? notags(trim($arr['tag']))           : '');
692         $arr['attach']        = ((x($arr,'attach'))        ? notags(trim($arr['attach']))        : '');
693         $arr['app']           = ((x($arr,'app'))           ? notags(trim($arr['app']))           : '');
694
695         if($arr['parent-uri'] === $arr['uri']) {
696                 $parent_id = 0;
697                 $allow_cid = $arr['allow_cid'];
698                 $allow_gid = $arr['allow_gid'];
699                 $deny_cid  = $arr['deny_cid'];
700                 $deny_gid  = $arr['deny_gid'];
701         }
702         else { 
703
704                 // find the parent and snarf the item id and ACL's
705                 // and anything else we need to inherit
706
707                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
708                         dbesc($arr['parent-uri']),
709                         intval($arr['uid'])
710                 );
711
712                 if(count($r)) {
713
714                         // is the new message multi-level threaded?
715                         // even though we don't support it now, preserve the info
716                         // and re-attach to the conversation parent.
717
718                         if($r[0]['uri'] != $r[0]['parent-uri']) {
719                                 $arr['thr-parent'] = $arr['parent-uri'];
720                                 $arr['parent-uri'] = $r[0]['parent-uri'];
721                         }
722
723                         $parent_id      = $r[0]['id'];
724                         $parent_deleted = $r[0]['deleted'];
725                         $allow_cid      = $r[0]['allow_cid'];
726                         $allow_gid      = $r[0]['allow_gid'];
727                         $deny_cid       = $r[0]['deny_cid'];
728                         $deny_gid       = $r[0]['deny_gid'];
729                         $arr['wall']    = $r[0]['wall'];
730                 }
731                 else {
732
733                         // Allow one to see reply tweets from status.net even when
734                         // we don't have or can't see the original post.
735
736                         if($force_parent) {
737                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
738                                 $parent_id = 0;
739                                 $arr['thr-parent'] = $arr['parent-uri'];
740                                 $arr['parent-uri'] = $arr['uri'];
741                                 $arr['gravity'] = 0;
742                         }
743                         else {
744                                 logger('item_store: item parent was not found - ignoring item');
745                                 return 0;
746                         }
747                 }
748         }
749
750         $arr['guid'] = get_guid();
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'] != CONTACT_IS_SHARING) && (! $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         if(! strlen($xml)) {
1001                 logger('consume_feed: empty input');
1002                 return;
1003         }
1004                 
1005         $feed = new SimplePie();
1006         $feed->set_raw_data($xml);
1007         if($datedir)
1008                 $feed->enable_order_by_date(true);
1009         else
1010                 $feed->enable_order_by_date(false);
1011         $feed->init();
1012
1013         if($feed->error())
1014                 logger('consume_feed: Error parsing XML: ' . $feed->error());
1015
1016         $permalink = $feed->get_permalink();
1017
1018         // Check at the feed level for updated contact name and/or photo
1019
1020         $name_updated  = '';
1021         $new_name = '';
1022         $photo_timestamp = '';
1023         $photo_url = '';
1024         $birthday = '';
1025
1026         $hubs = $feed->get_links('hub');
1027
1028         if(count($hubs))
1029                 $hub = implode(',', $hubs);
1030
1031         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1032         if($rawtags) {
1033                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1034                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1035                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1036                         $new_name = $elems['name'][0]['data'];
1037                 } 
1038                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1039                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1040                         $photo_url = $elems['link'][0]['attribs']['']['href'];
1041                 }
1042
1043                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1044                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1045                 }
1046         }
1047
1048         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1049                 logger('consume_feed: Updating photo for ' . $contact['name']);
1050                 require_once("Photo.php");
1051                 $photo_failure = false;
1052                 $have_photo = false;
1053
1054                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1055                         intval($contact['id']),
1056                         intval($contact['uid'])
1057                 );
1058                 if(count($r)) {
1059                         $resource_id = $r[0]['resource-id'];
1060                         $have_photo = true;
1061                 }
1062                 else {
1063                         $resource_id = photo_new_resource();
1064                 }
1065                         
1066                 $img_str = fetch_url($photo_url,true);
1067                 $img = new Photo($img_str);
1068                 if($img->is_valid()) {
1069                         if($have_photo) {
1070                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1071                                         dbesc($resource_id),
1072                                         intval($contact['id']),
1073                                         intval($contact['uid'])
1074                                 );
1075                         }
1076                                 
1077                         $img->scaleImageSquare(175);
1078                                 
1079                         $hash = $resource_id;
1080                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1081                                 
1082                         $img->scaleImage(80);
1083                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1084
1085                         $img->scaleImage(48);
1086                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1087
1088                         $a = get_app();
1089
1090                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
1091                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1092                                 dbesc(datetime_convert()),
1093                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1094                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1095                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1096                                 intval($contact['uid']),
1097                                 intval($contact['id'])
1098                         );
1099                 }
1100         }
1101
1102         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1103                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1104                         dbesc(notags(trim($new_name))),
1105                         dbesc(datetime_convert()),
1106                         intval($contact['uid']),
1107                         intval($contact['id'])
1108                 );
1109         }
1110
1111         if(strlen($birthday)) {
1112                 if(substr($birthday,0,4) != $contact['bdyear']) {
1113                         logger('consume_feed: updating birthday: ' . $birthday);
1114
1115                         /**
1116                          *
1117                          * Add new birthday event for this person
1118                          *
1119                          * $bdtext is just a readable placeholder in case the event is shared
1120                          * with others. We will replace it during presentation to our $importer
1121                          * to contain a sparkle link and perhaps a photo. 
1122                          *
1123                          */
1124                          
1125                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1126
1127
1128                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1129                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1130                                 intval($contact['uid']),
1131                                 intval($contact['id']),
1132                                 dbesc(datetime_convert()),
1133                                 dbesc(datetime_convert()),
1134                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1135                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1136                                 dbesc($bdtext),
1137                                 dbesc('birthday')
1138                         );
1139                         
1140
1141                         // update bdyear
1142
1143                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1144                                 dbesc(substr($birthday,0,4)),
1145                                 intval($contact['uid']),
1146                                 intval($contact['id'])
1147                         );
1148
1149                         // This function is called twice without reloading the contact
1150                         // Make sure we only create one event. This is why &$contact 
1151                         // is a reference var in this function
1152
1153                         $contact['bdyear'] = substr($birthday,0,4);
1154                 }
1155
1156         }
1157
1158
1159         // process any deleted entries
1160
1161         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1162         if(is_array($del_entries) && count($del_entries)) {
1163                 foreach($del_entries as $dentry) {
1164                         $deleted = false;
1165                         if(isset($dentry['attribs']['']['ref'])) {
1166                                 $uri = $dentry['attribs']['']['ref'];
1167                                 $deleted = true;
1168                                 if(isset($dentry['attribs']['']['when'])) {
1169                                         $when = $dentry['attribs']['']['when'];
1170                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1171                                 }
1172                                 else
1173                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1174                         }
1175                         if($deleted && is_array($contact)) {
1176                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1177                                         dbesc($uri),
1178                                         intval($importer['uid']),
1179                                         intval($contact['id'])
1180                                 );
1181                                 if(count($r)) {
1182                                         $item = $r[0];
1183
1184                                         if(! $item['deleted'])
1185                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1186
1187                                         if($item['uri'] == $item['parent-uri']) {
1188                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1189                                                         `body` = '', `title` = ''
1190                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1191                                                         dbesc($when),
1192                                                         dbesc(datetime_convert()),
1193                                                         dbesc($item['uri']),
1194                                                         intval($importer['uid'])
1195                                                 );
1196                                         }
1197                                         else {
1198                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1199                                                         `body` = '', `title` = '' 
1200                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1201                                                         dbesc($when),
1202                                                         dbesc(datetime_convert()),
1203                                                         dbesc($uri),
1204                                                         intval($importer['uid'])
1205                                                 );
1206                                                 if($item['last-child']) {
1207                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1208                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1209                                                                 dbesc(datetime_convert()),
1210                                                                 dbesc($item['parent-uri']),
1211                                                                 intval($item['uid'])
1212                                                         );
1213                                                         // who is the last child now? 
1214                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1215                                                                 ORDER BY `created` DESC LIMIT 1",
1216                                                                         dbesc($item['parent-uri']),
1217                                                                         intval($importer['uid'])
1218                                                         );
1219                                                         if(count($r)) {
1220                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1221                                                                         intval($r[0]['id'])
1222                                                                 );
1223                                                         }
1224                                                 }       
1225                                         }
1226                                 }       
1227                         }
1228                 }
1229         }
1230
1231         // Now process the feed
1232
1233         if($feed->get_item_quantity()) {                
1234
1235                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1236
1237         // in inverse date order
1238                 if ($datedir)
1239                         $items = array_reverse($feed->get_items());
1240                 else
1241                         $items = $feed->get_items();
1242
1243
1244                 foreach($items as $item) {
1245
1246                         $is_reply = false;              
1247                         $item_id = $item->get_id();
1248                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1249                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1250                                 $is_reply = true;
1251                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1252                         }
1253
1254                         if(($is_reply) && is_array($contact)) {
1255
1256                                 // Have we seen it? If not, import it.
1257         
1258                                 $item_id  = $item->get_id();
1259                                 $datarray = get_atom_elements($feed,$item);
1260
1261                                 if(! x($datarray,'author-name'))
1262                                         $datarray['author-name'] = $contact['name'];
1263                                 if(! x($datarray,'author-link'))
1264                                         $datarray['author-link'] = $contact['url'];
1265                                 if(! x($datarray,'author-avatar'))
1266                                         $datarray['author-avatar'] = $contact['thumb'];
1267
1268
1269                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1270                                         dbesc($item_id),
1271                                         intval($importer['uid'])
1272                                 );
1273
1274                                 // Update content if 'updated' changes
1275
1276                                 if(count($r)) {
1277                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1278                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1279                                                         dbesc($datarray['body']),
1280                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1281                                                         dbesc($item_id),
1282                                                         intval($importer['uid'])
1283                                                 );
1284                                         }
1285
1286                                         // update last-child if it changes
1287
1288                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1289                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1290                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1291                                                         dbesc(datetime_convert()),
1292                                                         dbesc($parent_uri),
1293                                                         intval($importer['uid'])
1294                                                 );
1295                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1296                                                         intval($allow[0]['data']),
1297                                                         dbesc(datetime_convert()),
1298                                                         dbesc($item_id),
1299                                                         intval($importer['uid'])
1300                                                 );
1301                                         }
1302                                         continue;
1303                                 }
1304
1305                                 $force_parent = false;
1306                                 if($contact['network'] === 'stat') {
1307                                         $force_parent = true;
1308                                         if(strlen($datarray['title']))
1309                                                 unset($datarray['title']);
1310                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1311                                                 dbesc(datetime_convert()),
1312                                                 dbesc($parent_uri),
1313                                                 intval($importer['uid'])
1314                                         );
1315                                         $datarray['last-child'] = 1;
1316                                 }
1317
1318                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1319                                         // one way feed - no remote comment ability
1320                                         $datarray['last-child'] = 0;
1321                                 }
1322                                 $datarray['parent-uri'] = $parent_uri;
1323                                 $datarray['uid'] = $importer['uid'];
1324                                 $datarray['contact-id'] = $contact['id'];
1325                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1326                                         $datarray['type'] = 'activity';
1327                                         $datarray['gravity'] = GRAVITY_LIKE;
1328                                 }
1329
1330                                 $r = item_store($datarray,$force_parent);
1331                                 continue;
1332                         }
1333
1334                         else {
1335
1336                                 // Head post of a conversation. Have we seen it? If not, import it.
1337
1338                                 $item_id  = $item->get_id();
1339
1340                                 $datarray = get_atom_elements($feed,$item);
1341
1342                                 if(is_array($contact)) {
1343                                         if(! x($datarray,'author-name'))
1344                                                 $datarray['author-name'] = $contact['name'];
1345                                         if(! x($datarray,'author-link'))
1346                                                 $datarray['author-link'] = $contact['url'];
1347                                         if(! x($datarray,'author-avatar'))
1348                                                 $datarray['author-avatar'] = $contact['thumb'];
1349                                 }
1350
1351                                 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1352                                         $ev = bbtoevent($datarray['body']);
1353                                         if(x($ev,'desc') && x($ev,'start')) {
1354                                                 $ev['uid'] = $importer['uid'];
1355                                                 $ev['uri'] = $item_id;
1356                                                 $ev['edited'] = $datarray['edited'];
1357                                                 $ev['private'] = $datarray['private'];
1358
1359                                                 if(is_array($contact))
1360                                                         $ev['cid'] = $contact['id'];
1361                                                 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1362                                                         dbesc($item_id),
1363                                                         intval($importer['uid'])
1364                                                 );
1365                                                 if(count($r))
1366                                                         $ev['id'] = $r[0]['id'];
1367                                                 $xyz = event_store($ev);
1368                                                 continue;
1369                                         }
1370                                 }
1371
1372                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1373                                         dbesc($item_id),
1374                                         intval($importer['uid'])
1375                                 );
1376
1377                                 // Update content if 'updated' changes
1378
1379                                 if(count($r)) {
1380                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1381                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1382                                                         dbesc($datarray['body']),
1383                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1384                                                         dbesc($item_id),
1385                                                         intval($importer['uid'])
1386                                                 );
1387                                         }
1388
1389                                         // update last-child if it changes
1390
1391                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1392                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1393                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1394                                                         intval($allow[0]['data']),
1395                                                         dbesc(datetime_convert()),
1396                                                         dbesc($item_id),
1397                                                         intval($importer['uid'])
1398                                                 );
1399                                         }
1400                                         continue;
1401                                 }
1402
1403                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1404                                         logger('consume-feed: New follower');
1405                                         new_follower($importer,$contact,$datarray,$item);
1406                                         return;
1407                                 }
1408                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1409                                         lose_follower($importer,$contact,$datarray,$item);
1410                                         return;
1411                                 }
1412                                 if(! is_array($contact))
1413                                         return;
1414
1415                                 if($contact['network'] === 'stat' || stristr($permalink,'twitter.com')) {
1416                                         if(strlen($datarray['title']))
1417                                                 unset($datarray['title']);
1418                                         $datarray['last-child'] = 1;
1419                                 }
1420
1421                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1422                                         // one way feed - no remote comment ability
1423                                         $datarray['last-child'] = 0;
1424                                 }
1425
1426                                 // This is my contact on another system, but it's really me.
1427                                 // Turn this into a wall post.
1428
1429                                 if($contact['remote_self'])
1430                                         $datarray['wall'] = 1;
1431
1432                                 $datarray['parent-uri'] = $item_id;
1433                                 $datarray['uid'] = $importer['uid'];
1434                                 $datarray['contact-id'] = $contact['id'];
1435                                 $r = item_store($datarray);
1436                                 continue;
1437
1438                         }
1439                 }
1440         }
1441 }
1442
1443 function new_follower($importer,$contact,$datarray,$item) {
1444         $url = notags(trim($datarray['author-link']));
1445         $name = notags(trim($datarray['author-name']));
1446         $photo = notags(trim($datarray['author-avatar']));
1447
1448         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1449         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1450                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1451
1452         if(is_array($contact)) {
1453                 if($contact['network'] == 'stat' && $contact['rel'] == CONTACT_IS_SHARING) {
1454                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1455                                 intval(CONTACT_IS_FRIEND),
1456                                 intval($contact['id']),
1457                                 intval($importer['uid'])
1458                         );
1459                 }
1460
1461                 // send email notification to owner?
1462         }
1463         else {
1464         
1465                 // create contact record
1466
1467                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
1468                         `blocked`, `readonly`, `pending`, `writable` )
1469                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
1470                         intval($importer['uid']),
1471                         dbesc(datetime_convert()),
1472                         dbesc($url),
1473                         dbesc($name),
1474                         dbesc($nick),
1475                         dbesc($photo),
1476                         dbesc('stat'),
1477                         intval(CONTACT_IS_FOLLOWER)
1478                 );
1479                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1480                                 intval($importer['uid']),
1481                                 dbesc($url),
1482                                 intval(CONTACT_IS_FOLLOWER)
1483                 );
1484                 if(count($r))
1485                                 $contact_record = $r[0];
1486
1487                 // create notification  
1488                 $hash = random_string();
1489
1490                 if(is_array($contact_record)) {
1491                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1492                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1493                                 intval($importer['uid']),
1494                                 intval($contact_record['id']),
1495                                 dbesc($hash),
1496                                 dbesc(datetime_convert())
1497                         );
1498                 }
1499                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1500                         intval($importer['uid'])
1501                 );
1502                 $a = get_app();
1503                 if(count($r)) {
1504                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1505                                 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
1506                                 $email = replace_macros($email_tpl, array(
1507                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1508                                         '$url' => $url,
1509                                         '$myname' => $r[0]['username'],
1510                                         '$siteurl' => $a->get_baseurl(),
1511                                         '$sitename' => $a->config['sitename']
1512                                 ));
1513                                 $res = mail($r[0]['email'], 
1514                                         t("You have a new follower at ") . $a->config['sitename'],
1515                                         $email,
1516                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
1517                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
1518                                         . 'Content-transfer-encoding: 8bit' );
1519                         
1520                         }
1521                 }
1522         }
1523 }
1524
1525 function lose_follower($importer,$contact,$datarray,$item) {
1526
1527         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1528                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1529                         intval(CONTACT_IS_SHARING),
1530                         intval($contact['id'])
1531                 );
1532         }
1533         else {
1534                 contact_remove($contact['id']);
1535         }
1536 }
1537
1538
1539 function subscribe_to_hub($url,$importer,$contact) {
1540
1541         if(is_array($importer)) {
1542                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1543                         intval($importer['uid'])
1544                 );
1545         }
1546         if(! count($r))
1547                 return;
1548
1549         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1550
1551         // Use a single verify token, even if multiple hubs
1552
1553         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1554
1555         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1556
1557         logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1558
1559         if(! strlen($contact['hub-verify'])) {
1560                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1561                         dbesc($verify_token),
1562                         intval($contact['id'])
1563                 );
1564         }
1565
1566         post_url($url,$params);                 
1567         return;
1568
1569 }
1570
1571
1572 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1573         $o = '';
1574         if(! $tag)
1575                 return $o;
1576         $name = xmlify($name);
1577         $uri = xmlify($uri);
1578         $h = intval($h);
1579         $w = intval($w);
1580         $photo = xmlify($photo);
1581
1582
1583         $o .= "<$tag>\r\n";
1584         $o .= "<name>$name</name>\r\n";
1585         $o .= "<uri>$uri</uri>\r\n";
1586         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1587         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1588
1589         call_hooks('atom_author', $o);
1590
1591         $o .= "</$tag>\r\n";
1592         return $o;
1593 }
1594
1595 function atom_entry($item,$type,$author,$owner,$comment = false) {
1596
1597         $a = get_app();
1598
1599         if($item['deleted'])
1600                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1601
1602
1603         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
1604                 $body = fix_private_photos($item['body'],$owner['uid']);
1605         else
1606                 $body = $item['body'];
1607
1608
1609         $o = "\r\n\r\n<entry>\r\n";
1610
1611         if(is_array($author))
1612                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1613         else
1614                 $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']));
1615         if(strlen($item['owner-name']))
1616                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1617
1618         if($item['parent'] != $item['id'])
1619                 $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";
1620
1621         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1622         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1623         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1624         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1625         $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
1626         $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($body) : $body) . '</content>' . "\r\n";
1627         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1628         if($comment)
1629                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1630
1631         if($item['location']) {
1632                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1633                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1634         }
1635
1636         if($item['coord'])
1637                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1638
1639         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1640                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1641
1642         if($item['extid'])
1643                 $o .= '<dfrn:extid>' . $item['extid'] . '</dfrn:extid>' . "\r\n";
1644
1645         if($item['app'])
1646                 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . $item['app'] . '" ></statusnet:notice_info>';
1647         $verb = construct_verb($item);
1648         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1649         $actobj = construct_activity_object($item);
1650         if(strlen($actobj))
1651                 $o .= $actobj;
1652         $actarg = construct_activity_target($item);
1653         if(strlen($actarg))
1654                 $o .= $actarg;
1655
1656         $tags = item_getfeedtags($item);
1657         if(count($tags)) {
1658                 foreach($tags as $t) {
1659                         $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
1660                 }
1661         }
1662
1663         $o .= item_getfeedattach($item);
1664
1665         $mentioned = get_mentions($item);
1666         if($mentioned)
1667                 $o .= $mentioned;
1668         
1669         call_hooks('atom_entry', $o);
1670
1671         $o .= '</entry>' . "\r\n";
1672         
1673         return $o;
1674 }
1675
1676 function fix_private_photos($s,$uid) {
1677         $a = get_app();
1678         logger('fix_private_photos');
1679
1680         if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
1681                 $image = $matches[1];
1682                 logger('fix_private_photos: found photo ' . $image);
1683                 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
1684                         $i = basename($image);
1685                         $i = str_replace('.jpg','',$i);
1686                         $x = strpos($i,'-');
1687                         if($x) {
1688                                 $res = substr($i,$x+1);
1689                                 $i = substr($i,0,$x);
1690                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1691                                         dbesc($i),
1692                                         intval($res),
1693                                         intval($uid)
1694                                 );
1695                                 if(count($r)) {
1696                                         logger('replacing photo');
1697                                         $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
1698                                 }
1699                         }
1700                         logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
1701                 }       
1702         }
1703         return($s);
1704 }
1705
1706
1707
1708 function item_getfeedtags($item) {
1709         $ret = array();
1710         $matches = false;
1711         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1712         if($cnt) {
1713                 for($x = 0; $x < count($matches); $x ++) {
1714                         if($matches[1][$x])
1715                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1716                 }
1717         }
1718         $matches = false; 
1719         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1720         if($cnt) {
1721                 for($x = 0; $x < count($matches); $x ++) {
1722                         if($matches[1][$x])
1723                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1724                 }
1725         } 
1726         return $ret;
1727 }
1728
1729 function item_getfeedattach($item) {
1730         $ret = '';
1731         $arr = explode(',',$item['attach']);
1732         if(count($arr)) {
1733                 foreach($arr as $r) {
1734                         $matches = false;
1735                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
1736                         if($cnt) {
1737                                 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
1738                                 if(intval($matches[2]))
1739                                         $ret .= 'length="' . intval($matches[2]) . '" ';
1740                                 if($matches[4] !== ' ')
1741                                         $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
1742                                 $ret .= ' />' . "\r\n";
1743                         }
1744                 }
1745         }
1746         return $ret;
1747 }
1748
1749
1750         
1751 function item_expire($uid,$days) {
1752
1753         if((! $uid) || (! $days))
1754                 return;
1755
1756         $r = q("SELECT * FROM `item` 
1757                 WHERE `uid` = %d 
1758                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
1759                 AND `id` = `parent` 
1760                 AND `deleted` = 0",
1761                 intval($uid),
1762                 intval($days)
1763         );
1764
1765         if(! count($r))
1766                 return;
1767  
1768         logger('expire: # items=' . count($r) );
1769
1770         foreach($r as $item) {
1771
1772                 // Only expire posts, not photos and photo comments
1773
1774                 if(strlen($item['resource-id']))
1775                         continue;
1776
1777                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1778                         dbesc(datetime_convert()),
1779                         dbesc(datetime_convert()),
1780                         intval($item['id'])
1781                 );
1782
1783                 // kill the kids
1784
1785                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1786                         dbesc(datetime_convert()),
1787                         dbesc(datetime_convert()),
1788                         dbesc($item['parent-uri']),
1789                         intval($item['uid'])
1790                 );
1791
1792         }
1793
1794         proc_run('php',"include/notifier.php","expire","$uid");
1795
1796 }
1797
1798
1799 function drop_items($items) {
1800         $uid = 0;
1801
1802         if(count($items)) {
1803                 foreach($items as $item) {
1804                         $owner = drop_item($item,false);
1805                         if($owner && ! $uid)
1806                                 $uid = $owner;
1807                 }
1808         }
1809
1810         // multiple threads may have been deleted, send an expire notification
1811
1812         if($uid)
1813                 proc_run('php',"include/notifier.php","expire","$uid");
1814 }
1815
1816
1817 function drop_item($id,$interactive = true) {
1818
1819         $a = get_app();
1820
1821         // locate item to be deleted
1822
1823         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
1824                 intval($id)
1825         );
1826
1827         if(! count($r)) {
1828                 if(! $interactive)
1829                         return 0;
1830                 notice( t('Item not found.') . EOL);
1831                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1832         }
1833
1834         $item = $r[0];
1835
1836         $owner = $item['uid'];
1837
1838         // check if logged in user is either the author or owner of this item
1839
1840         if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
1841
1842                 // delete the item
1843
1844                 $r = q("UPDATE `item` SET `deleted` = 1, `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1845                         dbesc(datetime_convert()),
1846                         dbesc(datetime_convert()),
1847                         intval($item['id'])
1848                 );
1849
1850                 // If item is a link to a photo resource, nuke all the associated photos 
1851                 // (visitors will not have photo resources)
1852                 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1853                 // generate a resource-id and therefore aren't intimately linked to the item. 
1854
1855                 if(strlen($item['resource-id'])) {
1856                         q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
1857                                 dbesc($item['resource-id']),
1858                                 intval($item['uid'])
1859                         );
1860                         // ignore the result
1861                 }
1862
1863                 // If item is a link to an event, nuke the event record.
1864
1865                 if(intval($item['event-id'])) {
1866                         q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1867                                 intval($item['event-id']),
1868                                 intval($item['uid'])
1869                         );
1870                         // ignore the result
1871                 }
1872
1873
1874                 // If it's the parent of a comment thread, kill all the kids
1875
1876                 if($item['uri'] == $item['parent-uri']) {
1877                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' 
1878                                 WHERE `parent-uri` = '%s' AND `uid` = %d ",
1879                                 dbesc(datetime_convert()),
1880                                 dbesc(datetime_convert()),
1881                                 dbesc($item['parent-uri']),
1882                                 intval($item['uid'])
1883                         );
1884                         // ignore the result
1885                 }
1886                 else {
1887                         // ensure that last-child is set in case the comment that had it just got wiped.
1888                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1889                                 dbesc(datetime_convert()),
1890                                 dbesc($item['parent-uri']),
1891                                 intval($item['uid'])
1892                         );
1893                         // who is the last child now? 
1894                         $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",
1895                                 dbesc($item['parent-uri']),
1896                                 intval($item['uid'])
1897                         );
1898                         if(count($r)) {
1899                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1900                                         intval($r[0]['id'])
1901                                 );
1902                         }       
1903                 }
1904                 $drop_id = intval($item['id']);
1905                         
1906                 // send the notification upstream/downstream as the case may be
1907
1908                 if(! $interactive)
1909                         return $owner;
1910
1911                 proc_run('php',"include/notifier.php","drop","$drop_id");
1912                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1913                 //NOTREACHED
1914         }
1915         else {
1916                 if(! $interactive)
1917                         return 0;
1918                 notice( t('Permission denied.') . EOL);
1919                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1920                 //NOTREACHED
1921         }
1922         
1923 }