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