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