]> git.mxchange.org Git - friendica.git/blob - include/items.php
community discovery cont., cleanup of DB debugging
[friendica.git] / include / items.php
1 <?php
2
3 require_once('include/bbcode.php');
4 require_once('include/oembed.php');
5 require_once('include/salmon.php');
6 require_once('include/crypto.php');
7
8 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
9
10         // default permissions - anonymous user
11
12         if(! strlen($owner_nick))
13                 killme();
14
15         $public_feed = (($dfrn_id) ? false : true);
16         $starred = false;
17         $converse = false;
18
19         if($public_feed && $a->argc > 2) {
20                 for($x = 2; $x < $a->argc; $x++) {
21                         if($a->argv[$x] == 'converse')
22                                 $converse = true;
23                         if($a->argv[$x] == 'starred')
24                                 $starred = true;
25                 }
26         }
27
28
29         $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid`  = '' AND `deny_gid`  = '' ";
30
31         $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
32                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
33                 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
34                 dbesc($owner_nick)
35         );
36
37         if(! count($r))
38                 killme();
39
40         $owner = $r[0];
41         $owner_id = $owner['user_uid'];
42         $owner_nick = $owner['nickname'];
43
44         $birthday = feed_birthday($owner_id,$owner['timezone']);
45
46         if(! $public_feed) {
47
48                 $sql_extra = '';
49                 switch($direction) {
50                         case (-1):
51                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
52                                 $my_id = $dfrn_id;
53                                 break;
54                         case 0:
55                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
56                                 $my_id = '1:' . $dfrn_id;
57                                 break;
58                         case 1:
59                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
60                                 $my_id = '0:' . $dfrn_id;
61                                 break;
62                         default:
63                                 return false;
64                                 break; // NOTREACHED
65                 }
66
67                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
68                         intval($owner_id)
69                 );
70
71                 if(! count($r))
72                         killme();
73
74                 $contact = $r[0];
75                 $groups = init_groups_visitor($contact['id']);
76
77                 if(count($groups)) {
78                         for($x = 0; $x < count($groups); $x ++) 
79                                 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
80                         $gs = implode('|', $groups);
81                 }
82                 else
83                         $gs = '<<>>' ; // Impossible to match 
84
85                 $sql_extra = sprintf(" 
86                         AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' ) 
87                         AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' ) 
88                         AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
89                         AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s') 
90                 ",
91                         intval($contact['id']),
92                         intval($contact['id']),
93                         dbesc($gs),
94                         dbesc($gs)
95                 );
96         }
97
98         if($public_feed)
99                 $sort = 'DESC';
100         else
101                 $sort = 'ASC';
102
103         if(! strlen($last_update))
104                 $last_update = 'now -30 days';
105
106         if($public_feed) {
107                 if(! $converse)
108                         $sql_extra .= " AND `contact`.`self` = 1 ";
109         }
110
111         $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
112
113         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
114                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, 
115                 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
116                 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, 
117                 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
118                 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
119                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
120                 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
121                 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0 
122                 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
123                 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
124                 $sql_extra
125                 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
126                 intval($owner_id),
127                 dbesc($check_date),
128                 dbesc($check_date),
129                 dbesc($sort)
130         );
131
132         // Will check further below if this actually returned results.
133         // We will provide an empty feed if that is the case.
134
135         $items = $r;
136
137         $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
138
139         $atom = '';
140
141         $hubxml = feed_hublinks();
142
143         $salmon = feed_salmonlinks($owner_nick);
144
145         $atom .= replace_macros($feed_template, array(
146                 '$version'      => xmlify(FRIENDICA_VERSION),
147                 '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
148                 '$feed_title'   => xmlify($owner['name']),
149                 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
150                 '$hub'          => $hubxml,
151                 '$salmon'       => $salmon,
152                 '$name'         => xmlify($owner['name']),
153                 '$profile_page' => xmlify($owner['url']),
154                 '$photo'        => xmlify($owner['photo']),
155                 '$thumb'        => xmlify($owner['thumb']),
156                 '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
157                 '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
158                 '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) , 
159                 '$birthday'     => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
160                 '$community'    => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
161         ));
162
163         call_hooks('atom_feed', $atom);
164
165         if(! count($items)) {
166
167                 call_hooks('atom_feed_end', $atom);
168
169                 $atom .= '</feed>' . "\r\n";
170                 return $atom;
171         }
172
173         foreach($items as $item) {
174
175                 // public feeds get html, our own nodes use bbcode
176
177                 if($public_feed) {
178                         $type = 'html';
179                         // catch any email that's in a public conversation and make sure it doesn't leak
180                         if($item['private'])
181                                 continue;
182                 }
183                 else {
184                         $type = 'text';
185                 }
186
187                 $atom .= atom_entry($item,$type,null,$owner,true);
188         }
189
190         call_hooks('atom_feed_end', $atom);
191
192         $atom .= '</feed>' . "\r\n";
193
194         return $atom;
195 }
196
197
198 function construct_verb($item) {
199         if($item['verb'])
200                 return $item['verb'];
201         return ACTIVITY_POST;
202 }
203
204 function construct_activity_object($item) {
205
206         if($item['object']) {
207                 $o = '<as:object>' . "\r\n";
208                 $r = parse_xml_string($item['object'],false);
209
210
211                 if(! $r)
212                         return '';
213                 if($r->type)
214                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
215                 if($r->id)
216                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
217                 if($r->title)
218                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
219                 if($r->link) {
220                         if(substr($r->link,0,1) === '<') {
221                                 // patch up some facebook "like" activity objects that got stored incorrectly
222                                 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
223                                 // we can probably remove this hack here and in the following function in a few months time.
224                                 if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
225                                         $r->link = str_replace('&','&amp;', $r->link);
226                                 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
227                                 $o .= $r->link;
228                         }                                       
229                         else
230                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
231                 }
232                 if($r->content)
233                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
234                 $o .= '</as:object>' . "\r\n";
235                 return $o;
236         }
237
238         return '';
239
240
241 function construct_activity_target($item) {
242
243         if($item['target']) {
244                 $o = '<as:target>' . "\r\n";
245                 $r = parse_xml_string($item['target'],false);
246                 if(! $r)
247                         return '';
248                 if($r->type)
249                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
250                 if($r->id)
251                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
252                 if($r->title)
253                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
254                 if($r->link) {
255                         if(substr($r->link,0,1) === '<') {
256                                 if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
257                                         $r->link = str_replace('&','&amp;', $r->link);
258                                 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
259                                 $o .= $r->link;
260                         }                                       
261                         else
262                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
263                 }
264                 if($r->content)
265                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
266                 $o .= '</as:target>' . "\r\n";
267                 return $o;
268         }
269
270         return '';
271
272
273
274
275
276 function get_atom_elements($feed,$item) {
277
278         require_once('library/HTMLPurifier.auto.php');
279         require_once('include/html2bbcode.php');
280
281         $best_photo = array();
282
283         $res = array();
284
285         $author = $item->get_author();
286         if($author) { 
287                 $res['author-name'] = unxmlify($author->get_name());
288                 $res['author-link'] = unxmlify($author->get_link());
289         }
290         else {
291                 $res['author-name'] = unxmlify($feed->get_title());
292                 $res['author-link'] = unxmlify($feed->get_permalink());
293         }
294         $res['uri'] = unxmlify($item->get_id());
295         $res['title'] = unxmlify($item->get_title());
296         $res['body'] = unxmlify($item->get_content());
297         $res['plink'] = unxmlify($item->get_link(0));
298
299         if($res['plink'])
300                 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
301         else
302                 $base_url = '';
303
304         // look for a photo. We should check media size and find the best one,
305         // but for now let's just find any author photo
306
307         $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
308
309         if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
310                 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
311                 foreach($base as $link) {
312                         if(!x($res, 'author-avatar') || !$res['author-avatar']) {
313                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
314                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
315                         }
316                 }
317         }                       
318
319         $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
320
321         if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
322                 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
323                 if($base && count($base)) {
324                         foreach($base as $link) {
325                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
326                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
327                                 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
328                                         if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
329                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
330                                 }
331                         }
332                 }
333         }
334
335         // No photo/profile-link on the item - look at the feed level
336
337         if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
338                 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
339                 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
340                         $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
341                         foreach($base as $link) {
342                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
343                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
344                                 if(! $res['author-avatar']) {
345                                         if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
346                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
347                                 }
348                         }
349                 }                       
350
351                 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
352
353                 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
354                         $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
355
356                         if($base && count($base)) {
357                                 foreach($base as $link) {
358                                         if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
359                                                 $res['author-link'] = unxmlify($link['attribs']['']['href']);
360                                         if(! (x($res,'author-avatar'))) {
361                                                 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
362                                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
363                                         }
364                                 }
365                         }
366                 }
367         }
368
369         $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
370         if($apps && $apps[0]['attribs']['']['source']) {
371                 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
372                 if($res['app'] === 'web')
373                         $res['app'] = 'OStatus';
374         }                  
375
376         // base64 encoded json structure representing Diaspora signature
377
378         $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
379         if($dsig) {
380                 $res['dsprsig'] = unxmlify($dsig[0]['data']);
381         }
382
383         $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
384         if($dguid)
385                 $res['guid'] = unxmlify($dguid[0]['data']);
386
387         $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
388         if($bm)
389                 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
390
391
392         /**
393          * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
394          */
395
396         $have_real_body = false;
397
398         $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
399         if($rawenv) {
400                 $have_real_body = true;
401                 $res['body'] = $rawenv[0]['data'];
402                 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
403                 // make sure nobody is trying to sneak some html tags by us
404                 $res['body'] = notags(base64url_decode($res['body']));
405         }
406
407         $maxlen = get_max_import_size();
408         if($maxlen && (strlen($res['body']) > $maxlen))
409                 $res['body'] = substr($res['body'],0, $maxlen);
410
411         // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust 
412         // the content type. Our own network only emits text normally, though it might have been converted to 
413         // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
414         // have to assume it is all html and needs to be purified.
415
416         // It doesn't matter all that much security wise - because before this content is used anywhere, we are 
417         // going to escape any tags we find regardless, but this lets us import a limited subset of html from 
418         // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining 
419         // html.
420
421         if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
422
423                 $res['body'] = reltoabs($res['body'],$base_url);
424
425                 $res['body'] = html2bb_video($res['body']);
426
427                 $res['body'] = oembed_html2bbcode($res['body']);
428
429                 $config = HTMLPurifier_Config::createDefault();
430                 $config->set('Cache.DefinitionImpl', null);
431
432                 // we shouldn't need a whitelist, because the bbcode converter
433                 // will strip out any unsupported tags.
434                 // $config->set('HTML.Allowed', 'p,b,a[href],i'); 
435
436                 $purifier = new HTMLPurifier($config);
437                 $res['body'] = $purifier->purify($res['body']);
438
439                 $res['body'] = html2bbcode($res['body']);
440         }
441
442         $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
443         if($allow && $allow[0]['data'] == 1)
444                 $res['last-child'] = 1;
445         else
446                 $res['last-child'] = 0;
447
448         $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
449         if($private && $private[0]['data'] == 1)
450                 $res['private'] = 1;
451         else
452                 $res['private'] = 0;
453
454         $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
455         if($extid && $extid[0]['data'])
456                 $res['extid'] = $extid[0]['data'];
457
458         $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
459         if($rawlocation)
460                 $res['location'] = unxmlify($rawlocation[0]['data']);
461
462
463         $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
464         if($rawcreated)
465                 $res['created'] = unxmlify($rawcreated[0]['data']);
466
467
468         $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
469         if($rawedited)
470                 $res['edited'] = unxmlify($rawedited[0]['data']);
471
472         if((x($res,'edited')) && (! (x($res,'created'))))
473                 $res['created'] = $res['edited']; 
474
475         if(! $res['created'])
476                 $res['created'] = $item->get_date('c');
477
478         if(! $res['edited'])
479                 $res['edited'] = $item->get_date('c');
480
481
482         // Disallow time travelling posts
483
484         $d1 = strtotime($res['created']);
485         $d2 = strtotime($res['edited']);
486         $d3 = strtotime('now');
487
488         if($d1 > $d3)
489                 $res['created'] = datetime_convert();
490         if($d2 > $d3)
491                 $res['edited'] = datetime_convert();
492
493         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
494         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
495                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
496         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
497                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
498         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
499                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
500         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
501                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
502
503         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
504                 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
505
506                 foreach($base as $link) {
507                         if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
508                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')                 
509                                         $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
510                         }
511                 }
512         }
513
514         $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
515         if($rawgeo)
516                 $res['coord'] = unxmlify($rawgeo[0]['data']);
517
518
519         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
520
521         // select between supported verbs
522
523         if($rawverb) {
524                 $res['verb'] = unxmlify($rawverb[0]['data']);
525         }
526
527         // translate OStatus unfollow to activity streams if it happened to get selected
528                 
529         if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
530                 $res['verb'] = ACTIVITY_UNFOLLOW;
531
532         $cats = $item->get_categories();
533         if($cats) {
534                 $tag_arr = array();
535                 foreach($cats as $cat) {
536                         $term = $cat->get_term();
537                         if(! $term)
538                                 $term = $cat->get_label();
539                         $scheme = $cat->get_scheme();
540                         if($scheme && $term && stristr($scheme,'X-DFRN:'))
541                                 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
542                         elseif($term)
543                                 $tag_arr[] = notags(trim($term));
544                 }
545                 $res['tag'] =  implode(',', $tag_arr);
546         }
547
548         $attach = $item->get_enclosures();
549         if($attach) {
550                 $att_arr = array();
551                 foreach($attach as $att) {
552                         $len   = intval($att->get_length());
553                         $link  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
554                         $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
555                         $type  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
556                         if(strpos($type,';'))
557                                 $type = substr($type,0,strpos($type,';'));
558                         if((! $link) || (strpos($link,'http') !== 0))
559                                 continue;
560
561                         if(! $title)
562                                 $title = ' ';
563                         if(! $type)
564                                 $type = 'application/octet-stream';
565
566                         $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]'; 
567                 }
568                 $res['attach'] = implode(',', $att_arr);
569         }
570
571         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
572
573         if($rawobj) {
574                 $res['object'] = '<object>' . "\n";
575                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
576                         $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
577                         $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
578                 }       
579                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
580                         $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
581                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
582                         $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
583                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
584                         $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
585                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
586                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
587                         if(! $body)
588                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
589                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
590                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
591                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
592
593                                 $body = html2bb_video($body);
594
595                                 $config = HTMLPurifier_Config::createDefault();
596                                 $config->set('Cache.DefinitionImpl', null);
597
598                                 $purifier = new HTMLPurifier($config);
599                                 $body = $purifier->purify($body);
600                                 $body = html2bbcode($body);
601                         }
602
603                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
604                 }
605
606                 $res['object'] .= '</object>' . "\n";
607         }
608
609         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
610
611         if($rawobj) {
612                 $res['target'] = '<target>' . "\n";
613                 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
614                         $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
615                 }       
616                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
617                         $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
618
619                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
620                         $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
621                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
622                         $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
623                 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
624                         $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
625                         if(! $body)
626                                 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
627                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
628                         $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
629                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
630
631                                 $body = html2bb_video($body);
632
633                                 $config = HTMLPurifier_Config::createDefault();
634                                 $config->set('Cache.DefinitionImpl', null);
635
636                                 $purifier = new HTMLPurifier($config);
637                                 $body = $purifier->purify($body);
638                                 $body = html2bbcode($body);
639                         }
640
641                         $res['target'] .= '<content>' . $body . '</content>' . "\n";
642                 }
643
644                 $res['target'] .= '</target>' . "\n";
645         }
646
647         $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
648
649         call_hooks('parse_atom', $arr);
650
651         return $res;
652 }
653
654 function encode_rel_links($links) {
655         $o = '';
656         if(! ((is_array($links)) && (count($links))))
657                 return $o;
658         foreach($links as $link) {
659                 $o .= '<link ';
660                 if($link['attribs']['']['rel'])
661                         $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
662                 if($link['attribs']['']['type'])
663                         $o .= 'type="' . $link['attribs']['']['type'] . '" ';
664                 if($link['attribs']['']['href'])
665                         $o .= 'href="' . $link['attribs']['']['href'] . '" ';
666                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
667                         $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
668                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
669                         $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
670                 $o .= ' />' . "\n" ;
671         }
672         return xmlify($o);
673 }
674
675 function item_store($arr,$force_parent = false) {
676
677         // If a Diaspora signature structure was passed in, pull it out of the 
678         // item array and set it aside for later storage.
679
680         $dsprsig = null;
681         if(x($arr,'dsprsig')) {
682                 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
683                 unset($arr['dsprsig']);
684         }
685
686         if(x($arr, 'gravity'))
687                 $arr['gravity'] = intval($arr['gravity']);
688         elseif($arr['parent-uri'] === $arr['uri'])
689                 $arr['gravity'] = 0;
690         elseif(activity_match($arr['verb'],ACTIVITY_POST))
691                 $arr['gravity'] = 6;
692         else      
693                 $arr['gravity'] = 6;   // extensible catchall
694
695         if(! x($arr,'type'))
696                 $arr['type']      = 'remote';
697
698         // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
699
700         if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false)) 
701                 $arr['body'] = strip_tags($arr['body']);
702
703
704         $arr['wall']          = ((x($arr,'wall'))          ? intval($arr['wall'])                : 0);
705         $arr['uri']           = ((x($arr,'uri'))           ? notags(trim($arr['uri']))           : random_string());
706         $arr['extid']         = ((x($arr,'extid'))         ? notags(trim($arr['extid']))         : '');
707         $arr['author-name']   = ((x($arr,'author-name'))   ? notags(trim($arr['author-name']))   : '');
708         $arr['author-link']   = ((x($arr,'author-link'))   ? notags(trim($arr['author-link']))   : '');
709         $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
710         $arr['owner-name']    = ((x($arr,'owner-name'))    ? notags(trim($arr['owner-name']))    : '');
711         $arr['owner-link']    = ((x($arr,'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
712         $arr['owner-avatar']  = ((x($arr,'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
713         $arr['created']       = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
714         $arr['edited']        = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
715         $arr['commented']     = datetime_convert();
716         $arr['received']      = datetime_convert();
717         $arr['changed']       = datetime_convert();
718         $arr['title']         = ((x($arr,'title'))         ? notags(trim($arr['title']))         : '');
719         $arr['location']      = ((x($arr,'location'))      ? notags(trim($arr['location']))      : '');
720         $arr['coord']         = ((x($arr,'coord'))         ? notags(trim($arr['coord']))         : '');
721         $arr['last-child']    = ((x($arr,'last-child'))    ? intval($arr['last-child'])          : 0 );
722         $arr['visible']       = ((x($arr,'visible') !== false) ? intval($arr['visible'])         : 1 );
723         $arr['deleted']       = 0;
724         $arr['parent-uri']    = ((x($arr,'parent-uri'))    ? notags(trim($arr['parent-uri']))    : '');
725         $arr['verb']          = ((x($arr,'verb'))          ? notags(trim($arr['verb']))          : '');
726         $arr['object-type']   = ((x($arr,'object-type'))   ? notags(trim($arr['object-type']))   : '');
727         $arr['object']        = ((x($arr,'object'))        ? trim($arr['object'])                : '');
728         $arr['target-type']   = ((x($arr,'target-type'))   ? notags(trim($arr['target-type']))   : '');
729         $arr['target']        = ((x($arr,'target'))        ? trim($arr['target'])                : '');
730         $arr['plink']         = ((x($arr,'plink'))         ? notags(trim($arr['plink']))         : '');
731         $arr['allow_cid']     = ((x($arr,'allow_cid'))     ? trim($arr['allow_cid'])             : '');
732         $arr['allow_gid']     = ((x($arr,'allow_gid'))     ? trim($arr['allow_gid'])             : '');
733         $arr['deny_cid']      = ((x($arr,'deny_cid'))      ? trim($arr['deny_cid'])              : '');
734         $arr['deny_gid']      = ((x($arr,'deny_gid'))      ? trim($arr['deny_gid'])              : '');
735         $arr['private']       = ((x($arr,'private'))       ? intval($arr['private'])             : 0 );
736         $arr['bookmark']      = ((x($arr,'bookmark'))      ? intval($arr['bookmark'])            : 0 );
737         $arr['body']          = ((x($arr,'body'))          ? trim($arr['body'])                  : '');
738         $arr['tag']           = ((x($arr,'tag'))           ? notags(trim($arr['tag']))           : '');
739         $arr['attach']        = ((x($arr,'attach'))        ? notags(trim($arr['attach']))        : '');
740         $arr['app']           = ((x($arr,'app'))           ? notags(trim($arr['app']))           : '');
741         $arr['origin']        = ((x($arr,'origin'))        ? intval($arr['origin'])              : 0 );
742         $arr['guid']          = ((x($arr,'guid'))          ? notags(trim($arr['guid']))          : get_guid());
743
744         if($arr['parent-uri'] === $arr['uri']) {
745                 $parent_id = 0;
746                 $parent_deleted = 0;
747                 $allow_cid = $arr['allow_cid'];
748                 $allow_gid = $arr['allow_gid'];
749                 $deny_cid  = $arr['deny_cid'];
750                 $deny_gid  = $arr['deny_gid'];
751         }
752         else { 
753
754                 // find the parent and snarf the item id and ACL's
755                 // and anything else we need to inherit
756
757                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
758                         dbesc($arr['parent-uri']),
759                         intval($arr['uid'])
760                 );
761
762                 if(count($r)) {
763
764                         // is the new message multi-level threaded?
765                         // even though we don't support it now, preserve the info
766                         // and re-attach to the conversation parent.
767
768                         if($r[0]['uri'] != $r[0]['parent-uri']) {
769                                 $arr['thr-parent'] = $arr['parent-uri'];
770                                 $arr['parent-uri'] = $r[0]['parent-uri'];
771                                 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d 
772                                         ORDER BY `id` ASC LIMIT 1",
773                                         dbesc($r[0]['parent-uri']),
774                                         dbesc($r[0]['parent-uri']),
775                                         intval($arr['uid'])
776                                 );
777                                 if($z && count($z))
778                                         $r = $z;
779                         }
780
781                         $parent_id      = $r[0]['id'];
782                         $parent_deleted = $r[0]['deleted'];
783                         $allow_cid      = $r[0]['allow_cid'];
784                         $allow_gid      = $r[0]['allow_gid'];
785                         $deny_cid       = $r[0]['deny_cid'];
786                         $deny_gid       = $r[0]['deny_gid'];
787                         $arr['wall']    = $r[0]['wall'];
788                 }
789                 else {
790
791                         // Allow one to see reply tweets from status.net even when
792                         // we don't have or can't see the original post.
793
794                         if($force_parent) {
795                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
796                                 $parent_id = 0;
797                                 $arr['thr-parent'] = $arr['parent-uri'];
798                                 $arr['parent-uri'] = $arr['uri'];
799                                 $arr['gravity'] = 0;
800                         }
801                         else {
802                                 logger('item_store: item parent was not found - ignoring item');
803                                 return 0;
804                         }
805                         
806                         $parent_deleted = 0;
807                 }
808         }
809
810         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
811                 dbesc($arr['uri']),
812                 intval($arr['uid'])
813         );
814         if($r && count($r)) {
815                 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
816                 return 0;
817         }
818
819         call_hooks('post_remote',$arr);
820
821         if(x($arr,'cancel')) {
822                 logger('item_store: post cancelled by plugin.');
823                 return 0;
824         }
825
826         dbesc_array($arr);
827
828         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
829
830         $r = dbq("INSERT INTO `item` (`" 
831                         . implode("`, `", array_keys($arr)) 
832                         . "`) VALUES ('" 
833                         . implode("', '", array_values($arr)) 
834                         . "')" );
835
836         // find the item we just created
837
838         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
839                 $arr['uri'],           // already dbesc'd
840                 intval($arr['uid'])
841         );
842
843         if(count($r)) {
844                 $current_post = $r[0]['id'];
845                 logger('item_store: created item ' . $current_post);
846         }
847         else {
848                 logger('item_store: could not locate created item');
849                 return 0;
850         }
851         if(count($r) > 1) {
852                 logger('item_store: duplicated post occurred. Removing duplicates.');
853                 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
854                         $arr['uri'],
855                         intval($arr['uid']),
856                         intval($current_post)
857                 );
858         }
859
860         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))      
861                 $parent_id = $current_post;
862
863         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
864                 $private = 1;
865         else
866                 $private = $arr['private']; 
867
868         // Set parent id - and also make sure to inherit the parent's ACL's.
869
870         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
871                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
872                 intval($parent_id),
873                 dbesc($allow_cid),
874                 dbesc($allow_gid),
875                 dbesc($deny_cid),
876                 dbesc($deny_gid),
877                 intval($private),
878                 intval($parent_deleted),
879                 intval($current_post)
880         );
881
882         // update the commented timestamp on the parent
883
884         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
885                 dbesc(datetime_convert()),
886                 dbesc(datetime_convert()),
887                 intval($parent_id)
888         );
889
890         if($dsprsig) {
891                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
892                         intval($current_post),
893                         dbesc($dsprsig->signed_text),
894                         dbesc($dsprsig->signature),
895                         dbesc($dsprsig->signer)
896                 );
897         }
898
899
900         /**
901          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
902          */
903
904         if($arr['last-child']) {
905                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
906                         dbesc($arr['uri']),
907                         intval($arr['uid']),
908                         intval($current_post)
909                 );
910         }
911
912         tag_deliver($arr['uid'],$current_post);
913
914         return $current_post;
915 }
916
917 function get_item_contact($item,$contacts) {
918         if(! count($contacts) || (! is_array($item)))
919                 return false;
920         foreach($contacts as $contact) {
921                 if($contact['id'] == $item['contact-id']) {
922                         return $contact;
923                         break; // NOTREACHED
924                 }
925         }
926         return false;
927 }
928
929
930 function tag_deliver($uid,$item_id) {
931
932         // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
933
934         $a = get_app();
935
936         $mention = false;
937
938         $u = q("select uid, nickname, language, username, email, `page-flags`, `notify-flags` from user where uid = %d limit 1",
939                 intval($uid)
940         );
941         if(! count($u))
942                 return;
943
944         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
945
946         $i = q("select * from item where id = %d and uid = %d limit 1",
947                 intval($item_id),
948                 intval($uid)
949         );
950         if(! count($i))
951                 return;
952
953         $item = $i[0];
954
955         $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
956
957         // Diaspora uses their own hardwired link URL in @-tags
958         // instead of the one we supply with webfinger
959
960         $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
961
962         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
963         if($cnt) {
964                 foreach($matches as $mtch) {
965                         if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
966                                 $mention = true;
967                                 logger('tag_deliver: mention found: ' . $mtch[2]);
968                         }
969                 }
970         }
971
972         if(! $mention)
973                 return;
974
975         // send a notification
976
977         require_once('include/enotify.php');
978         notification(array(
979                 'type'         => NOTIFY_TAGSELF,
980                 'notify_flags' => $u[0]['notify-flags'],
981                 'language'     => $u[0]['language'],
982                 'to_name'      => $u[0]['username'],
983                 'to_email'     => $u[0]['email'],
984                 'uid'          => $u[0]['uid'],
985                 'item'         => $item,
986                 'link'         => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
987                 'source_name'  => $item['author-name'],
988                 'source_link'  => $item['author-link'],
989                 'source_photo' => $item['author-avatar'],
990                 'verb'         => ACTIVITY_TAG,
991                 'otype'        => 'item'
992         ));
993
994         if(! $community_page)
995                 return;
996
997         // tgroup delivery - setup a second delivery chain
998         // prevent delivery looping - only proceed
999         // if the message originated elsewhere and is a top-level post
1000
1001         if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1002                 return;
1003
1004         // now change this copy of the post to a forum head message and deliver to all the tgroup members
1005
1006
1007         $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1008                 intval($u[0]['uid'])
1009         );
1010         if(! count($c))
1011                 return;
1012
1013         q("update item set wall = 1, origin = 1, forum_mode = 1, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s'  where id = %d limit 1",
1014                 dbesc($c[0]['name']),
1015                 dbesc($c[0]['url']),
1016                 dbesc($c[0]['thumb']),
1017                 intval($item_id)
1018         );
1019
1020         proc_run('php','include/notifier.php','tgroup',$item_id);                       
1021
1022 }
1023
1024
1025
1026
1027
1028
1029 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1030
1031         $a = get_app();
1032
1033 //      if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
1034 //              return 3;
1035
1036         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1037
1038         if($contact['duplex'] && $contact['dfrn-id'])
1039                 $idtosend = '0:' . $orig_id;
1040         if($contact['duplex'] && $contact['issued-id'])
1041                 $idtosend = '1:' . $orig_id;            
1042
1043         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1044
1045         $rino_enable = get_config('system','rino_encrypt');
1046
1047         if(! $rino_enable)
1048                 $rino = 0;
1049
1050         $ssl_val = intval(get_config('system','ssl_policy'));
1051         $ssl_policy = '';
1052
1053         switch($ssl_val){
1054                 case SSL_POLICY_FULL:
1055                         $ssl_policy = 'full';
1056                         break;
1057                 case SSL_POLICY_SELFSIGN:
1058                         $ssl_policy = 'self';
1059                         break;                  
1060                 case SSL_POLICY_NONE:
1061                 default:
1062                         $ssl_policy = 'none';
1063                         break;
1064         }
1065
1066         $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1067
1068         logger('dfrn_deliver: ' . $url);
1069
1070         $xml = fetch_url($url);
1071
1072         $curl_stat = $a->get_curl_code();
1073         if(! $curl_stat)
1074                 return(-1); // timed out
1075
1076         logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1077
1078         if(! $xml)
1079                 return 3;
1080
1081         if(strpos($xml,'<?xml') === false) {
1082                 logger('dfrn_deliver: no valid XML returned');
1083                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1084                 return 3;
1085         }
1086
1087         $res = parse_xml_string($xml);
1088
1089         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1090                 return (($res->status) ? $res->status : 3);
1091
1092         $postvars     = array();
1093         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1094         $challenge    = hex2bin((string) $res->challenge);
1095         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1096         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1097         $page         = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1098
1099         $final_dfrn_id = '';
1100
1101
1102         if(($contact['duplex'] && strlen($contact['pubkey'])) 
1103                 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1104                 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1105                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1106                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1107         }
1108         else {
1109                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1110                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1111         }
1112
1113         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1114
1115         if(strpos($final_dfrn_id,':') == 1)
1116                 $final_dfrn_id = substr($final_dfrn_id,2);
1117
1118         if($final_dfrn_id != $orig_id) {
1119                 logger('dfrn_deliver: wrong dfrn_id.');
1120                 // did not decode properly - cannot trust this site 
1121                 return 3;
1122         }
1123
1124         $postvars['dfrn_id']      = $idtosend;
1125         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1126         if($dissolve)
1127                 $postvars['dissolve'] = '1';
1128
1129
1130         if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1131                 $postvars['data'] = $atom;
1132                 $postvars['perm'] = 'rw';
1133         }
1134         else {
1135                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1136                 $postvars['perm'] = 'r';
1137         }
1138
1139         $postvars['ssl_policy'] = $ssl_policy;
1140
1141         if($page)
1142                 $postvars['page'] = '1';
1143         
1144         if($rino && $rino_allowed && (! $dissolve)) {
1145                 $key = substr(random_string(),0,16);
1146                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1147                 $postvars['data'] = $data;
1148                 logger('rino: sent key = ' . $key, LOGGER_DEBUG);       
1149
1150
1151                 if($dfrn_version >= 2.1) {      
1152                         if(($contact['duplex'] && strlen($contact['pubkey'])) 
1153                                 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1154                                 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1155
1156                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1157                         }
1158                         else {
1159                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1160                         }
1161                 }
1162                 else {
1163                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1164                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1165                         }
1166                         else {
1167                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1168                         }
1169                 }
1170
1171                 logger('md5 rawkey ' . md5($postvars['key']));
1172
1173                 $postvars['key'] = bin2hex($postvars['key']);
1174         }
1175
1176         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1177
1178         $xml = post_url($contact['notify'],$postvars);
1179
1180         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1181
1182         $curl_stat = $a->get_curl_code();
1183         if((! $curl_stat) || (! strlen($xml)))
1184                 return(-1); // timed out
1185
1186         if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1187                 return(-1);
1188
1189         if(strpos($xml,'<?xml') === false) {
1190                 logger('dfrn_deliver: phase 2: no valid XML returned');
1191                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1192                 return 3;
1193         }
1194
1195         $res = parse_xml_string($xml);
1196
1197         return $res->status; 
1198 }
1199
1200
1201 /**
1202  *
1203  * consume_feed - process atom feed and update anything/everything we might need to update
1204  *
1205  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1206  *
1207  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1208  *             It is this person's stuff that is going to be updated.
1209  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1210  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
1211  *             have a contact record.
1212  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
1213  *        might not) try and subscribe to it.
1214  * $datedir sorts in reverse order
1215  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been 
1216  *      imported prior to its children being seen in the stream unless we are certain
1217  *      of how the feed is arranged/ordered.
1218  * With $pass = 1, we only pull parent items out of the stream.
1219  * With $pass = 2, we only pull children (comments/likes).
1220  *
1221  * So running this twice, first with pass 1 and then with pass 2 will do the right
1222  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1223  * model where comments can have sub-threads. That would require some massive sorting
1224  * to get all the feed items into a mostly linear ordering, and might still require
1225  * recursion.  
1226  */
1227
1228 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1229
1230         require_once('library/simplepie/simplepie.inc');
1231
1232         if(! strlen($xml)) {
1233                 logger('consume_feed: empty input');
1234                 return;
1235         }
1236                 
1237         $feed = new SimplePie();
1238         $feed->set_raw_data($xml);
1239         if($datedir)
1240                 $feed->enable_order_by_date(true);
1241         else
1242                 $feed->enable_order_by_date(false);
1243         $feed->init();
1244
1245         if($feed->error())
1246                 logger('consume_feed: Error parsing XML: ' . $feed->error());
1247
1248         $permalink = $feed->get_permalink();
1249
1250         // Check at the feed level for updated contact name and/or photo
1251
1252         $name_updated  = '';
1253         $new_name = '';
1254         $photo_timestamp = '';
1255         $photo_url = '';
1256         $birthday = '';
1257
1258         $hubs = $feed->get_links('hub');
1259
1260         if(count($hubs))
1261                 $hub = implode(',', $hubs);
1262
1263         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1264         if(! $rawtags)
1265                 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1266         if($rawtags) {
1267                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1268                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1269                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1270                         $new_name = $elems['name'][0]['data'];
1271                 } 
1272                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1273                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1274                         $photo_url = $elems['link'][0]['attribs']['']['href'];
1275                 }
1276
1277                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1278                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1279                 }
1280         }
1281
1282         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1283                 logger('consume_feed: Updating photo for ' . $contact['name']);
1284                 require_once("Photo.php");
1285                 $photo_failure = false;
1286                 $have_photo = false;
1287
1288                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1289                         intval($contact['id']),
1290                         intval($contact['uid'])
1291                 );
1292                 if(count($r)) {
1293                         $resource_id = $r[0]['resource-id'];
1294                         $have_photo = true;
1295                 }
1296                 else {
1297                         $resource_id = photo_new_resource();
1298                 }
1299                         
1300                 $img_str = fetch_url($photo_url,true);
1301                 $img = new Photo($img_str);
1302                 if($img->is_valid()) {
1303                         if($have_photo) {
1304                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1305                                         dbesc($resource_id),
1306                                         intval($contact['id']),
1307                                         intval($contact['uid'])
1308                                 );
1309                         }
1310                                 
1311                         $img->scaleImageSquare(175);
1312                                 
1313                         $hash = $resource_id;
1314                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1315                                 
1316                         $img->scaleImage(80);
1317                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1318
1319                         $img->scaleImage(48);
1320                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1321
1322                         $a = get_app();
1323
1324                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'  
1325                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1326                                 dbesc(datetime_convert()),
1327                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1328                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1329                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1330                                 intval($contact['uid']),
1331                                 intval($contact['id'])
1332                         );
1333                 }
1334         }
1335
1336         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1337                 $r = q("select * from contact where uid = %d and id = %d limit 1",
1338                         intval($contact['uid']),
1339                         intval($contact['id'])
1340                 );
1341
1342                 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1343                         dbesc(notags(trim($new_name))),
1344                         dbesc(datetime_convert()),
1345                         intval($contact['uid']),
1346                         intval($contact['id'])
1347                 );
1348
1349                 // do our best to update the name on content items
1350
1351                 if(count($r)) {
1352                         q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1353                                 dbesc(notags(trim($new_name))),
1354                                 dbesc($r[0]['name']),
1355                                 dbesc($r[0]['url']),
1356                                 intval($contact['uid'])
1357                         );
1358                 }
1359         }
1360
1361         if(strlen($birthday)) {
1362                 if(substr($birthday,0,4) != $contact['bdyear']) {
1363                         logger('consume_feed: updating birthday: ' . $birthday);
1364
1365                         /**
1366                          *
1367                          * Add new birthday event for this person
1368                          *
1369                          * $bdtext is just a readable placeholder in case the event is shared
1370                          * with others. We will replace it during presentation to our $importer
1371                          * to contain a sparkle link and perhaps a photo. 
1372                          *
1373                          */
1374                          
1375                         $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1376
1377
1378                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1379                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1380                                 intval($contact['uid']),
1381                                 intval($contact['id']),
1382                                 dbesc(datetime_convert()),
1383                                 dbesc(datetime_convert()),
1384                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1385                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1386                                 dbesc($bdtext),
1387                                 dbesc('birthday')
1388                         );
1389                         
1390
1391                         // update bdyear
1392
1393                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1394                                 dbesc(substr($birthday,0,4)),
1395                                 intval($contact['uid']),
1396                                 intval($contact['id'])
1397                         );
1398
1399                         // This function is called twice without reloading the contact
1400                         // Make sure we only create one event. This is why &$contact 
1401                         // is a reference var in this function
1402
1403                         $contact['bdyear'] = substr($birthday,0,4);
1404                 }
1405
1406         }
1407
1408         $community_page = 0;
1409         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1410         if($rawtags) {
1411                 $community_page = intval($rawtags[0]['data']);
1412         }
1413         if(is_array($contact) && intval($contact['forum']) != $community_page) {
1414                 q("update contact set forum = %d where id = %d limit 1",
1415                         intval($community_page),
1416                         intval($contact['id'])
1417                 );
1418                 $contact['forum'] = (string) $community_page;
1419         }
1420
1421
1422         // process any deleted entries
1423
1424         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1425         if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1426                 foreach($del_entries as $dentry) {
1427                         $deleted = false;
1428                         if(isset($dentry['attribs']['']['ref'])) {
1429                                 $uri = $dentry['attribs']['']['ref'];
1430                                 $deleted = true;
1431                                 if(isset($dentry['attribs']['']['when'])) {
1432                                         $when = $dentry['attribs']['']['when'];
1433                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1434                                 }
1435                                 else
1436                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1437                         }
1438                         if($deleted && is_array($contact)) {
1439                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id` 
1440                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
1441                                         dbesc($uri),
1442                                         intval($importer['uid']),
1443                                         intval($contact['id'])
1444                                 );
1445                                 if(count($r)) {
1446                                         $item = $r[0];
1447
1448                                         if(! $item['deleted'])
1449                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1450
1451                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1452                                                 $xo = parse_xml_string($item['object'],false);
1453                                                 $xt = parse_xml_string($item['target'],false);
1454                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
1455                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1456                                                                 dbesc($xt->id),
1457                                                                 intval($importer['importer_uid'])
1458                                                         );
1459                                                         if(count($i)) {
1460
1461                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
1462
1463                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1464                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1465                                                                 $author_copy = (($item['origin']) ? true : false);
1466
1467                                                                 if($owner_remove && $author_copy)
1468                                                                         continue;
1469                                                                 if($author_remove || $owner_remove) {
1470                                                                         $tags = explode(',',$i[0]['tag']);
1471                                                                         $newtags = array();
1472                                                                         if(count($tags)) {
1473                                                                                 foreach($tags as $tag)
1474                                                                                         if(trim($tag) !== trim($xo->body))
1475                                                                                                 $newtags[] = trim($tag);
1476                                                                         }
1477                                                                         q("update item set tag = '%s' where id = %d limit 1",
1478                                                                                 dbesc(implode(',',$newtags)),
1479                                                                                 intval($i[0]['id'])
1480                                                                         );
1481                                                                 }
1482                                                         }
1483                                                 }
1484                                         }
1485
1486                                         if($item['uri'] == $item['parent-uri']) {
1487                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1488                                                         `body` = '', `title` = ''
1489                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1490                                                         dbesc($when),
1491                                                         dbesc(datetime_convert()),
1492                                                         dbesc($item['uri']),
1493                                                         intval($importer['uid'])
1494                                                 );
1495                                         }
1496                                         else {
1497                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1498                                                         `body` = '', `title` = '' 
1499                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1500                                                         dbesc($when),
1501                                                         dbesc(datetime_convert()),
1502                                                         dbesc($uri),
1503                                                         intval($importer['uid'])
1504                                                 );
1505                                                 if($item['last-child']) {
1506                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1507                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1508                                                                 dbesc(datetime_convert()),
1509                                                                 dbesc($item['parent-uri']),
1510                                                                 intval($item['uid'])
1511                                                         );
1512                                                         // who is the last child now? 
1513                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d 
1514                                                                 ORDER BY `created` DESC LIMIT 1",
1515                                                                         dbesc($item['parent-uri']),
1516                                                                         intval($importer['uid'])
1517                                                         );
1518                                                         if(count($r)) {
1519                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1520                                                                         intval($r[0]['id'])
1521                                                                 );
1522                                                         }
1523                                                 }       
1524                                         }
1525                                 }       
1526                         }
1527                 }
1528         }
1529
1530         // Now process the feed
1531
1532         if($feed->get_item_quantity()) {                
1533
1534                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1535
1536         // in inverse date order
1537                 if ($datedir)
1538                         $items = array_reverse($feed->get_items());
1539                 else
1540                         $items = $feed->get_items();
1541
1542
1543                 foreach($items as $item) {
1544
1545                         $is_reply = false;              
1546                         $item_id = $item->get_id();
1547                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1548                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1549                                 $is_reply = true;
1550                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1551                         }
1552
1553                         if(($is_reply) && is_array($contact)) {
1554
1555                                 if($pass == 1)
1556                                         continue;
1557
1558                                 // Have we seen it? If not, import it.
1559         
1560                                 $item_id  = $item->get_id();
1561                                 $datarray = get_atom_elements($feed,$item);
1562
1563
1564                                 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1565                                         $datarray['author-name'] = $contact['name'];
1566                                 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1567                                         $datarray['author-link'] = $contact['url'];
1568                                 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1569                                         $datarray['author-avatar'] = $contact['thumb'];
1570
1571                                 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1572                                         logger('consume_feed: no author information! ' . print_r($datarray,true));
1573                                         continue;
1574                                 }
1575
1576                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1577                                         dbesc($item_id),
1578                                         intval($importer['uid'])
1579                                 );
1580
1581                                 // Update content if 'updated' changes
1582
1583                                 if(count($r)) {
1584                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1585                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1586                                                         dbesc($datarray['title']),
1587                                                         dbesc($datarray['body']),
1588                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1589                                                         dbesc($item_id),
1590                                                         intval($importer['uid'])
1591                                                 );
1592                                         }
1593
1594                                         // update last-child if it changes
1595
1596                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1597                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1598                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1599                                                         dbesc(datetime_convert()),
1600                                                         dbesc($parent_uri),
1601                                                         intval($importer['uid'])
1602                                                 );
1603                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1604                                                         intval($allow[0]['data']),
1605                                                         dbesc(datetime_convert()),
1606                                                         dbesc($item_id),
1607                                                         intval($importer['uid'])
1608                                                 );
1609                                         }
1610                                         continue;
1611                                 }
1612
1613                                 $force_parent = false;
1614                                 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1615                                         if($contact['network'] === NETWORK_OSTATUS)
1616                                                 $force_parent = true;
1617                                         if(strlen($datarray['title']))
1618                                                 unset($datarray['title']);
1619                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1620                                                 dbesc(datetime_convert()),
1621                                                 dbesc($parent_uri),
1622                                                 intval($importer['uid'])
1623                                         );
1624                                         $datarray['last-child'] = 1;
1625                                 }
1626
1627                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1628                                         // one way feed - no remote comment ability
1629                                         $datarray['last-child'] = 0;
1630                                 }
1631                                 $datarray['parent-uri'] = $parent_uri;
1632                                 $datarray['uid'] = $importer['uid'];
1633                                 $datarray['contact-id'] = $contact['id'];
1634                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1635                                         $datarray['type'] = 'activity';
1636                                         $datarray['gravity'] = GRAVITY_LIKE;
1637                                         // only one like or dislike per person
1638                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
1639                                                 intval($datarray['uid']),
1640                                                 intval($datarray['contact-id']),
1641                                                 dbesc($datarray['verb'])
1642                                         );
1643                                         if($r && count($r))
1644                                                 continue; 
1645                                 }
1646
1647                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1648                                         $xo = parse_xml_string($datarray['object'],false);
1649                                         $xt = parse_xml_string($datarray['target'],false);
1650
1651                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
1652                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1653                                                         dbesc($xt->id),
1654                                                         intval($importer['importer_uid'])
1655                                                 );
1656                                                 if(! count($r))
1657                                                         continue;
1658
1659                                                 // extract tag, if not duplicate, add to parent item
1660                                                 if($xo->id && $xo->content) {
1661                                                         $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1662                                                         if(! (stristr($r[0]['tag'],$newtag))) {
1663                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1664                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1665                                                                         intval($r[0]['id'])
1666                                                                 );
1667                                                         }
1668                                                 }
1669                                         }
1670                                 }
1671
1672                                 $r = item_store($datarray,$force_parent);
1673                                 continue;
1674                         }
1675
1676                         else {
1677
1678                                 // Head post of a conversation. Have we seen it? If not, import it.
1679
1680                                 $item_id  = $item->get_id();
1681
1682                                 $datarray = get_atom_elements($feed,$item);
1683
1684                                 if(is_array($contact)) {
1685                                         if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1686                                                 $datarray['author-name'] = $contact['name'];
1687                                         if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1688                                                 $datarray['author-link'] = $contact['url'];
1689                                         if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1690                                                 $datarray['author-avatar'] = $contact['thumb'];
1691                                 }
1692
1693                                 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1694                                         logger('consume_feed: no author information! ' . print_r($datarray,true));
1695                                         continue;
1696                                 }
1697
1698                                 // special handling for events
1699
1700                                 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1701                                         $ev = bbtoevent($datarray['body']);
1702                                         if(x($ev,'desc') && x($ev,'start')) {
1703                                                 $ev['uid'] = $importer['uid'];
1704                                                 $ev['uri'] = $item_id;
1705                                                 $ev['edited'] = $datarray['edited'];
1706                                                 $ev['private'] = $datarray['private'];
1707
1708                                                 if(is_array($contact))
1709                                                         $ev['cid'] = $contact['id'];
1710                                                 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1711                                                         dbesc($item_id),
1712                                                         intval($importer['uid'])
1713                                                 );
1714                                                 if(count($r))
1715                                                         $ev['id'] = $r[0]['id'];
1716                                                 $xyz = event_store($ev);
1717                                                 continue;
1718                                         }
1719                                 }
1720
1721                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1722                                         dbesc($item_id),
1723                                         intval($importer['uid'])
1724                                 );
1725
1726                                 // Update content if 'updated' changes
1727
1728                                 if(count($r)) {
1729                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1730                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1731                                                         dbesc($datarray['title']),
1732                                                         dbesc($datarray['body']),
1733                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1734                                                         dbesc($item_id),
1735                                                         intval($importer['uid'])
1736                                                 );
1737                                         }
1738
1739                                         // update last-child if it changes
1740
1741                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1742                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1743                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1744                                                         intval($allow[0]['data']),
1745                                                         dbesc(datetime_convert()),
1746                                                         dbesc($item_id),
1747                                                         intval($importer['uid'])
1748                                                 );
1749                                         }
1750                                         continue;
1751                                 }
1752
1753                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1754                                         logger('consume-feed: New follower');
1755                                         new_follower($importer,$contact,$datarray,$item);
1756                                         return;
1757                                 }
1758                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
1759                                         lose_follower($importer,$contact,$datarray,$item);
1760                                         return;
1761                                 }
1762
1763                                 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1764                                         logger('consume-feed: New friend request');
1765                                         new_follower($importer,$contact,$datarray,$item,true);
1766                                         return;
1767                                 }
1768                                 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND))  {
1769                                         lose_sharer($importer,$contact,$datarray,$item);
1770                                         return;
1771                                 }
1772
1773
1774                                 if(! is_array($contact))
1775                                         return;
1776
1777                                 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1778                                         if(strlen($datarray['title']))
1779                                                 unset($datarray['title']);
1780                                         $datarray['last-child'] = 1;
1781                                 }
1782
1783                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1784                                         // one way feed - no remote comment ability
1785                                         $datarray['last-child'] = 0;
1786                                 }
1787
1788                                 // This is my contact on another system, but it's really me.
1789                                 // Turn this into a wall post.
1790
1791                                 if($contact['remote_self'])
1792                                         $datarray['wall'] = 1;
1793
1794                                 $datarray['parent-uri'] = $item_id;
1795                                 $datarray['uid'] = $importer['uid'];
1796                                 $datarray['contact-id'] = $contact['id'];
1797
1798                                 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1799                                         // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery, 
1800                                         // but otherwise there's a possible data mixup on the sender's system.
1801                                         // the tgroup delivery code called from item_store will correct it if it's a forum,
1802                                         // but we're going to unconditionally correct it here so that the post will always be owned by our contact. 
1803                                         logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
1804                                         $datarray['owner-name']   = $contact['name'];
1805                                         $datarray['owner-link']   = $contact['url'];
1806                                         $datarray['owner-avatar'] = $contact['thumb'];
1807                                 }
1808
1809                                 $r = item_store($datarray);
1810                                 continue;
1811
1812                         }
1813                 }
1814         }
1815 }
1816
1817 function local_delivery($importer,$data) {
1818
1819         $a = get_app();
1820
1821         if($importer['readonly']) {
1822                 // We aren't receiving stuff from this person. But we will quietly ignore them
1823                 // rather than a blatant "go away" message.
1824                 logger('local_delivery: ignoring');
1825                 return 0;
1826                 //NOTREACHED
1827         }
1828
1829         // Consume notification feed. This may differ from consuming a public feed in several ways
1830         // - might contain email or friend suggestions
1831         // - might contain remote followup to our message
1832         //              - in which case we need to accept it and then notify other conversants
1833         // - we may need to send various email notifications
1834
1835         $feed = new SimplePie();
1836         $feed->set_raw_data($data);
1837         $feed->enable_order_by_date(false);
1838         $feed->init();
1839
1840         $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1841         if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1842                 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1843                 $newloc = array();
1844                 $newloc['uid'] = $importer['importer_uid'];
1845                 $newloc['cid'] = $importer['id'];
1846                 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1847                 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1848                 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1849                 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1850                 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1851                 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1852                 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1853                 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1854                 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1855                 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1856                 
1857                 // TODO
1858                 // merge with current record, current contents have priority
1859                 // update record, set url-updated
1860                 // update profile photos
1861                 // schedule a scan?
1862
1863         }
1864
1865         // handle friend suggestion notification
1866
1867         $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1868         if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1869                 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1870                 $fsugg = array();
1871                 $fsugg['uid'] = $importer['importer_uid'];
1872                 $fsugg['cid'] = $importer['id'];
1873                 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1874                 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1875                 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1876                 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1877                 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1878
1879                 // Does our member already have a friend matching this description?
1880
1881                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1882                         dbesc($fsugg['name']),
1883                         dbesc(normalise_link($fsugg['url'])),
1884                         intval($fsugg['uid'])
1885                 );
1886                 if(count($r))
1887                         return 0;
1888
1889                 // Do we already have an fcontact record for this person?
1890
1891                 $fid = 0;
1892                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1893                         dbesc($fsugg['url']),
1894                         dbesc($fsugg['name']),
1895                         dbesc($fsugg['request'])
1896                 );
1897                 if(count($r)) {
1898                         $fid = $r[0]['id'];
1899                 }
1900                 if(! $fid)
1901                         $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1902                         dbesc($fsugg['name']),
1903                         dbesc($fsugg['url']),
1904                         dbesc($fsugg['photo']),
1905                         dbesc($fsugg['request'])
1906                 );
1907                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1908                         dbesc($fsugg['url']),
1909                         dbesc($fsugg['name']),
1910                         dbesc($fsugg['request'])
1911                 );
1912                 if(count($r)) {
1913                         $fid = $r[0]['id'];
1914                 }
1915                 // database record did not get created. Quietly give up.
1916                 else
1917                         return 0;
1918
1919                 $hash = random_string();
1920  
1921                 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1922                         VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1923                         intval($fsugg['uid']),
1924                         intval($fid),
1925                         intval($fsugg['cid']),
1926                         dbesc($fsugg['body']),
1927                         dbesc($hash),
1928                         dbesc(datetime_convert()),
1929                         intval(0)
1930                 );
1931
1932                 notification(array(
1933                         'type'         => NOTIFY_SUGGEST,
1934                         'notify_flags' => $importer['notify-flags'],
1935                         'language'     => $importer['language'],
1936                         'to_name'      => $importer['username'],
1937                         'to_email'     => $importer['email'],
1938                         'uid'          => $importer['importer_uid'],
1939                         'item'         => $fsugg,
1940                         'link'         => $a->get_baseurl() . '/notifications/intros',
1941                         'source_name'  => $importer['name'],
1942                         'source_link'  => $importer['url'],
1943                         'source_photo' => $importer['photo'],
1944                         'verb'         => ACTIVITY_REQ_FRIEND,
1945                         'otype'        => 'intro'
1946                 ));
1947
1948                 return 0;
1949         }
1950
1951         $ismail = false;
1952
1953         $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
1954         if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
1955
1956                 logger('local_delivery: private message received');
1957
1958                 $ismail = true;
1959                 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
1960
1961                 $msg = array();
1962                 $msg['uid'] = $importer['importer_uid'];
1963                 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
1964                 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
1965                 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
1966                 $msg['contact-id'] = $importer['id'];
1967                 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
1968                 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
1969                 $msg['seen'] = 0;
1970                 $msg['replied'] = 0;
1971                 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
1972                 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
1973                 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
1974                 
1975                 dbesc_array($msg);
1976
1977                 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) 
1978                         . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
1979
1980                 // send notifications.
1981
1982                 require_once('include/enotify.php');
1983
1984                 $notif_params = array(
1985                         'type' => NOTIFY_MAIL,
1986                         'notify_flags' => $importer['notify-flags'],
1987                         'language' => $importer['language'],
1988                         'to_name' => $importer['username'],
1989                         'to_email' => $importer['email'],
1990                         'uid' => $importer['importer_uid'],
1991                         'item' => $msg,
1992                         'source_name' => $msg['from-name'],
1993                         'source_link' => $importer['url'],
1994                         'source_photo' => $importer['thumb'],
1995                         'verb' => ACTIVITY_POST,
1996                         'otype' => 'mail'
1997                 );
1998                         
1999                 notification($notif_params);
2000                 return 0;
2001
2002                 // NOTREACHED
2003         }       
2004
2005         $community_page = 0;
2006         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2007         if($rawtags) {
2008                 $community_page = intval($rawtags[0]['data']);
2009         }
2010         if(intval($importer['forum']) != $community_page) {
2011                 q("update contact set forum = %d where id = %d limit 1",
2012                         intval($community_page),
2013                         intval($importer['id'])
2014                 );
2015                 $importer['forum'] = (string) $community_page;
2016         }
2017         
2018         logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2019
2020         // process any deleted entries
2021
2022         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2023         if(is_array($del_entries) && count($del_entries)) {
2024                 foreach($del_entries as $dentry) {
2025                         $deleted = false;
2026                         if(isset($dentry['attribs']['']['ref'])) {
2027                                 $uri = $dentry['attribs']['']['ref'];
2028                                 $deleted = true;
2029                                 if(isset($dentry['attribs']['']['when'])) {
2030                                         $when = $dentry['attribs']['']['when'];
2031                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2032                                 }
2033                                 else
2034                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2035                         }
2036                         if($deleted) {
2037
2038                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2039                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
2040                                         dbesc($uri),
2041                                         intval($importer['importer_uid']),
2042                                         intval($importer['id'])
2043                                 );
2044
2045                                 if(count($r)) {
2046                                         $item = $r[0];
2047
2048                                         if($item['deleted'])
2049                                                 continue;
2050
2051                                         logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2052
2053                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
2054                                                 $xo = parse_xml_string($item['object'],false);
2055                                                 $xt = parse_xml_string($item['target'],false);
2056
2057                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
2058                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2059                                                                 dbesc($xt->id),
2060                                                                 intval($importer['importer_uid'])
2061                                                         );
2062                                                         if(count($i)) {
2063
2064                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2065                                                                 
2066                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2067                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2068                                                                 $author_copy = (($item['origin']) ? true : false); 
2069
2070                                                                 if($owner_remove && $author_copy)
2071                                                                         continue;
2072                                                                 if($author_remove || $owner_remove) {                                                           
2073                                                                         $tags = explode(',',$i[0]['tag']);
2074                                                                         $newtags = array();
2075                                                                         if(count($tags)) {
2076                                                                                 foreach($tags as $tag)
2077                                                                                         if(trim($tag) !== trim($xo->body))
2078                                                                                                 $newtags[] = trim($tag);
2079                                                                         }
2080                                                                         q("update item set tag = '%s' where id = %d limit 1",
2081                                                                                 dbesc(implode(',',$newtags)),
2082                                                                                 intval($i[0]['id'])
2083                                                                         );
2084                                                                 }
2085                                                         }
2086                                                 }
2087                                         }
2088
2089                                         if($item['uri'] == $item['parent-uri']) {
2090                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2091                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
2092                                                         dbesc($when),
2093                                                         dbesc(datetime_convert()),
2094                                                         dbesc($item['uri']),
2095                                                         intval($importer['importer_uid'])
2096                                                 );
2097                                         }
2098                                         else {
2099                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
2100                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2101                                                         dbesc($when),
2102                                                         dbesc(datetime_convert()),
2103                                                         dbesc($uri),
2104                                                         intval($importer['importer_uid'])
2105                                                 );
2106                                                 if($item['last-child']) {
2107                                                         // ensure that last-child is set in case the comment that had it just got wiped.
2108                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2109                                                                 dbesc(datetime_convert()),
2110                                                                 dbesc($item['parent-uri']),
2111                                                                 intval($item['uid'])
2112                                                         );
2113                                                         // who is the last child now? 
2114                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2115                                                                 ORDER BY `created` DESC LIMIT 1",
2116                                                                         dbesc($item['parent-uri']),
2117                                                                         intval($importer['importer_uid'])
2118                                                         );
2119                                                         if(count($r)) {
2120                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2121                                                                         intval($r[0]['id'])
2122                                                                 );
2123                                                         }       
2124                                                 }
2125                                         }       
2126                                 }
2127                         }
2128                 }
2129         }
2130
2131
2132         foreach($feed->get_items() as $item) {
2133
2134                 $is_reply = false;              
2135                 $item_id = $item->get_id();
2136                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2137                 if(isset($rawthread[0]['attribs']['']['ref'])) {
2138                         $is_reply = true;
2139                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
2140                 }
2141
2142                 if($is_reply) {
2143                         $community = false;
2144
2145                         if($importer['page-flags'] == PAGE_COMMUNITY) {
2146                                 $sql_extra = '';
2147                                 $community = true;
2148                                 logger('local_delivery: possible community reply');
2149                         }
2150                         else
2151                                 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2152  
2153                         // was the top-level post for this reply written by somebody on this site? 
2154                         // Specifically, the recipient? 
2155
2156                         $is_a_remote_comment = false;
2157
2158                         $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`, 
2159                                 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` 
2160                                 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` 
2161                                 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2162                                 AND `item`.`uid` = %d 
2163                                 $sql_extra
2164                                 LIMIT 1",
2165                                 dbesc($parent_uri),
2166                                 dbesc($parent_uri),
2167                                 intval($importer['importer_uid'])
2168                         );
2169                         if($r && count($r))
2170                                 $is_a_remote_comment = true;                    
2171
2172                         // Does this have the characteristics of a community comment?
2173                         // If it's a reply to a wall post on a community page it's a 
2174                         // valid community comment. Also forum_mode makes it valid for sure. 
2175                         // If neither, it's not.
2176
2177                         if($is_a_remote_comment && $community) {
2178                                 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2179                                         $is_a_remote_comment = false;
2180                                         logger('local_delivery: not a community reply');
2181                                 }
2182                         }
2183
2184                         if($is_a_remote_comment) {
2185                                 logger('local_delivery: received remote comment');
2186                                 $is_like = false;
2187                                 // remote reply to our post. Import and then notify everybody else.
2188                                 $datarray = get_atom_elements($feed,$item);
2189
2190
2191                                 // TODO: make this next part work against both delivery threads of a community post
2192
2193 //                              if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2194 //                                      logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] ); 
2195                                         // they won't know what to do so don't report an error. Just quietly die.
2196 //                                      return 0;
2197 //                              }                                       
2198
2199                                 $datarray['type'] = 'remote-comment';
2200                                 $datarray['wall'] = 1;
2201                                 $datarray['parent-uri'] = $parent_uri;
2202                                 $datarray['uid'] = $importer['importer_uid'];
2203                                 $datarray['owner-name'] = $r[0]['name'];
2204                                 $datarray['owner-link'] = $r[0]['url'];
2205                                 $datarray['owner-avatar'] = $r[0]['thumb'];
2206                                 $datarray['contact-id'] = $importer['id'];
2207                                 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2208                                         $is_like = true;
2209                                         $datarray['type'] = 'activity';
2210                                         $datarray['gravity'] = GRAVITY_LIKE;
2211                                         $datarray['last-child'] = 0;
2212                                         // only one like or dislike per person
2213                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2214                                                 intval($datarray['uid']),
2215                                                 intval($datarray['contact-id']),
2216                                                 dbesc($datarray['verb'])
2217                                         );
2218                                         if($r && count($r))
2219                                                 continue; 
2220                                 }
2221
2222                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2223
2224
2225                                         $xo = parse_xml_string($datarray['object'],false);
2226                                         $xt = parse_xml_string($datarray['target'],false);
2227
2228                                         if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
2229
2230                                                 // extract tag, if not duplicate, and this user allows tags, add to parent item                                         
2231
2232                                                 if($xo->id && $xo->content) {
2233                                                         $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2234
2235                                                         if(! (stristr($r[0]['tag'],$newtag))) {
2236                                                                 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2237                                                                         intval($importer['importer_uid'])
2238                                                                 );
2239                                                                 if(count($i) && ! ($i[0]['blocktags'])) {
2240                                                                         q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2241                                                                                 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2242                                                                                 intval($r[0]['id'])
2243                                                                         );
2244                                                                 }
2245                                                         }
2246                                                 }                                                                                                       
2247                                         }
2248                                 }
2249
2250 //                              if($community) {
2251 //                                      $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2252 //                                      if(! stristr($datarray['tag'],$newtag)) {
2253 //                                              if(strlen($datarray['tag']))
2254 //                                                      $datarray['tag'] .= ',';
2255 //                                              $datarray['tag'] .= $newtag;
2256 //                                      }
2257 //                              }
2258
2259
2260                                 $posted_id = item_store($datarray);
2261                                 $parent = 0;
2262
2263                                 if($posted_id) {
2264                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2265                                                 intval($posted_id),
2266                                                 intval($importer['importer_uid'])
2267                                         );
2268                                         if(count($r))
2269                                                 $parent = $r[0]['parent'];
2270                         
2271                                         if(! $is_like) {
2272                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2273                                                         dbesc(datetime_convert()),
2274                                                         intval($importer['importer_uid']),
2275                                                         intval($r[0]['parent'])
2276                                                 );
2277
2278                                                 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2279                                                         dbesc(datetime_convert()),
2280                                                         intval($importer['importer_uid']),
2281                                                         intval($posted_id)
2282                                                 );
2283                                         }
2284
2285                                         if($posted_id && $parent) {
2286                                 
2287                                                 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2288                                         
2289                                                 if((! $is_like) && (! $importer['self'])) {
2290
2291                                                         require_once('include/enotify.php');
2292
2293                                                         notification(array(
2294                                                                 'type'         => NOTIFY_COMMENT,
2295                                                                 'notify_flags' => $importer['notify-flags'],
2296                                                                 'language'     => $importer['language'],
2297                                                                 'to_name'      => $importer['username'],
2298                                                                 'to_email'     => $importer['email'],
2299                                                                 'uid'          => $importer['importer_uid'],
2300                                                                 'item'         => $datarray,
2301                                                                 'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2302                                                                 'source_name'  => stripslashes($datarray['author-name']),
2303                                                                 'source_link'  => $datarray['author-link'],
2304                                                                 'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
2305                                                                         ? $importer['thumb'] : $datarray['author-avatar']),
2306                                                                 'verb'         => ACTIVITY_POST,
2307                                                                 'otype'        => 'item',
2308                                                                 'parent'       => $parent,
2309
2310                                                         ));
2311
2312                                                 }
2313                                         }
2314
2315                                         return 0;
2316                                         // NOTREACHED
2317                                 }
2318                         }
2319                         else {
2320
2321                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2322
2323                                 $item_id  = $item->get_id();
2324                                 $datarray = get_atom_elements($feed,$item);
2325
2326                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2327                                         dbesc($item_id),
2328                                         intval($importer['importer_uid'])
2329                                 );
2330
2331                                 // Update content if 'updated' changes
2332
2333                                 if(count($r)) {
2334                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2335                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2336                                                         dbesc($datarray['title']),
2337                                                         dbesc($datarray['body']),
2338                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2339                                                         dbesc($item_id),
2340                                                         intval($importer['importer_uid'])
2341                                                 );
2342                                         }
2343
2344                                         // update last-child if it changes
2345
2346                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2347                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2348                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2349                                                         dbesc(datetime_convert()),
2350                                                         dbesc($parent_uri),
2351                                                         intval($importer['importer_uid'])
2352                                                 );
2353                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2354                                                         intval($allow[0]['data']),
2355                                                         dbesc(datetime_convert()),
2356                                                         dbesc($item_id),
2357                                                         intval($importer['importer_uid'])
2358                                                 );
2359                                         }
2360                                         continue;
2361                                 }
2362
2363                                 $datarray['parent-uri'] = $parent_uri;
2364                                 $datarray['uid'] = $importer['importer_uid'];
2365                                 $datarray['contact-id'] = $importer['id'];
2366                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2367                                         $datarray['type'] = 'activity';
2368                                         $datarray['gravity'] = GRAVITY_LIKE;
2369                                         // only one like or dislike per person
2370                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2371                                                 intval($datarray['uid']),
2372                                                 intval($datarray['contact-id']),
2373                                                 dbesc($datarray['verb'])
2374                                         );
2375                                         if($r && count($r))
2376                                                 continue; 
2377
2378                                 }
2379
2380                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2381
2382                                         $xo = parse_xml_string($datarray['object'],false);
2383                                         $xt = parse_xml_string($datarray['target'],false);
2384
2385                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
2386                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2387                                                         dbesc($xt->id),
2388                                                         intval($importer['importer_uid'])
2389                                                 );
2390                                                 if(! count($r))
2391                                                         continue;                               
2392
2393                                                 // extract tag, if not duplicate, add to parent item                                            
2394                                                 if($xo->content) {
2395                                                         if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2396                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2397                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2398                                                                         intval($r[0]['id'])
2399                                                                 );
2400                                                         }
2401                                                 }                                                                                                       
2402                                         }
2403                                 }
2404
2405                                 $posted_id = item_store($datarray);
2406
2407                                 // find out if our user is involved in this conversation and wants to be notified.
2408                         
2409                                 if($datarray['type'] != 'activity') {
2410
2411                                         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
2412                                                 dbesc($parent_uri),
2413                                                 intval($importer['importer_uid'])
2414                                         );
2415
2416                                         if(count($myconv)) {
2417                                                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2418
2419                                                 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2420                                                 if(! link_compare($datarray['author-link'],$importer_url)) {
2421
2422                                                         
2423                                                         foreach($myconv as $conv) {
2424
2425                                                                 // now if we find a match, it means we're in this conversation
2426         
2427                                                                 if(! link_compare($conv['author-link'],$importer_url))
2428                                                                         continue;
2429
2430                                                                 require_once('include/enotify.php');
2431                                                                 
2432                                                                 $conv_parent = $conv['parent'];
2433
2434                                                                 notification(array(
2435                                                                         'type'         => NOTIFY_COMMENT,
2436                                                                         'notify_flags' => $importer['notify-flags'],
2437                                                                         'language'     => $importer['language'],
2438                                                                         'to_name'      => $importer['username'],
2439                                                                         'to_email'     => $importer['email'],
2440                                                                         'uid'          => $importer['importer_uid'],
2441                                                                         'item'         => $datarray,
2442                                                                         'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2443                                                                         'source_name'  => stripslashes($datarray['author-name']),
2444                                                                         'source_link'  => $datarray['author-link'],
2445                                                                         'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
2446                                                                                 ? $importer['thumb'] : $datarray['author-avatar']),
2447                                                                         'verb'         => ACTIVITY_POST,
2448                                                                         'otype'        => 'item',
2449                                                                         'parent'       => $conv_parent,
2450
2451                                                                 ));
2452
2453                                                                 // only send one notification
2454                                                                 break;
2455                                                         }
2456                                                 }
2457                                         }
2458                                 }
2459                                 continue;
2460                         }
2461                 }
2462
2463                 else {
2464
2465                         // Head post of a conversation. Have we seen it? If not, import it.
2466
2467
2468                         $item_id  = $item->get_id();
2469                         $datarray = get_atom_elements($feed,$item);
2470
2471                         if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2472                                 $ev = bbtoevent($datarray['body']);
2473                                 if(x($ev,'desc') && x($ev,'start')) {
2474                                         $ev['cid'] = $importer['id'];
2475                                         $ev['uid'] = $importer['uid'];
2476                                         $ev['uri'] = $item_id;
2477                                         $ev['edited'] = $datarray['edited'];
2478                                         $ev['private'] = $datarray['private'];
2479
2480                                         $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2481                                                 dbesc($item_id),
2482                                                 intval($importer['uid'])
2483                                         );
2484                                         if(count($r))
2485                                                 $ev['id'] = $r[0]['id'];
2486                                         $xyz = event_store($ev);
2487                                         continue;
2488                                 }
2489                         }
2490
2491                         $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2492                                 dbesc($item_id),
2493                                 intval($importer['importer_uid'])
2494                         );
2495
2496                         // Update content if 'updated' changes
2497
2498                         if(count($r)) {
2499                                 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2500                                         $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2501                                                 dbesc($datarray['title']),
2502                                                 dbesc($datarray['body']),
2503                                                 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2504                                                 dbesc($item_id),
2505                                                 intval($importer['importer_uid'])
2506                                         );
2507                                 }
2508
2509                                 // update last-child if it changes
2510
2511                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2512                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2513                                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2514                                                 intval($allow[0]['data']),
2515                                                 dbesc(datetime_convert()),
2516                                                 dbesc($item_id),
2517                                                 intval($importer['importer_uid'])
2518                                         );
2519                                 }
2520                                 continue;
2521                         }
2522
2523                         // This is my contact on another system, but it's really me.
2524                         // Turn this into a wall post.
2525
2526                         if($importer['remote_self'])
2527                                 $datarray['wall'] = 1;
2528
2529                         $datarray['parent-uri'] = $item_id;
2530                         $datarray['uid'] = $importer['importer_uid'];
2531                         $datarray['contact-id'] = $importer['id'];
2532
2533                         if(! link_compare($datarray['owner-link'],$contact['url'])) {
2534                                 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery, 
2535                                 // but otherwise there's a possible data mixup on the sender's system.
2536                                 // the tgroup delivery code called from item_store will correct it if it's a forum,
2537                                 // but we're going to unconditionally correct it here so that the post will always be owned by our contact. 
2538                                 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2539                                 $datarray['owner-name']   = $importer['senderName'];
2540                                 $datarray['owner-link']   = $importer['url'];
2541                                 $datarray['owner-avatar'] = $importer['thumb'];
2542                         }
2543
2544                         $r = item_store($datarray);
2545                         continue;
2546                 }
2547         }
2548
2549         return 0;
2550         // NOTREACHED
2551
2552 }
2553
2554
2555 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2556         $url = notags(trim($datarray['author-link']));
2557         $name = notags(trim($datarray['author-name']));
2558         $photo = notags(trim($datarray['author-avatar']));
2559
2560         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2561         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2562                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2563
2564         if(is_array($contact)) {
2565                 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2566                         || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2567                         $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2568                                 intval(CONTACT_IS_FRIEND),
2569                                 intval($contact['id']),
2570                                 intval($importer['uid'])
2571                         );
2572                 }
2573                 // send email notification to owner?
2574         }
2575         else {
2576         
2577                 // create contact record
2578
2579                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`, 
2580                         `blocked`, `readonly`, `pending`, `writable` )
2581                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2582                         intval($importer['uid']),
2583                         dbesc(datetime_convert()),
2584                         dbesc($url),
2585                         dbesc(normalise_link($url)),
2586                         dbesc($name),
2587                         dbesc($nick),
2588                         dbesc($photo),
2589                         dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2590                         intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2591                 );
2592                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2593                                 intval($importer['uid']),
2594                                 dbesc($url)
2595                 );
2596                 if(count($r))
2597                                 $contact_record = $r[0];
2598
2599                 // create notification  
2600                 $hash = random_string();
2601
2602                 if(is_array($contact_record)) {
2603                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2604                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2605                                 intval($importer['uid']),
2606                                 intval($contact_record['id']),
2607                                 dbesc($hash),
2608                                 dbesc(datetime_convert())
2609                         );
2610                 }
2611                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2612                         intval($importer['uid'])
2613                 );
2614                 $a = get_app();
2615                 if(count($r)) {
2616                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2617                                 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2618                                 $email = replace_macros($email_tpl, array(
2619                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2620                                         '$url' => $url,
2621                                         '$myname' => $r[0]['username'],
2622                                         '$siteurl' => $a->get_baseurl(),
2623                                         '$sitename' => $a->config['sitename']
2624                                 ));
2625                                 $res = mail($r[0]['email'], 
2626                                         (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2627                                         $email,
2628                                         'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2629                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
2630                                         . 'Content-transfer-encoding: 8bit' );
2631                         
2632                         }
2633                 }
2634         }
2635 }
2636
2637 function lose_follower($importer,$contact,$datarray,$item) {
2638
2639         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2640                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2641                         intval(CONTACT_IS_SHARING),
2642                         intval($contact['id'])
2643                 );
2644         }
2645         else {
2646                 contact_remove($contact['id']);
2647         }
2648 }
2649
2650 function lose_sharer($importer,$contact,$datarray,$item) {
2651
2652         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2653                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2654                         intval(CONTACT_IS_FOLLOWER),
2655                         intval($contact['id'])
2656                 );
2657         }
2658         else {
2659                 contact_remove($contact['id']);
2660         }
2661 }
2662
2663
2664 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2665
2666         if(is_array($importer)) {
2667                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2668                         intval($importer['uid'])
2669                 );
2670         }
2671
2672         // Diaspora has different message-ids in feeds than they do 
2673         // through the direct Diaspora protocol. If we try and use
2674         // the feed, we'll get duplicates. So don't.
2675
2676         if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2677                 return;
2678
2679         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2680
2681         // Use a single verify token, even if multiple hubs
2682
2683         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2684
2685         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2686
2687         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
2688
2689         if(! strlen($contact['hub-verify'])) {
2690                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2691                         dbesc($verify_token),
2692                         intval($contact['id'])
2693                 );
2694         }
2695
2696         post_url($url,$params);                 
2697         return;
2698
2699 }
2700
2701
2702 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2703         $o = '';
2704         if(! $tag)
2705                 return $o;
2706         $name = xmlify($name);
2707         $uri = xmlify($uri);
2708         $h = intval($h);
2709         $w = intval($w);
2710         $photo = xmlify($photo);
2711
2712
2713         $o .= "<$tag>\r\n";
2714         $o .= "<name>$name</name>\r\n";
2715         $o .= "<uri>$uri</uri>\r\n";
2716         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2717         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2718
2719         call_hooks('atom_author', $o);
2720
2721         $o .= "</$tag>\r\n";
2722         return $o;
2723 }
2724
2725 function atom_entry($item,$type,$author,$owner,$comment = false) {
2726
2727         $a = get_app();
2728
2729         if(! $item['parent'])
2730                 return;
2731
2732         if($item['deleted'])
2733                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2734
2735
2736         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2737                 $body = fix_private_photos($item['body'],$owner['uid']);
2738         else
2739                 $body = $item['body'];
2740
2741
2742         $o = "\r\n\r\n<entry>\r\n";
2743
2744         if(is_array($author))
2745                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2746         else
2747                 $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']));
2748         if(strlen($item['owner-name']))
2749                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2750
2751         if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2752                 $o .= '<thr:in-reply-to ref="' . xmlify($item['parent-uri']) . '" type="text/html" href="' .  xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
2753
2754         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2755         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2756         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2757         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2758         $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2759         $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2760         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2761         if($comment)
2762                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2763
2764         if($item['location']) {
2765                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2766                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2767         }
2768
2769         if($item['coord'])
2770                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2771
2772         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2773                 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2774
2775         if($item['extid'])
2776                 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2777         if($item['bookmark'])
2778                 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2779
2780         if($item['app'])
2781                 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2782
2783         if($item['guid'])
2784                 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2785
2786         if($item['signed_text']) {
2787                 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2788                 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2789         }
2790
2791         $verb = construct_verb($item);
2792         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2793         $actobj = construct_activity_object($item);
2794         if(strlen($actobj))
2795                 $o .= $actobj;
2796         $actarg = construct_activity_target($item);
2797         if(strlen($actarg))
2798                 $o .= $actarg;
2799
2800         $tags = item_getfeedtags($item);
2801         if(count($tags)) {
2802                 foreach($tags as $t) {
2803                         $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2804                 }
2805         }
2806
2807         $o .= item_getfeedattach($item);
2808
2809         $mentioned = get_mentions($item);
2810         if($mentioned)
2811                 $o .= $mentioned;
2812         
2813         call_hooks('atom_entry', $o);
2814
2815         $o .= '</entry>' . "\r\n";
2816         
2817         return $o;
2818 }
2819
2820 function fix_private_photos($s,$uid) {
2821         $a = get_app();
2822         logger('fix_private_photos');
2823
2824         if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2825                 $image = $matches[1];
2826                 logger('fix_private_photos: found photo ' . $image);
2827                 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
2828                         $i = basename($image);
2829                         $i = str_replace('.jpg','',$i);
2830                         $x = strpos($i,'-');
2831                         if($x) {
2832                                 $res = substr($i,$x+1);
2833                                 $i = substr($i,0,$x);
2834                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2835                                         dbesc($i),
2836                                         intval($res),
2837                                         intval($uid)
2838                                 );
2839                                 if(count($r)) {
2840                                         logger('replacing photo');
2841                                         $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2842                                 }
2843                         }
2844                         logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2845                 }       
2846         }
2847         return($s);
2848 }
2849
2850
2851
2852 function item_getfeedtags($item) {
2853         $ret = array();
2854         $matches = false;
2855         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2856         if($cnt) {
2857                 for($x = 0; $x < $cnt; $x ++) {
2858                         if($matches[1][$x])
2859                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
2860                 }
2861         }
2862         $matches = false; 
2863         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2864         if($cnt) {
2865                 for($x = 0; $x < $cnt; $x ++) {
2866                         if($matches[1][$x])
2867                                 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
2868                 }
2869         } 
2870         return $ret;
2871 }
2872
2873 function item_getfeedattach($item) {
2874         $ret = '';
2875         $arr = explode(',',$item['attach']);
2876         if(count($arr)) {
2877                 foreach($arr as $r) {
2878                         $matches = false;
2879                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
2880                         if($cnt) {
2881                                 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
2882                                 if(intval($matches[2]))
2883                                         $ret .= 'length="' . intval($matches[2]) . '" ';
2884                                 if($matches[4] !== ' ')
2885                                         $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
2886                                 $ret .= ' />' . "\r\n";
2887                         }
2888                 }
2889         }
2890         return $ret;
2891 }
2892
2893
2894         
2895 function item_expire($uid,$days) {
2896
2897         if((! $uid) || (! $days))
2898                 return;
2899
2900         $r = q("SELECT * FROM `item` 
2901                 WHERE `uid` = %d 
2902                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
2903                 AND `id` = `parent` 
2904                 AND `deleted` = 0",
2905                 intval($uid),
2906                 intval($days)
2907         );
2908
2909         if(! count($r))
2910                 return;
2911
2912         $expire_items = get_pconfig($uid, 'expire','items');
2913         $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
2914         
2915         $expire_notes = get_pconfig($uid, 'expire','notes');
2916         $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
2917
2918         $expire_starred = get_pconfig($uid, 'expire','starred');
2919         $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
2920         
2921         $expire_photos = get_pconfig($uid, 'expire','photos');
2922         $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
2923  
2924         logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2925
2926         foreach($r as $item) {
2927
2928                 // Only expire posts, not photos and photo comments
2929
2930                 if($expire_photos==0 && strlen($item['resource-id']))
2931                         continue;
2932                 if($expire_starred==0 && intval($item['starred']))
2933                         continue;
2934                 if($expire_notes==0 && $item['type']=='note')
2935                         continue;
2936                 if($expire_items==0 && $item['type']!='note')
2937                         continue;
2938
2939                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2940                         dbesc(datetime_convert()),
2941                         dbesc(datetime_convert()),
2942                         intval($item['id'])
2943                 );
2944
2945                 // kill the kids
2946
2947                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2948                         dbesc(datetime_convert()),
2949                         dbesc(datetime_convert()),
2950                         dbesc($item['parent-uri']),
2951                         intval($item['uid'])
2952                 );
2953
2954         }
2955
2956         proc_run('php',"include/notifier.php","expire","$uid");
2957         
2958 }
2959
2960
2961 function drop_items($items) {
2962         $uid = 0;
2963
2964         if((! local_user()) && (! $remote_user()))
2965                 return;
2966
2967         if(count($items)) {
2968                 foreach($items as $item) {
2969                         $owner = drop_item($item,false);
2970                         if($owner && ! $uid)
2971                                 $uid = $owner;
2972                 }
2973         }
2974
2975         // multiple threads may have been deleted, send an expire notification
2976
2977         if($uid)
2978                 proc_run('php',"include/notifier.php","expire","$uid");
2979 }
2980
2981
2982 function drop_item($id,$interactive = true) {
2983
2984         $a = get_app();
2985
2986         // locate item to be deleted
2987
2988         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
2989                 intval($id)
2990         );
2991
2992         if(! count($r)) {
2993                 if(! $interactive)
2994                         return 0;
2995                 notice( t('Item not found.') . EOL);
2996                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2997         }
2998
2999         $item = $r[0];
3000
3001         $owner = $item['uid'];
3002
3003         // check if logged in user is either the author or owner of this item
3004
3005         if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3006
3007                 // delete the item
3008
3009                 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3010                         dbesc(datetime_convert()),
3011                         dbesc(datetime_convert()),
3012                         intval($item['id'])
3013                 );
3014
3015                 // If item is a link to a photo resource, nuke all the associated photos 
3016                 // (visitors will not have photo resources)
3017                 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3018                 // generate a resource-id and therefore aren't intimately linked to the item. 
3019
3020                 if(strlen($item['resource-id'])) {
3021                         q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3022                                 dbesc($item['resource-id']),
3023                                 intval($item['uid'])
3024                         );
3025                         // ignore the result
3026                 }
3027
3028                 // If item is a link to an event, nuke the event record.
3029
3030                 if(intval($item['event-id'])) {
3031                         q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3032                                 intval($item['event-id']),
3033                                 intval($item['uid'])
3034                         );
3035                         // ignore the result
3036                 }
3037
3038
3039                 // If it's the parent of a comment thread, kill all the kids
3040
3041                 if($item['uri'] == $item['parent-uri']) {
3042                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3043                                 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3044                                 dbesc(datetime_convert()),
3045                                 dbesc(datetime_convert()),
3046                                 dbesc($item['parent-uri']),
3047                                 intval($item['uid'])
3048                         );
3049                         // ignore the result
3050                 }
3051                 else {
3052                         // ensure that last-child is set in case the comment that had it just got wiped.
3053                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3054                                 dbesc(datetime_convert()),
3055                                 dbesc($item['parent-uri']),
3056                                 intval($item['uid'])
3057                         );
3058                         // who is the last child now? 
3059                         $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",
3060                                 dbesc($item['parent-uri']),
3061                                 intval($item['uid'])
3062                         );
3063                         if(count($r)) {
3064                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3065                                         intval($r[0]['id'])
3066                                 );
3067                         }       
3068                 }
3069                 $drop_id = intval($item['id']);
3070                         
3071                 // send the notification upstream/downstream as the case may be
3072
3073                 if(! $interactive)
3074                         return $owner;
3075
3076                 proc_run('php',"include/notifier.php","drop","$drop_id");
3077                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3078                 //NOTREACHED
3079         }
3080         else {
3081                 if(! $interactive)
3082                         return 0;
3083                 notice( t('Permission denied.') . EOL);
3084                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3085                 //NOTREACHED
3086         }
3087         
3088 }