]> git.mxchange.org Git - friendica.git/blob - include/items.php
8c6134f94f7fa205e56a581cef1ed7be1aea88c2
[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         call_hooks('post_remote',$arr);
751
752         dbesc_array($arr);
753
754         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
755
756         $r = dbq("INSERT INTO `item` (`" 
757                         . implode("`, `", array_keys($arr)) 
758                         . "`) VALUES ('" 
759                         . implode("', '", array_values($arr)) 
760                         . "')" );
761
762         // find the item we just created
763
764         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
765                 $arr['uri'],           // already dbesc'd
766                 intval($arr['uid'])
767         );
768         if(! count($r)) {
769                 // This is not good, but perhaps we encountered a rare race/cache condition, so back off and try again. 
770                 sleep(3);
771                 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
772                         $arr['uri'],           // already dbesc'd
773                         intval($arr['uid'])
774                 );
775         }
776
777         if(count($r)) {
778                 $current_post = $r[0]['id'];
779                 logger('item_store: created item ' . $current_post);
780         }
781         else {
782                 logger('item_store: could not locate created item');
783                 return 0;
784         }
785
786         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
787                 $parent_id = $current_post;
788
789         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
790                 $private = 1;
791         else
792                 $private = $arr['private']; 
793
794         // Set parent id - and also make sure to inherit the parent's ACL's.
795
796         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
797                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
798                 intval($parent_id),
799                 dbesc($allow_cid),
800                 dbesc($allow_gid),
801                 dbesc($deny_cid),
802                 dbesc($deny_gid),
803                 intval($private),
804                 intval($parent_deleted),
805                 intval($current_post)
806         );
807
808         /**
809          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
810          */
811
812         if($arr['last-child']) {
813                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
814                         dbesc($arr['uri']),
815                         intval($arr['uid']),
816                         intval($current_post)
817                 );
818         }
819
820         return $current_post;
821 }
822
823 function get_item_contact($item,$contacts) {
824         if(! count($contacts) || (! is_array($item)))
825                 return false;
826         foreach($contacts as $contact) {
827                 if($contact['id'] == $item['contact-id']) {
828                         return $contact;
829                         break; // NOTREACHED
830                 }
831         }
832         return false;
833 }
834
835
836 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
837
838         $a = get_app();
839
840         if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
841                 return 3;
842
843         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
844
845         if($contact['duplex'] && $contact['dfrn-id'])
846                 $idtosend = '0:' . $orig_id;
847         if($contact['duplex'] && $contact['issued-id'])
848                 $idtosend = '1:' . $orig_id;            
849
850         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
851
852         $rino_enable = get_config('system','rino_encrypt');
853
854         if(! $rino_enable)
855                 $rino = 0;
856
857         $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
858
859         logger('dfrn_deliver: ' . $url);
860
861         $xml = fetch_url($url);
862
863         $curl_stat = $a->get_curl_code();
864         if(! $curl_stat)
865                 return(-1); // timed out
866
867         logger('dfrn_deliver: ' . $xml);
868
869         if(! $xml)
870                 return 3;
871
872         if(strpos($xml,'<?xml') === false) {
873                 logger('dfrn_deliver: no valid XML returned');
874                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
875                 return 3;
876         }
877
878         $res = parse_xml_string($xml);
879
880         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
881                 return (($res->status) ? $res->status : 3);
882
883         $postvars     = array();
884         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
885         $challenge    = hex2bin((string) $res->challenge);
886         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
887         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
888
889         $final_dfrn_id = '';
890
891
892         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
893                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
894                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
895         }
896         else {
897                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
898                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
899         }
900
901         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
902
903         if(strpos($final_dfrn_id,':') == 1)
904                 $final_dfrn_id = substr($final_dfrn_id,2);
905
906         if($final_dfrn_id != $orig_id) {
907                 logger('dfrn_deliver: wrong dfrn_id.');
908                 // did not decode properly - cannot trust this site 
909                 return 3;
910         }
911
912         $postvars['dfrn_id']      = $idtosend;
913         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
914         if($dissolve)
915                 $postvars['dissolve'] = '1';
916
917
918         if((($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
919                 $postvars['data'] = $atom;
920                 $postvars['perm'] = 'rw';
921         }
922         else {
923                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
924                 $postvars['perm'] = 'r';
925         }
926
927         if($rino && $rino_allowed && (! $dissolve)) {
928                 $key = substr(random_string(),0,16);
929                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
930                 $postvars['data'] = $data;
931                 logger('rino: sent key = ' . $key);     
932
933
934                 if($dfrn_version >= 2.1) {      
935                         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
936                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
937                         }
938                         else {
939                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
940                         }
941                 }
942                 else {
943                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
944                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
945                         }
946                         else {
947                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
948                         }
949                 }
950
951                 logger('md5 rawkey ' . md5($postvars['key']));
952
953                 $postvars['key'] = bin2hex($postvars['key']);
954         }
955
956         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
957
958         $xml = post_url($contact['notify'],$postvars);
959
960         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
961
962         $curl_stat = $a->get_curl_code();
963         if((! $curl_stat) || (! strlen($xml)))
964                 return(-1); // timed out
965
966         if(strpos($xml,'<?xml') === false) {
967                 logger('dfrn_deliver: phase 2: no valid XML returned');
968                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
969                 return 3;
970         }
971
972         $res = parse_xml_string($xml);
973
974         return $res->status; 
975 }
976
977
978 /**
979  *
980  * consume_feed - process atom feed and update anything/everything we might need to update
981  *
982  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
983  *
984  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
985  *             It is this person's stuff that is going to be updated.
986  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
987  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
988  *             have a contact record.
989  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
990  *        might not) try and subscribe to it.
991  *
992  */
993
994 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $secure_feed = false) {
995
996         require_once('library/simplepie/simplepie.inc');
997
998         $feed = new SimplePie();
999         $feed->set_raw_data($xml);
1000         if($datedir)
1001                 $feed->enable_order_by_date(true);
1002         else
1003                 $feed->enable_order_by_date(false);
1004         $feed->init();
1005
1006         if($feed->error())
1007                 logger('consume_feed: Error parsing XML: ' . $feed->error());
1008
1009         $permalink = $feed->get_permalink();
1010
1011         // Check at the feed level for updated contact name and/or photo
1012
1013         $name_updated  = '';
1014         $new_name = '';
1015         $photo_timestamp = '';
1016         $photo_url = '';
1017         $birthday = '';
1018
1019         $hubs = $feed->get_links('hub');
1020
1021         if(count($hubs))
1022                 $hub = implode(',', $hubs);
1023
1024         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1025         if($rawtags) {
1026                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1027                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1028                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1029                         $new_name = $elems['name'][0]['data'];
1030                 } 
1031                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1032                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1033                         $photo_url = $elems['link'][0]['attribs']['']['href'];
1034                 }
1035
1036                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1037                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1038                 }
1039         }
1040
1041         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1042                 logger('consume_feed: Updating photo for ' . $contact['name']);
1043                 require_once("Photo.php");
1044                 $photo_failure = false;
1045                 $have_photo = false;
1046
1047                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1048                         intval($contact['id']),
1049                         intval($contact['uid'])
1050                 );
1051                 if(count($r)) {
1052                         $resource_id = $r[0]['resource-id'];
1053                         $have_photo = true;
1054                 }
1055                 else {
1056                         $resource_id = photo_new_resource();
1057                 }
1058                         
1059                 $img_str = fetch_url($photo_url,true);
1060                 $img = new Photo($img_str);
1061                 if($img->is_valid()) {
1062                         if($have_photo) {
1063                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1064                                         dbesc($resource_id),
1065                                         intval($contact['id']),
1066                                         intval($contact['uid'])
1067                                 );
1068                         }
1069                                 
1070                         $img->scaleImageSquare(175);
1071                                 
1072                         $hash = $resource_id;
1073                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1074                                 
1075                         $img->scaleImage(80);
1076                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1077
1078                         $img->scaleImage(48);
1079                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1080
1081                         $a = get_app();
1082
1083                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
1084                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1085                                 dbesc(datetime_convert()),
1086                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1087                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1088                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1089                                 intval($contact['uid']),
1090                                 intval($contact['id'])
1091                         );
1092                 }
1093         }
1094
1095         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1096                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1097                         dbesc(notags(trim($new_name))),
1098                         dbesc(datetime_convert()),
1099                         intval($contact['uid']),
1100                         intval($contact['id'])
1101                 );
1102         }
1103
1104         if(strlen($birthday)) {
1105                 if(substr($birthday,0,4) != $contact['bdyear']) {
1106                         logger('consume_feed: updating birthday: ' . $birthday);
1107
1108                         /**
1109                          *
1110                          * Add new birthday event for this person
1111                          *
1112                          * $bdtext is just a readable placeholder in case the event is shared
1113                          * with others. We will replace it during presentation to our $importer
1114                          * to contain a sparkle link and perhaps a photo. 
1115                          *
1116                          */
1117                          
1118                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1119
1120
1121                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1122                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1123                                 intval($contact['uid']),
1124                                 intval($contact['id']),
1125                                 dbesc(datetime_convert()),
1126                                 dbesc(datetime_convert()),
1127                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1128                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1129                                 dbesc($bdtext),
1130                                 dbesc('birthday')
1131                         );
1132                         
1133
1134                         // update bdyear
1135
1136                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1137                                 dbesc(substr($birthday,0,4)),
1138                                 intval($contact['uid']),
1139                                 intval($contact['id'])
1140                         );
1141
1142                         // This function is called twice without reloading the contact
1143                         // Make sure we only create one event. This is why &$contact 
1144                         // is a reference var in this function
1145
1146                         $contact['bdyear'] = substr($birthday,0,4);
1147                 }
1148
1149         }
1150
1151
1152         // process any deleted entries
1153
1154         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1155         if(is_array($del_entries) && count($del_entries)) {
1156                 foreach($del_entries as $dentry) {
1157                         $deleted = false;
1158                         if(isset($dentry['attribs']['']['ref'])) {
1159                                 $uri = $dentry['attribs']['']['ref'];
1160                                 $deleted = true;
1161                                 if(isset($dentry['attribs']['']['when'])) {
1162                                         $when = $dentry['attribs']['']['when'];
1163                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1164                                 }
1165                                 else
1166                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1167                         }
1168                         if($deleted && is_array($contact)) {
1169                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1170                                         dbesc($uri),
1171                                         intval($importer['uid']),
1172                                         intval($contact['id'])
1173                                 );
1174                                 if(count($r)) {
1175                                         $item = $r[0];
1176
1177                                         if(! $item['deleted'])
1178                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1179
1180                                         if($item['uri'] == $item['parent-uri']) {
1181                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1182                                                         `body` = '', `title` = ''
1183                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1184                                                         dbesc($when),
1185                                                         dbesc(datetime_convert()),
1186                                                         dbesc($item['uri']),
1187                                                         intval($importer['uid'])
1188                                                 );
1189                                         }
1190                                         else {
1191                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1192                                                         `body` = '', `title` = '' 
1193                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1194                                                         dbesc($when),
1195                                                         dbesc(datetime_convert()),
1196                                                         dbesc($uri),
1197                                                         intval($importer['uid'])
1198                                                 );
1199                                                 if($item['last-child']) {
1200                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1201                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1202                                                                 dbesc(datetime_convert()),
1203                                                                 dbesc($item['parent-uri']),
1204                                                                 intval($item['uid'])
1205                                                         );
1206                                                         // who is the last child now? 
1207                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1208                                                                 ORDER BY `created` DESC LIMIT 1",
1209                                                                         dbesc($item['parent-uri']),
1210                                                                         intval($importer['uid'])
1211                                                         );
1212                                                         if(count($r)) {
1213                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1214                                                                         intval($r[0]['id'])
1215                                                                 );
1216                                                         }
1217                                                 }       
1218                                         }
1219                                 }       
1220                         }
1221                 }
1222         }
1223
1224         // Now process the feed
1225
1226         if($feed->get_item_quantity()) {                
1227
1228                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1229
1230         // in inverse date order
1231                 if ($datedir)
1232                         $items = array_reverse($feed->get_items());
1233                 else
1234                         $items = $feed->get_items();
1235
1236
1237                 foreach($items as $item) {
1238
1239                         $is_reply = false;              
1240                         $item_id = $item->get_id();
1241                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1242                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1243                                 $is_reply = true;
1244                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1245                         }
1246
1247                         if(($is_reply) && is_array($contact)) {
1248
1249                                 // Have we seen it? If not, import it.
1250         
1251                                 $item_id  = $item->get_id();
1252                                 $datarray = get_atom_elements($feed,$item);
1253
1254                                 if(! x($datarray,'author-name'))
1255                                         $datarray['author-name'] = $contact['name'];
1256                                 if(! x($datarray,'author-link'))
1257                                         $datarray['author-link'] = $contact['url'];
1258                                 if(! x($datarray,'author-avatar'))
1259                                         $datarray['author-avatar'] = $contact['thumb'];
1260
1261
1262                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1263                                         dbesc($item_id),
1264                                         intval($importer['uid'])
1265                                 );
1266
1267                                 // Update content if 'updated' changes
1268
1269                                 if(count($r)) {
1270                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1271                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1272                                                         dbesc($datarray['body']),
1273                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1274                                                         dbesc($item_id),
1275                                                         intval($importer['uid'])
1276                                                 );
1277                                         }
1278
1279                                         // update last-child if it changes
1280
1281                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1282                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1283                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1284                                                         dbesc(datetime_convert()),
1285                                                         dbesc($parent_uri),
1286                                                         intval($importer['uid'])
1287                                                 );
1288                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1289                                                         intval($allow[0]['data']),
1290                                                         dbesc(datetime_convert()),
1291                                                         dbesc($item_id),
1292                                                         intval($importer['uid'])
1293                                                 );
1294                                         }
1295                                         continue;
1296                                 }
1297
1298                                 $force_parent = false;
1299                                 if($contact['network'] === 'stat') {
1300                                         $force_parent = true;
1301                                         if(strlen($datarray['title']))
1302                                                 unset($datarray['title']);
1303                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1304                                                 dbesc(datetime_convert()),
1305                                                 dbesc($parent_uri),
1306                                                 intval($importer['uid'])
1307                                         );
1308                                         $datarray['last-child'] = 1;
1309                                 }
1310
1311                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1312                                         // one way feed - no remote comment ability
1313                                         $datarray['last-child'] = 0;
1314                                 }
1315                                 $datarray['parent-uri'] = $parent_uri;
1316                                 $datarray['uid'] = $importer['uid'];
1317                                 $datarray['contact-id'] = $contact['id'];
1318                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1319                                         $datarray['type'] = 'activity';
1320                                         $datarray['gravity'] = GRAVITY_LIKE;
1321                                 }
1322
1323                                 $r = item_store($datarray,$force_parent);
1324                                 continue;
1325                         }
1326
1327                         else {
1328
1329                                 // Head post of a conversation. Have we seen it? If not, import it.
1330
1331                                 $item_id  = $item->get_id();
1332
1333                                 $datarray = get_atom_elements($feed,$item);
1334
1335                                 if(is_array($contact)) {
1336                                         if(! x($datarray,'author-name'))
1337                                                 $datarray['author-name'] = $contact['name'];
1338                                         if(! x($datarray,'author-link'))
1339                                                 $datarray['author-link'] = $contact['url'];
1340                                         if(! x($datarray,'author-avatar'))
1341                                                 $datarray['author-avatar'] = $contact['thumb'];
1342                                 }
1343
1344                                 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1345                                         $ev = bbtoevent($datarray['body']);
1346                                         if(x($ev,'desc') && x($ev,'start')) {
1347                                                 $ev['uid'] = $importer['uid'];
1348                                                 $ev['uri'] = $item_id;
1349                                                 $ev['edited'] = $datarray['edited'];
1350                                                 $ev['private'] = $datarray['private'];
1351
1352                                                 if(is_array($contact))
1353                                                         $ev['cid'] = $contact['id'];
1354                                                 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1355                                                         dbesc($item_id),
1356                                                         intval($importer['uid'])
1357                                                 );
1358                                                 if(count($r))
1359                                                         $ev['id'] = $r[0]['id'];
1360                                                 $xyz = event_store($ev);
1361                                                 continue;
1362                                         }
1363                                 }
1364
1365                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1366                                         dbesc($item_id),
1367                                         intval($importer['uid'])
1368                                 );
1369
1370                                 // Update content if 'updated' changes
1371
1372                                 if(count($r)) {
1373                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1374                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1375                                                         dbesc($datarray['body']),
1376                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1377                                                         dbesc($item_id),
1378                                                         intval($importer['uid'])
1379                                                 );
1380                                         }
1381
1382                                         // update last-child if it changes
1383
1384                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1385                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1386                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1387                                                         intval($allow[0]['data']),
1388                                                         dbesc(datetime_convert()),
1389                                                         dbesc($item_id),
1390                                                         intval($importer['uid'])
1391                                                 );
1392                                         }
1393                                         continue;
1394                                 }
1395
1396                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1397                                         logger('consume-feed: New follower');
1398                                         new_follower($importer,$contact,$datarray,$item);
1399                                         return;
1400                                 }
1401                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1402                                         lose_follower($importer,$contact,$datarray,$item);
1403                                         return;
1404                                 }
1405                                 if(! is_array($contact))
1406                                         return;
1407
1408                                 if($contact['network'] === 'stat' || stristr($permalink,'twitter.com')) {
1409                                         if(strlen($datarray['title']))
1410                                                 unset($datarray['title']);
1411                                         $datarray['last-child'] = 1;
1412                                 }
1413
1414                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1415                                         // one way feed - no remote comment ability
1416                                         $datarray['last-child'] = 0;
1417                                 }
1418
1419                                 // This is my contact on another system, but it's really me.
1420                                 // Turn this into a wall post.
1421
1422                                 if($contact['remote_self'])
1423                                         $datarray['wall'] = 1;
1424
1425                                 $datarray['parent-uri'] = $item_id;
1426                                 $datarray['uid'] = $importer['uid'];
1427                                 $datarray['contact-id'] = $contact['id'];
1428                                 $r = item_store($datarray);
1429                                 continue;
1430
1431                         }
1432                 }
1433         }
1434 }
1435
1436 function new_follower($importer,$contact,$datarray,$item) {
1437         $url = notags(trim($datarray['author-link']));
1438         $name = notags(trim($datarray['author-name']));
1439         $photo = notags(trim($datarray['author-avatar']));
1440
1441         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1442         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1443                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1444
1445         if(is_array($contact)) {
1446                 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
1447                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1448                                 intval(REL_BUD),
1449                                 intval($contact['id']),
1450                                 intval($importer['uid'])
1451                         );
1452                 }
1453
1454                 // send email notification to owner?
1455         }
1456         else {
1457         
1458                 // create contact record
1459
1460                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
1461                         `blocked`, `readonly`, `pending`, `writable` )
1462                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
1463                         intval($importer['uid']),
1464                         dbesc(datetime_convert()),
1465                         dbesc($url),
1466                         dbesc($name),
1467                         dbesc($nick),
1468                         dbesc($photo),
1469                         dbesc('stat'),
1470                         intval(REL_VIP)
1471                 );
1472                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1473                                 intval($importer['uid']),
1474                                 dbesc($url),
1475                                 intval(REL_VIP)
1476                 );
1477                 if(count($r))
1478                                 $contact_record = $r[0];
1479
1480                 // create notification  
1481                 $hash = random_string();
1482
1483                 if(is_array($contact_record)) {
1484                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1485                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1486                                 intval($importer['uid']),
1487                                 intval($contact_record['id']),
1488                                 dbesc($hash),
1489                                 dbesc(datetime_convert())
1490                         );
1491                 }
1492                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1493                         intval($importer['uid'])
1494                 );
1495                 $a = get_app();
1496                 if(count($r)) {
1497                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1498                                 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
1499                                 $email = replace_macros($email_tpl, array(
1500                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1501                                         '$url' => $url,
1502                                         '$myname' => $r[0]['username'],
1503                                         '$siteurl' => $a->get_baseurl(),
1504                                         '$sitename' => $a->config['sitename']
1505                                 ));
1506                                 $res = mail($r[0]['email'], 
1507                                         t("You have a new follower at ") . $a->config['sitename'],
1508                                         $email,
1509                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
1510                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
1511                                         . 'Content-transfer-encoding: 8bit' );
1512                         
1513                         }
1514                 }
1515         }
1516 }
1517
1518 function lose_follower($importer,$contact,$datarray,$item) {
1519
1520         if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1521                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1522                         intval(REL_FAN),
1523                         intval($contact['id'])
1524                 );
1525         }
1526         else {
1527                 contact_remove($contact['id']);
1528         }
1529 }
1530
1531
1532 function subscribe_to_hub($url,$importer,$contact) {
1533
1534         if(is_array($importer)) {
1535                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1536                         intval($importer['uid'])
1537                 );
1538         }
1539         if(! count($r))
1540                 return;
1541
1542         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1543
1544         // Use a single verify token, even if multiple hubs
1545
1546         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1547
1548         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1549
1550         logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1551
1552         if(! strlen($contact['hub-verify'])) {
1553                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1554                         dbesc($verify_token),
1555                         intval($contact['id'])
1556                 );
1557         }
1558
1559         post_url($url,$params);                 
1560         return;
1561
1562 }
1563
1564
1565 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1566         $o = '';
1567         if(! $tag)
1568                 return $o;
1569         $name = xmlify($name);
1570         $uri = xmlify($uri);
1571         $h = intval($h);
1572         $w = intval($w);
1573         $photo = xmlify($photo);
1574
1575
1576         $o .= "<$tag>\r\n";
1577         $o .= "<name>$name</name>\r\n";
1578         $o .= "<uri>$uri</uri>\r\n";
1579         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1580         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1581
1582         call_hooks('atom_author', $o);
1583
1584         $o .= "</$tag>\r\n";
1585         return $o;
1586 }
1587
1588 function atom_entry($item,$type,$author,$owner,$comment = false) {
1589
1590         $a = get_app();
1591
1592         if($item['deleted'])
1593                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1594
1595
1596         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
1597                 $body = fix_private_photos($item['body'],$owner['uid']);
1598         else
1599                 $body = $item['body'];
1600
1601
1602         $o = "\r\n\r\n<entry>\r\n";
1603
1604         if(is_array($author))
1605                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1606         else
1607                 $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']));
1608         if(strlen($item['owner-name']))
1609                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1610
1611         if($item['parent'] != $item['id'])
1612                 $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";
1613
1614         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1615         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1616         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1617         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1618         $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
1619         $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($body) : $body) . '</content>' . "\r\n";
1620         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1621         if($comment)
1622                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1623
1624         if($item['location']) {
1625                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1626                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1627         }
1628
1629         if($item['coord'])
1630                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1631
1632         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1633                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1634
1635         if($item['extid'])
1636                 $o .= '<dfrn:extid>' . $item['extid'] . '</dfrn:extid>' . "\r\n";
1637
1638         if($item['app'])
1639                 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . $item['app'] . '" ></statusnet:notice_info>';
1640         $verb = construct_verb($item);
1641         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1642         $actobj = construct_activity_object($item);
1643         if(strlen($actobj))
1644                 $o .= $actobj;
1645         $actarg = construct_activity_target($item);
1646         if(strlen($actarg))
1647                 $o .= $actarg;
1648
1649         $tags = item_getfeedtags($item);
1650         if(count($tags)) {
1651                 foreach($tags as $t) {
1652                         $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
1653                 }
1654         }
1655
1656         $o .= item_getfeedattach($item);
1657
1658         $mentioned = get_mentions($item);
1659         if($mentioned)
1660                 $o .= $mentioned;
1661         
1662         call_hooks('atom_entry', $o);
1663
1664         $o .= '</entry>' . "\r\n";
1665         
1666         return $o;
1667 }
1668
1669 function fix_private_photos($s,$uid) {
1670         $a = get_app();
1671         logger('fix_private_photos');
1672
1673         if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
1674                 $image = $matches[1];
1675                 logger('fix_private_photos: found photo ' . $image);
1676                 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
1677                         $i = basename($image);
1678                         $i = str_replace('.jpg','',$i);
1679                         $x = strpos($i,'-');
1680                         if($x) {
1681                                 $res = substr($i,$x+1);
1682                                 $i = substr($i,0,$x);
1683                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1684                                         dbesc($i),
1685                                         intval($res),
1686                                         intval($uid)
1687                                 );
1688                                 if(count($r)) {
1689                                         logger('replacing photo');
1690                                         $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
1691                                 }
1692                         }
1693                         logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
1694                 }       
1695         }
1696         return($s);
1697 }
1698
1699
1700
1701 function item_getfeedtags($item) {
1702         $ret = array();
1703         $matches = false;
1704         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1705         if($cnt) {
1706                 for($x = 0; $x < count($matches); $x ++) {
1707                         if($matches[1][$x])
1708                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1709                 }
1710         }
1711         $matches = false; 
1712         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1713         if($cnt) {
1714                 for($x = 0; $x < count($matches); $x ++) {
1715                         if($matches[1][$x])
1716                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1717                 }
1718         } 
1719         return $ret;
1720 }
1721
1722 function item_getfeedattach($item) {
1723         $ret = '';
1724         $arr = explode(',',$item['attach']);
1725         if(count($arr)) {
1726                 foreach($arr as $r) {
1727                         $matches = false;
1728                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
1729                         if($cnt) {
1730                                 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
1731                                 if(intval($matches[2]))
1732                                         $ret .= 'length="' . intval($matches[2]) . '" ';
1733                                 if($matches[4] !== ' ')
1734                                         $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
1735                                 $ret .= ' />' . "\r\n";
1736                         }
1737                 }
1738         }
1739         return $ret;
1740 }
1741
1742
1743         
1744 function item_expire($uid,$days) {
1745
1746         if((! $uid) || (! $days))
1747                 return;
1748
1749         $r = q("SELECT * FROM `item` 
1750                 WHERE `uid` = %d 
1751                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
1752                 AND `id` = `parent` 
1753                 AND `deleted` = 0",
1754                 intval($uid),
1755                 intval($days)
1756         );
1757
1758         if(! count($r))
1759                 return;
1760  
1761         logger('expire: # items=' . count($r) );
1762
1763         foreach($r as $item) {
1764
1765                 // Only expire posts, not photos and photo comments
1766
1767                 if(strlen($item['resource-id']))
1768                         continue;
1769
1770                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1771                         dbesc(datetime_convert()),
1772                         dbesc(datetime_convert()),
1773                         intval($item['id'])
1774                 );
1775
1776                 // kill the kids
1777
1778                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1779                         dbesc(datetime_convert()),
1780                         dbesc(datetime_convert()),
1781                         dbesc($item['parent-uri']),
1782                         intval($item['uid'])
1783                 );
1784
1785         }
1786
1787         proc_run('php',"include/notifier.php","expire","$uid");
1788
1789 }
1790
1791
1792 function drop_items($items) {
1793         $uid = 0;
1794
1795         if(count($items)) {
1796                 foreach($items as $item) {
1797                         $owner = drop_item($item,false);
1798                         if($owner && ! $uid)
1799                                 $uid = $owner;
1800                 }
1801         }
1802
1803         // multiple threads may have been deleted, send an expire notification
1804
1805         if($uid)
1806                 proc_run('php',"include/notifier.php","expire","$uid");
1807 }
1808
1809
1810 function drop_item($id,$interactive = true) {
1811
1812         $a = get_app();
1813
1814         // locate item to be deleted
1815
1816         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
1817                 intval($id)
1818         );
1819
1820         if(! count($r)) {
1821                 if(! $interactive)
1822                         return 0;
1823                 notice( t('Item not found.') . EOL);
1824                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1825         }
1826
1827         $item = $r[0];
1828
1829         $owner = $item['uid'];
1830
1831         // check if logged in user is either the author or owner of this item
1832
1833         if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
1834
1835                 // delete the item
1836
1837                 $r = q("UPDATE `item` SET `deleted` = 1, `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1838                         dbesc(datetime_convert()),
1839                         dbesc(datetime_convert()),
1840                         intval($item['id'])
1841                 );
1842
1843                 // If item is a link to a photo resource, nuke all the associated photos 
1844                 // (visitors will not have photo resources)
1845                 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1846                 // generate a resource-id and therefore aren't intimately linked to the item. 
1847
1848                 if(strlen($item['resource-id'])) {
1849                         q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
1850                                 dbesc($item['resource-id']),
1851                                 intval($item['uid'])
1852                         );
1853                         // ignore the result
1854                 }
1855
1856                 // If item is a link to an event, nuke the event record.
1857
1858                 if(intval($item['event-id'])) {
1859                         q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1860                                 intval($item['event-id']),
1861                                 intval($item['uid'])
1862                         );
1863                         // ignore the result
1864                 }
1865
1866
1867                 // If it's the parent of a comment thread, kill all the kids
1868
1869                 if($item['uri'] == $item['parent-uri']) {
1870                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' 
1871                                 WHERE `parent-uri` = '%s' AND `uid` = %d ",
1872                                 dbesc(datetime_convert()),
1873                                 dbesc(datetime_convert()),
1874                                 dbesc($item['parent-uri']),
1875                                 intval($item['uid'])
1876                         );
1877                         // ignore the result
1878                 }
1879                 else {
1880                         // ensure that last-child is set in case the comment that had it just got wiped.
1881                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1882                                 dbesc(datetime_convert()),
1883                                 dbesc($item['parent-uri']),
1884                                 intval($item['uid'])
1885                         );
1886                         // who is the last child now? 
1887                         $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",
1888                                 dbesc($item['parent-uri']),
1889                                 intval($item['uid'])
1890                         );
1891                         if(count($r)) {
1892                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1893                                         intval($r[0]['id'])
1894                                 );
1895                         }       
1896                 }
1897                 $drop_id = intval($item['id']);
1898                         
1899                 // send the notification upstream/downstream as the case may be
1900
1901                 if(! $interactive)
1902                         return $owner;
1903
1904                 proc_run('php',"include/notifier.php","drop","$drop_id");
1905                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1906                 //NOTREACHED
1907         }
1908         else {
1909                 if(! $interactive)
1910                         return 0;
1911                 notice( t('Permission denied.') . EOL);
1912                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1913                 //NOTREACHED
1914         }
1915         
1916 }