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