]> git.mxchange.org Git - friendica.git/blob - include/items.php
stuff to make connecting to diaspora profiles easier
[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         // Disallow time travelling posts
405
406         $d1 = strtotime($res['created']);
407         $d2 = strtotime($res['edited']);
408         $d3 = strtotime('now');
409
410         if($d1 > $d3)
411                 $res['created'] = datetime_convert();
412         if($d2 > $d3)
413                 $res['edited'] = datetime_convert();
414
415         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
416         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
417                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
418         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
419                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
420         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
421                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
422         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
423                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
424
425         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
426                 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
427
428                 foreach($base as $link) {
429                         if(! $res['owner-avatar']) {
430                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')                 
431                                         $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
432                         }
433                 }
434         }
435
436         $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
437         if($rawgeo)
438                 $res['coord'] = unxmlify($rawgeo[0]['data']);
439
440
441         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
442
443         // select between supported verbs
444
445         if($rawverb) {
446                 $res['verb'] = unxmlify($rawverb[0]['data']);
447         }
448
449         // translate OStatus unfollow to activity streams if it happened to get selected
450                 
451         if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
452                 $res['verb'] = ACTIVITY_UNFOLLOW;
453
454                 
455
456         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
457
458         if($rawobj) {
459                 $res['object'] = '<object>' . "\n";
460                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
461                         $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
462                         $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
463                 }       
464                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
465                         $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
466                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
467                         $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
468                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
469                         $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
470                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
471                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
472                         if(! $body)
473                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
474                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
475                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
476                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
477
478                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
479                                         '[youtube]$1[/youtube]', $body);
480
481                                 $config = HTMLPurifier_Config::createDefault();
482                                 $config->set('Cache.DefinitionImpl', null);
483
484                                 $purifier = new HTMLPurifier($config);
485                                 $body = $purifier->purify($body);
486                                 $body = html2bbcode($body);
487                         }
488
489                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
490                 }
491
492                 $res['object'] .= '</object>' . "\n";
493         }
494
495         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
496
497         if($rawobj) {
498                 $res['target'] = '<target>' . "\n";
499                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
500                         $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
501                 }       
502                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
503                         $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
504
505                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
506                         $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
507                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
508                         $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
509                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
510                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
511                         if(! $body)
512                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
513                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
514                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
515                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
516
517                                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
518                                         '[youtube]$1[/youtube]', $body);
519
520                                 $config = HTMLPurifier_Config::createDefault();
521                                 $config->set('Cache.DefinitionImpl', null);
522
523                                 $purifier = new HTMLPurifier($config);
524                                 $body = $purifier->purify($body);
525                                 $body = html2bbcode($body);
526                         }
527
528                         $res['target'] .= '<content>' . $body . '</content>' . "\n";
529                 }
530
531                 $res['target'] .= '</target>' . "\n";
532         }
533
534         $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
535
536         call_hooks('parse_atom', $arr);
537
538         return $res;
539 }
540
541 function encode_rel_links($links) {
542         $o = '';
543         if(! ((is_array($links)) && (count($links))))
544                 return $o;
545         foreach($links as $link) {
546                 $o .= '<link ';
547                 if($link['attribs']['']['rel'])
548                         $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
549                 if($link['attribs']['']['type'])
550                         $o .= 'type="' . $link['attribs']['']['type'] . '" ';
551                 if($link['attribs']['']['href'])
552                         $o .= 'href="' . $link['attribs']['']['href'] . '" ';
553                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
554                         $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
555                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
556                         $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
557                 $o .= ' />' . "\n" ;
558         }
559         return xmlify($o);
560 }
561
562 function item_store($arr,$force_parent = false) {
563
564         if($arr['gravity'])
565                 $arr['gravity'] = intval($arr['gravity']);
566         elseif($arr['parent-uri'] == $arr['uri'])
567                 $arr['gravity'] = 0;
568         elseif(activity_match($arr['verb'],ACTIVITY_POST))
569                 $arr['gravity'] = 6;
570         else      
571                 $arr['gravity'] = 6;   // extensible catchall
572
573         if(! x($arr,'type'))
574                 $arr['type']      = 'remote';
575
576         // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
577
578         if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false)) 
579                 $arr['body'] = strip_tags($arr['body']);
580
581
582         $arr['wall']          = ((x($arr,'wall'))          ? intval($arr['wall'])                : 0);
583         $arr['uri']           = ((x($arr,'uri'))           ? notags(trim($arr['uri']))           : random_string());
584         $arr['author-name']   = ((x($arr,'author-name'))   ? notags(trim($arr['author-name']))   : '');
585         $arr['author-link']   = ((x($arr,'author-link'))   ? notags(trim($arr['author-link']))   : '');
586         $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
587         $arr['owner-name']    = ((x($arr,'owner-name'))    ? notags(trim($arr['owner-name']))    : '');
588         $arr['owner-link']    = ((x($arr,'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
589         $arr['owner-avatar']  = ((x($arr,'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
590         $arr['created']       = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
591         $arr['edited']        = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
592         $arr['changed']       = datetime_convert();
593         $arr['title']         = ((x($arr,'title'))         ? notags(trim($arr['title']))         : '');
594         $arr['location']      = ((x($arr,'location'))      ? notags(trim($arr['location']))      : '');
595         $arr['coord']         = ((x($arr,'coord'))         ? notags(trim($arr['coord']))         : '');
596         $arr['last-child']    = ((x($arr,'last-child'))    ? intval($arr['last-child'])          : 0 );
597         $arr['visible']       = ((x($arr,'visible') !== false) ? intval($arr['visible'])         : 1 );
598         $arr['deleted']       = 0;
599         $arr['parent-uri']    = ((x($arr,'parent-uri'))    ? notags(trim($arr['parent-uri']))    : '');
600         $arr['verb']          = ((x($arr,'verb'))          ? notags(trim($arr['verb']))          : '');
601         $arr['object-type']   = ((x($arr,'object-type'))   ? notags(trim($arr['object-type']))   : '');
602         $arr['object']        = ((x($arr,'object'))        ? trim($arr['object'])                : '');
603         $arr['target-type']   = ((x($arr,'target-type'))   ? notags(trim($arr['target-type']))   : '');
604         $arr['target']        = ((x($arr,'target'))        ? trim($arr['target'])                : '');
605         $arr['plink']         = ((x($arr,'plink'))         ? notags(trim($arr['plink']))         : '');
606         $arr['allow_cid']     = ((x($arr,'allow_cid'))     ? trim($arr['allow_cid'])             : '');
607         $arr['allow_gid']     = ((x($arr,'allow_gid'))     ? trim($arr['allow_gid'])             : '');
608         $arr['deny_cid']      = ((x($arr,'deny_cid'))      ? trim($arr['deny_cid'])              : '');
609         $arr['deny_gid']      = ((x($arr,'deny_gid'))      ? trim($arr['deny_gid'])              : '');
610         $arr['private']       = ((x($arr,'private'))       ? intval($arr['private'])             : 0 );
611         $arr['body']          = ((x($arr,'body'))          ? trim($arr['body'])                  : '');
612
613         if($arr['parent-uri'] === $arr['uri']) {
614                 $parent_id = 0;
615                 $allow_cid = $arr['allow_cid'];
616                 $allow_gid = $arr['allow_gid'];
617                 $deny_cid  = $arr['deny_cid'];
618                 $deny_gid  = $arr['deny_gid'];
619         }
620         else { 
621
622                 // find the parent and snarf the item id and ACL's
623                 // and anything else we need to inherit
624
625                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
626                         dbesc($arr['parent-uri']),
627                         intval($arr['uid'])
628                 );
629
630                 if(count($r)) {
631
632                         // is the new message multi-level threaded?
633                         // even though we don't support it now, preserve the info
634                         // and re-attach to the conversation parent.
635
636                         if($r[0]['uri'] != $r[0]['parent-uri']) {
637                                 $arr['thr-parent'] = $arr['parent-uri'];
638                                 $arr['parent-uri'] = $r[0]['parent-uri'];
639                         }
640
641                         $parent_id      = $r[0]['id'];
642                         $parent_deleted = $r[0]['deleted'];
643                         $allow_cid      = $r[0]['allow_cid'];
644                         $allow_gid      = $r[0]['allow_gid'];
645                         $deny_cid       = $r[0]['deny_cid'];
646                         $deny_gid       = $r[0]['deny_gid'];
647                         $arr['wall']    = $r[0]['wall'];
648                 }
649                 else {
650
651                         // Allow one to see reply tweets from status.net even when
652                         // we don't have or can't see the original post.
653
654                         if($force_parent) {
655                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
656                                 $parent_id = 0;
657                                 $arr['thr-parent'] = $arr['parent-uri'];
658                                 $arr['parent-uri'] = $arr['uri'];
659                         }
660                         else {
661                                 logger('item_store: item parent was not found - ignoring item');
662                                 return 0;
663                         }
664                 }
665         }
666
667         call_hooks('post_remote',$arr);
668
669         dbesc_array($arr);
670
671         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
672
673         $r = dbq("INSERT INTO `item` (`" 
674                         . implode("`, `", array_keys($arr)) 
675                         . "`) VALUES ('" 
676                         . implode("', '", array_values($arr)) 
677                         . "')" );
678
679         // find the item we just created
680
681         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
682                 $arr['uri'],           // already dbesc'd
683                 intval($arr['uid'])
684         );
685         if(count($r)) {
686                 $current_post = $r[0]['id'];
687                 logger('item_store: created item ' . $current_post);
688         }
689         else {
690                 logger('item_store: could not locate created item');
691                 return 0;
692         }
693
694         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
695                 $parent_id = $current_post;
696
697         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
698                 $private = 1;
699         else
700                 $private = $arr['private']; 
701
702         // Set parent id - and also make sure to inherit the parent's ACL's.
703
704         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
705                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
706                 intval($parent_id),
707                 dbesc($allow_cid),
708                 dbesc($allow_gid),
709                 dbesc($deny_cid),
710                 dbesc($deny_gid),
711                 intval($private),
712                 intval($parent_deleted),
713                 intval($current_post)
714         );
715
716         /**
717          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
718          */
719
720         if($arr['last-child']) {
721                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
722                         dbesc($arr['uri']),
723                         intval($arr['uid']),
724                         intval($current_post)
725                 );
726         }
727
728         return $current_post;
729 }
730
731 function get_item_contact($item,$contacts) {
732         if(! count($contacts) || (! is_array($item)))
733                 return false;
734         foreach($contacts as $contact) {
735                 if($contact['id'] == $item['contact-id']) {
736                         return $contact;
737                         break; // NOTREACHED
738                 }
739         }
740         return false;
741 }
742
743
744 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
745
746         $a = get_app();
747
748         if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
749                 return 3;
750
751         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
752
753         if($contact['duplex'] && $contact['dfrn-id'])
754                 $idtosend = '0:' . $orig_id;
755         if($contact['duplex'] && $contact['issued-id'])
756                 $idtosend = '1:' . $orig_id;            
757
758         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
759
760         $rino_enable = get_config('system','rino_encrypt');
761
762         if(! $rino_enable)
763                 $rino = 0;
764
765         $url = $contact['notify'] . '?dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
766
767         logger('dfrn_deliver: ' . $url);
768
769         $xml = fetch_url($url);
770
771         $curl_stat = $a->get_curl_code();
772         if(! $curl_stat)
773                 return(-1); // timed out
774
775         logger('dfrn_deliver: ' . $xml);
776
777         if(! $xml)
778                 return 3;
779
780         if(strpos($xml,'<?xml') === false) {
781                 logger('dfrn_deliver: no valid XML returned');
782                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
783                 return 3;
784         }
785
786         $res = simplexml_load_string($xml);
787
788         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
789                 return (($res->status) ? $res->status : 3);
790
791         $postvars     = array();
792         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
793         $challenge    = hex2bin((string) $res->challenge);
794         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
795         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
796
797         $final_dfrn_id = '';
798
799
800         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
801                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
802                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
803         }
804         else {
805                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
806                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
807         }
808
809         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
810
811         if(strpos($final_dfrn_id,':') == 1)
812                 $final_dfrn_id = substr($final_dfrn_id,2);
813
814         if($final_dfrn_id != $orig_id) {
815                 logger('dfrn_deliver: wrong dfrn_id.');
816                 // did not decode properly - cannot trust this site 
817                 return 3;
818         }
819
820         $postvars['dfrn_id']      = $idtosend;
821         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
822         if($dissolve)
823                 $postvars['dissolve'] = '1';
824
825         if(($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked']) && (! $contact['readonly'])) {
826                 $postvars['data'] = $atom;
827         }
828         elseif($owner['page-flags'] == PAGE_COMMUNITY) {
829                 $postvars['data'] = $atom;
830         }
831         else {
832                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
833         }
834
835         if($rino && $rino_allowed && (! $dissolve)) {
836                 $key = substr(random_string(),0,16);
837                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
838                 $postvars['data'] = $data;
839                 logger('rino: sent key = ' . $key);     
840
841
842                 if($dfrn_version >= 2.1) {      
843                         if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
844                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
845                         }
846                         else {
847                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
848                         }
849                 }
850                 else {
851                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
852                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
853                         }
854                         else {
855                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
856                         }
857                 }
858
859                 logger('md5 rawkey ' . md5($postvars['key']));
860
861                 $postvars['key'] = bin2hex($postvars['key']);
862         }
863
864         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
865
866         $xml = post_url($contact['notify'],$postvars);
867
868         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
869
870         $curl_stat = $a->get_curl_code();
871         if((! $curl_stat) || (! strlen($xml)))
872                 return(-1); // timed out
873
874
875         if(strpos($xml,'<?xml') === false) {
876                 logger('dfrn_deliver: phase 2: no valid XML returned');
877                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
878                 return 3;
879         }
880
881         $res = simplexml_load_string($xml);
882
883         return $res->status;
884  
885 }
886
887
888 /**
889  *
890  * consume_feed - process atom feed and update anything/everything we might need to update
891  *
892  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
893  *
894  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
895  *             It is this person's stuff that is going to be updated.
896  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
897  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
898  *             have a contact record.
899  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
900  *        might not) try and subscribe to it.
901  *
902  */
903
904 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0) {
905
906         require_once('simplepie/simplepie.inc');
907
908         if(! $contact)
909                 logger('consume feed: anonymous');
910         $feed = new SimplePie();
911         $feed->set_raw_data($xml);
912         if($datedir)
913                 $feed->enable_order_by_date(true);
914         else
915                 $feed->enable_order_by_date(false);
916         $feed->init();
917
918         if($feed->error())
919                 logger('consume_feed: Error parsing XML: ' . $feed->error());
920
921
922         // Check at the feed level for updated contact name and/or photo
923
924         $name_updated  = '';
925         $new_name = '';
926         $photo_timestamp = '';
927         $photo_url = '';
928         $birthday = '';
929
930         $hubs = $feed->get_links('hub');
931
932         if(count($hubs))
933                 $hub = implode(',', $hubs);
934
935         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
936         if($rawtags) {
937                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
938                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
939                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
940                         $new_name = $elems['name'][0]['data'];
941                 } 
942                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
943                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
944                         $photo_url = $elems['link'][0]['attribs']['']['href'];
945                 }
946
947                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
948                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
949                 }
950         }
951
952         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
953                 logger('consume_feed: Updating photo for ' . $contact['name']);
954                 require_once("Photo.php");
955                 $photo_failure = false;
956                 $have_photo = false;
957
958                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
959                         intval($contact['id']),
960                         intval($contact['uid'])
961                 );
962                 if(count($r)) {
963                         $resource_id = $r[0]['resource-id'];
964                         $have_photo = true;
965                 }
966                 else {
967                         $resource_id = photo_new_resource();
968                 }
969                         
970                 $img_str = fetch_url($photo_url,true);
971                 $img = new Photo($img_str);
972                 if($img->is_valid()) {
973                         if($have_photo) {
974                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
975                                         dbesc($resource_id),
976                                         intval($contact['id']),
977                                         intval($contact['uid'])
978                                 );
979                         }
980                                 
981                         $img->scaleImageSquare(175);
982                                 
983                         $hash = $resource_id;
984                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
985                                 
986                         $img->scaleImage(80);
987                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
988
989                         $img->scaleImage(48);
990                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 6);
991
992                         $a = get_app();
993
994                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
995                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
996                                 dbesc(datetime_convert()),
997                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
998                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
999                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1000                                 intval($contact['uid']),
1001                                 intval($contact['id'])
1002                         );
1003                 }
1004         }
1005
1006         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1007                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1008                         dbesc(notags(trim($new_name))),
1009                         dbesc(datetime_convert()),
1010                         intval($contact['uid']),
1011                         intval($contact['id'])
1012                 );
1013         }
1014
1015         if(strlen($birthday)) {
1016                 if(substr($birthday,0,4) != $contact['bdyear']) {
1017                         logger('consume_feed: updating birthday: ' . $birthday);
1018
1019                         /**
1020                          *
1021                          * Add new birthday event for this person
1022                          *
1023                          * $bdtext is just a readable placeholder in case the event is shared
1024                          * with others. We will replace it during presentation to our $importer
1025                          * to contain a sparkle link and perhaps a photo. 
1026                          *
1027                          */
1028                          
1029                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1030
1031
1032                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1033                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1034                                 intval($contact['uid']),
1035                                 intval($contact['id']),
1036                                 dbesc(datetime_convert()),
1037                                 dbesc(datetime_convert()),
1038                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1039                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1040                                 dbesc($bdtext),
1041                                 dbesc('birthday')
1042                         );
1043                         
1044
1045                         // update bdyear
1046
1047                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1048                                 dbesc(substr($birthday,0,4)),
1049                                 intval($contact['uid']),
1050                                 intval($contact['id'])
1051                         );
1052
1053                         // This function is called twice without reloading the contact
1054                         // Make sure we only create one event. This is why &$contact 
1055                         // is a reference var in this function
1056
1057                         $contact['bdyear'] = substr($birthday,0,4);
1058                 }
1059
1060         }
1061
1062
1063         // process any deleted entries
1064
1065         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1066         if(is_array($del_entries) && count($del_entries)) {
1067                 foreach($del_entries as $dentry) {
1068                         $deleted = false;
1069                         if(isset($dentry['attribs']['']['ref'])) {
1070                                 $uri = $dentry['attribs']['']['ref'];
1071                                 $deleted = true;
1072                                 if(isset($dentry['attribs']['']['when'])) {
1073                                         $when = $dentry['attribs']['']['when'];
1074                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1075                                 }
1076                                 else
1077                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1078                         }
1079                         if($deleted && is_array($contact)) {
1080                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1081                                         dbesc($uri),
1082                                         intval($importer['uid']),
1083                                         intval($contact['id'])
1084                                 );
1085                                 if(count($r)) {
1086                                         $item = $r[0];
1087
1088                                         if(! $item['deleted'])
1089                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1090
1091                                         if($item['uri'] == $item['parent-uri']) {
1092                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1093                                                         `body` = '', `title` = ''
1094                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1095                                                         dbesc($when),
1096                                                         dbesc(datetime_convert()),
1097                                                         dbesc($item['uri']),
1098                                                         intval($importer['uid'])
1099                                                 );
1100                                         }
1101                                         else {
1102                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1103                                                         `body` = '', `title` = '' 
1104                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1105                                                         dbesc($when),
1106                                                         dbesc(datetime_convert()),
1107                                                         dbesc($uri),
1108                                                         intval($importer['uid'])
1109                                                 );
1110                                                 if($item['last-child']) {
1111                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1112                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1113                                                                 dbesc(datetime_convert()),
1114                                                                 dbesc($item['parent-uri']),
1115                                                                 intval($item['uid'])
1116                                                         );
1117                                                         // who is the last child now? 
1118                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1119                                                                 ORDER BY `created` DESC LIMIT 1",
1120                                                                         dbesc($item['parent-uri']),
1121                                                                         intval($importer['uid'])
1122                                                         );
1123                                                         if(count($r)) {
1124                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1125                                                                         intval($r[0]['id'])
1126                                                                 );
1127                                                         }
1128                                                 }       
1129                                         }
1130                                 }       
1131                         }
1132                 }
1133         }
1134
1135         // Now process the feed
1136
1137         if($feed->get_item_quantity()) {                
1138
1139                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1140
1141         // in inverse date order
1142                 if ($datedir)
1143                         $items = array_reverse($feed->get_items());
1144                 else
1145                         $items = $feed->get_items();
1146
1147
1148                 foreach($items as $item) {
1149
1150                         $is_reply = false;              
1151                         $item_id = $item->get_id();
1152                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1153                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1154                                 $is_reply = true;
1155                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1156                         }
1157
1158                         if(($is_reply) && is_array($contact)) {
1159
1160                                 // Have we seen it? If not, import it.
1161         
1162                                 $item_id  = $item->get_id();
1163                                 $datarray = get_atom_elements($feed,$item);
1164
1165                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1166                                         dbesc($item_id),
1167                                         intval($importer['uid'])
1168                                 );
1169
1170                                 // Update content if 'updated' changes
1171
1172                                 if(count($r)) {
1173                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1174                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1175                                                         dbesc($datarray['body']),
1176                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1177                                                         dbesc($item_id),
1178                                                         intval($importer['uid'])
1179                                                 );
1180                                         }
1181
1182                                         // update last-child if it changes
1183
1184                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1185                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1186                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1187                                                         dbesc(datetime_convert()),
1188                                                         dbesc($parent_uri),
1189                                                         intval($importer['uid'])
1190                                                 );
1191                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1192                                                         intval($allow[0]['data']),
1193                                                         dbesc(datetime_convert()),
1194                                                         dbesc($item_id),
1195                                                         intval($importer['uid'])
1196                                                 );
1197                                         }
1198                                         continue;
1199                                 }
1200
1201                                 $force_parent = false;
1202                                 if($contact['network'] === 'stat') {
1203                                         $force_parent = true;
1204                                         if(strlen($datarray['title']))
1205                                                 unset($datarray['title']);
1206                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1207                                                 dbesc(datetime_convert()),
1208                                                 dbesc($parent_uri),
1209                                                 intval($importer['uid'])
1210                                         );
1211                                         $datarray['last-child'] = 1;
1212                                 }
1213
1214                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1215                                         // one way feed - no remote comment ability
1216                                         $datarray['last-child'] = 0;
1217                                 }
1218                                 $datarray['parent-uri'] = $parent_uri;
1219                                 $datarray['uid'] = $importer['uid'];
1220                                 $datarray['contact-id'] = $contact['id'];
1221                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1222                                         $datarray['type'] = 'activity';
1223                                         $datarray['gravity'] = GRAVITY_LIKE;
1224                                 }
1225
1226                                 $r = item_store($datarray,$force_parent);
1227                                 continue;
1228                         }
1229
1230                         else {
1231
1232                                 // Head post of a conversation. Have we seen it? If not, import it.
1233
1234                                 $item_id  = $item->get_id();
1235                                 $datarray = get_atom_elements($feed,$item);
1236
1237                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1238                                         dbesc($item_id),
1239                                         intval($importer['uid'])
1240                                 );
1241
1242                                 // Update content if 'updated' changes
1243
1244                                 if(count($r)) {
1245                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1246                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1247                                                         dbesc($datarray['body']),
1248                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1249                                                         dbesc($item_id),
1250                                                         intval($importer['uid'])
1251                                                 );
1252                                         }
1253
1254                                         // update last-child if it changes
1255
1256                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1257                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1258                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1259                                                         intval($allow[0]['data']),
1260                                                         dbesc(datetime_convert()),
1261                                                         dbesc($item_id),
1262                                                         intval($importer['uid'])
1263                                                 );
1264                                         }
1265                                         continue;
1266                                 }
1267
1268                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1269                                         logger('consume-feed: New follower');
1270                                         new_follower($importer,$contact,$datarray,$item);
1271                                         return;
1272                                 }
1273                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1274                                         lose_follower($importer,$contact,$datarray,$item);
1275                                         return;
1276                                 }
1277                                 if(! is_array($contact))
1278                                         return;
1279
1280                                 if($contact['network'] === 'stat') {
1281                                         if(strlen($datarray['title']))
1282                                                 unset($datarray['title']);
1283                                         $datarray['last-child'] = 1;
1284                                 }
1285
1286                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1287                                         // one way feed - no remote comment ability
1288                                         $datarray['last-child'] = 0;
1289                                 }
1290
1291                                 $datarray['parent-uri'] = $item_id;
1292                                 $datarray['uid'] = $importer['uid'];
1293                                 $datarray['contact-id'] = $contact['id'];
1294                                 $r = item_store($datarray);
1295                                 continue;
1296
1297                         }
1298                 }
1299         }
1300 }
1301
1302 function new_follower($importer,$contact,$datarray,$item) {
1303         $url = notags(trim($datarray['author-link']));
1304         $name = notags(trim($datarray['author-name']));
1305         $photo = notags(trim($datarray['author-avatar']));
1306
1307         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1308         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1309                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1310
1311         if(is_array($contact)) {
1312                 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
1313                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1314                                 intval(REL_BUD),
1315                                 intval($contact['id']),
1316                                 intval($importer['uid'])
1317                         );
1318                 }
1319
1320                 // send email notification to owner?
1321         }
1322         else {
1323         
1324                 // create contact record - set to readonly
1325
1326                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
1327                         `blocked`, `readonly`, `pending` )
1328                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1 ) ",
1329                         intval($importer['uid']),
1330                         dbesc(datetime_convert()),
1331                         dbesc($url),
1332                         dbesc($name),
1333                         dbesc($nick),
1334                         dbesc($photo),
1335                         dbesc('stat'),
1336                         intval(REL_VIP)
1337                 );
1338                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1339                                 intval($importer['uid']),
1340                                 dbesc($url),
1341                                 intval(REL_VIP)
1342                 );
1343                 if(count($r))
1344                                 $contact_record = $r[0];
1345
1346                 // create notification  
1347                 $hash = random_string();
1348
1349                 if(is_array($contact_record)) {
1350                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1351                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1352                                 intval($importer['uid']),
1353                                 intval($contact_record['id']),
1354                                 dbesc($hash),
1355                                 dbesc(datetime_convert())
1356                         );
1357                 }
1358                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1359                         intval($importer['uid'])
1360                 );
1361                 $a = get_app();
1362                 if(count($r)) {
1363                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1364                                 $email_tpl = load_view_file('view/follow_notify_eml.tpl');
1365                                 $email = replace_macros($email_tpl, array(
1366                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1367                                         '$url' => $url,
1368                                         '$myname' => $r[0]['username'],
1369                                         '$siteurl' => $a->get_baseurl(),
1370                                         '$sitename' => $a->config['sitename']
1371                                 ));
1372                                 $res = mail($r[0]['email'], 
1373                                         t("You have a new follower at ") . $a->config['sitename'],
1374                                         $email,
1375                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
1376                         
1377                         }
1378                 }
1379         }
1380 }
1381
1382 function lose_follower($importer,$contact,$datarray,$item) {
1383
1384         if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1385                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1386                         intval(REL_FAN),
1387                         intval($contact['id'])
1388                 );
1389         }
1390         else {
1391                 contact_remove($contact['id']);
1392         }
1393 }
1394
1395
1396 function subscribe_to_hub($url,$importer,$contact) {
1397
1398         if(is_array($importer)) {
1399                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1400                         intval($importer['uid'])
1401                 );
1402         }
1403         if(! count($r))
1404                 return;
1405
1406         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1407
1408         // Use a single verify token, even if multiple hubs
1409
1410         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1411
1412         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1413
1414         logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1415
1416         if(! strlen($contact['hub-verify'])) {
1417                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1418                         dbesc($verify_token),
1419                         intval($contact['id'])
1420                 );
1421         }
1422
1423         post_url($url,$params);                 
1424         return;
1425
1426 }
1427
1428
1429 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1430         $o = '';
1431         if(! $tag)
1432                 return $o;
1433         $name = xmlify($name);
1434         $uri = xmlify($uri);
1435         $h = intval($h);
1436         $w = intval($w);
1437         $photo = xmlify($photo);
1438
1439
1440         $o .= "<$tag>\r\n";
1441         $o .= "<name>$name</name>\r\n";
1442         $o .= "<uri>$uri</uri>\r\n";
1443         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1444         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1445
1446         call_hooks('atom_author', $o);
1447
1448         $o .= "</$tag>\r\n";
1449         return $o;
1450 }
1451
1452 function atom_entry($item,$type,$author,$owner,$comment = false) {
1453
1454         if($item['deleted'])
1455                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1456
1457         $a = get_app();
1458
1459         $o = "\r\n\r\n<entry>\r\n";
1460
1461         if(is_array($author))
1462                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1463         else
1464                 $o .= atom_author('author',$item['name'],$item['url'],80,80,$item['thumb']);
1465         if(strlen($item['owner-name']))
1466                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1467
1468         if($item['parent'] != $item['id'])
1469                 $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";
1470
1471         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1472         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1473         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1474         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1475         $o .= '<dfrn:env>' . base64url_encode($item['body'], true) . '</dfrn:env>' . "\r\n";
1476         $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($item['body']) : $item['body']) . '</content>' . "\r\n";
1477         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1478         if($comment)
1479                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1480
1481         if($item['location']) {
1482                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1483                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1484         }
1485
1486         if($item['coord'])
1487                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1488
1489         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1490                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1491
1492         $verb = construct_verb($item);
1493         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1494         $actobj = construct_activity_object($item);
1495         if(strlen($actobj))
1496                 $o .= $actobj;
1497         $actarg = construct_activity_target($item);
1498         if(strlen($actarg))
1499                 $o .= $actarg;
1500
1501         $mentioned = get_mentions($item);
1502         if($mentioned)
1503                 $o .= $mentioned;
1504         
1505         call_hooks('atom_entry', $o);
1506
1507         $o .= '</entry>' . "\r\n";
1508         
1509         return $o;
1510 }
1511         
1512 function item_expire($uid,$days) {
1513
1514         if((! $uid) || (! $days))
1515                 return;
1516
1517         $r = q("SELECT * FROM `item` 
1518                 WHERE `uid` = %d 
1519                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
1520                 AND `id` = `parent` 
1521                 AND `deleted` = 0",
1522                 intval($uid),
1523                 intval($days)
1524         );
1525
1526         if(! count($r))
1527                 return;
1528  
1529         logger('expire: # items=' . count($r) );
1530
1531         foreach($r as $item) {
1532
1533                 // Only expire posts, not photos and photo comments
1534
1535                 if(strlen($item['resource-id']))
1536                         continue;
1537
1538                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1539                         dbesc(datetime_convert()),
1540                         dbesc(datetime_convert()),
1541                         intval($item['id'])
1542                 );
1543
1544                 // kill the kids
1545
1546                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1547                         dbesc(datetime_convert()),
1548                         dbesc(datetime_convert()),
1549                         dbesc($item['parent-uri']),
1550                         intval($item['uid'])
1551                 );
1552
1553         }
1554
1555         proc_run('php',"include/notifier.php","expire","$uid");
1556
1557 }