]> git.mxchange.org Git - friendica.git/blob - include/items.php
Merge branch 'master' of git://github.com/friendika/friendika
[friendica.git] / include / items.php
1 <?php
2
3 require_once('bbcode.php');
4 require_once('oembed.php');
5 require_once('include/salmon.php');
6
7 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
8
9
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 = load_view_file('view/atom_feed.tpl');
117
118         $atom = '';
119
120         $hubxml = feed_hublinks();
121
122         $salmon = feed_salmonlinks($owner_nick);
123
124         $atom .= replace_macros($feed_template, array(
125                 '$version'      => xmlify(FRIENDIKA_VERSION),
126                 '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
127                 '$feed_title'   => xmlify($owner['name']),
128                 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
129                 '$hub'          => $hubxml,
130                 '$salmon'       => $salmon,
131                 '$name'         => xmlify($owner['name']),
132                 '$profile_page' => xmlify($owner['url']),
133                 '$photo'        => xmlify($owner['photo']),
134                 '$thumb'        => xmlify($owner['thumb']),
135                 '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
136                 '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
137                 '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) , 
138                 '$birthday'     => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
139         ));
140
141         call_hooks('atom_feed', $atom);
142
143         if(! count($items)) {
144
145                 call_hooks('atom_feed_end', $atom);
146
147                 $atom .= '</feed>' . "\r\n";
148                 return $atom;
149         }
150
151         foreach($items as $item) {
152
153                 // public feeds get html, our own nodes use bbcode
154
155                 if($dfrn_id === '') {
156                         $type = 'html';
157                 }
158                 else {
159                         $type = 'text';
160                 }
161
162                 $atom .= atom_entry($item,$type,null,$owner,true);
163         }
164
165         call_hooks('atom_feed_end', $atom);
166
167         $atom .= '</feed>' . "\r\n";
168
169         return $atom;
170 }
171
172
173 function construct_verb($item) {
174         if($item['verb'])
175                 return $item['verb'];
176         return ACTIVITY_POST;
177 }
178
179 function construct_activity_object($item) {
180
181         if($item['object']) {
182                 $o = '<as:object>' . "\r\n";
183                 $r = @simplexml_load_string($item['object']);
184                 if($r->type)
185                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
186                 if($r->id)
187                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
188                 if($r->title)
189                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
190                 if($r->link) {
191                         if(substr($r->link,0,1) === '<') 
192                                 $o .= $r->link;
193                         else
194                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
195                 }
196                 if($r->content)
197                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
198                 $o .= '</as:object>' . "\r\n";
199                 return $o;
200         }
201
202         return '';
203
204
205 function construct_activity_target($item) {
206
207         if($item['target']) {
208                 $o = '<as:target>' . "\r\n";
209                 $r = @simplexml_load_string($item['target']);
210                 if($r->type)
211                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
212                 if($r->id)
213                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
214                 if($r->title)
215                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
216                 if($r->link) {
217                         if(substr($r->link,0,1) === '<') 
218                                 $o .= $r->link;
219                         else
220                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
221                 }
222                 if($r->content)
223                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
224                 $o .= '</as:target>' . "\r\n";
225                 return $o;
226         }
227
228         return '';
229
230
231
232
233
234 function get_atom_elements($feed,$item) {
235
236         require_once('library/HTMLPurifier.auto.php');
237         require_once('include/html2bbcode.php');
238
239         $best_photo = array();
240
241         $res = array();
242
243         $author = $item->get_author();
244         $res['author-name'] = unxmlify($author->get_name());
245         $res['author-link'] = unxmlify($author->get_link());
246         $res['uri'] = unxmlify($item->get_id());
247         $res['title'] = unxmlify($item->get_title());
248         $res['body'] = unxmlify($item->get_content());
249         $res['plink'] = unxmlify($item->get_link(0));
250
251         // look for a photo. We should check media size and find the best one,
252         // but for now let's just find any author photo
253
254         $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
255
256         if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
257                 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
258                 foreach($base as $link) {
259                         if(! $res['author-avatar']) {
260                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
261                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
262                         }
263                 }
264         }                       
265
266         $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
267
268         if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
269                 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
270                 if($base && count($base)) {
271                         foreach($base as $link) {
272                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
273                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
274                                 if(! $res['author-avatar']) {
275                                         if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
276                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
277                                 }
278                         }
279                 }
280         }
281
282         // No photo/profile-link on the item - look at the feed level
283
284         if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
285                 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
286                 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
287                         $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
288                         foreach($base as $link) {
289                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
290                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
291                                 if(! $res['author-avatar']) {
292                                         if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
293                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
294                                 }
295                         }
296                 }                       
297
298                 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
299
300                 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
301                         $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
302
303                         if($base && count($base)) {
304                                 foreach($base as $link) {
305                                         if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
306                                                 $res['author-link'] = unxmlify($link['attribs']['']['href']);
307                                         if(! (x($res,'author-avatar'))) {
308                                                 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
309                                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
310                                         }
311                                 }
312                         }
313                 }
314         }
315
316
317         /**
318          * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
319          */
320
321         $have_real_body = false;
322
323         $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
324         if($rawenv) {
325                 $have_real_body = true;
326                 $res['body'] = $rawenv[0]['data'];
327                 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
328                 // make sure nobody is trying to sneak some html tags by us
329                 $res['body'] = notags(base64url_decode($res['body']));
330         }
331
332         $maxlen = get_max_import_size();
333         if($maxlen && (strlen($res['body']) > $maxlen))
334                 $res['body'] = substr($res['body'],0, $maxlen);
335
336         // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust 
337         // the content type. Our own network only emits text normally, though it might have been converted to 
338         // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
339         // have to assume it is all html and needs to be purified.
340
341         // It doesn't matter all that much security wise - because before this content is used anywhere, we are 
342         // going to escape any tags we find regardless, but this lets us import a limited subset of html from 
343         // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining 
344         // html.
345
346
347         if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
348
349                 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
350                         '[youtube]$1[/youtube]', $res['body']);
351
352                 $res['body'] = oembed_html2bbcode($res['body']);
353
354                 $config = HTMLPurifier_Config::createDefault();
355                 $config->set('Cache.DefinitionImpl', null);
356
357                 // we shouldn't need a whitelist, because the bbcode converter
358                 // will strip out any unsupported tags.
359                 // $config->set('HTML.Allowed', 'p,b,a[href],i'); 
360
361                 $purifier = new HTMLPurifier($config);
362                 $res['body'] = $purifier->purify($res['body']);
363
364                 $res['body'] = html2bbcode($res['body']);
365         }
366
367         $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
368         if($allow && $allow[0]['data'] == 1)
369                 $res['last-child'] = 1;
370         else
371                 $res['last-child'] = 0;
372
373         $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
374         if($private && $private[0]['data'] == 1)
375                 $res['private'] = 1;
376         else
377                 $res['private'] = 0;
378
379
380         $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
381         if($rawlocation)
382                 $res['location'] = unxmlify($rawlocation[0]['data']);
383
384
385         $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
386         if($rawcreated)
387                 $res['created'] = unxmlify($rawcreated[0]['data']);
388
389
390         $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
391         if($rawedited)
392                 $res['edited'] = unxmlify($rawedited[0]['data']);
393
394         if((x($res,'edited')) && (! (x($res,'created'))))
395                 $res['created'] = $res['edited']; 
396
397         if(! $res['created'])
398                 $res['created'] = $item->get_date('c');
399
400         if(! $res['edited'])
401                 $res['edited'] = $item->get_date('c');
402
403
404         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
405         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
406                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
407         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
408                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
409         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
410                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
411         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
412                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
413
414         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
415                 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
416
417                 foreach($base as $link) {
418                         if(! $res['owner-avatar']) {
419                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')                 
420                                         $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
421                         }
422                 }
423         }
424
425         $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
426         if($rawgeo)
427                 $res['coord'] = unxmlify($rawgeo[0]['data']);
428
429
430         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
431
432         // select between supported verbs
433
434         if($rawverb) {
435                 $res['verb'] = unxmlify($rawverb[0]['data']);
436         }
437
438         // translate OStatus unfollow to activity streams if it happened to get selected
439                 
440         if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
441                 $res['verb'] = ACTIVITY_UNFOLLOW;
442
443                 
444
445         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
446
447         if($rawobj) {
448                 $res['object'] = '<object>' . "\n";
449                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
450                         $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
451                         $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
452                 }       
453                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
454                         $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
455                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
456                         $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
457                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
458                         $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
459                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
460                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
461                         if(! $body)
462                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
463                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
464                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
465                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
466
467                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
468                                         '[youtube]$1[/youtube]', $body);
469
470                                 $config = HTMLPurifier_Config::createDefault();
471                                 $config->set('Cache.DefinitionImpl', null);
472
473                                 $purifier = new HTMLPurifier($config);
474                                 $body = $purifier->purify($body);
475                                 $body = html2bbcode($body);
476                         }
477
478                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
479                 }
480
481                 $res['object'] .= '</object>' . "\n";
482         }
483
484         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
485
486         if($rawobj) {
487                 $res['target'] = '<target>' . "\n";
488                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
489                         $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
490                 }       
491                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
492                         $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
493
494                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
495                         $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
496                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
497                         $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
498                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
499                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
500                         if(! $body)
501                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
502                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
503                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
504                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
505
506                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
507                                         '[youtube]$1[/youtube]', $body);
508
509                                 $config = HTMLPurifier_Config::createDefault();
510                                 $config->set('Cache.DefinitionImpl', null);
511
512                                 $purifier = new HTMLPurifier($config);
513                                 $body = $purifier->purify($body);
514                                 $body = html2bbcode($body);
515                         }
516
517                         $res['target'] .= '<content>' . $body . '</content>' . "\n";
518                 }
519
520                 $res['target'] .= '</target>' . "\n";
521         }
522
523         $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
524
525         call_hooks('parse_atom', $arr);
526
527         return $res;
528 }
529
530 function encode_rel_links($links) {
531         $o = '';
532         if(! ((is_array($links)) && (count($links))))
533                 return $o;
534         foreach($links as $link) {
535                 $o .= '<link ';
536                 if($link['attribs']['']['rel'])
537                         $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
538                 if($link['attribs']['']['type'])
539                         $o .= 'type="' . $link['attribs']['']['type'] . '" ';
540                 if($link['attribs']['']['href'])
541                         $o .= 'href="' . $link['attribs']['']['href'] . '" ';
542                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
543                         $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
544                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
545                         $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
546                 $o .= ' />' . "\n" ;
547         }
548         return xmlify($o);
549 }
550
551 function item_store($arr,$force_parent = false) {
552
553         if($arr['gravity'])
554                 $arr['gravity'] = intval($arr['gravity']);
555         elseif($arr['parent-uri'] == $arr['uri'])
556                 $arr['gravity'] = 0;
557         elseif(activity_match($arr['verb'],ACTIVITY_POST))
558                 $arr['gravity'] = 6;
559         else      
560                 $arr['gravity'] = 6;   // extensible catchall
561
562         if(! x($arr,'type'))
563                 $arr['type']      = 'remote';
564
565         // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
566
567         if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false)) 
568                 $arr['body'] = strip_tags($arr['body']);
569
570
571         $arr['wall']          = ((x($arr,'wall'))          ? intval($arr['wall'])                : 0);
572         $arr['uri']           = ((x($arr,'uri'))           ? notags(trim($arr['uri']))           : random_string());
573         $arr['author-name']   = ((x($arr,'author-name'))   ? notags(trim($arr['author-name']))   : '');
574         $arr['author-link']   = ((x($arr,'author-link'))   ? notags(trim($arr['author-link']))   : '');
575         $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
576         $arr['owner-name']    = ((x($arr,'owner-name'))    ? notags(trim($arr['owner-name']))    : '');
577         $arr['owner-link']    = ((x($arr,'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
578         $arr['owner-avatar']  = ((x($arr,'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
579         $arr['created']       = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
580         $arr['edited']        = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
581         $arr['changed']       = datetime_convert();
582         $arr['title']         = ((x($arr,'title'))         ? notags(trim($arr['title']))         : '');
583         $arr['location']      = ((x($arr,'location'))      ? notags(trim($arr['location']))      : '');
584         $arr['coord']         = ((x($arr,'coord'))         ? notags(trim($arr['coord']))         : '');
585         $arr['last-child']    = ((x($arr,'last-child'))    ? intval($arr['last-child'])          : 0 );
586         $arr['visible']       = ((x($arr,'visible') !== false) ? intval($arr['visible'])         : 1 );
587         $arr['deleted']       = 0;
588         $arr['parent-uri']    = ((x($arr,'parent-uri'))    ? notags(trim($arr['parent-uri']))    : '');
589         $arr['verb']          = ((x($arr,'verb'))          ? notags(trim($arr['verb']))          : '');
590         $arr['object-type']   = ((x($arr,'object-type'))   ? notags(trim($arr['object-type']))   : '');
591         $arr['object']        = ((x($arr,'object'))        ? trim($arr['object'])                : '');
592         $arr['target-type']   = ((x($arr,'target-type'))   ? notags(trim($arr['target-type']))   : '');
593         $arr['target']        = ((x($arr,'target'))        ? trim($arr['target'])                : '');
594         $arr['plink']         = ((x($arr,'plink'))         ? notags(trim($arr['plink']))         : '');
595         $arr['allow_cid']     = ((x($arr,'allow_cid'))     ? trim($arr['allow_cid'])             : '');
596         $arr['allow_gid']     = ((x($arr,'allow_gid'))     ? trim($arr['allow_gid'])             : '');
597         $arr['deny_cid']      = ((x($arr,'deny_cid'))      ? trim($arr['deny_cid'])              : '');
598         $arr['deny_gid']      = ((x($arr,'deny_gid'))      ? trim($arr['deny_gid'])              : '');
599         $arr['private']       = ((x($arr,'private'))       ? intval($arr['private'])             : 0 );
600         $arr['body']          = ((x($arr,'body'))          ? trim($arr['body'])                  : '');
601
602         if($arr['parent-uri'] === $arr['uri']) {
603                 $parent_id = 0;
604                 $allow_cid = $arr['allow_cid'];
605                 $allow_gid = $arr['allow_gid'];
606                 $deny_cid  = $arr['deny_cid'];
607                 $deny_gid  = $arr['deny_gid'];
608         }
609         else { 
610
611                 // find the parent and snarf the item id and ACL's
612                 // and anything else we need to inherit
613
614                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
615                         dbesc($arr['parent-uri']),
616                         intval($arr['uid'])
617                 );
618
619                 if(count($r)) {
620
621                         // is the new message multi-level threaded?
622                         // even though we don't support it now, preserve the info
623                         // and re-attach to the conversation parent.
624
625                         if($r[0]['uri'] != $r[0]['parent-uri']) {
626                                 $arr['thr-parent'] = $arr['parent-uri'];
627                                 $arr['parent-uri'] = $r[0]['parent-uri'];
628                         }
629
630                         $parent_id      = $r[0]['id'];
631                         $parent_deleted = $r[0]['deleted'];
632                         $allow_cid      = $r[0]['allow_cid'];
633                         $allow_gid      = $r[0]['allow_gid'];
634                         $deny_cid       = $r[0]['deny_cid'];
635                         $deny_gid       = $r[0]['deny_gid'];
636                         $arr['wall']    = $r[0]['wall'];
637                 }
638                 else {
639
640                         // Allow one to see reply tweets from status.net even when
641                         // we don't have or can't see the original post.
642
643                         if($force_parent) {
644                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
645                                 $parent_id = 0;
646                                 $arr['thr-parent'] = $arr['parent-uri'];
647                                 $arr['parent-uri'] = $arr['uri'];
648                         }
649                         else {
650                                 logger('item_store: item parent was not found - ignoring item');
651                                 return 0;
652                         }
653                 }
654         }
655
656         call_hooks('post_remote',$arr);
657
658         dbesc_array($arr);
659
660         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
661
662         $r = dbq("INSERT INTO `item` (`" 
663                         . implode("`, `", array_keys($arr)) 
664                         . "`) VALUES ('" 
665                         . implode("', '", array_values($arr)) 
666                         . "')" );
667
668         // find the item we just created
669
670         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
671                 $arr['uri'],           // already dbesc'd
672                 intval($arr['uid'])
673         );
674         if(count($r)) {
675                 $current_post = $r[0]['id'];
676                 logger('item_store: created item ' . $current_post);
677         }
678         else {
679                 logger('item_store: could not locate created item');
680                 return 0;
681         }
682
683         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
684                 $parent_id = $current_post;
685
686         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
687                 $private = 1;
688         else
689                 $private = $arr['private']; 
690
691         // Set parent id - and also make sure to inherit the parent's ACL's.
692
693         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
694                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
695                 intval($parent_id),
696                 dbesc($allow_cid),
697                 dbesc($allow_gid),
698                 dbesc($deny_cid),
699                 dbesc($deny_gid),
700                 intval($private),
701                 intval($parent_deleted),
702                 intval($current_post)
703         );
704
705         return $current_post;
706 }
707
708 function get_item_contact($item,$contacts) {
709         if(! count($contacts) || (! is_array($item)))
710                 return false;
711         foreach($contacts as $contact) {
712                 if($contact['id'] == $item['contact-id']) {
713                         return $contact;
714                         break; // NOTREACHED
715                 }
716         }
717         return false;
718 }
719
720
721 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
722
723         $a = get_app();
724
725         if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
726                 return 3;
727
728         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
729
730         if($contact['duplex'] && $contact['dfrn-id'])
731                 $idtosend = '0:' . $orig_id;
732         if($contact['duplex'] && $contact['issued-id'])
733                 $idtosend = '1:' . $orig_id;            
734
735         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
736
737         $rino_enable = get_config('system','rino_encrypt');
738
739         if(! $rino_enable)
740                 $rino = 0;
741
742         $url = $contact['notify'] . '?dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
743
744         logger('dfrn_deliver: ' . $url);
745
746         $xml = fetch_url($url);
747
748         $curl_stat = $a->get_curl_code();
749         if(! $curl_stat)
750                 return(-1); // timed out
751
752         logger('dfrn_deliver: ' . $xml);
753
754         if(! $xml)
755                 return 3;
756
757         if(strpos($xml,'<?xml') === false) {
758                 logger('dfrn_deliver: no valid XML returned');
759                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
760                 return 3;
761         }
762
763         $res = simplexml_load_string($xml);
764
765         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
766                 return (($res->status) ? $res->status : 3);
767
768         $postvars     = array();
769         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
770         $challenge    = hex2bin((string) $res->challenge);
771         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
772         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
773
774         $final_dfrn_id = '';
775
776
777         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
778                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
779                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
780         }
781         else {
782                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
783                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
784         }
785
786         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
787
788         if(strpos($final_dfrn_id,':') == 1)
789                 $final_dfrn_id = substr($final_dfrn_id,2);
790
791         if($final_dfrn_id != $orig_id) {
792                 logger('dfrn_deliver: wrong dfrn_id.');
793                 // did not decode properly - cannot trust this site 
794                 return 3;
795         }
796
797         $postvars['dfrn_id']      = $idtosend;
798         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
799         if($dissolve)
800                 $postvars['dissolve'] = '1';
801
802         if(($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked']) && (! $contact['readonly'])) {
803                 $postvars['data'] = $atom;
804         }
805         elseif($owner['page-flags'] == PAGE_COMMUNITY) {
806                 $postvars['data'] = $atom;
807         }
808         else {
809                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
810         }
811
812         if($rino && $rino_allowed && (! $dissolve)) {
813                 $key = substr(random_string(),0,16);
814                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
815                 $postvars['data'] = $data;
816                 logger('rino: sent key = ' . $key);     
817
818
819                 if($dfrn_version >= 2.1) {      
820                         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
821                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
822                         }
823                         else {
824                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
825                         }
826                 }
827                 else {
828                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
829                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
830                         }
831                         else {
832                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
833                         }
834                 }
835
836                 logger('md5 rawkey ' . md5($postvars['key']));
837
838                 $postvars['key'] = bin2hex($postvars['key']);
839         }
840
841         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
842
843         $xml = post_url($contact['notify'],$postvars);
844
845         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
846
847         $curl_stat = $a->get_curl_code();
848         if((! $curl_stat) || (! strlen($xml)))
849                 return(-1); // timed out
850
851
852         if(strpos($xml,'<?xml') === false) {
853                 logger('dfrn_deliver: phase 2: no valid XML returned');
854                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
855                 return 3;
856         }
857
858         $res = simplexml_load_string($xml);
859
860         return $res->status;
861  
862 }
863
864
865 /**
866  *
867  * consume_feed - process atom feed and update anything/everything we might need to update
868  *
869  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
870  *
871  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
872  *             It is this person's stuff that is going to be updated.
873  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
874  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
875  *             have a contact record.
876  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
877  *        might not) try and subscribe to it.
878  *
879  */
880
881 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0) {
882
883         require_once('simplepie/simplepie.inc');
884
885         $feed = new SimplePie();
886         $feed->set_raw_data($xml);
887         if($datedir)
888                 $feed->enable_order_by_date(true);
889         else
890                 $feed->enable_order_by_date(false);
891         $feed->init();
892
893         if($feed->error())
894                 logger('consume_feed: Error parsing XML: ' . $feed->error());
895
896
897         // Check at the feed level for updated contact name and/or photo
898
899         $name_updated  = '';
900         $new_name = '';
901         $photo_timestamp = '';
902         $photo_url = '';
903         $birthday = '';
904
905         $hubs = $feed->get_links('hub');
906
907         if(count($hubs))
908                 $hub = implode(',', $hubs);
909
910         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
911         if($rawtags) {
912                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
913                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
914                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
915                         $new_name = $elems['name'][0]['data'];
916                 } 
917                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
918                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
919                         $photo_url = $elems['link'][0]['attribs']['']['href'];
920                 }
921
922                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
923                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
924                 }
925         }
926
927         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
928                 logger('consume_feed: Updating photo for ' . $contact['name']);
929                 require_once("Photo.php");
930                 $photo_failure = false;
931                 $have_photo = false;
932
933                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
934                         intval($contact['id']),
935                         intval($contact['uid'])
936                 );
937                 if(count($r)) {
938                         $resource_id = $r[0]['resource-id'];
939                         $have_photo = true;
940                 }
941                 else {
942                         $resource_id = photo_new_resource();
943                 }
944                         
945                 $img_str = fetch_url($photo_url,true);
946                 $img = new Photo($img_str);
947                 if($img->is_valid()) {
948                         if($have_photo) {
949                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
950                                         dbesc($resource_id),
951                                         intval($contact['id']),
952                                         intval($contact['uid'])
953                                 );
954                         }
955                                 
956                         $img->scaleImageSquare(175);
957                                 
958                         $hash = $resource_id;
959                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
960                                 
961                         $img->scaleImage(80);
962                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
963
964                         $img->scaleImage(48);
965                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 6);
966
967                         $a = get_app();
968
969                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
970                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
971                                 dbesc(datetime_convert()),
972                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
973                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
974                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
975                                 intval($contact['uid']),
976                                 intval($contact['id'])
977                         );
978                 }
979         }
980
981         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
982                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
983                         dbesc(notags(trim($new_name))),
984                         dbesc(datetime_convert()),
985                         intval($contact['uid']),
986                         intval($contact['id'])
987                 );
988         }
989
990         if(strlen($birthday)) {
991                 if(substr($birthday,0,4) != $contact['bdyear']) {
992                         logger('consume_feed: updating birthday: ' . $birthday);
993
994                         /**
995                          *
996                          * Add new birthday event for this person
997                          *
998                          * $bdtext is just a readable placeholder in case the event is shared
999                          * with others. We will replace it during presentation to our $importer
1000                          * to contain a sparkle link and perhaps a photo. 
1001                          *
1002                          */
1003                          
1004                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1005
1006
1007                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1008                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1009                                 intval($contact['uid']),
1010                                 intval($contact['id']),
1011                                 dbesc(datetime_convert()),
1012                                 dbesc(datetime_convert()),
1013                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1014                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1015                                 dbesc($bdtext),
1016                                 dbesc('birthday')
1017                         );
1018                         
1019
1020                         // update bdyear
1021
1022                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1023                                 dbesc(substr($birthday,0,4)),
1024                                 intval($contact['uid']),
1025                                 intval($contact['id'])
1026                         );
1027
1028                         // This function is called twice without reloading the contact
1029                         // Make sure we only create one event. This is why &$contact 
1030                         // is a reference var in this function
1031
1032                         $contact['bdyear'] = substr($birthday,0,4);
1033                 }
1034
1035         }
1036
1037
1038         // process any deleted entries
1039
1040         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1041         if(is_array($del_entries) && count($del_entries)) {
1042                 foreach($del_entries as $dentry) {
1043                         $deleted = false;
1044                         if(isset($dentry['attribs']['']['ref'])) {
1045                                 $uri = $dentry['attribs']['']['ref'];
1046                                 $deleted = true;
1047                                 if(isset($dentry['attribs']['']['when'])) {
1048                                         $when = $dentry['attribs']['']['when'];
1049                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1050                                 }
1051                                 else
1052                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1053                         }
1054                         if($deleted && is_array($contact)) {
1055                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1056                                         dbesc($uri),
1057                                         intval($importer['uid']),
1058                                         intval($contact['id'])
1059                                 );
1060                                 if(count($r)) {
1061                                         $item = $r[0];
1062
1063                                         if(! $item['deleted'])
1064                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1065
1066                                         if($item['uri'] == $item['parent-uri']) {
1067                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1068                                                         `body` = '', `title` = ''
1069                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1070                                                         dbesc($when),
1071                                                         dbesc(datetime_convert()),
1072                                                         dbesc($item['uri']),
1073                                                         intval($importer['uid'])
1074                                                 );
1075                                         }
1076                                         else {
1077                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1078                                                         `body` = '', `title` = '' 
1079                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1080                                                         dbesc($when),
1081                                                         dbesc(datetime_convert()),
1082                                                         dbesc($uri),
1083                                                         intval($importer['uid'])
1084                                                 );
1085                                                 if($item['last-child']) {
1086                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1087                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1088                                                                 dbesc(datetime_convert()),
1089                                                                 dbesc($item['parent-uri']),
1090                                                                 intval($item['uid'])
1091                                                         );
1092                                                         // who is the last child now? 
1093                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1094                                                                 ORDER BY `created` DESC LIMIT 1",
1095                                                                         dbesc($item['parent-uri']),
1096                                                                         intval($importer['uid'])
1097                                                         );
1098                                                         if(count($r)) {
1099                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1100                                                                         intval($r[0]['id'])
1101                                                                 );
1102                                                         }
1103                                                 }       
1104                                         }
1105                                 }       
1106                         }
1107                 }
1108         }
1109
1110         // Now process the feed
1111
1112         if($feed->get_item_quantity()) {                
1113
1114                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1115
1116         // in inverse date order
1117                 if ($datedir)
1118                         $items = array_reverse($feed->get_items());
1119                 else
1120                         $items = $feed->get_items();
1121
1122
1123                 foreach($items as $item) {
1124
1125                         $is_reply = false;              
1126                         $item_id = $item->get_id();
1127                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1128                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1129                                 $is_reply = true;
1130                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1131                         }
1132
1133                         if(($is_reply) && is_array($contact)) {
1134
1135                                 // Have we seen it? If not, import it.
1136         
1137                                 $item_id  = $item->get_id();
1138                                 $datarray = get_atom_elements($feed,$item);
1139
1140                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1141                                         dbesc($item_id),
1142                                         intval($importer['uid'])
1143                                 );
1144
1145                                 // Update content if 'updated' changes
1146
1147                                 if(count($r)) {
1148                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1149                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1150                                                         dbesc($datarray['body']),
1151                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1152                                                         dbesc($item_id),
1153                                                         intval($importer['uid'])
1154                                                 );
1155                                         }
1156
1157                                         // update last-child if it changes
1158
1159                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1160                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1161                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1162                                                         dbesc(datetime_convert()),
1163                                                         dbesc($parent_uri),
1164                                                         intval($importer['uid'])
1165                                                 );
1166                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1167                                                         intval($allow[0]['data']),
1168                                                         dbesc(datetime_convert()),
1169                                                         dbesc($item_id),
1170                                                         intval($importer['uid'])
1171                                                 );
1172                                         }
1173                                         continue;
1174                                 }
1175
1176                                 $force_parent = false;
1177                                 if($contact['network'] === 'stat') {
1178                                         $force_parent = true;
1179                                         if(strlen($datarray['title']))
1180                                                 unset($datarray['title']);
1181                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1182                                                 dbesc(datetime_convert()),
1183                                                 dbesc($parent_uri),
1184                                                 intval($importer['uid'])
1185                                         );
1186                                         $datarray['last-child'] = 1;
1187                                 }
1188
1189                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1190                                         // one way feed - no remote comment ability
1191                                         $datarray['last-child'] = 0;
1192                                 }
1193                                 $datarray['parent-uri'] = $parent_uri;
1194                                 $datarray['uid'] = $importer['uid'];
1195                                 $datarray['contact-id'] = $contact['id'];
1196                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1197                                         $datarray['type'] = 'activity';
1198                                         $datarray['gravity'] = GRAVITY_LIKE;
1199                                 }
1200
1201                                 $r = item_store($datarray,$force_parent);
1202                                 continue;
1203                         }
1204
1205                         else {
1206
1207                                 // Head post of a conversation. Have we seen it? If not, import it.
1208
1209                                 $item_id  = $item->get_id();
1210                                 $datarray = get_atom_elements($feed,$item);
1211
1212                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1213                                         dbesc($item_id),
1214                                         intval($importer['uid'])
1215                                 );
1216
1217                                 // Update content if 'updated' changes
1218
1219                                 if(count($r)) {
1220                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1221                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1222                                                         dbesc($datarray['body']),
1223                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1224                                                         dbesc($item_id),
1225                                                         intval($importer['uid'])
1226                                                 );
1227                                         }
1228
1229                                         // update last-child if it changes
1230
1231                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1232                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1233                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1234                                                         intval($allow[0]['data']),
1235                                                         dbesc(datetime_convert()),
1236                                                         dbesc($item_id),
1237                                                         intval($importer['uid'])
1238                                                 );
1239                                         }
1240                                         continue;
1241                                 }
1242
1243                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1244                                         logger('consume-feed: New follower');
1245                                         new_follower($importer,$contact,$datarray,$item);
1246                                         return;
1247                                 }
1248                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1249                                         lose_follower($importer,$contact,$datarray,$item);
1250                                         return;
1251                                 }
1252                                 if(! is_array($contact))
1253                                         return;
1254
1255                                 if($contact['network'] === 'stat') {
1256                                         if(strlen($datarray['title']))
1257                                                 unset($datarray['title']);
1258                                         $datarray['last-child'] = 1;
1259                                 }
1260
1261                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1262                                         // one way feed - no remote comment ability
1263                                         $datarray['last-child'] = 0;
1264                                 }
1265
1266                                 $datarray['parent-uri'] = $item_id;
1267                                 $datarray['uid'] = $importer['uid'];
1268                                 $datarray['contact-id'] = $contact['id'];
1269                                 $r = item_store($datarray);
1270                                 continue;
1271
1272                         }
1273                 }
1274         }
1275 }
1276
1277 function new_follower($importer,$contact,$datarray,$item) {
1278         $url = notags(trim($datarray['author-link']));
1279         $name = notags(trim($datarray['author-name']));
1280         $photo = notags(trim($datarray['author-avatar']));
1281
1282         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1283         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1284                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1285
1286         if(is_array($contact)) {
1287                 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
1288                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1289                                 intval(REL_BUD),
1290                                 intval($contact['id']),
1291                                 intval($importer['uid'])
1292                         );
1293                 }
1294
1295                 // send email notification to owner?
1296         }
1297         else {
1298         
1299                 // create contact record - set to readonly
1300
1301                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
1302                         `blocked`, `readonly`, `pending` )
1303                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1 ) ",
1304                         intval($importer['uid']),
1305                         dbesc(datetime_convert()),
1306                         dbesc($url),
1307                         dbesc($name),
1308                         dbesc($nick),
1309                         dbesc($photo),
1310                         dbesc('stat'),
1311                         intval(REL_VIP)
1312                 );
1313                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1314                                 intval($importer['uid']),
1315                                 dbesc($url),
1316                                 intval(REL_VIP)
1317                 );
1318                 if(count($r))
1319                                 $contact_record = $r[0];
1320
1321                 // create notification  
1322                 $hash = random_string();
1323
1324                 if(is_array($contact_record)) {
1325                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1326                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1327                                 intval($importer['uid']),
1328                                 intval($contact_record['id']),
1329                                 dbesc($hash),
1330                                 dbesc(datetime_convert())
1331                         );
1332                 }
1333                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1334                         intval($importer['uid'])
1335                 );
1336                 $a = get_app();
1337                 if(count($r)) {
1338                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1339                                 $email_tpl = load_view_file('view/follow_notify_eml.tpl');
1340                                 $email = replace_macros($email_tpl, array(
1341                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1342                                         '$url' => $url,
1343                                         '$myname' => $r[0]['username'],
1344                                         '$siteurl' => $a->get_baseurl(),
1345                                         '$sitename' => $a->config['sitename']
1346                                 ));
1347                                 $res = mail($r[0]['email'], 
1348                                         t("You have a new follower at ") . $a->config['sitename'],
1349                                         $email,
1350                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
1351                         
1352                         }
1353                 }
1354         }
1355 }
1356
1357 function lose_follower($importer,$contact,$datarray,$item) {
1358
1359         if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1360                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1361                         intval(REL_FAN),
1362                         intval($contact['id'])
1363                 );
1364         }
1365         else {
1366                 contact_remove($contact['id']);
1367         }
1368 }
1369
1370
1371 function subscribe_to_hub($url,$importer,$contact) {
1372
1373         if(is_array($importer)) {
1374                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1375                         intval($importer['uid'])
1376                 );
1377         }
1378         if(! count($r))
1379                 return;
1380
1381         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1382
1383         // Use a single verify token, even if multiple hubs
1384
1385         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1386
1387         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1388
1389         logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1390
1391         if(! strlen($contact['hub-verify'])) {
1392                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1393                         dbesc($verify_token),
1394                         intval($contact['id'])
1395                 );
1396         }
1397
1398         post_url($url,$params);                 
1399         return;
1400
1401 }
1402
1403
1404 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1405         $o = '';
1406         if(! $tag)
1407                 return $o;
1408         $name = xmlify($name);
1409         $uri = xmlify($uri);
1410         $h = intval($h);
1411         $w = intval($w);
1412         $photo = xmlify($photo);
1413
1414
1415         $o .= "<$tag>\r\n";
1416         $o .= "<name>$name</name>\r\n";
1417         $o .= "<uri>$uri</uri>\r\n";
1418         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1419         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1420
1421         call_hooks('atom_author', $o);
1422
1423         $o .= "</$tag>\r\n";
1424         return $o;
1425 }
1426
1427 function atom_entry($item,$type,$author,$owner,$comment = false) {
1428
1429         if($item['deleted'])
1430                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1431
1432         $a = get_app();
1433
1434         $o = "\r\n\r\n<entry>\r\n";
1435
1436         if(is_array($author))
1437                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1438         else
1439                 $o .= atom_author('author',$item['name'],$item['url'],80,80,$item['thumb']);
1440         if(strlen($item['owner-name']))
1441                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1442
1443         if($item['parent'] != $item['id'])
1444                 $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";
1445
1446         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1447         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1448         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1449         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1450         $o .= '<dfrn:env>' . base64url_encode($item['body'], true) . '</dfrn:env>' . "\r\n";
1451         $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($item['body']) : $item['body']) . '</content>' . "\r\n";
1452         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1453         if($comment)
1454                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1455
1456         if($item['location']) {
1457                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1458                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1459         }
1460
1461         if($item['coord'])
1462                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1463
1464         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1465                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1466
1467         $verb = construct_verb($item);
1468         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1469         $actobj = construct_activity_object($item);
1470         if(strlen($actobj))
1471                 $o .= $actobj;
1472         $actarg = construct_activity_target($item);
1473         if(strlen($actarg))
1474                 $o .= $actarg;
1475
1476         $mentioned = get_mentions($item);
1477         if($mentioned)
1478                 $o .= $mentioned;
1479         
1480         call_hooks('atom_entry', $o);
1481
1482         $o .= '</entry>' . "\r\n";
1483         
1484         return $o;
1485 }
1486