]> git.mxchange.org Git - friendica.git/blob - include/items.php
153debd7d321f803f2fa11a5fc934f0647092ae4
[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
613                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
614                         dbesc($arr['parent-uri']),
615                         intval($arr['uid'])
616                 );
617
618                 if(count($r)) {
619
620                         // is the new message multi-level threaded?
621                         // even though we don't support it now, preserve the info
622                         // and re-attach to the conversation parent.
623
624                         if($r[0]['uri'] != $r[0]['parent-uri']) {
625                                 $arr['thr-parent'] = $arr['parent-uri'];
626                                 $arr['parent-uri'] = $r[0]['parent-uri'];
627                         }
628
629                         $parent_id      = $r[0]['id'];
630                         $parent_deleted = $r[0]['deleted'];
631                         $allow_cid      = $r[0]['allow_cid'];
632                         $allow_gid      = $r[0]['allow_gid'];
633                         $deny_cid       = $r[0]['deny_cid'];
634                         $deny_gid       = $r[0]['deny_gid'];
635                 }
636                 else {
637
638                         // Allow one to see reply tweets from status.net even when
639                         // we don't have or can't see the original post.
640
641                         if($force_parent) {
642                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
643                                 $parent_id = 0;
644                                 $arr['thr-parent'] = $arr['parent-uri'];
645                                 $arr['parent-uri'] = $arr['uri'];
646                         }
647                         else {
648                                 logger('item_store: item parent was not found - ignoring item');
649                                 return 0;
650                         }
651                 }
652         }
653
654         call_hooks('post_remote',$arr);
655
656         dbesc_array($arr);
657
658         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
659
660         $r = dbq("INSERT INTO `item` (`" 
661                         . implode("`, `", array_keys($arr)) 
662                         . "`) VALUES ('" 
663                         . implode("', '", array_values($arr)) 
664                         . "')" );
665
666         // find the item we just created
667
668         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
669                 $arr['uri'],           // already dbesc'd
670                 intval($arr['uid'])
671         );
672         if(count($r)) {
673                 $current_post = $r[0]['id'];
674                 logger('item_store: created item ' . $current_post);
675         }
676         else {
677                 logger('item_store: could not locate created item');
678                 return 0;
679         }
680
681         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
682                 $parent_id = $current_post;
683
684         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
685                 $private = 1;
686         else
687                 $private = $arr['private']; 
688
689         // Set parent id - and also make sure to inherit the parent's ACL's.
690
691         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
692                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
693                 intval($parent_id),
694                 dbesc($allow_cid),
695                 dbesc($allow_gid),
696                 dbesc($deny_cid),
697                 dbesc($deny_gid),
698                 intval($private),
699                 intval($parent_deleted),
700                 intval($current_post)
701         );
702
703         return $current_post;
704 }
705
706 function get_item_contact($item,$contacts) {
707         if(! count($contacts) || (! is_array($item)))
708                 return false;
709         foreach($contacts as $contact) {
710                 if($contact['id'] == $item['contact-id']) {
711                         return $contact;
712                         break; // NOTREACHED
713                 }
714         }
715         return false;
716 }
717
718
719 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
720
721         $a = get_app();
722
723         if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
724                 return 3;
725
726         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
727
728         if($contact['duplex'] && $contact['dfrn-id'])
729                 $idtosend = '0:' . $orig_id;
730         if($contact['duplex'] && $contact['issued-id'])
731                 $idtosend = '1:' . $orig_id;            
732
733         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
734
735         $rino_enable = get_config('system','rino_encrypt');
736
737         if(! $rino_enable)
738                 $rino = 0;
739
740         $url = $contact['notify'] . '?dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
741
742         logger('dfrn_deliver: ' . $url);
743
744         $xml = fetch_url($url);
745
746         $curl_stat = $a->get_curl_code();
747         if(! $curl_stat)
748                 return(-1); // timed out
749
750         logger('dfrn_deliver: ' . $xml);
751
752         if(! $xml)
753                 return 3;
754
755         if(strpos($xml,'<?xml') === false) {
756                 logger('dfrn_deliver: no valid XML returned');
757                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
758                 return 3;
759         }
760
761         $res = simplexml_load_string($xml);
762
763         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
764                 return (($res->status) ? $res->status : 3);
765
766         $postvars     = array();
767         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
768         $challenge    = hex2bin((string) $res->challenge);
769         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
770         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
771
772         $final_dfrn_id = '';
773
774
775         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
776                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
777                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
778         }
779         else {
780                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
781                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
782         }
783
784         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
785
786         if(strpos($final_dfrn_id,':') == 1)
787                 $final_dfrn_id = substr($final_dfrn_id,2);
788
789         if($final_dfrn_id != $orig_id) {
790                 logger('dfrn_deliver: wrong dfrn_id.');
791                 // did not decode properly - cannot trust this site 
792                 return 3;
793         }
794
795         $postvars['dfrn_id']      = $idtosend;
796         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
797         if($dissolve)
798                 $postvars['dissolve'] = '1';
799
800         if(($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked']) && (! $contact['readonly'])) {
801                 $postvars['data'] = $atom;
802         }
803         elseif($owner['page-flags'] == PAGE_COMMUNITY) {
804                 $postvars['data'] = $atom;
805         }
806         else {
807                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
808         }
809
810         if($rino && $rino_allowed && (! $dissolve)) {
811                 $key = substr(random_string(),0,16);
812                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
813                 $postvars['data'] = $data;
814                 logger('rino: sent key = ' . $key);     
815
816
817                 if($dfrn_version >= 2.1) {      
818                         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
819                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
820                         }
821                         else {
822                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
823                         }
824                 }
825                 else {
826                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
827                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
828                         }
829                         else {
830                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
831                         }
832                 }
833
834                 logger('md5 rawkey ' . md5($postvars['key']));
835
836                 $postvars['key'] = bin2hex($postvars['key']);
837         }
838
839         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
840
841         $xml = post_url($contact['notify'],$postvars);
842
843         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
844
845         $curl_stat = $a->get_curl_code();
846         if((! $curl_stat) || (! strlen($xml)))
847                 return(-1); // timed out
848
849
850         if(strpos($xml,'<?xml') === false) {
851                 logger('dfrn_deliver: phase 2: no valid XML returned');
852                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
853                 return 3;
854         }
855
856         $res = simplexml_load_string($xml);
857
858         return $res->status;
859  
860 }
861
862
863 /**
864  *
865  * consume_feed - process atom feed and update anything/everything we might need to update
866  *
867  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
868  *
869  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
870  *             It is this person's stuff that is going to be updated.
871  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
872  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
873  *             have a contact record.
874  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
875  *        might not) try and subscribe to it.
876  *
877  */
878
879 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0) {
880
881         require_once('simplepie/simplepie.inc');
882
883         $feed = new SimplePie();
884         $feed->set_raw_data($xml);
885         if($datedir)
886                 $feed->enable_order_by_date(true);
887         else
888                 $feed->enable_order_by_date(false);
889         $feed->init();
890
891         if($feed->error())
892                 logger('consume_feed: Error parsing XML: ' . $feed->error());
893
894
895         // Check at the feed level for updated contact name and/or photo
896
897         $name_updated  = '';
898         $new_name = '';
899         $photo_timestamp = '';
900         $photo_url = '';
901         $birthday = '';
902
903         $hubs = $feed->get_links('hub');
904
905         if(count($hubs))
906                 $hub = implode(',', $hubs);
907
908         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
909         if($rawtags) {
910                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
911                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
912                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
913                         $new_name = $elems['name'][0]['data'];
914                 } 
915                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
916                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
917                         $photo_url = $elems['link'][0]['attribs']['']['href'];
918                 }
919
920                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
921                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
922                 }
923         }
924
925         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
926                 logger('consume_feed: Updating photo for ' . $contact['name']);
927                 require_once("Photo.php");
928                 $photo_failure = false;
929                 $have_photo = false;
930
931                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
932                         intval($contact['id']),
933                         intval($contact['uid'])
934                 );
935                 if(count($r)) {
936                         $resource_id = $r[0]['resource-id'];
937                         $have_photo = true;
938                 }
939                 else {
940                         $resource_id = photo_new_resource();
941                 }
942                         
943                 $img_str = fetch_url($photo_url,true);
944                 $img = new Photo($img_str);
945                 if($img->is_valid()) {
946                         if($have_photo) {
947                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
948                                         dbesc($resource_id),
949                                         intval($contact['id']),
950                                         intval($contact['uid'])
951                                 );
952                         }
953                                 
954                         $img->scaleImageSquare(175);
955                                 
956                         $hash = $resource_id;
957                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
958                                 
959                         $img->scaleImage(80);
960                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
961
962                         $img->scaleImage(48);
963                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 6);
964
965                         $a = get_app();
966
967                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
968                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
969                                 dbesc(datetime_convert()),
970                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
971                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
972                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
973                                 intval($contact['uid']),
974                                 intval($contact['id'])
975                         );
976                 }
977         }
978
979         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
980                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
981                         dbesc(notags(trim($new_name))),
982                         dbesc(datetime_convert()),
983                         intval($contact['uid']),
984                         intval($contact['id'])
985                 );
986         }
987
988         if(strlen($birthday)) {
989                 if(substr($birthday,0,4) != $contact['bdyear']) {
990                         logger('consume_feed: updating birthday: ' . $birthday);
991
992                         /**
993                          *
994                          * Add new birthday event for this person
995                          *
996                          * $bdtext is just a readable placeholder in case the event is shared
997                          * with others. We will replace it during presentation to our $importer
998                          * to contain a sparkle link and perhaps a photo. 
999                          *
1000                          */
1001                          
1002                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1003
1004
1005                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1006                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1007                                 intval($contact['uid']),
1008                                 intval($contact['id']),
1009                                 dbesc(datetime_convert()),
1010                                 dbesc(datetime_convert()),
1011                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1012                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1013                                 dbesc($bdtext),
1014                                 dbesc('birthday')
1015                         );
1016                         
1017
1018                         // update bdyear
1019
1020                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1021                                 dbesc(substr($birthday,0,4)),
1022                                 intval($contact['uid']),
1023                                 intval($contact['id'])
1024                         );
1025
1026                         // This function is called twice without reloading the contact
1027                         // Make sure we only create one event. This is why &$contact 
1028                         // is a reference var in this function
1029
1030                         $contact['bdyear'] = substr($birthday,0,4);
1031                 }
1032
1033         }
1034
1035
1036         // process any deleted entries
1037
1038         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1039         if(is_array($del_entries) && count($del_entries)) {
1040                 foreach($del_entries as $dentry) {
1041                         $deleted = false;
1042                         if(isset($dentry['attribs']['']['ref'])) {
1043                                 $uri = $dentry['attribs']['']['ref'];
1044                                 $deleted = true;
1045                                 if(isset($dentry['attribs']['']['when'])) {
1046                                         $when = $dentry['attribs']['']['when'];
1047                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1048                                 }
1049                                 else
1050                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1051                         }
1052                         if($deleted && is_array($contact)) {
1053                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1054                                         dbesc($uri),
1055                                         intval($importer['uid']),
1056                                         intval($contact['id'])
1057                                 );
1058                                 if(count($r)) {
1059                                         $item = $r[0];
1060
1061                                         if(! $item['deleted'])
1062                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1063
1064                                         if($item['uri'] == $item['parent-uri']) {
1065                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1066                                                         `body` = '', `title` = ''
1067                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1068                                                         dbesc($when),
1069                                                         dbesc(datetime_convert()),
1070                                                         dbesc($item['uri']),
1071                                                         intval($importer['uid'])
1072                                                 );
1073                                         }
1074                                         else {
1075                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1076                                                         `body` = '', `title` = '' 
1077                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1078                                                         dbesc($when),
1079                                                         dbesc(datetime_convert()),
1080                                                         dbesc($uri),
1081                                                         intval($importer['uid'])
1082                                                 );
1083                                                 if($item['last-child']) {
1084                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1085                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1086                                                                 dbesc(datetime_convert()),
1087                                                                 dbesc($item['parent-uri']),
1088                                                                 intval($item['uid'])
1089                                                         );
1090                                                         // who is the last child now? 
1091                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1092                                                                 ORDER BY `created` DESC LIMIT 1",
1093                                                                         dbesc($item['parent-uri']),
1094                                                                         intval($importer['uid'])
1095                                                         );
1096                                                         if(count($r)) {
1097                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1098                                                                         intval($r[0]['id'])
1099                                                                 );
1100                                                         }
1101                                                 }       
1102                                         }
1103                                 }       
1104                         }
1105                 }
1106         }
1107
1108         // Now process the feed
1109
1110         if($feed->get_item_quantity()) {                
1111
1112                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1113
1114         // in inverse date order
1115                 if ($datedir)
1116                         $items = array_reverse($feed->get_items());
1117                 else
1118                         $items = $feed->get_items();
1119
1120
1121                 foreach($items as $item) {
1122
1123                         $is_reply = false;              
1124                         $item_id = $item->get_id();
1125                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1126                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1127                                 $is_reply = true;
1128                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1129                         }
1130
1131                         if(($is_reply) && is_array($contact)) {
1132
1133                                 // Have we seen it? If not, import it.
1134         
1135                                 $item_id = $item->get_id();
1136
1137                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1138                                         dbesc($item_id),
1139                                         intval($importer['uid'])
1140                                 );
1141
1142                                 // FIXME update content if 'updated' changes
1143                                 if(count($r)) {
1144                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1145                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1146                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1147                                                         dbesc(datetime_convert()),
1148                                                         dbesc($parent_uri),
1149                                                         intval($importer['uid'])
1150                                                 );
1151                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1152                                                         intval($allow[0]['data']),
1153                                                         dbesc(datetime_convert()),
1154                                                         dbesc($item_id),
1155                                                         intval($importer['uid'])
1156                                                 );
1157                                         }
1158                                         continue;
1159                                 }
1160
1161                                 $datarray = get_atom_elements($feed,$item);
1162                                 $force_parent = false;
1163                                 if($contact['network'] === 'stat') {
1164                                         $force_parent = true;
1165                                         if(strlen($datarray['title']))
1166                                                 unset($datarray['title']);
1167                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1168                                                 dbesc(datetime_convert()),
1169                                                 dbesc($parent_uri),
1170                                                 intval($importer['uid'])
1171                                         );
1172                                         $datarray['last-child'] = 1;
1173                                 }
1174
1175                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1176                                         // one way feed - no remote comment ability
1177                                         $datarray['last-child'] = 0;
1178                                 }
1179                                 $datarray['parent-uri'] = $parent_uri;
1180                                 $datarray['uid'] = $importer['uid'];
1181                                 $datarray['contact-id'] = $contact['id'];
1182                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1183                                         $datarray['type'] = 'activity';
1184                                         $datarray['gravity'] = GRAVITY_LIKE;
1185                                 }
1186
1187                                 $r = item_store($datarray,$force_parent);
1188                                 continue;
1189                         }
1190
1191                         else {
1192                                 // Head post of a conversation. Have we seen it? If not, import it.
1193
1194                                 $item_id = $item->get_id();
1195                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1196                                         dbesc($item_id),
1197                                         intval($importer['uid'])
1198                                 );
1199                                 if(count($r)) {
1200                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1201                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1202                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1203                                                         intval($allow[0]['data']),
1204                                                         dbesc(datetime_convert()),
1205                                                         dbesc($item_id),
1206                                                         intval($importer['uid'])
1207                                                 );
1208                                         }
1209                                         continue;
1210                                 }
1211                                 $datarray = get_atom_elements($feed,$item);
1212
1213                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1214                                         logger('consume-feed: New follower');
1215                                         new_follower($importer,$contact,$datarray,$item);
1216                                         return;
1217                                 }
1218                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1219                                         lose_follower($importer,$contact,$datarray,$item);
1220                                         return;
1221                                 }
1222                                 if(! is_array($contact))
1223                                         return;
1224
1225                                 if($contact['network'] === 'stat') {
1226                                         if(strlen($datarray['title']))
1227                                                 unset($datarray['title']);
1228                                         $datarray['last-child'] = 1;
1229                                 }
1230
1231                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1232                                         // one way feed - no remote comment ability
1233                                         $datarray['last-child'] = 0;
1234                                 }
1235
1236                                 $datarray['parent-uri'] = $item_id;
1237                                 $datarray['uid'] = $importer['uid'];
1238                                 $datarray['contact-id'] = $contact['id'];
1239                                 $r = item_store($datarray);
1240                                 continue;
1241
1242                         }
1243                 }
1244         }
1245 }
1246
1247 function new_follower($importer,$contact,$datarray,$item) {
1248         $url = notags(trim($datarray['author-link']));
1249         $name = notags(trim($datarray['author-name']));
1250         $photo = notags(trim($datarray['author-avatar']));
1251
1252         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1253         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1254                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1255
1256         if(is_array($contact)) {
1257                 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
1258                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1259                                 intval(REL_BUD),
1260                                 intval($contact['id']),
1261                                 intval($importer['uid'])
1262                         );
1263                 }
1264
1265                 // send email notification to owner?
1266         }
1267         else {
1268         
1269                 // create contact record - set to readonly
1270
1271                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
1272                         `blocked`, `readonly`, `pending` )
1273                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1 ) ",
1274                         intval($importer['uid']),
1275                         dbesc(datetime_convert()),
1276                         dbesc($url),
1277                         dbesc($name),
1278                         dbesc($nick),
1279                         dbesc($photo),
1280                         dbesc('stat'),
1281                         intval(REL_VIP)
1282                 );
1283                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1284                                 intval($importer['uid']),
1285                                 dbesc($url),
1286                                 intval(REL_VIP)
1287                 );
1288                 if(count($r))
1289                                 $contact_record = $r[0];
1290
1291                 // create notification  
1292                 $hash = random_string();
1293
1294                 if(is_array($contact_record)) {
1295                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1296                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1297                                 intval($importer['uid']),
1298                                 intval($contact_record['id']),
1299                                 dbesc($hash),
1300                                 dbesc(datetime_convert())
1301                         );
1302                 }
1303                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1304                         intval($importer['uid'])
1305                 );
1306                 $a = get_app();
1307                 if(count($r)) {
1308                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1309                                 $email_tpl = load_view_file('view/follow_notify_eml.tpl');
1310                                 $email = replace_macros($email_tpl, array(
1311                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1312                                         '$url' => $url,
1313                                         '$myname' => $r[0]['username'],
1314                                         '$siteurl' => $a->get_baseurl(),
1315                                         '$sitename' => $a->config['sitename']
1316                                 ));
1317                                 $res = mail($r[0]['email'], 
1318                                         t("You have a new follower at ") . $a->config['sitename'],
1319                                         $email,
1320                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
1321                         
1322                         }
1323                 }
1324         }
1325 }
1326
1327 function lose_follower($importer,$contact,$datarray,$item) {
1328
1329         if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1330                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1331                         intval(REL_FAN),
1332                         intval($contact['id'])
1333                 );
1334         }
1335         else {
1336                 contact_remove($contact['id']);
1337         }
1338 }
1339
1340
1341 function subscribe_to_hub($url,$importer,$contact) {
1342
1343         if(is_array($importer)) {
1344                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1345                         intval($importer['uid'])
1346                 );
1347         }
1348         if(! count($r))
1349                 return;
1350
1351         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1352
1353         // Use a single verify token, even if multiple hubs
1354
1355         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1356
1357         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1358
1359         logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1360
1361         if(! strlen($contact['hub-verify'])) {
1362                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1363                         dbesc($verify_token),
1364                         intval($contact['id'])
1365                 );
1366         }
1367
1368         post_url($url,$params);                 
1369         return;
1370
1371 }
1372
1373
1374 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1375         $o = '';
1376         if(! $tag)
1377                 return $o;
1378         $name = xmlify($name);
1379         $uri = xmlify($uri);
1380         $h = intval($h);
1381         $w = intval($w);
1382         $photo = xmlify($photo);
1383
1384
1385         $o .= "<$tag>\r\n";
1386         $o .= "<name>$name</name>\r\n";
1387         $o .= "<uri>$uri</uri>\r\n";
1388         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1389         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1390
1391         call_hooks('atom_author', $o);
1392
1393         $o .= "</$tag>\r\n";
1394         return $o;
1395 }
1396
1397 function atom_entry($item,$type,$author,$owner,$comment = false) {
1398
1399         if($item['deleted'])
1400                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1401
1402         $a = get_app();
1403
1404         $o = "\r\n\r\n<entry>\r\n";
1405
1406         if(is_array($author))
1407                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1408         else
1409                 $o .= atom_author('author',$item['name'],$item['url'],80,80,$item['thumb']);
1410         if(strlen($item['owner-name']))
1411                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1412
1413         if($item['parent'] != $item['id'])
1414                 $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";
1415
1416         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1417         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1418         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1419         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1420         $o .= '<dfrn:env>' . base64url_encode($item['body'], true) . '</dfrn:env>' . "\r\n";
1421         $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($item['body']) : $item['body']) . '</content>' . "\r\n";
1422         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1423         if($comment)
1424                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1425
1426         if($item['location']) {
1427                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1428                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1429         }
1430
1431         if($item['coord'])
1432                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1433
1434         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1435                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1436
1437         $verb = construct_verb($item);
1438         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1439         $actobj = construct_activity_object($item);
1440         if(strlen($actobj))
1441                 $o .= $actobj;
1442         $actarg = construct_activity_target($item);
1443         if(strlen($actarg))
1444                 $o .= $actarg;
1445
1446         $mentioned = get_mentions($item);
1447         if($mentioned)
1448                 $o .= $mentioned;
1449         
1450         call_hooks('atom_entry', $o);
1451
1452         $o .= '</entry>' . "\r\n";
1453         
1454         return $o;
1455 }
1456