]> git.mxchange.org Git - friendica.git/blob - include/items.php
change language dynamically - bound to F8 key
[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         $feed = new SimplePie();
909         $feed->set_raw_data($xml);
910         if($datedir)
911                 $feed->enable_order_by_date(true);
912         else
913                 $feed->enable_order_by_date(false);
914         $feed->init();
915
916         if($feed->error())
917                 logger('consume_feed: Error parsing XML: ' . $feed->error());
918
919
920         // Check at the feed level for updated contact name and/or photo
921
922         $name_updated  = '';
923         $new_name = '';
924         $photo_timestamp = '';
925         $photo_url = '';
926         $birthday = '';
927
928         $hubs = $feed->get_links('hub');
929
930         if(count($hubs))
931                 $hub = implode(',', $hubs);
932
933         $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
934         if($rawtags) {
935                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
936                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
937                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
938                         $new_name = $elems['name'][0]['data'];
939                 } 
940                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
941                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
942                         $photo_url = $elems['link'][0]['attribs']['']['href'];
943                 }
944
945                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
946                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
947                 }
948         }
949
950         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
951                 logger('consume_feed: Updating photo for ' . $contact['name']);
952                 require_once("Photo.php");
953                 $photo_failure = false;
954                 $have_photo = false;
955
956                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
957                         intval($contact['id']),
958                         intval($contact['uid'])
959                 );
960                 if(count($r)) {
961                         $resource_id = $r[0]['resource-id'];
962                         $have_photo = true;
963                 }
964                 else {
965                         $resource_id = photo_new_resource();
966                 }
967                         
968                 $img_str = fetch_url($photo_url,true);
969                 $img = new Photo($img_str);
970                 if($img->is_valid()) {
971                         if($have_photo) {
972                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
973                                         dbesc($resource_id),
974                                         intval($contact['id']),
975                                         intval($contact['uid'])
976                                 );
977                         }
978                                 
979                         $img->scaleImageSquare(175);
980                                 
981                         $hash = $resource_id;
982                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
983                                 
984                         $img->scaleImage(80);
985                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
986
987                         $img->scaleImage(48);
988                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 6);
989
990                         $a = get_app();
991
992                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
993                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
994                                 dbesc(datetime_convert()),
995                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
996                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
997                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
998                                 intval($contact['uid']),
999                                 intval($contact['id'])
1000                         );
1001                 }
1002         }
1003
1004         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1005                 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1006                         dbesc(notags(trim($new_name))),
1007                         dbesc(datetime_convert()),
1008                         intval($contact['uid']),
1009                         intval($contact['id'])
1010                 );
1011         }
1012
1013         if(strlen($birthday)) {
1014                 if(substr($birthday,0,4) != $contact['bdyear']) {
1015                         logger('consume_feed: updating birthday: ' . $birthday);
1016
1017                         /**
1018                          *
1019                          * Add new birthday event for this person
1020                          *
1021                          * $bdtext is just a readable placeholder in case the event is shared
1022                          * with others. We will replace it during presentation to our $importer
1023                          * to contain a sparkle link and perhaps a photo. 
1024                          *
1025                          */
1026                          
1027                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1028
1029
1030                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1031                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1032                                 intval($contact['uid']),
1033                                 intval($contact['id']),
1034                                 dbesc(datetime_convert()),
1035                                 dbesc(datetime_convert()),
1036                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1037                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1038                                 dbesc($bdtext),
1039                                 dbesc('birthday')
1040                         );
1041                         
1042
1043                         // update bdyear
1044
1045                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1046                                 dbesc(substr($birthday,0,4)),
1047                                 intval($contact['uid']),
1048                                 intval($contact['id'])
1049                         );
1050
1051                         // This function is called twice without reloading the contact
1052                         // Make sure we only create one event. This is why &$contact 
1053                         // is a reference var in this function
1054
1055                         $contact['bdyear'] = substr($birthday,0,4);
1056                 }
1057
1058         }
1059
1060
1061         // process any deleted entries
1062
1063         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1064         if(is_array($del_entries) && count($del_entries)) {
1065                 foreach($del_entries as $dentry) {
1066                         $deleted = false;
1067                         if(isset($dentry['attribs']['']['ref'])) {
1068                                 $uri = $dentry['attribs']['']['ref'];
1069                                 $deleted = true;
1070                                 if(isset($dentry['attribs']['']['when'])) {
1071                                         $when = $dentry['attribs']['']['when'];
1072                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1073                                 }
1074                                 else
1075                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1076                         }
1077                         if($deleted && is_array($contact)) {
1078                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1079                                         dbesc($uri),
1080                                         intval($importer['uid']),
1081                                         intval($contact['id'])
1082                                 );
1083                                 if(count($r)) {
1084                                         $item = $r[0];
1085
1086                                         if(! $item['deleted'])
1087                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1088
1089                                         if($item['uri'] == $item['parent-uri']) {
1090                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1091                                                         `body` = '', `title` = ''
1092                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1093                                                         dbesc($when),
1094                                                         dbesc(datetime_convert()),
1095                                                         dbesc($item['uri']),
1096                                                         intval($importer['uid'])
1097                                                 );
1098                                         }
1099                                         else {
1100                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1101                                                         `body` = '', `title` = '' 
1102                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1103                                                         dbesc($when),
1104                                                         dbesc(datetime_convert()),
1105                                                         dbesc($uri),
1106                                                         intval($importer['uid'])
1107                                                 );
1108                                                 if($item['last-child']) {
1109                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1110                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1111                                                                 dbesc(datetime_convert()),
1112                                                                 dbesc($item['parent-uri']),
1113                                                                 intval($item['uid'])
1114                                                         );
1115                                                         // who is the last child now? 
1116                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d 
1117                                                                 ORDER BY `created` DESC LIMIT 1",
1118                                                                         dbesc($item['parent-uri']),
1119                                                                         intval($importer['uid'])
1120                                                         );
1121                                                         if(count($r)) {
1122                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1123                                                                         intval($r[0]['id'])
1124                                                                 );
1125                                                         }
1126                                                 }       
1127                                         }
1128                                 }       
1129                         }
1130                 }
1131         }
1132
1133         // Now process the feed
1134
1135         if($feed->get_item_quantity()) {                
1136
1137                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1138
1139         // in inverse date order
1140                 if ($datedir)
1141                         $items = array_reverse($feed->get_items());
1142                 else
1143                         $items = $feed->get_items();
1144
1145
1146                 foreach($items as $item) {
1147
1148                         $is_reply = false;              
1149                         $item_id = $item->get_id();
1150                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1151                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1152                                 $is_reply = true;
1153                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1154                         }
1155
1156                         if(($is_reply) && is_array($contact)) {
1157
1158                                 // Have we seen it? If not, import it.
1159         
1160                                 $item_id  = $item->get_id();
1161                                 $datarray = get_atom_elements($feed,$item);
1162
1163                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1164                                         dbesc($item_id),
1165                                         intval($importer['uid'])
1166                                 );
1167
1168                                 // Update content if 'updated' changes
1169
1170                                 if(count($r)) {
1171                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1172                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1173                                                         dbesc($datarray['body']),
1174                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1175                                                         dbesc($item_id),
1176                                                         intval($importer['uid'])
1177                                                 );
1178                                         }
1179
1180                                         // update last-child if it changes
1181
1182                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1183                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1184                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1185                                                         dbesc(datetime_convert()),
1186                                                         dbesc($parent_uri),
1187                                                         intval($importer['uid'])
1188                                                 );
1189                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1190                                                         intval($allow[0]['data']),
1191                                                         dbesc(datetime_convert()),
1192                                                         dbesc($item_id),
1193                                                         intval($importer['uid'])
1194                                                 );
1195                                         }
1196                                         continue;
1197                                 }
1198
1199                                 $force_parent = false;
1200                                 if($contact['network'] === 'stat') {
1201                                         $force_parent = true;
1202                                         if(strlen($datarray['title']))
1203                                                 unset($datarray['title']);
1204                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1205                                                 dbesc(datetime_convert()),
1206                                                 dbesc($parent_uri),
1207                                                 intval($importer['uid'])
1208                                         );
1209                                         $datarray['last-child'] = 1;
1210                                 }
1211
1212                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1213                                         // one way feed - no remote comment ability
1214                                         $datarray['last-child'] = 0;
1215                                 }
1216                                 $datarray['parent-uri'] = $parent_uri;
1217                                 $datarray['uid'] = $importer['uid'];
1218                                 $datarray['contact-id'] = $contact['id'];
1219                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1220                                         $datarray['type'] = 'activity';
1221                                         $datarray['gravity'] = GRAVITY_LIKE;
1222                                 }
1223
1224                                 $r = item_store($datarray,$force_parent);
1225                                 continue;
1226                         }
1227
1228                         else {
1229
1230                                 // Head post of a conversation. Have we seen it? If not, import it.
1231
1232                                 $item_id  = $item->get_id();
1233                                 $datarray = get_atom_elements($feed,$item);
1234
1235                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1236                                         dbesc($item_id),
1237                                         intval($importer['uid'])
1238                                 );
1239
1240                                 // Update content if 'updated' changes
1241
1242                                 if(count($r)) {
1243                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1244                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1245                                                         dbesc($datarray['body']),
1246                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1247                                                         dbesc($item_id),
1248                                                         intval($importer['uid'])
1249                                                 );
1250                                         }
1251
1252                                         // update last-child if it changes
1253
1254                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1255                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1256                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1257                                                         intval($allow[0]['data']),
1258                                                         dbesc(datetime_convert()),
1259                                                         dbesc($item_id),
1260                                                         intval($importer['uid'])
1261                                                 );
1262                                         }
1263                                         continue;
1264                                 }
1265
1266                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1267                                         logger('consume-feed: New follower');
1268                                         new_follower($importer,$contact,$datarray,$item);
1269                                         return;
1270                                 }
1271                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1272                                         lose_follower($importer,$contact,$datarray,$item);
1273                                         return;
1274                                 }
1275                                 if(! is_array($contact))
1276                                         return;
1277
1278                                 if($contact['network'] === 'stat') {
1279                                         if(strlen($datarray['title']))
1280                                                 unset($datarray['title']);
1281                                         $datarray['last-child'] = 1;
1282                                 }
1283
1284                                 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1285                                         // one way feed - no remote comment ability
1286                                         $datarray['last-child'] = 0;
1287                                 }
1288
1289                                 $datarray['parent-uri'] = $item_id;
1290                                 $datarray['uid'] = $importer['uid'];
1291                                 $datarray['contact-id'] = $contact['id'];
1292                                 $r = item_store($datarray);
1293                                 continue;
1294
1295                         }
1296                 }
1297         }
1298 }
1299
1300 function new_follower($importer,$contact,$datarray,$item) {
1301         $url = notags(trim($datarray['author-link']));
1302         $name = notags(trim($datarray['author-name']));
1303         $photo = notags(trim($datarray['author-avatar']));
1304
1305         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1306         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1307                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1308
1309         if(is_array($contact)) {
1310                 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
1311                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1312                                 intval(REL_BUD),
1313                                 intval($contact['id']),
1314                                 intval($importer['uid'])
1315                         );
1316                 }
1317
1318                 // send email notification to owner?
1319         }
1320         else {
1321         
1322                 // create contact record - set to readonly
1323
1324                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`, 
1325                         `blocked`, `readonly`, `pending` )
1326                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1 ) ",
1327                         intval($importer['uid']),
1328                         dbesc(datetime_convert()),
1329                         dbesc($url),
1330                         dbesc($name),
1331                         dbesc($nick),
1332                         dbesc($photo),
1333                         dbesc('stat'),
1334                         intval(REL_VIP)
1335                 );
1336                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1337                                 intval($importer['uid']),
1338                                 dbesc($url),
1339                                 intval(REL_VIP)
1340                 );
1341                 if(count($r))
1342                                 $contact_record = $r[0];
1343
1344                 // create notification  
1345                 $hash = random_string();
1346
1347                 if(is_array($contact_record)) {
1348                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1349                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1350                                 intval($importer['uid']),
1351                                 intval($contact_record['id']),
1352                                 dbesc($hash),
1353                                 dbesc(datetime_convert())
1354                         );
1355                 }
1356                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1357                         intval($importer['uid'])
1358                 );
1359                 $a = get_app();
1360                 if(count($r)) {
1361                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1362                                 $email_tpl = load_view_file('view/follow_notify_eml.tpl');
1363                                 $email = replace_macros($email_tpl, array(
1364                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1365                                         '$url' => $url,
1366                                         '$myname' => $r[0]['username'],
1367                                         '$siteurl' => $a->get_baseurl(),
1368                                         '$sitename' => $a->config['sitename']
1369                                 ));
1370                                 $res = mail($r[0]['email'], 
1371                                         t("You have a new follower at ") . $a->config['sitename'],
1372                                         $email,
1373                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
1374                         
1375                         }
1376                 }
1377         }
1378 }
1379
1380 function lose_follower($importer,$contact,$datarray,$item) {
1381
1382         if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1383                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1384                         intval(REL_FAN),
1385                         intval($contact['id'])
1386                 );
1387         }
1388         else {
1389                 contact_remove($contact['id']);
1390         }
1391 }
1392
1393
1394 function subscribe_to_hub($url,$importer,$contact) {
1395
1396         if(is_array($importer)) {
1397                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1398                         intval($importer['uid'])
1399                 );
1400         }
1401         if(! count($r))
1402                 return;
1403
1404         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1405
1406         // Use a single verify token, even if multiple hubs
1407
1408         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1409
1410         $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1411
1412         logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1413
1414         if(! strlen($contact['hub-verify'])) {
1415                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1416                         dbesc($verify_token),
1417                         intval($contact['id'])
1418                 );
1419         }
1420
1421         post_url($url,$params);                 
1422         return;
1423
1424 }
1425
1426
1427 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1428         $o = '';
1429         if(! $tag)
1430                 return $o;
1431         $name = xmlify($name);
1432         $uri = xmlify($uri);
1433         $h = intval($h);
1434         $w = intval($w);
1435         $photo = xmlify($photo);
1436
1437
1438         $o .= "<$tag>\r\n";
1439         $o .= "<name>$name</name>\r\n";
1440         $o .= "<uri>$uri</uri>\r\n";
1441         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1442         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1443
1444         call_hooks('atom_author', $o);
1445
1446         $o .= "</$tag>\r\n";
1447         return $o;
1448 }
1449
1450 function atom_entry($item,$type,$author,$owner,$comment = false) {
1451
1452         if($item['deleted'])
1453                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1454
1455         $a = get_app();
1456
1457         $o = "\r\n\r\n<entry>\r\n";
1458
1459         if(is_array($author))
1460                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1461         else
1462                 $o .= atom_author('author',$item['name'],$item['url'],80,80,$item['thumb']);
1463         if(strlen($item['owner-name']))
1464                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1465
1466         if($item['parent'] != $item['id'])
1467                 $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";
1468
1469         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1470         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1471         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1472         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1473         $o .= '<dfrn:env>' . base64url_encode($item['body'], true) . '</dfrn:env>' . "\r\n";
1474         $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($item['body']) : $item['body']) . '</content>' . "\r\n";
1475         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1476         if($comment)
1477                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1478
1479         if($item['location']) {
1480                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1481                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1482         }
1483
1484         if($item['coord'])
1485                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1486
1487         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1488                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1489
1490         $verb = construct_verb($item);
1491         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1492         $actobj = construct_activity_object($item);
1493         if(strlen($actobj))
1494                 $o .= $actobj;
1495         $actarg = construct_activity_target($item);
1496         if(strlen($actarg))
1497                 $o .= $actarg;
1498
1499         $mentioned = get_mentions($item);
1500         if($mentioned)
1501                 $o .= $mentioned;
1502         
1503         call_hooks('atom_entry', $o);
1504
1505         $o .= '</entry>' . "\r\n";
1506         
1507         return $o;
1508 }
1509         
1510 function item_expire($uid,$days) {
1511
1512         if((! $uid) || (! $days))
1513                 return;
1514
1515         $r = q("SELECT * FROM `item` 
1516                 WHERE `uid` = %d 
1517                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
1518                 AND `id` = `parent` 
1519                 AND `deleted` = 0",
1520                 intval($uid),
1521                 intval($days)
1522         );
1523
1524         if(! count($r))
1525                 return;
1526  
1527         logger('expire: # items=' . count($r) );
1528
1529         foreach($r as $item) {
1530
1531                 // Only expire posts, not photos and photo comments
1532
1533                 if(strlen($item['resource-id']))
1534                         continue;
1535
1536                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1537                         dbesc(datetime_convert()),
1538                         dbesc(datetime_convert()),
1539                         intval($item['id'])
1540                 );
1541
1542                 // kill the kids
1543
1544                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1545                         dbesc(datetime_convert()),
1546                         dbesc(datetime_convert()),
1547                         dbesc($item['parent-uri']),
1548                         intval($item['uid'])
1549                 );
1550
1551         }
1552
1553         proc_run('php',"include/notifier.php","expire","$uid");
1554
1555 }