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