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