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