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