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