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