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