]> git.mxchange.org Git - friendica.git/blob - include/items.php
ostatus auto completion now seems to work.
[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 require_once('include/Photo.php');
8 require_once('include/tags.php');
9 require_once('include/text.php');
10 require_once('include/email.php');
11 require_once('include/ostatus_conversation.php');
12
13 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
14
15
16         $sitefeed    = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
17         $public_feed = (($dfrn_id) ? false : true);
18         $starred     = false;   // not yet implemented, possible security issues
19         $converse    = false;
20
21         if($public_feed && $a->argc > 2) {
22                 for($x = 2; $x < $a->argc; $x++) {
23                         if($a->argv[$x] == 'converse')
24                                 $converse = true;
25                         if($a->argv[$x] == 'starred')
26                                 $starred = true;
27                         if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
28                                 $category = $a->argv[$x+1];
29                 }
30         }
31
32
33
34         // default permissions - anonymous user
35
36         $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid`  = '' AND `deny_gid`  = '' ";
37
38         $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
39                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
40                 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
41                 dbesc($owner_nick)
42         );
43
44         if(! count($r))
45                 killme();
46
47         $owner = $r[0];
48         $owner_id = $owner['user_uid'];
49         $owner_nick = $owner['nickname'];
50
51         $birthday = feed_birthday($owner_id,$owner['timezone']);
52
53         if(! $public_feed) {
54
55                 $sql_extra = '';
56                 switch($direction) {
57                         case (-1):
58                                 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
59                                 $my_id = $dfrn_id;
60                                 break;
61                         case 0:
62                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
63                                 $my_id = '1:' . $dfrn_id;
64                                 break;
65                         case 1:
66                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
67                                 $my_id = '0:' . $dfrn_id;
68                                 break;
69                         default:
70                                 return false;
71                                 break; // NOTREACHED
72                 }
73
74                 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
75                         intval($owner_id)
76                 );
77
78                 if(! count($r))
79                         killme();
80
81                 $contact = $r[0];
82                 require_once('include/security.php');
83                 $groups = init_groups_visitor($contact['id']);
84
85                 if(count($groups)) {
86                         for($x = 0; $x < count($groups); $x ++) 
87                                 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
88                         $gs = implode('|', $groups);
89                 }
90                 else
91                         $gs = '<<>>' ; // Impossible to match 
92
93                 $sql_extra = sprintf(" 
94                         AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' ) 
95                         AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' ) 
96                         AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
97                         AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s') 
98                 ",
99                         intval($contact['id']),
100                         intval($contact['id']),
101                         dbesc($gs),
102                         dbesc($gs)
103                 );
104         }
105
106         if($public_feed)
107                 $sort = 'DESC';
108         else
109                 $sort = 'ASC';
110
111         if(! strlen($last_update))
112                 $last_update = 'now -30 days';
113
114         if(isset($category)) {
115                 $sql_extra .= file_tag_file_query('item',$category,'category');
116         }
117
118         if($public_feed) {
119                 if(! $converse)
120                         $sql_extra .= " AND `contact`.`self` = 1 ";
121         }
122
123         $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
124
125         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
126                 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`, 
127                 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
128                 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`, 
129                 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
130                 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
131                 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
132                 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
133                 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0 
134                 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
135                 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
136                 $sql_extra
137                 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
138                 intval($owner_id),
139                 dbesc($check_date),
140                 dbesc($check_date),
141                 dbesc($sort)
142         );
143
144         // Will check further below if this actually returned results.
145         // We will provide an empty feed if that is the case.
146
147         $items = $r;
148
149         $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
150
151         $atom = '';
152
153         $hubxml = feed_hublinks();
154
155         $salmon = feed_salmonlinks($owner_nick);
156
157         $atom .= replace_macros($feed_template, array(
158                 '$version'      => xmlify(FRIENDICA_VERSION),
159                 '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
160                 '$feed_title'   => xmlify($owner['name']),
161                 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
162                 '$hub'          => $hubxml,
163                 '$salmon'       => $salmon,
164                 '$name'         => xmlify($owner['name']),
165                 '$profile_page' => xmlify($owner['url']),
166                 '$photo'        => xmlify($owner['photo']),
167                 '$thumb'        => xmlify($owner['thumb']),
168                 '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
169                 '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
170                 '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) , 
171                 '$birthday'     => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
172                 '$community'    => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
173         ));
174
175         call_hooks('atom_feed', $atom);
176
177         if(! count($items)) {
178
179                 call_hooks('atom_feed_end', $atom);
180
181                 $atom .= '</feed>' . "\r\n";
182                 return $atom;
183         }
184
185         foreach($items as $item) {
186
187                 // prevent private email from leaking.
188                 if($item['network'] === NETWORK_MAIL)
189                         continue;
190
191                 // public feeds get html, our own nodes use bbcode
192
193                 if($public_feed) {
194                         $type = 'html';
195                         // catch any email that's in a public conversation and make sure it doesn't leak
196                         if($item['private'])
197                                 continue;
198                 }
199                 else {
200                         $type = 'text';
201                 }
202
203                 $atom .= atom_entry($item,$type,null,$owner,true);
204         }
205
206         call_hooks('atom_feed_end', $atom);
207
208         $atom .= '</feed>' . "\r\n";
209
210         return $atom;
211 }
212
213
214 function construct_verb($item) {
215         if($item['verb'])
216                 return $item['verb'];
217         return ACTIVITY_POST;
218 }
219
220 function construct_activity_object($item) {
221
222         if($item['object']) {
223                 $o = '<as:object>' . "\r\n";
224                 $r = parse_xml_string($item['object'],false);
225
226
227                 if(! $r)
228                         return '';
229                 if($r->type)
230                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
231                 if($r->id)
232                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
233                 if($r->title)
234                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
235                 if($r->link) {
236                         if(substr($r->link,0,1) === '<') {
237                                 // patch up some facebook "like" activity objects that got stored incorrectly
238                                 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
239                                 // we can probably remove this hack here and in the following function in a few months time.
240                                 if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
241                                         $r->link = str_replace('&','&amp;', $r->link);
242                                 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
243                                 $o .= $r->link;
244                         }
245                         else
246                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
247                 }
248                 if($r->content)
249                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
250                 $o .= '</as:object>' . "\r\n";
251                 return $o;
252         }
253
254         return '';
255
256
257 function construct_activity_target($item) {
258
259         if($item['target']) {
260                 $o = '<as:target>' . "\r\n";
261                 $r = parse_xml_string($item['target'],false);
262                 if(! $r)
263                         return '';
264                 if($r->type)
265                         $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
266                 if($r->id)
267                         $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
268                 if($r->title)
269                         $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
270                 if($r->link) {
271                         if(substr($r->link,0,1) === '<') {
272                                 if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
273                                         $r->link = str_replace('&','&amp;', $r->link);
274                                 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
275                                 $o .= $r->link;
276                         }
277                         else
278                                 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
279                 }
280                 if($r->content)
281                         $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
282                 $o .= '</as:target>' . "\r\n";
283                 return $o;
284         }
285
286         return '';
287 }
288
289 /* limit_body_size()
290  *
291  *              The purpose of this function is to apply system message length limits to
292  *              imported messages without including any embedded photos in the length
293  */
294 if(! function_exists('limit_body_size')) {
295 function limit_body_size($body) {
296
297         logger('limit_body_size: start', LOGGER_DEBUG);
298
299         $maxlen = get_max_import_size();
300
301         // If the length of the body, including the embedded images, is smaller
302         // than the maximum, then don't waste time looking for the images
303         if($maxlen && (strlen($body) > $maxlen)) {
304
305                 logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
306
307                 $orig_body = $body;
308                 $new_body = '';
309                 $textlen = 0;
310                 $max_found = false;
311
312                 $img_start = strpos($orig_body, '[img');
313                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
314                 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
315                 while(($img_st_close !== false) && ($img_end !== false)) {
316
317                         $img_st_close++; // make it point to AFTER the closing bracket
318                         $img_end += $img_start;
319                         $img_end += strlen('[/img]');
320
321                         if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
322                                 // This is an embedded image
323
324                                 if( ($textlen + $img_start) > $maxlen ) {
325                                         if($textlen < $maxlen) {
326                                                 logger('limit_body_size: the limit happens before an embedded image', LOGGER_DEBUG);
327                                                 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
328                                                 $textlen = $maxlen;
329                                         }
330                                 }
331                                 else {
332                                         $new_body = $new_body . substr($orig_body, 0, $img_start);
333                                         $textlen += $img_start;
334                                 }
335
336                                 $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
337                         }
338                         else {
339
340                                 if( ($textlen + $img_end) > $maxlen ) {
341                                         if($textlen < $maxlen) {
342                                                 logger('limit_body_size: the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
343                                                 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
344                                                 $textlen = $maxlen;
345                                         }
346                                 }
347                                 else {
348                                         $new_body = $new_body . substr($orig_body, 0, $img_end);
349                                         $textlen += $img_end;
350                                 }
351                         }
352                         $orig_body = substr($orig_body, $img_end);
353
354                         if($orig_body === false) // in case the body ends on a closing image tag
355                                 $orig_body = '';
356
357                         $img_start = strpos($orig_body, '[img');
358                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
359                         $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
360                 }
361
362                 if( ($textlen + strlen($orig_body)) > $maxlen) {
363                         if($textlen < $maxlen) {
364                                 logger('limit_body_size: the limit happens after the end of the last image', LOGGER_DEBUG);
365                                 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
366                                 $textlen = $maxlen;
367                         }
368                 }
369                 else {
370                         logger('limit_body_size: the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
371                         $new_body = $new_body . $orig_body;
372                         $textlen += strlen($orig_body);
373                 }
374
375                 return $new_body;
376         }
377         else
378                 return $body;
379 }}
380
381 function title_is_body($title, $body) {
382
383         $title = strip_tags($title);
384         $title = trim($title);
385         $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
386         $title = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $title);
387
388         $body = strip_tags($body);
389         $body = trim($body);
390         $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
391         $body = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $body);
392
393         if (strlen($title) < strlen($body))
394                 $body = substr($body, 0, strlen($title));
395
396         if (($title != $body) and (substr($title, -3) == "...")) {
397                 $pos = strrpos($title, "...");
398                 if ($pos > 0) {
399                         $title = substr($title, 0, $pos);
400                         $body = substr($body, 0, $pos);
401                 }
402         }
403
404         return($title == $body);
405 }
406
407
408
409 function get_atom_elements($feed,$item) {
410
411         require_once('library/HTMLPurifier.auto.php');
412         require_once('include/html2bbcode.php');
413
414         $best_photo = array();
415
416         $res = array();
417
418         $author = $item->get_author();
419         if($author) { 
420                 $res['author-name'] = unxmlify($author->get_name());
421                 $res['author-link'] = unxmlify($author->get_link());
422         }
423         else {
424                 $res['author-name'] = unxmlify($feed->get_title());
425                 $res['author-link'] = unxmlify($feed->get_permalink());
426         }
427         $res['uri'] = unxmlify($item->get_id());
428         $res['title'] = unxmlify($item->get_title());
429         $res['body'] = unxmlify($item->get_content());
430         $res['plink'] = unxmlify($item->get_link(0));
431
432         // removing the content of the title if its identically to the body
433         // This helps with auto generated titles e.g. from tumblr
434         if (title_is_body($res["title"], $res["body"]))
435                 $res['title'] = "";
436
437         if($res['plink'])
438                 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
439         else
440                 $base_url = '';
441
442         // look for a photo. We should check media size and find the best one,
443         // but for now let's just find any author photo
444
445         $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
446
447         if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
448                 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
449                 foreach($base as $link) {
450                         if(!x($res, 'author-avatar') || !$res['author-avatar']) {
451                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
452                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
453                         }
454                 }
455         }
456
457         $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
458
459         if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
460                 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
461                 if($base && count($base)) {
462                         foreach($base as $link) {
463                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
464                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
465                                 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
466                                         if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
467                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
468                                 }
469                         }
470                 }
471         }
472
473         // No photo/profile-link on the item - look at the feed level
474
475         if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
476                 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
477                 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
478                         $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
479                         foreach($base as $link) {
480                                 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
481                                         $res['author-link'] = unxmlify($link['attribs']['']['href']);
482                                 if(! $res['author-avatar']) {
483                                         if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
484                                                 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
485                                 }
486                         }
487                 }
488
489                 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
490
491                 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
492                         $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
493
494                         if($base && count($base)) {
495                                 foreach($base as $link) {
496                                         if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
497                                                 $res['author-link'] = unxmlify($link['attribs']['']['href']);
498                                         if(! (x($res,'author-avatar'))) {
499                                                 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
500                                                         $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
501                                         }
502                                 }
503                         }
504                 }
505         }
506
507         $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
508         if($apps && $apps[0]['attribs']['']['source']) {
509                 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
510                 if($res['app'] === 'web')
511                         $res['app'] = 'OStatus';
512         }
513
514         // base64 encoded json structure representing Diaspora signature
515
516         $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
517         if($dsig) {
518                 $res['dsprsig'] = unxmlify($dsig[0]['data']);
519         }
520
521         $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
522         if($dguid)
523                 $res['guid'] = unxmlify($dguid[0]['data']);
524
525         $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
526         if($bm)
527                 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
528
529
530         /**
531          * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
532          */
533
534         $have_real_body = false;
535
536         $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
537         if($rawenv) {
538                 $have_real_body = true;
539                 $res['body'] = $rawenv[0]['data'];
540                 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
541                 // make sure nobody is trying to sneak some html tags by us
542                 $res['body'] = notags(base64url_decode($res['body']));
543         }
544
545         
546         $res['body'] = limit_body_size($res['body']);
547
548         // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust 
549         // the content type. Our own network only emits text normally, though it might have been converted to 
550         // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
551         // have to assume it is all html and needs to be purified.
552
553         // It doesn't matter all that much security wise - because before this content is used anywhere, we are 
554         // going to escape any tags we find regardless, but this lets us import a limited subset of html from 
555         // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining 
556         // html.
557
558         if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
559
560                 $res['body'] = reltoabs($res['body'],$base_url);
561
562                 $res['body'] = html2bb_video($res['body']);
563
564                 $res['body'] = oembed_html2bbcode($res['body']);
565
566                 $config = HTMLPurifier_Config::createDefault();
567                 $config->set('Cache.DefinitionImpl', null);
568
569                 // we shouldn't need a whitelist, because the bbcode converter
570                 // will strip out any unsupported tags.
571
572                 $purifier = new HTMLPurifier($config);
573                 $res['body'] = $purifier->purify($res['body']);
574
575                 $res['body'] = @html2bbcode($res['body']);
576
577
578         }
579         elseif(! $have_real_body) {
580
581                 // it's not one of our messages and it has no tags
582                 // so it's probably just text. We'll escape it just to be safe.
583
584                 $res['body'] = escape_tags($res['body']);
585         }
586
587
588         // this tag is obsolete but we keep it for really old sites
589
590         $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
591         if($allow && $allow[0]['data'] == 1)
592                 $res['last-child'] = 1;
593         else
594                 $res['last-child'] = 0;
595
596         $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
597         if($private && intval($private[0]['data']) > 0)
598                 $res['private'] = intval($private[0]['data']);
599         else
600                 $res['private'] = 0;
601
602         $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
603         if($extid && $extid[0]['data'])
604                 $res['extid'] = $extid[0]['data'];
605
606         $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
607         if($rawlocation)
608                 $res['location'] = unxmlify($rawlocation[0]['data']);
609
610
611         $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
612         if($rawcreated)
613                 $res['created'] = unxmlify($rawcreated[0]['data']);
614
615
616         $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
617         if($rawedited)
618                 $res['edited'] = unxmlify($rawedited[0]['data']);
619
620         if((x($res,'edited')) && (! (x($res,'created'))))
621                 $res['created'] = $res['edited']; 
622
623         if(! $res['created'])
624                 $res['created'] = $item->get_date('c');
625
626         if(! $res['edited'])
627                 $res['edited'] = $item->get_date('c');
628
629
630         // Disallow time travelling posts
631
632         $d1 = strtotime($res['created']);
633         $d2 = strtotime($res['edited']);
634         $d3 = strtotime('now');
635
636         if($d1 > $d3)
637                 $res['created'] = datetime_convert();
638         if($d2 > $d3)
639                 $res['edited'] = datetime_convert();
640
641         $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
642         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
643                 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
644         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
645                 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
646         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
647                 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
648         elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
649                 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
650
651         if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
652                 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
653
654                 foreach($base as $link) {
655                         if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
656                                 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
657                                         $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
658                         }
659                 }
660         }
661
662         $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
663         if($rawgeo)
664                 $res['coord'] = unxmlify($rawgeo[0]['data']);
665
666
667         $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
668
669         // select between supported verbs
670
671         if($rawverb) {
672                 $res['verb'] = unxmlify($rawverb[0]['data']);
673         }
674
675         // translate OStatus unfollow to activity streams if it happened to get selected
676
677         if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
678                 $res['verb'] = ACTIVITY_UNFOLLOW;
679
680         $cats = $item->get_categories();
681         if($cats) {
682                 $tag_arr = array();
683                 foreach($cats as $cat) {
684                         $term = $cat->get_term();
685                         if(! $term)
686                                 $term = $cat->get_label();
687                         $scheme = $cat->get_scheme();
688                         if($scheme && $term && stristr($scheme,'X-DFRN:'))
689                                 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
690                         elseif($term)
691                                 $tag_arr[] = notags(trim($term));
692                 }
693                 $res['tag'] =  implode(',', $tag_arr);
694         }
695
696         $attach = $item->get_enclosures();
697         if($attach) {
698                 $att_arr = array();
699                 foreach($attach as $att) {
700                         $len   = intval($att->get_length());
701                         $link  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
702                         $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
703                         $type  = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
704                         if(strpos($type,';'))
705                                 $type = substr($type,0,strpos($type,';'));
706                         if((! $link) || (strpos($link,'http') !== 0))
707                                 continue;
708
709                         if(! $title)
710                                 $title = ' ';
711                         if(! $type)
712                                 $type = 'application/octet-stream';
713
714                         $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]'; 
715                 }
716                 $res['attach'] = implode(',', $att_arr);
717         }
718
719         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
720
721         if($rawobj) {
722                 $res['object'] = '<object>' . "\n";
723                 $child = $rawobj[0]['child'];
724                 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
725                         $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
726                         $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
727                 }
728                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
729                         $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
730                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
731                         $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
732                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
733                         $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
734                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
735                         $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
736                         if(! $body)
737                                 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
738                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
739                         $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
740                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
741
742                                 $body = html2bb_video($body);
743
744                                 $config = HTMLPurifier_Config::createDefault();
745                                 $config->set('Cache.DefinitionImpl', null);
746
747                                 $purifier = new HTMLPurifier($config);
748                                 $body = $purifier->purify($body);
749                                 $body = html2bbcode($body);
750                         }
751
752                         $res['object'] .= '<content>' . $body . '</content>' . "\n";
753                 }
754
755                 $res['object'] .= '</object>' . "\n";
756         }
757
758         $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
759
760         if($rawobj) {
761                 $res['target'] = '<target>' . "\n";
762                 $child = $rawobj[0]['child'];
763                 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
764                         $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
765                 }
766                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
767                         $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
768                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
769                         $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
770                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
771                         $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
772                 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
773                         $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
774                         if(! $body)
775                                 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
776                         // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
777                         $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
778                         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
779
780                                 $body = html2bb_video($body);
781
782                                 $config = HTMLPurifier_Config::createDefault();
783                                 $config->set('Cache.DefinitionImpl', null);
784
785                                 $purifier = new HTMLPurifier($config);
786                                 $body = $purifier->purify($body);
787                                 $body = html2bbcode($body);
788                         }
789
790                         $res['target'] .= '<content>' . $body . '</content>' . "\n";
791                 }
792
793                 $res['target'] .= '</target>' . "\n";
794         }
795
796         // This is some experimental stuff. By now retweets are shown with "RT:"
797         // But: There is data so that the message could be shown similar to native retweets
798         // There is some better way to parse this array - but it didn't worked for me.
799         $child = $item->feed->data["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["feed"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["entry"][0]["child"]["http://activitystrea.ms/spec/1.0/"][object][0]["child"];
800         if (is_array($child)) {
801                 logger('get_atom_elements: Looking for status.net repeated message');
802
803                 $message = $child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["content"][0]["data"];
804                 $orig_uri = $child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["id"][0]["data"];
805                 $author = $child[SIMPLEPIE_NAMESPACE_ATOM_10]["author"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10];
806                 $uri = $author["uri"][0]["data"];
807                 $name = $author["name"][0]["data"];
808                 $avatar = @array_shift($author["link"][2]["attribs"]);
809                 $avatar = $avatar["href"];
810
811                 if (($name != "") and ($uri != "") and ($avatar != "") and ($message != "")) {
812                         logger('get_atom_elements: fixing sender of repeated message.');
813
814                         if (intval(get_config('system','new_share'))) {
815                                 $prefix = "[share author='".str_replace("'", "&#039;",$name).
816                                                 "' profile='".$uri.
817                                                 "' avatar='".$avatar.
818                                                 "' link='".$orig_uri."']";
819
820                                 $res["body"] = $prefix.html2bbcode($message)."[/share]";
821                         } else {
822                                 $res["owner-name"] = $res["author-name"];
823                                 $res["owner-link"] = $res["author-link"];
824                                 $res["owner-avatar"] = $res["author-avatar"];
825
826                                 $res["author-name"] = $name;
827                                 $res["author-link"] = $uri;
828                                 $res["author-avatar"] = $avatar;
829
830                                 $res["body"] = html2bbcode($message);
831                         }
832                 }
833         }
834
835         // Search for ostatus conversation url
836         $links = $item->feed->data["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["feed"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["entry"][0]["child"]["http://www.w3.org/2005/Atom"]["link"];
837
838         foreach ($links as $link) {
839                 $conversation = array_shift($link["attribs"]);
840
841                 if ($conversation["rel"] == "ostatus:conversation") {
842                         $res["ostatus_conversation"] = $conversation["href"];
843                         logger('get_atom_elements: found conversation url '.$res["ostatus_conversation"]);
844                 }
845         };
846
847         $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
848
849         call_hooks('parse_atom', $arr);
850
851         //if (($res["title"] != "") or (strpos($res["body"], "RT @") > 0)) {
852         //if (strpos($res["body"], "RT @") !== false) {
853         /*if (strpos($res["body"], "@") !== false) {
854                 $debugfile = tempnam("/var/www/virtual/pirati.ca/phptmp/", "item-res2-");
855                 file_put_contents($debugfile, serialize($arr));
856         }*/
857
858         return $res;
859 }
860
861 function encode_rel_links($links) {
862         $o = '';
863         if(! ((is_array($links)) && (count($links))))
864                 return $o;
865         foreach($links as $link) {
866                 $o .= '<link ';
867                 if($link['attribs']['']['rel'])
868                         $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
869                 if($link['attribs']['']['type'])
870                         $o .= 'type="' . $link['attribs']['']['type'] . '" ';
871                 if($link['attribs']['']['href'])
872                         $o .= 'href="' . $link['attribs']['']['href'] . '" ';
873                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
874                         $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
875                 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
876                         $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
877                 $o .= ' />' . "\n" ;
878         }
879         return xmlify($o);
880 }
881
882
883
884 function item_store($arr,$force_parent = false) {
885
886         // If a Diaspora signature structure was passed in, pull it out of the 
887         // item array and set it aside for later storage.
888
889         $dsprsig = null;
890         if(x($arr,'dsprsig')) {
891                 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
892                 unset($arr['dsprsig']);
893         }
894
895         // if an OStatus conversation url was passed in, it is stored and then
896         // removed from the array.
897         $ostatus_conversation = null;
898
899         if (isset($arr["ostatus_conversation"])) {
900                 $ostatus_conversation = $arr["ostatus_conversation"];
901                 unset($arr["ostatus_conversation"]);
902         }
903
904         if(x($arr, 'gravity'))
905                 $arr['gravity'] = intval($arr['gravity']);
906         elseif($arr['parent-uri'] === $arr['uri'])
907                 $arr['gravity'] = 0;
908         elseif(activity_match($arr['verb'],ACTIVITY_POST))
909                 $arr['gravity'] = 6;
910         else
911                 $arr['gravity'] = 6;   // extensible catchall
912
913         if(! x($arr,'type'))
914                 $arr['type']      = 'remote';
915
916         // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
917
918         if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false)) 
919                 $arr['body'] = strip_tags($arr['body']);
920
921
922         if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
923                 require_once('library/langdet/Text/LanguageDetect.php');
924                 $naked_body = preg_replace('/\[(.+?)\]/','',$arr['body']);
925                 $l = new Text_LanguageDetect;
926                 //$lng = $l->detectConfidence($naked_body);
927                 //$arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
928                 $lng = $l->detect($naked_body, 3);
929
930                 if (sizeof($lng) > 0) {
931                         $postopts = "";
932
933                         foreach ($lng as $language => $score) {
934                                 if ($postopts == "")
935                                         $postopts = "lang=";
936                                 else
937                                         $postopts .= ":";
938
939                                 $postopts .= $language.";".$score;
940                         }
941                         $arr['postopts'] = $postopts;
942                 }
943         }
944
945         $arr['wall']          = ((x($arr,'wall'))          ? intval($arr['wall'])                : 0);
946         $arr['uri']           = ((x($arr,'uri'))           ? notags(trim($arr['uri']))           : random_string());
947         $arr['extid']         = ((x($arr,'extid'))         ? notags(trim($arr['extid']))         : '');
948         $arr['author-name']   = ((x($arr,'author-name'))   ? notags(trim($arr['author-name']))   : '');
949         $arr['author-link']   = ((x($arr,'author-link'))   ? notags(trim($arr['author-link']))   : '');
950         $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
951         $arr['owner-name']    = ((x($arr,'owner-name'))    ? notags(trim($arr['owner-name']))    : '');
952         $arr['owner-link']    = ((x($arr,'owner-link'))    ? notags(trim($arr['owner-link']))    : '');
953         $arr['owner-avatar']  = ((x($arr,'owner-avatar'))  ? notags(trim($arr['owner-avatar']))  : '');
954         $arr['created']       = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
955         $arr['edited']        = ((x($arr,'edited')  !== false) ? datetime_convert('UTC','UTC',$arr['edited'])  : datetime_convert());
956         $arr['commented']     = datetime_convert();
957         $arr['received']      = datetime_convert();
958         $arr['changed']       = datetime_convert();
959         $arr['title']         = ((x($arr,'title'))         ? notags(trim($arr['title']))         : '');
960         $arr['location']      = ((x($arr,'location'))      ? notags(trim($arr['location']))      : '');
961         $arr['coord']         = ((x($arr,'coord'))         ? notags(trim($arr['coord']))         : '');
962         $arr['last-child']    = ((x($arr,'last-child'))    ? intval($arr['last-child'])          : 0 );
963         $arr['visible']       = ((x($arr,'visible') !== false) ? intval($arr['visible'])         : 1 );
964         $arr['deleted']       = 0;
965         $arr['parent-uri']    = ((x($arr,'parent-uri'))    ? notags(trim($arr['parent-uri']))    : '');
966         $arr['verb']          = ((x($arr,'verb'))          ? notags(trim($arr['verb']))          : '');
967         $arr['object-type']   = ((x($arr,'object-type'))   ? notags(trim($arr['object-type']))   : '');
968         $arr['object']        = ((x($arr,'object'))        ? trim($arr['object'])                : '');
969         $arr['target-type']   = ((x($arr,'target-type'))   ? notags(trim($arr['target-type']))   : '');
970         $arr['target']        = ((x($arr,'target'))        ? trim($arr['target'])                : '');
971         $arr['plink']         = ((x($arr,'plink'))         ? notags(trim($arr['plink']))         : '');
972         $arr['allow_cid']     = ((x($arr,'allow_cid'))     ? trim($arr['allow_cid'])             : '');
973         $arr['allow_gid']     = ((x($arr,'allow_gid'))     ? trim($arr['allow_gid'])             : '');
974         $arr['deny_cid']      = ((x($arr,'deny_cid'))      ? trim($arr['deny_cid'])              : '');
975         $arr['deny_gid']      = ((x($arr,'deny_gid'))      ? trim($arr['deny_gid'])              : '');
976         $arr['private']       = ((x($arr,'private'))       ? intval($arr['private'])             : 0 );
977         $arr['bookmark']      = ((x($arr,'bookmark'))      ? intval($arr['bookmark'])            : 0 );
978         $arr['body']          = ((x($arr,'body'))          ? trim($arr['body'])                  : '');
979         $arr['tag']           = ((x($arr,'tag'))           ? notags(trim($arr['tag']))           : '');
980         $arr['attach']        = ((x($arr,'attach'))        ? notags(trim($arr['attach']))        : '');
981         $arr['app']           = ((x($arr,'app'))           ? notags(trim($arr['app']))           : '');
982         $arr['origin']        = ((x($arr,'origin'))        ? intval($arr['origin'])              : 0 );
983         $arr['guid']          = ((x($arr,'guid'))          ? notags(trim($arr['guid']))          : get_guid());
984
985
986         $arr['thr-parent'] = $arr['parent-uri'];
987         if($arr['parent-uri'] === $arr['uri']) {
988                 $parent_id = 0;
989                 $parent_deleted = 0;
990                 $allow_cid = $arr['allow_cid'];
991                 $allow_gid = $arr['allow_gid'];
992                 $deny_cid  = $arr['deny_cid'];
993                 $deny_gid  = $arr['deny_gid'];
994         }
995         else {
996
997                 // find the parent and snarf the item id and ACLs
998                 // and anything else we need to inherit
999
1000                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
1001                         dbesc($arr['parent-uri']),
1002                         intval($arr['uid'])
1003                 );
1004
1005                 if(count($r)) {
1006
1007                         // is the new message multi-level threaded?
1008                         // even though we don't support it now, preserve the info
1009                         // and re-attach to the conversation parent.
1010
1011                         if($r[0]['uri'] != $r[0]['parent-uri']) {
1012                                 $arr['parent-uri'] = $r[0]['parent-uri'];
1013                                 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d 
1014                                         ORDER BY `id` ASC LIMIT 1",
1015                                         dbesc($r[0]['parent-uri']),
1016                                         dbesc($r[0]['parent-uri']),
1017                                         intval($arr['uid'])
1018                                 );
1019                                 if($z && count($z))
1020                                         $r = $z;
1021                         }
1022
1023                         $parent_id      = $r[0]['id'];
1024                         $parent_deleted = $r[0]['deleted'];
1025                         $allow_cid      = $r[0]['allow_cid'];
1026                         $allow_gid      = $r[0]['allow_gid'];
1027                         $deny_cid       = $r[0]['deny_cid'];
1028                         $deny_gid       = $r[0]['deny_gid'];
1029                         $arr['wall']    = $r[0]['wall'];
1030
1031                         // if the parent is private, force privacy for the entire conversation
1032                         // This differs from the above settings as it subtly allows comments from 
1033                         // email correspondents to be private even if the overall thread is not. 
1034
1035                         if($r[0]['private'])
1036                                 $arr['private'] = $r[0]['private'];
1037
1038                         // Edge case. We host a public forum that was originally posted to privately.
1039                         // The original author commented, but as this is a comment, the permissions
1040                         // weren't fixed up so it will still show the comment as private unless we fix it here. 
1041
1042                         if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
1043                                 $arr['private'] = 0;
1044                 }
1045                 else {
1046
1047                         // Allow one to see reply tweets from status.net even when
1048                         // we don't have or can't see the original post.
1049
1050                         if($force_parent) {
1051                                 logger('item_store: $force_parent=true, reply converted to top-level post.');
1052                                 $parent_id = 0;
1053                                 $arr['parent-uri'] = $arr['uri'];
1054                                 $arr['gravity'] = 0;
1055                         }
1056                         else {
1057                                 logger('item_store: item parent was not found - ignoring item');
1058                                 return 0;
1059                         }
1060
1061                         $parent_deleted = 0;
1062                 }
1063         }
1064
1065         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1066                 dbesc($arr['uri']),
1067                 intval($arr['uid'])
1068         );
1069         if($r && count($r)) {
1070                 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
1071                 return 0;
1072         }
1073
1074         call_hooks('post_remote',$arr);
1075
1076         if(x($arr,'cancel')) {
1077                 logger('item_store: post cancelled by plugin.');
1078                 return 0;
1079         }
1080
1081         dbesc_array($arr);
1082
1083         logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
1084
1085         $r = dbq("INSERT INTO `item` (`" 
1086                         . implode("`, `", array_keys($arr)) 
1087                         . "`) VALUES ('" 
1088                         . implode("', '", array_values($arr)) 
1089                         . "')" );
1090
1091         // find the item we just created
1092
1093         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
1094                 $arr['uri'],           // already dbesc'd
1095                 intval($arr['uid'])
1096         );
1097
1098         if(count($r)) {
1099                 $current_post = $r[0]['id'];
1100                 logger('item_store: created item ' . $current_post);
1101                 create_tags_from_item($r[0]['id']);
1102         } else {
1103                 logger('item_store: could not locate created item');
1104                 return 0;
1105         }
1106         if(count($r) > 1) {
1107                 logger('item_store: duplicated post occurred. Removing duplicates.');
1108                 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
1109                         $arr['uri'],
1110                         intval($arr['uid']),
1111                         intval($current_post)
1112                 );
1113         }
1114
1115         if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
1116                 $parent_id = $current_post;
1117
1118         if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
1119                 $private = 1;
1120         else
1121                 $private = $arr['private']; 
1122
1123         // Set parent id - and also make sure to inherit the parent's ACL's.
1124
1125         $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
1126                 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
1127                 intval($parent_id),
1128                 dbesc($allow_cid),
1129                 dbesc($allow_gid),
1130                 dbesc($deny_cid),
1131                 dbesc($deny_gid),
1132                 intval($private),
1133                 intval($parent_deleted),
1134                 intval($current_post)
1135         );
1136         create_tags_from_item($current_post);
1137
1138         // Complete ostatus threads
1139         if ($ostatus_conversation)
1140                 complete_conversation($current_post, $ostatus_conversation);
1141
1142         $arr['id'] = $current_post;
1143         $arr['parent'] = $parent_id;
1144         $arr['allow_cid'] = $allow_cid;
1145         $arr['allow_gid'] = $allow_gid;
1146         $arr['deny_cid'] = $deny_cid;
1147         $arr['deny_gid'] = $deny_gid;
1148         $arr['private'] = $private;
1149         $arr['deleted'] = $parent_deleted;
1150         call_hooks('post_remote_end',$arr);
1151
1152         // update the commented timestamp on the parent
1153
1154         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1155                 dbesc(datetime_convert()),
1156                 dbesc(datetime_convert()),
1157                 intval($parent_id)
1158         );
1159
1160         if($dsprsig) {
1161                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1162                         intval($current_post),
1163                         dbesc($dsprsig->signed_text),
1164                         dbesc($dsprsig->signature),
1165                         dbesc($dsprsig->signer)
1166                 );
1167         }
1168
1169
1170         /**
1171          * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1172          */
1173
1174         if($arr['last-child']) {
1175                 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1176                         dbesc($arr['uri']),
1177                         intval($arr['uid']),
1178                         intval($current_post)
1179                 );
1180         }
1181
1182         tag_deliver($arr['uid'],$current_post);
1183
1184         // Store the fresh generated item into the cache
1185         $cachefile = get_cachefile($arr["guid"]."-".hash("md5", $arr['body']));
1186
1187         if (($cachefile != '') AND !file_exists($cachefile)) {
1188                 $s = prepare_text($arr['body']);
1189                 $a = get_app();
1190                 $stamp1 = microtime(true);
1191                 file_put_contents($cachefile, $s);
1192                 $a->save_timestamp($stamp1, "file");
1193                 logger('item_store: put item '.$current_post.' into cachefile '.$cachefile);
1194         }
1195
1196         return $current_post;
1197 }
1198
1199 function get_item_contact($item,$contacts) {
1200         if(! count($contacts) || (! is_array($item)))
1201                 return false;
1202         foreach($contacts as $contact) {
1203                 if($contact['id'] == $item['contact-id']) {
1204                         return $contact;
1205                         break; // NOTREACHED
1206                 }
1207         }
1208         return false;
1209 }
1210
1211
1212 function tag_deliver($uid,$item_id) {
1213
1214         // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1215
1216         $a = get_app();
1217
1218         $mention = false;
1219
1220         $u = q("select * from user where uid = %d limit 1",
1221                 intval($uid)
1222         );
1223         if(! count($u))
1224                 return;
1225
1226         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1227         $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1228
1229
1230         $i = q("select * from item where id = %d and uid = %d limit 1",
1231                 intval($item_id),
1232                 intval($uid)
1233         );
1234         if(! count($i))
1235                 return;
1236
1237         $item = $i[0];
1238
1239         $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1240
1241         // Diaspora uses their own hardwired link URL in @-tags
1242         // instead of the one we supply with webfinger
1243
1244         $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1245
1246         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1247         if($cnt) {
1248                 foreach($matches as $mtch) {
1249                         if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1250                                 $mention = true;
1251                                 logger('tag_deliver: mention found: ' . $mtch[2]);
1252                         }
1253                 }
1254         }
1255
1256         if(! $mention)
1257                 return;
1258
1259         // send a notification
1260
1261         // use a local photo if we have one
1262
1263         $r = q("select * from contact where uid = %d and nurl = '%s' limit 1",
1264                 intval($u[0]['uid']),
1265                 dbesc(normalise_link($item['author-link']))
1266         );
1267         $photo = (($r && count($r)) ? $r[0]['thumb'] : $item['author-avatar']);
1268
1269
1270         require_once('include/enotify.php');
1271         notification(array(
1272                 'type'         => NOTIFY_TAGSELF,
1273                 'notify_flags' => $u[0]['notify-flags'],
1274                 'language'     => $u[0]['language'],
1275                 'to_name'      => $u[0]['username'],
1276                 'to_email'     => $u[0]['email'],
1277                 'uid'          => $u[0]['uid'],
1278                 'item'         => $item,
1279                 'link'         => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1280                 'source_name'  => $item['author-name'],
1281                 'source_link'  => $item['author-link'],
1282                 'source_photo' => $photo,
1283                 'verb'         => ACTIVITY_TAG,
1284                 'otype'        => 'item'
1285         ));
1286
1287
1288         $arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
1289
1290         call_hooks('tagged', $arr);
1291
1292         if((! $community_page) && (! $prvgroup))
1293                 return;
1294
1295
1296         // tgroup delivery - setup a second delivery chain
1297         // prevent delivery looping - only proceed
1298         // if the message originated elsewhere and is a top-level post
1299
1300         if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1301                 return;
1302
1303         // now change this copy of the post to a forum head message and deliver to all the tgroup members
1304
1305
1306         $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1307                 intval($u[0]['uid'])
1308         );
1309         if(! count($c))
1310                 return;
1311
1312         // also reset all the privacy bits to the forum default permissions
1313
1314         $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1315
1316         $forum_mode = (($prvgroup) ? 2 : 1);
1317
1318         q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s', 
1319                 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'  where id = %d limit 1",
1320                 intval($forum_mode),
1321                 dbesc($c[0]['name']),
1322                 dbesc($c[0]['url']),
1323                 dbesc($c[0]['thumb']),
1324                 intval($private),
1325                 dbesc($u[0]['allow_cid']),
1326                 dbesc($u[0]['allow_gid']),
1327                 dbesc($u[0]['deny_cid']),
1328                 dbesc($u[0]['deny_gid']),
1329                 intval($item_id)
1330         );
1331
1332         proc_run('php','include/notifier.php','tgroup',$item_id);
1333
1334 }
1335
1336
1337
1338 function tgroup_check($uid,$item) {
1339
1340         $a = get_app();
1341
1342         $mention = false;
1343
1344         // check that the message originated elsewhere and is a top-level post
1345
1346         if(($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri']))
1347                 return false;
1348
1349
1350         $u = q("select * from user where uid = %d limit 1",
1351                 intval($uid)
1352         );
1353         if(! count($u))
1354                 return false;
1355
1356         $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1357         $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1358
1359
1360         $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1361
1362         // Diaspora uses their own hardwired link URL in @-tags
1363         // instead of the one we supply with webfinger
1364
1365         $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1366
1367         $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1368         if($cnt) {
1369                 foreach($matches as $mtch) {
1370                         if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1371                                 $mention = true;
1372                                 logger('tgroup_check: mention found: ' . $mtch[2]);
1373                         }
1374                 }
1375         }
1376
1377         if(! $mention)
1378                 return false;
1379
1380         if((! $community_page) && (! $prvgroup))
1381                 return false;
1382
1383
1384
1385         return true;
1386
1387 }
1388
1389
1390
1391
1392
1393
1394 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1395
1396         $a = get_app();
1397
1398         $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1399
1400         if($contact['duplex'] && $contact['dfrn-id'])
1401                 $idtosend = '0:' . $orig_id;
1402         if($contact['duplex'] && $contact['issued-id'])
1403                 $idtosend = '1:' . $orig_id;
1404
1405         $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1406
1407         $rino_enable = get_config('system','rino_encrypt');
1408
1409         if(! $rino_enable)
1410                 $rino = 0;
1411
1412         $ssl_val = intval(get_config('system','ssl_policy'));
1413         $ssl_policy = '';
1414
1415         switch($ssl_val){
1416                 case SSL_POLICY_FULL:
1417                         $ssl_policy = 'full';
1418                         break;
1419                 case SSL_POLICY_SELFSIGN:
1420                         $ssl_policy = 'self';
1421                         break;
1422                 case SSL_POLICY_NONE:
1423                 default:
1424                         $ssl_policy = 'none';
1425                         break;
1426         }
1427
1428         $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1429
1430         logger('dfrn_deliver: ' . $url);
1431
1432         $xml = fetch_url($url);
1433
1434         $curl_stat = $a->get_curl_code();
1435         if(! $curl_stat)
1436                 return(-1); // timed out
1437
1438         logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1439
1440         if(! $xml)
1441                 return 3;
1442
1443         if(strpos($xml,'<?xml') === false) {
1444                 logger('dfrn_deliver: no valid XML returned');
1445                 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1446                 return 3;
1447         }
1448
1449         $res = parse_xml_string($xml);
1450
1451         if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1452                 return (($res->status) ? $res->status : 3);
1453
1454         $postvars     = array();
1455         $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1456         $challenge    = hex2bin((string) $res->challenge);
1457         $perm         = (($res->perm) ? $res->perm : null);
1458         $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1459         $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1460         $page         = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1461
1462         if($owner['page-flags'] == PAGE_PRVGROUP)
1463                 $page = 2;
1464
1465         $final_dfrn_id = '';
1466
1467         if($perm) {
1468                 if((($perm == 'rw') && (! intval($contact['writable']))) 
1469                 || (($perm == 'r') && (intval($contact['writable'])))) {
1470                         q("update contact set writable = %d where id = %d limit 1",
1471                                 intval(($perm == 'rw') ? 1 : 0),
1472                                 intval($contact['id'])
1473                         );
1474                         $contact['writable'] = (string) 1 - intval($contact['writable']);
1475                 }
1476         }
1477
1478         if(($contact['duplex'] && strlen($contact['pubkey'])) 
1479                 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1480                 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1481                 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1482                 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1483         }
1484         else {
1485                 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1486                 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1487         }
1488
1489         $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1490
1491         if(strpos($final_dfrn_id,':') == 1)
1492                 $final_dfrn_id = substr($final_dfrn_id,2);
1493
1494         if($final_dfrn_id != $orig_id) {
1495                 logger('dfrn_deliver: wrong dfrn_id.');
1496                 // did not decode properly - cannot trust this site 
1497                 return 3;
1498         }
1499
1500         $postvars['dfrn_id']      = $idtosend;
1501         $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1502         if($dissolve)
1503                 $postvars['dissolve'] = '1';
1504
1505
1506         if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1507                 $postvars['data'] = $atom;
1508                 $postvars['perm'] = 'rw';
1509         }
1510         else {
1511                 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1512                 $postvars['perm'] = 'r';
1513         }
1514
1515         $postvars['ssl_policy'] = $ssl_policy;
1516
1517         if($page)
1518                 $postvars['page'] = $page;
1519         
1520         if($rino && $rino_allowed && (! $dissolve)) {
1521                 $key = substr(random_string(),0,16);
1522                 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1523                 $postvars['data'] = $data;
1524                 logger('rino: sent key = ' . $key, LOGGER_DEBUG);       
1525
1526
1527                 if($dfrn_version >= 2.1) {      
1528                         if(($contact['duplex'] && strlen($contact['pubkey'])) 
1529                                 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1530                                 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1531
1532                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1533                         }
1534                         else {
1535                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1536                         }
1537                 }
1538                 else {
1539                         if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1540                                 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1541                         }
1542                         else {
1543                                 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1544                         }
1545                 }
1546
1547                 logger('md5 rawkey ' . md5($postvars['key']));
1548
1549                 $postvars['key'] = bin2hex($postvars['key']);
1550         }
1551
1552         logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1553
1554         $xml = post_url($contact['notify'],$postvars);
1555
1556         logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1557
1558         $curl_stat = $a->get_curl_code();
1559         if((! $curl_stat) || (! strlen($xml)))
1560                 return(-1); // timed out
1561
1562         if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1563                 return(-1);
1564
1565         if(strpos($xml,'<?xml') === false) {
1566                 logger('dfrn_deliver: phase 2: no valid XML returned');
1567                 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1568                 return 3;
1569         }
1570
1571         if($contact['term-date'] != '0000-00-00 00:00:00') {
1572                 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1573                 require_once('include/Contact.php');
1574                 unmark_for_death($contact);
1575         }
1576
1577         $res = parse_xml_string($xml);
1578
1579         return $res->status; 
1580 }
1581
1582
1583 /**
1584  *
1585  * consume_feed - process atom feed and update anything/everything we might need to update
1586  *
1587  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1588  *
1589  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1590  *             It is this person's stuff that is going to be updated.
1591  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1592  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST 
1593  *             have a contact record.
1594  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or 
1595  *        might not) try and subscribe to it.
1596  * $datedir sorts in reverse order
1597  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been 
1598  *      imported prior to its children being seen in the stream unless we are certain
1599  *      of how the feed is arranged/ordered.
1600  * With $pass = 1, we only pull parent items out of the stream.
1601  * With $pass = 2, we only pull children (comments/likes).
1602  *
1603  * So running this twice, first with pass 1 and then with pass 2 will do the right
1604  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1605  * model where comments can have sub-threads. That would require some massive sorting
1606  * to get all the feed items into a mostly linear ordering, and might still require
1607  * recursion.  
1608  */
1609
1610 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1611
1612         require_once('library/simplepie/simplepie.inc');
1613
1614         if(! strlen($xml)) {
1615                 logger('consume_feed: empty input');
1616                 return;
1617         }
1618
1619         $feed = new SimplePie();
1620         $feed->set_raw_data($xml);
1621         if($datedir)
1622                 $feed->enable_order_by_date(true);
1623         else
1624                 $feed->enable_order_by_date(false);
1625         $feed->init();
1626
1627         if($feed->error())
1628                 logger('consume_feed: Error parsing XML: ' . $feed->error());
1629
1630         $permalink = $feed->get_permalink();
1631
1632         // Check at the feed level for updated contact name and/or photo
1633
1634         $name_updated  = '';
1635         $new_name = '';
1636         $photo_timestamp = '';
1637         $photo_url = '';
1638         $birthday = '';
1639
1640         $hubs = $feed->get_links('hub');
1641         logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1642
1643         if(count($hubs))
1644                 $hub = implode(',', $hubs);
1645
1646         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1647         if(! $rawtags)
1648                 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1649         if($rawtags) {
1650                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1651                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1652                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1653                         $new_name = $elems['name'][0]['data'];
1654                 }
1655                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1656                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1657                         $photo_url = $elems['link'][0]['attribs']['']['href'];
1658                 }
1659
1660                 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1661                         $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1662                 }
1663         }
1664
1665         if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1666                 logger('consume_feed: Updating photo for ' . $contact['name']);
1667                 require_once("include/Photo.php");
1668                 $photo_failure = false;
1669                 $have_photo = false;
1670
1671                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1672                         intval($contact['id']),
1673                         intval($contact['uid'])
1674                 );
1675                 if(count($r)) {
1676                         $resource_id = $r[0]['resource-id'];
1677                         $have_photo = true;
1678                 }
1679                 else {
1680                         $resource_id = photo_new_resource();
1681                 }
1682                         
1683                 $img_str = fetch_url($photo_url,true);
1684                 // guess mimetype from headers or filename
1685                 $type = guess_image_type($photo_url,true);
1686                 
1687                 
1688                 $img = new Photo($img_str, $type);
1689                 if($img->is_valid()) {
1690                         if($have_photo) {
1691                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1692                                         dbesc($resource_id),
1693                                         intval($contact['id']),
1694                                         intval($contact['uid'])
1695                                 );
1696                         }
1697
1698                         $img->scaleImageSquare(175);
1699
1700                         $hash = $resource_id;
1701                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1702
1703                         $img->scaleImage(80);
1704                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1705
1706                         $img->scaleImage(48);
1707                         $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1708
1709                         $a = get_app();
1710
1711                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1712                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1713                                 dbesc(datetime_convert()),
1714                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1715                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1716                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1717                                 intval($contact['uid']),
1718                                 intval($contact['id'])
1719                         );
1720                 }
1721         }
1722
1723         if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1724                 $r = q("select * from contact where uid = %d and id = %d limit 1",
1725                         intval($contact['uid']),
1726                         intval($contact['id'])
1727                 );
1728
1729                 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1730                         dbesc(notags(trim($new_name))),
1731                         dbesc(datetime_convert()),
1732                         intval($contact['uid']),
1733                         intval($contact['id'])
1734                 );
1735
1736                 // do our best to update the name on content items
1737
1738                 if(count($r)) {
1739                         q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1740                                 dbesc(notags(trim($new_name))),
1741                                 dbesc($r[0]['name']),
1742                                 dbesc($r[0]['url']),
1743                                 intval($contact['uid'])
1744                         );
1745                 }
1746         }
1747
1748         if(strlen($birthday)) {
1749                 if(substr($birthday,0,4) != $contact['bdyear']) {
1750                         logger('consume_feed: updating birthday: ' . $birthday);
1751
1752                         /**
1753                          *
1754                          * Add new birthday event for this person
1755                          *
1756                          * $bdtext is just a readable placeholder in case the event is shared
1757                          * with others. We will replace it during presentation to our $importer
1758                          * to contain a sparkle link and perhaps a photo. 
1759                          *
1760                          */
1761
1762                         $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
1763                         $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
1764
1765
1766                         $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1767                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1768                                 intval($contact['uid']),
1769                                 intval($contact['id']),
1770                                 dbesc(datetime_convert()),
1771                                 dbesc(datetime_convert()),
1772                                 dbesc(datetime_convert('UTC','UTC', $birthday)),
1773                                 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1774                                 dbesc($bdtext),
1775                                 dbesc($bdtext2),
1776                                 dbesc('birthday')
1777                         );
1778
1779
1780                         // update bdyear
1781
1782                         q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1783                                 dbesc(substr($birthday,0,4)),
1784                                 intval($contact['uid']),
1785                                 intval($contact['id'])
1786                         );
1787
1788                         // This function is called twice without reloading the contact
1789                         // Make sure we only create one event. This is why &$contact 
1790                         // is a reference var in this function
1791
1792                         $contact['bdyear'] = substr($birthday,0,4);
1793                 }
1794
1795         }
1796
1797         $community_page = 0;
1798         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1799         if($rawtags) {
1800                 $community_page = intval($rawtags[0]['data']);
1801         }
1802         if(is_array($contact) && intval($contact['forum']) != $community_page) {
1803                 q("update contact set forum = %d where id = %d limit 1",
1804                         intval($community_page),
1805                         intval($contact['id'])
1806                 );
1807                 $contact['forum'] = (string) $community_page;
1808         }
1809
1810
1811         // process any deleted entries
1812
1813         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1814         if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1815                 foreach($del_entries as $dentry) {
1816                         $deleted = false;
1817                         if(isset($dentry['attribs']['']['ref'])) {
1818                                 $uri = $dentry['attribs']['']['ref'];
1819                                 $deleted = true;
1820                                 if(isset($dentry['attribs']['']['when'])) {
1821                                         $when = $dentry['attribs']['']['when'];
1822                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1823                                 }
1824                                 else
1825                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1826                         }
1827                         if($deleted && is_array($contact)) {
1828                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id` 
1829                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1830                                         dbesc($uri),
1831                                         intval($importer['uid']),
1832                                         intval($contact['id'])
1833                                 );
1834                                 if(count($r)) {
1835                                         $item = $r[0];
1836
1837                                         if(! $item['deleted'])
1838                                                 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1839
1840                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1841                                                 $xo = parse_xml_string($item['object'],false);
1842                                                 $xt = parse_xml_string($item['target'],false);
1843                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
1844                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1845                                                                 dbesc($xt->id),
1846                                                                 intval($importer['importer_uid'])
1847                                                         );
1848                                                         if(count($i)) {
1849
1850                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
1851
1852                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1853                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1854                                                                 $author_copy = (($item['origin']) ? true : false);
1855
1856                                                                 if($owner_remove && $author_copy)
1857                                                                         continue;
1858                                                                 if($author_remove || $owner_remove) {
1859                                                                         $tags = explode(',',$i[0]['tag']);
1860                                                                         $newtags = array();
1861                                                                         if(count($tags)) {
1862                                                                                 foreach($tags as $tag)
1863                                                                                         if(trim($tag) !== trim($xo->body))
1864                                                                                                 $newtags[] = trim($tag);
1865                                                                         }
1866                                                                         q("update item set tag = '%s' where id = %d limit 1",
1867                                                                                 dbesc(implode(',',$newtags)),
1868                                                                                 intval($i[0]['id'])
1869                                                                         );
1870                                                                         create_tags_from_item($i[0]['id']);
1871                                                                 }
1872                                                         }
1873                                                 }
1874                                         }
1875
1876                                         if($item['uri'] == $item['parent-uri']) {
1877                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1878                                                         `body` = '', `title` = ''
1879                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
1880                                                         dbesc($when),
1881                                                         dbesc(datetime_convert()),
1882                                                         dbesc($item['uri']),
1883                                                         intval($importer['uid'])
1884                                                 );
1885                                                 create_tags_from_itemuri($item['uri'], $importer['uid']);
1886                                         }
1887                                         else {
1888                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1889                                                         `body` = '', `title` = '' 
1890                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1891                                                         dbesc($when),
1892                                                         dbesc(datetime_convert()),
1893                                                         dbesc($uri),
1894                                                         intval($importer['uid'])
1895                                                 );
1896                                                 create_tags_from_itemuri($uri, $importer['uid']);
1897                                                 if($item['last-child']) {
1898                                                         // ensure that last-child is set in case the comment that had it just got wiped.
1899                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1900                                                                 dbesc(datetime_convert()),
1901                                                                 dbesc($item['parent-uri']),
1902                                                                 intval($item['uid'])
1903                                                         );
1904                                                         // who is the last child now? 
1905                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d 
1906                                                                 ORDER BY `created` DESC LIMIT 1",
1907                                                                         dbesc($item['parent-uri']),
1908                                                                         intval($importer['uid'])
1909                                                         );
1910                                                         if(count($r)) {
1911                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1912                                                                         intval($r[0]['id'])
1913                                                                 );
1914                                                         }
1915                                                 }       
1916                                         }
1917                                 }       
1918                         }
1919                 }
1920         }
1921
1922         // Now process the feed
1923
1924         if($feed->get_item_quantity()) {
1925
1926                 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1927
1928         // in inverse date order
1929                 if ($datedir)
1930                         $items = array_reverse($feed->get_items());
1931                 else
1932                         $items = $feed->get_items();
1933
1934
1935                 foreach($items as $item) {
1936
1937                         $is_reply = false;
1938                         $item_id = $item->get_id();
1939                         $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1940                         if(isset($rawthread[0]['attribs']['']['ref'])) {
1941                                 $is_reply = true;
1942                                 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1943                         }
1944
1945                         if(($is_reply) && is_array($contact)) {
1946
1947                                 if($pass == 1)
1948                                         continue;
1949
1950                                 // not allowed to post
1951
1952                                 if($contact['rel'] == CONTACT_IS_FOLLOWER)
1953                                         continue;
1954
1955
1956                                 // Have we seen it? If not, import it.
1957
1958                                 $item_id  = $item->get_id();
1959                                 $datarray = get_atom_elements($feed,$item);
1960
1961                                 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1962                                         $datarray['author-name'] = $contact['name'];
1963                                 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1964                                         $datarray['author-link'] = $contact['url'];
1965                                 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1966                                         $datarray['author-avatar'] = $contact['thumb'];
1967
1968                                 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1969                                         logger('consume_feed: no author information! ' . print_r($datarray,true));
1970                                         continue;
1971                                 }
1972
1973                                 $force_parent = false;
1974                                 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1975                                         if($contact['network'] === NETWORK_OSTATUS)
1976                                                 $force_parent = true;
1977                                         if(strlen($datarray['title']))
1978                                                 unset($datarray['title']);
1979                                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1980                                                 dbesc(datetime_convert()),
1981                                                 dbesc($parent_uri),
1982                                                 intval($importer['uid'])
1983                                         );
1984                                         $datarray['last-child'] = 1;
1985                                 }
1986
1987
1988                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1989                                         dbesc($item_id),
1990                                         intval($importer['uid'])
1991                                 );
1992
1993                                 // Update content if 'updated' changes
1994
1995                                 if(count($r)) {
1996                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
1997
1998                                                 // do not accept (ignore) an earlier edit than one we currently have.
1999                                                 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2000                                                         continue;
2001
2002                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2003                                                         dbesc($datarray['title']),
2004                                                         dbesc($datarray['body']),
2005                                                         dbesc($datarray['tag']),
2006                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2007                                                         dbesc($item_id),
2008                                                         intval($importer['uid'])
2009                                                 );
2010                                                 create_tags_from_itemuri($item_id, $importer['uid']);
2011                                         }
2012
2013                                         // update last-child if it changes
2014
2015                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2016                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2017                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2018                                                         dbesc(datetime_convert()),
2019                                                         dbesc($parent_uri),
2020                                                         intval($importer['uid'])
2021                                                 );
2022                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2023                                                         intval($allow[0]['data']),
2024                                                         dbesc(datetime_convert()),
2025                                                         dbesc($item_id),
2026                                                         intval($importer['uid'])
2027                                                 );
2028                                         }
2029                                         continue;
2030                                 }
2031
2032
2033                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
2034                                         // one way feed - no remote comment ability
2035                                         $datarray['last-child'] = 0;
2036                                 }
2037                                 $datarray['parent-uri'] = $parent_uri;
2038                                 $datarray['uid'] = $importer['uid'];
2039                                 $datarray['contact-id'] = $contact['id'];
2040                                 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
2041                                         $datarray['type'] = 'activity';
2042                                         $datarray['gravity'] = GRAVITY_LIKE;
2043                                         // only one like or dislike per person
2044                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`parent-uri` = '%s' OR `thr-parent` = '%s') limit 1",
2045                                                 intval($datarray['uid']),
2046                                                 intval($datarray['contact-id']),
2047                                                 dbesc($datarray['verb']),
2048                                                 dbesc($parent_uri),
2049                                                 dbesc($parent_uri)
2050                                         );
2051                                         if($r && count($r))
2052                                                 continue;
2053                                 }
2054
2055                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2056                                         $xo = parse_xml_string($datarray['object'],false);
2057                                         $xt = parse_xml_string($datarray['target'],false);
2058
2059                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
2060                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2061                                                         dbesc($xt->id),
2062                                                         intval($importer['importer_uid'])
2063                                                 );
2064                                                 if(! count($r))
2065                                                         continue;
2066
2067                                                 // extract tag, if not duplicate, add to parent item
2068                                                 if($xo->id && $xo->content) {
2069                                                         $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2070                                                         if(! (stristr($r[0]['tag'],$newtag))) {
2071                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2072                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2073                                                                         intval($r[0]['id'])
2074                                                                 );
2075                                                                 create_tags_from_item($r[0]['id']);
2076                                                         }
2077                                                 }
2078                                         }
2079                                 }
2080
2081                                 $r = item_store($datarray,$force_parent);
2082                                 continue;
2083                         }
2084
2085                         else {
2086
2087                                 // Head post of a conversation. Have we seen it? If not, import it.
2088
2089                                 $item_id  = $item->get_id();
2090
2091                                 $datarray = get_atom_elements($feed,$item);
2092
2093                                 if(is_array($contact)) {
2094                                         if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
2095                                                 $datarray['author-name'] = $contact['name'];
2096                                         if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
2097                                                 $datarray['author-link'] = $contact['url'];
2098                                         if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
2099                                                 $datarray['author-avatar'] = $contact['thumb'];
2100                                 }
2101
2102                                 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
2103                                         logger('consume_feed: no author information! ' . print_r($datarray,true));
2104                                         continue;
2105                                 }
2106
2107                                 // special handling for events
2108
2109                                 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2110                                         $ev = bbtoevent($datarray['body']);
2111                                         if(x($ev,'desc') && x($ev,'start')) {
2112                                                 $ev['uid'] = $importer['uid'];
2113                                                 $ev['uri'] = $item_id;
2114                                                 $ev['edited'] = $datarray['edited'];
2115                                                 $ev['private'] = $datarray['private'];
2116
2117                                                 if(is_array($contact))
2118                                                         $ev['cid'] = $contact['id'];
2119                                                 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2120                                                         dbesc($item_id),
2121                                                         intval($importer['uid'])
2122                                                 );
2123                                                 if(count($r))
2124                                                         $ev['id'] = $r[0]['id'];
2125                                                 $xyz = event_store($ev);
2126                                                 continue;
2127                                         }
2128                                 }
2129
2130                                 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
2131                                         if(strlen($datarray['title']))
2132                                                 unset($datarray['title']);
2133                                         $datarray['last-child'] = 1;
2134                                 }
2135
2136
2137                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2138                                         dbesc($item_id),
2139                                         intval($importer['uid'])
2140                                 );
2141
2142                                 // Update content if 'updated' changes
2143
2144                                 if(count($r)) {
2145                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
2146
2147                                                 // do not accept (ignore) an earlier edit than one we currently have.
2148                                                 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2149                                                         continue;
2150
2151                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2152                                                         dbesc($datarray['title']),
2153                                                         dbesc($datarray['body']),
2154                                                         dbesc($datarray['tag']),
2155                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2156                                                         dbesc($item_id),
2157                                                         intval($importer['uid'])
2158                                                 );
2159                                                 create_tags_from_itemuri($item_id, $importer['uid']);
2160                                         }
2161
2162                                         // update last-child if it changes
2163
2164                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2165                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2166                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2167                                                         intval($allow[0]['data']),
2168                                                         dbesc(datetime_convert()),
2169                                                         dbesc($item_id),
2170                                                         intval($importer['uid'])
2171                                                 );
2172                                         }
2173                                         continue;
2174                                 }
2175
2176                                 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
2177                                         logger('consume-feed: New follower');
2178                                         new_follower($importer,$contact,$datarray,$item);
2179                                         return;
2180                                 }
2181                                 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW))  {
2182                                         lose_follower($importer,$contact,$datarray,$item);
2183                                         return;
2184                                 }
2185
2186                                 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
2187                                         logger('consume-feed: New friend request');
2188                                         new_follower($importer,$contact,$datarray,$item,true);
2189                                         return;
2190                                 }
2191                                 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND))  {
2192                                         lose_sharer($importer,$contact,$datarray,$item);
2193                                         return;
2194                                 }
2195
2196
2197                                 if(! is_array($contact))
2198                                         return;
2199
2200
2201                                 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
2202                                                 // one way feed - no remote comment ability
2203                                                 $datarray['last-child'] = 0;
2204                                 }
2205                                 if($contact['network'] === NETWORK_FEED)
2206                                         $datarray['private'] = 2;
2207
2208                                 // This is my contact on another system, but it's really me.
2209                                 // Turn this into a wall post.
2210
2211                                 if($contact['remote_self']) {
2212                                         $datarray['wall'] = 1;
2213                                         if($contact['network'] === NETWORK_FEED) {
2214                                                 $datarray['private'] = 0;
2215                                         }
2216                                 }
2217
2218                                 $datarray['parent-uri'] = $item_id;
2219                                 $datarray['uid'] = $importer['uid'];
2220                                 $datarray['contact-id'] = $contact['id'];
2221
2222                                 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2223                                         // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery, 
2224                                         // but otherwise there's a possible data mixup on the sender's system.
2225                                         // the tgroup delivery code called from item_store will correct it if it's a forum,
2226                                         // but we're going to unconditionally correct it here so that the post will always be owned by our contact. 
2227                                         logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
2228                                         $datarray['owner-name']   = $contact['name'];
2229                                         $datarray['owner-link']   = $contact['url'];
2230                                         $datarray['owner-avatar'] = $contact['thumb'];
2231                                 }
2232
2233                                 // We've allowed "followers" to reach this point so we can decide if they are 
2234                                 // posting an @-tag delivery, which followers are allowed to do for certain
2235                                 // page types. Now that we've parsed the post, let's check if it is legit. Otherwise ignore it. 
2236
2237                                 if(($contact['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['uid'],$datarray)))
2238                                         continue;
2239
2240
2241                                 $r = item_store($datarray);
2242                                 continue;
2243
2244                         }
2245                 }
2246         }
2247 }
2248
2249 function local_delivery($importer,$data) {
2250         $a = get_app();
2251
2252     logger(__function__, LOGGER_TRACE);
2253
2254         if($importer['readonly']) {
2255                 // We aren't receiving stuff from this person. But we will quietly ignore them
2256                 // rather than a blatant "go away" message.
2257                 logger('local_delivery: ignoring');
2258                 return 0;
2259                 //NOTREACHED
2260         }
2261
2262         // Consume notification feed. This may differ from consuming a public feed in several ways
2263         // - might contain email or friend suggestions
2264         // - might contain remote followup to our message
2265         //              - in which case we need to accept it and then notify other conversants
2266         // - we may need to send various email notifications
2267
2268         $feed = new SimplePie();
2269         $feed->set_raw_data($data);
2270         $feed->enable_order_by_date(false);
2271         $feed->init();
2272
2273
2274         if($feed->error())
2275                 logger('local_delivery: Error parsing XML: ' . $feed->error());
2276
2277
2278         // Check at the feed level for updated contact name and/or photo
2279
2280         $name_updated  = '';
2281         $new_name = '';
2282         $photo_timestamp = '';
2283         $photo_url = '';
2284
2285
2286         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
2287
2288 // Fallback should not be needed here. If it isn't DFRN it won't have DFRN updated tags
2289 //      if(! $rawtags)
2290 //              $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
2291
2292         if($rawtags) {
2293                 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
2294                 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
2295                         $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
2296                         $new_name = $elems['name'][0]['data'];
2297                 }
2298                 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
2299                         $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
2300                         $photo_url = $elems['link'][0]['attribs']['']['href'];
2301                 }
2302         }
2303
2304         if(($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $importer['avatar-date'])) {
2305                 logger('local_delivery: Updating photo for ' . $importer['name']);
2306                 require_once("include/Photo.php");
2307                 $photo_failure = false;
2308                 $have_photo = false;
2309
2310                 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
2311                         intval($importer['id']),
2312                         intval($importer['importer_uid'])
2313                 );
2314                 if(count($r)) {
2315                         $resource_id = $r[0]['resource-id'];
2316                         $have_photo = true;
2317                 }
2318                 else {
2319                         $resource_id = photo_new_resource();
2320                 }
2321                         
2322                 $img_str = fetch_url($photo_url,true);
2323                 // guess mimetype from headers or filename
2324                 $type = guess_image_type($photo_url,true);
2325                 
2326                 
2327                 $img = new Photo($img_str, $type);
2328                 if($img->is_valid()) {
2329                         if($have_photo) {
2330                                 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
2331                                         dbesc($resource_id),
2332                                         intval($importer['id']),
2333                                         intval($importer['importer_uid'])
2334                                 );
2335                         }
2336
2337                         $img->scaleImageSquare(175);
2338
2339                         $hash = $resource_id;
2340                         $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 4);
2341
2342                         $img->scaleImage(80);
2343                         $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 5);
2344
2345                         $img->scaleImage(48);
2346                         $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 6);
2347
2348                         $a = get_app();
2349
2350                         q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
2351                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
2352                                 dbesc(datetime_convert()),
2353                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
2354                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
2355                                 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
2356                                 intval($importer['importer_uid']),
2357                                 intval($importer['id'])
2358                         );
2359                 }
2360         }
2361
2362         if(($name_updated) && (strlen($new_name)) && ($name_updated > $importer['name-date'])) {
2363                 $r = q("select * from contact where uid = %d and id = %d limit 1",
2364                         intval($importer['importer_uid']),
2365                         intval($importer['id'])
2366                 );
2367
2368                 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2369                         dbesc(notags(trim($new_name))),
2370                         dbesc(datetime_convert()),
2371                         intval($importer['importer_uid']),
2372                         intval($importer['id'])
2373                 );
2374
2375                 // do our best to update the name on content items
2376
2377                 if(count($r)) {
2378                         q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
2379                                 dbesc(notags(trim($new_name))),
2380                                 dbesc($r[0]['name']),
2381                                 dbesc($r[0]['url']),
2382                                 intval($importer['importer_uid'])
2383                         );
2384                 }
2385         }
2386
2387
2388
2389         // Currently unsupported - needs a lot of work
2390         $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
2391         if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
2392                 $base = $reloc[0]['child'][NAMESPACE_DFRN];
2393                 $newloc = array();
2394                 $newloc['uid'] = $importer['importer_uid'];
2395                 $newloc['cid'] = $importer['id'];
2396                 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
2397                 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
2398                 $newloc['thumb'] = notags(unxmlify($base['thumb'][0]['data']));
2399                 $newloc['micro'] = notags(unxmlify($base['micro'][0]['data']));
2400                 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
2401                 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
2402                 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
2403                 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
2404                 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
2405                 $newloc['sitepubkey'] = notags(unxmlify($base['sitepubkey'][0]['data']));
2406                 /** relocated user must have original key pair */
2407                 /*$newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
2408                 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));*/
2409
2410         logger("items:relocate contact ".print_r($newloc, true).print_r($importer, true), LOGGER_DEBUG);
2411
2412         // update contact
2413         $r = q("SELECT photo, url FROM contact WHERE id=%d AND uid=%d;",
2414                     intval($importer['id']),
2415                                         intval($importer['importer_uid']));
2416                 if ($r === false)
2417                         return 1;
2418         $old = $r[0];
2419
2420         $x = q("UPDATE contact SET
2421                         name = '%s',
2422                         photo = '%s',
2423                         thumb = '%s',
2424                         micro = '%s',
2425                         url = '%s',
2426                         request = '%s',
2427                         confirm = '%s',
2428                         notify = '%s',
2429                         poll = '%s',
2430                         `site-pubkey` = '%s'
2431                 WHERE id=%d AND uid=%d;",
2432                     dbesc($newloc['name']),
2433                     dbesc($newloc['photo']),
2434                     dbesc($newloc['thumb']),
2435                     dbesc($newloc['micro']),
2436                     dbesc($newloc['url']),
2437                     dbesc($newloc['request']),
2438                     dbesc($newloc['confirm']),
2439                     dbesc($newloc['notify']),
2440                     dbesc($newloc['poll']),
2441                     dbesc($newloc['sitepubkey']),
2442                     intval($importer['id']),
2443                                         intval($importer['importer_uid']));
2444
2445         if ($x === false)
2446                         return 1;
2447         // update items
2448         $fields = array(
2449             'owner-link' => array($old['url'], $newloc['url']),
2450             'author-link' => array($old['url'], $newloc['url']),
2451             'owner-avatar' => array($old['photo'], $newloc['photo']),
2452             'author-avatar' => array($old['photo'], $newloc['photo']),
2453         );
2454         foreach ($fields as $n=>$f){
2455             $x = q("UPDATE item SET `%s`='%s' WHERE `%s`='%s' AND uid=%d",
2456                         $n, dbesc($f[1]),
2457                         $n, dbesc($f[0]),
2458                         intval($importer['importer_uid']));
2459                         if ($x === false)
2460                                 return 1;
2461                 }
2462
2463                 // TODO
2464                 // merge with current record, current contents have priority
2465                 // update record, set url-updated
2466                 // update profile photos
2467                 // schedule a scan?
2468         return 0;
2469         }
2470
2471
2472         // handle friend suggestion notification
2473
2474         $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
2475         if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
2476                 $base = $sugg[0]['child'][NAMESPACE_DFRN];
2477                 $fsugg = array();
2478                 $fsugg['uid'] = $importer['importer_uid'];
2479                 $fsugg['cid'] = $importer['id'];
2480                 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
2481                 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
2482                 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
2483                 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
2484                 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
2485
2486                 // Does our member already have a friend matching this description?
2487
2488                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
2489                         dbesc($fsugg['name']),
2490                         dbesc(normalise_link($fsugg['url'])),
2491                         intval($fsugg['uid'])
2492                 );
2493                 if(count($r))
2494                         return 0;
2495
2496                 // Do we already have an fcontact record for this person?
2497
2498                 $fid = 0;
2499                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2500                         dbesc($fsugg['url']),
2501                         dbesc($fsugg['name']),
2502                         dbesc($fsugg['request'])
2503                 );
2504                 if(count($r)) {
2505                         $fid = $r[0]['id'];
2506
2507                         // OK, we do. Do we already have an introduction for this person ?
2508                         $r = q("select id from intro where uid = %d and fid = %d limit 1",
2509                                 intval($fsugg['uid']),
2510                                 intval($fid)
2511                         );
2512                         if(count($r))
2513                                 return 0;
2514                 }
2515                 if(! $fid)
2516                         $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2517                         dbesc($fsugg['name']),
2518                         dbesc($fsugg['url']),
2519                         dbesc($fsugg['photo']),
2520                         dbesc($fsugg['request'])
2521                 );
2522                 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2523                         dbesc($fsugg['url']),
2524                         dbesc($fsugg['name']),
2525                         dbesc($fsugg['request'])
2526                 );
2527                 if(count($r)) {
2528                         $fid = $r[0]['id'];
2529                 }
2530                 // database record did not get created. Quietly give up.
2531                 else
2532                         return 0;
2533
2534
2535                 $hash = random_string();
2536
2537                 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2538                         VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2539                         intval($fsugg['uid']),
2540                         intval($fid),
2541                         intval($fsugg['cid']),
2542                         dbesc($fsugg['body']),
2543                         dbesc($hash),
2544                         dbesc(datetime_convert()),
2545                         intval(0)
2546                 );
2547
2548                 notification(array(
2549                         'type'         => NOTIFY_SUGGEST,
2550                         'notify_flags' => $importer['notify-flags'],
2551                         'language'     => $importer['language'],
2552                         'to_name'      => $importer['username'],
2553                         'to_email'     => $importer['email'],
2554                         'uid'          => $importer['importer_uid'],
2555                         'item'         => $fsugg,
2556                         'link'         => $a->get_baseurl() . '/notifications/intros',
2557                         'source_name'  => $importer['name'],
2558                         'source_link'  => $importer['url'],
2559                         'source_photo' => $importer['photo'],
2560                         'verb'         => ACTIVITY_REQ_FRIEND,
2561                         'otype'        => 'intro'
2562                 ));
2563
2564                 return 0;
2565         }
2566
2567         $ismail = false;
2568
2569         $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2570         if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2571
2572                 logger('local_delivery: private message received');
2573
2574                 $ismail = true;
2575                 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2576
2577                 $msg = array();
2578                 $msg['uid'] = $importer['importer_uid'];
2579                 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2580                 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2581                 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2582                 $msg['contact-id'] = $importer['id'];
2583                 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2584                 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2585                 $msg['seen'] = 0;
2586                 $msg['replied'] = 0;
2587                 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2588                 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2589                 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2590
2591                 dbesc_array($msg);
2592
2593                 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) 
2594                         . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2595
2596                 // send notifications.
2597
2598                 require_once('include/enotify.php');
2599
2600                 $notif_params = array(
2601                         'type' => NOTIFY_MAIL,
2602                         'notify_flags' => $importer['notify-flags'],
2603                         'language' => $importer['language'],
2604                         'to_name' => $importer['username'],
2605                         'to_email' => $importer['email'],
2606                         'uid' => $importer['importer_uid'],
2607                         'item' => $msg,
2608                         'source_name' => $msg['from-name'],
2609                         'source_link' => $importer['url'],
2610                         'source_photo' => $importer['thumb'],
2611                         'verb' => ACTIVITY_POST,
2612                         'otype' => 'mail'
2613                 );
2614
2615                 notification($notif_params);
2616                 return 0;
2617
2618                 // NOTREACHED
2619         }
2620
2621         $community_page = 0;
2622         $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2623         if($rawtags) {
2624                 $community_page = intval($rawtags[0]['data']);
2625         }
2626         if(intval($importer['forum']) != $community_page) {
2627                 q("update contact set forum = %d where id = %d limit 1",
2628                         intval($community_page),
2629                         intval($importer['id'])
2630                 );
2631                 $importer['forum'] = (string) $community_page;
2632         }
2633
2634         logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2635
2636         // process any deleted entries
2637
2638         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2639         if(is_array($del_entries) && count($del_entries)) {
2640                 foreach($del_entries as $dentry) {
2641                         $deleted = false;
2642                         if(isset($dentry['attribs']['']['ref'])) {
2643                                 $uri = $dentry['attribs']['']['ref'];
2644                                 $deleted = true;
2645                                 if(isset($dentry['attribs']['']['when'])) {
2646                                         $when = $dentry['attribs']['']['when'];
2647                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2648                                 }
2649                                 else
2650                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2651                         }
2652                         if($deleted) {
2653
2654                                 // check for relayed deletes to our conversation
2655
2656                                 $is_reply = false;              
2657                                 $r = q("select * from item where uri = '%s' and uid = %d limit 1",
2658                                         dbesc($uri),
2659                                         intval($importer['importer_uid'])
2660                                 );
2661                                 if(count($r)) {
2662                                         $parent_uri = $r[0]['parent-uri'];
2663                                         if($r[0]['id'] != $r[0]['parent'])
2664                                                 $is_reply = true;
2665                                 }                               
2666
2667                                 if($is_reply) {
2668                                         $community = false;
2669
2670                                         if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2671                                                 $sql_extra = '';
2672                                                 $community = true;
2673                                                 logger('local_delivery: possible community delete');
2674                                         }
2675                                         else
2676                                                 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2677  
2678                                         // was the top-level post for this reply written by somebody on this site? 
2679                                         // Specifically, the recipient? 
2680
2681                                         $is_a_remote_delete = false;
2682
2683                                         // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2684                                         $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`, 
2685                                                 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` 
2686                                                 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` 
2687                                                 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2688                                                 AND `item`.`uid` = %d 
2689                                                 $sql_extra
2690                                                 LIMIT 1",
2691                                                 dbesc($parent_uri),
2692                                                 dbesc($parent_uri),
2693                                                 dbesc($parent_uri),
2694                                                 intval($importer['importer_uid'])
2695                                         );
2696                                         if($r && count($r))
2697                                                 $is_a_remote_delete = true;
2698
2699                                         // Does this have the characteristics of a community or private group comment?
2700                                         // If it's a reply to a wall post on a community/prvgroup page it's a 
2701                                         // valid community comment. Also forum_mode makes it valid for sure. 
2702                                         // If neither, it's not.
2703
2704                                         if($is_a_remote_delete && $community) {
2705                                                 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2706                                                         $is_a_remote_delete = false;
2707                                                         logger('local_delivery: not a community delete');
2708                                                 }
2709                                         }
2710
2711                                         if($is_a_remote_delete) {
2712                                                 logger('local_delivery: received remote delete');
2713                                         }
2714                                 }
2715
2716                                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2717                                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2718                                         dbesc($uri),
2719                                         intval($importer['importer_uid']),
2720                                         intval($importer['id'])
2721                                 );
2722
2723                                 if(count($r)) {
2724                                         $item = $r[0];
2725
2726                                         if($item['deleted'])
2727                                                 continue;
2728
2729                                         logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2730
2731                                         if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2732                                                 $xo = parse_xml_string($item['object'],false);
2733                                                 $xt = parse_xml_string($item['target'],false);
2734
2735                                                 if($xt->type === ACTIVITY_OBJ_NOTE) {
2736                                                         $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2737                                                                 dbesc($xt->id),
2738                                                                 intval($importer['importer_uid'])
2739                                                         );
2740                                                         if(count($i)) {
2741
2742                                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2743
2744                                                                 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2745                                                                 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2746                                                                 $author_copy = (($item['origin']) ? true : false);
2747
2748                                                                 if($owner_remove && $author_copy)
2749                                                                         continue;
2750                                                                 if($author_remove || $owner_remove) {
2751                                                                         $tags = explode(',',$i[0]['tag']);
2752                                                                         $newtags = array();
2753                                                                         if(count($tags)) {
2754                                                                                 foreach($tags as $tag)
2755                                                                                         if(trim($tag) !== trim($xo->body))
2756                                                                                                 $newtags[] = trim($tag);
2757                                                                         }
2758                                                                         q("update item set tag = '%s' where id = %d limit 1",
2759                                                                                 dbesc(implode(',',$newtags)),
2760                                                                                 intval($i[0]['id'])
2761                                                                         );
2762                                                                         create_tags_from_item($i[0]['id']);
2763                                                                 }
2764                                                         }
2765                                                 }
2766                                         }
2767
2768                                         if($item['uri'] == $item['parent-uri']) {
2769                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2770                                                         `body` = '', `title` = ''
2771                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
2772                                                         dbesc($when),
2773                                                         dbesc(datetime_convert()),
2774                                                         dbesc($item['uri']),
2775                                                         intval($importer['importer_uid'])
2776                                                 );
2777                                                 create_tags_from_itemuri($item['uri'], $importer['importer_uid']);
2778                                         }
2779                                         else {
2780                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2781                                                         `body` = '', `title` = ''
2782                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2783                                                         dbesc($when),
2784                                                         dbesc(datetime_convert()),
2785                                                         dbesc($uri),
2786                                                         intval($importer['importer_uid'])
2787                                                 );
2788                                                 create_tags_from_itemuri($uri, $importer['importer_uid']);
2789                                                 if($item['last-child']) {
2790                                                         // ensure that last-child is set in case the comment that had it just got wiped.
2791                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2792                                                                 dbesc(datetime_convert()),
2793                                                                 dbesc($item['parent-uri']),
2794                                                                 intval($item['uid'])
2795                                                         );
2796                                                         // who is the last child now?
2797                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2798                                                                 ORDER BY `created` DESC LIMIT 1",
2799                                                                         dbesc($item['parent-uri']),
2800                                                                         intval($importer['importer_uid'])
2801                                                         );
2802                                                         if(count($r)) {
2803                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2804                                                                         intval($r[0]['id'])
2805                                                                 );
2806                                                         }
2807                                                 }
2808                                                 // if this is a relayed delete, propagate it to other recipients
2809
2810                                                 if($is_a_remote_delete)
2811                                                         proc_run('php',"include/notifier.php","drop",$item['id']);
2812                                         }
2813                                 }
2814                         }
2815                 }
2816         }
2817
2818
2819         foreach($feed->get_items() as $item) {
2820
2821                 $is_reply = false;              
2822                 $item_id = $item->get_id();
2823                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2824                 if(isset($rawthread[0]['attribs']['']['ref'])) {
2825                         $is_reply = true;
2826                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
2827                 }
2828
2829                 if($is_reply) {
2830                         $community = false;
2831
2832                         if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2833                                 $sql_extra = '';
2834                                 $community = true;
2835                                 logger('local_delivery: possible community reply');
2836                         }
2837                         else
2838                                 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2839  
2840                         // was the top-level post for this reply written by somebody on this site? 
2841                         // Specifically, the recipient? 
2842
2843                         $is_a_remote_comment = false;
2844                         $top_uri = $parent_uri;
2845                         
2846                         $r = q("select `item`.`parent-uri` from `item`
2847                                 WHERE `item`.`uri` = '%s'
2848                                 LIMIT 1",
2849                                 dbesc($parent_uri)
2850                         );
2851                         if($r && count($r)) {
2852                                 $top_uri = $r[0]['parent-uri'];
2853
2854                                 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2855                                 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`, 
2856                                         `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` 
2857                                         LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` 
2858                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2859                                         AND `item`.`uid` = %d 
2860                                         $sql_extra
2861                                         LIMIT 1",
2862                                         dbesc($top_uri),
2863                                         dbesc($top_uri),
2864                                         dbesc($top_uri),
2865                                         intval($importer['importer_uid'])
2866                                 );
2867                                 if($r && count($r))
2868                                         $is_a_remote_comment = true;
2869                         }
2870
2871                         // Does this have the characteristics of a community or private group comment?
2872                         // If it's a reply to a wall post on a community/prvgroup page it's a 
2873                         // valid community comment. Also forum_mode makes it valid for sure. 
2874                         // If neither, it's not.
2875
2876                         if($is_a_remote_comment && $community) {
2877                                 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2878                                         $is_a_remote_comment = false;
2879                                         logger('local_delivery: not a community reply');
2880                                 }
2881                         }
2882
2883                         if($is_a_remote_comment) {
2884                                 logger('local_delivery: received remote comment');
2885                                 $is_like = false;
2886                                 // remote reply to our post. Import and then notify everybody else.
2887
2888                                 $datarray = get_atom_elements($feed,$item);
2889
2890                                 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body`  FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2891                                         dbesc($item_id),
2892                                         intval($importer['importer_uid'])
2893                                 );
2894
2895                                 // Update content if 'updated' changes
2896
2897                                 if(count($r)) {
2898                                         $iid = $r[0]['id'];
2899                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2900
2901                                                 // do not accept (ignore) an earlier edit than one we currently have.
2902                                                 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2903                                                         continue;
2904
2905                                                 logger('received updated comment' , LOGGER_DEBUG);
2906                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2907                                                         dbesc($datarray['title']),
2908                                                         dbesc($datarray['body']),
2909                                                         dbesc($datarray['tag']),
2910                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2911                                                         dbesc($item_id),
2912                                                         intval($importer['importer_uid'])
2913                                                 );
2914                                                 create_tags_from_itemuri($item_id, $importer['importer_uid']);
2915
2916                                                 proc_run('php',"include/notifier.php","comment-import",$iid);
2917
2918                                         }
2919
2920                                         continue;
2921                                 }
2922
2923
2924
2925                                 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2926                                         intval($importer['importer_uid'])
2927                                 );
2928
2929
2930                                 $datarray['type'] = 'remote-comment';
2931                                 $datarray['wall'] = 1;
2932                                 $datarray['parent-uri'] = $parent_uri;
2933                                 $datarray['uid'] = $importer['importer_uid'];
2934                                 $datarray['owner-name'] = $own[0]['name'];
2935                                 $datarray['owner-link'] = $own[0]['url'];
2936                                 $datarray['owner-avatar'] = $own[0]['thumb'];
2937                                 $datarray['contact-id'] = $importer['id'];
2938
2939                                 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2940                                         $is_like = true;
2941                                         $datarray['type'] = 'activity';
2942                                         $datarray['gravity'] = GRAVITY_LIKE;
2943                                         $datarray['last-child'] = 0;
2944                                         // only one like or dislike per person
2945                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb = '%s' and (`thr-parent` = '%s' or `parent-uri` = '%s') and deleted = 0 limit 1",
2946                                                 intval($datarray['uid']),
2947                                                 intval($datarray['contact-id']),
2948                                                 dbesc($datarray['verb']),
2949                                                 dbesc($datarray['parent-uri']),
2950                                                 dbesc($datarray['parent-uri'])
2951
2952                                         );
2953                                         if($r && count($r))
2954                                                 continue;
2955                                 }
2956
2957                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2958
2959                                         $xo = parse_xml_string($datarray['object'],false);
2960                                         $xt = parse_xml_string($datarray['target'],false);
2961
2962                                         if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2963
2964                                                 // fetch the parent item
2965
2966                                                 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2967                                                         dbesc($xt->id),
2968                                                         intval($importer['importer_uid'])
2969                                                 );
2970                                                 if(! count($tagp))
2971                                                         continue;
2972
2973                                                 // extract tag, if not duplicate, and this user allows tags, add to parent item
2974
2975                                                 if($xo->id && $xo->content) {
2976                                                         $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2977                                                         if(! (stristr($tagp[0]['tag'],$newtag))) {
2978                                                                 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2979                                                                         intval($importer['importer_uid'])
2980                                                                 );
2981                                                                 if(count($i) && ! intval($i[0]['blocktags'])) {
2982                                                                         q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2983                                                                                 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2984                                                                                 intval($tagp[0]['id']),
2985                                                                                 dbesc(datetime_convert())
2986                                                                         );
2987                                                                         create_tags_from_item($tagp[0]['id']);
2988                                                                 }
2989                                                         }
2990                                                 }
2991                                         }
2992                                 }
2993
2994
2995                                 $posted_id = item_store($datarray);
2996                                 $parent = 0;
2997
2998                                 if($posted_id) {
2999                                         $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3000                                                 intval($posted_id),
3001                                                 intval($importer['importer_uid'])
3002                                         );
3003                                         if(count($r)) {
3004                                                 $parent = $r[0]['parent'];
3005                                                 $parent_uri = $r[0]['parent-uri'];
3006                                         }
3007
3008                                         if(! $is_like) {
3009                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
3010                                                         dbesc(datetime_convert()),
3011                                                         intval($importer['importer_uid']),
3012                                                         intval($r[0]['parent'])
3013                                                 );
3014
3015                                                 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
3016                                                         dbesc(datetime_convert()),
3017                                                         intval($importer['importer_uid']),
3018                                                         intval($posted_id)
3019                                                 );
3020                                         }
3021
3022                                         if($posted_id && $parent) {
3023
3024                                                 proc_run('php',"include/notifier.php","comment-import","$posted_id");
3025
3026                                                 if((! $is_like) && (! $importer['self'])) {
3027
3028                                                         require_once('include/enotify.php');
3029
3030                                                         notification(array(
3031                                                                 'type'         => NOTIFY_COMMENT,
3032                                                                 'notify_flags' => $importer['notify-flags'],
3033                                                                 'language'     => $importer['language'],
3034                                                                 'to_name'      => $importer['username'],
3035                                                                 'to_email'     => $importer['email'],
3036                                                                 'uid'          => $importer['importer_uid'],
3037                                                                 'item'         => $datarray,
3038                                                                 'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3039                                                                 'source_name'  => stripslashes($datarray['author-name']),
3040                                                                 'source_link'  => $datarray['author-link'],
3041                                                                 'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
3042                                                                         ? $importer['thumb'] : $datarray['author-avatar']),
3043                                                                 'verb'         => ACTIVITY_POST,
3044                                                                 'otype'        => 'item',
3045                                                                 'parent'       => $parent,
3046                                                                 'parent_uri'   => $parent_uri,
3047                                                         ));
3048
3049                                                 }
3050                                         }
3051
3052                                         return 0;
3053                                         // NOTREACHED
3054                                 }
3055                         }
3056                         else {
3057
3058                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
3059
3060                                 $item_id  = $item->get_id();
3061                                 $datarray = get_atom_elements($feed,$item);
3062
3063                                 if($importer['rel'] == CONTACT_IS_FOLLOWER)
3064                                         continue;
3065
3066                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3067                                         dbesc($item_id),
3068                                         intval($importer['importer_uid'])
3069                                 );
3070
3071                                 // Update content if 'updated' changes
3072
3073                                 if(count($r)) {
3074                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
3075
3076                                                 // do not accept (ignore) an earlier edit than one we currently have.
3077                                                 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
3078                                                         continue;
3079
3080                                                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3081                                                         dbesc($datarray['title']),
3082                                                         dbesc($datarray['body']),
3083                                                         dbesc($datarray['tag']),
3084                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
3085                                                         dbesc($item_id),
3086                                                         intval($importer['importer_uid'])
3087                                                 );
3088                                                 create_tags_from_itemuri($item_id, $importer['importer_uid']);
3089                                         }
3090
3091                                         // update last-child if it changes
3092
3093                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
3094                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
3095                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
3096                                                         dbesc(datetime_convert()),
3097                                                         dbesc($parent_uri),
3098                                                         intval($importer['importer_uid'])
3099                                                 );
3100                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3101                                                         intval($allow[0]['data']),
3102                                                         dbesc(datetime_convert()),
3103                                                         dbesc($item_id),
3104                                                         intval($importer['importer_uid'])
3105                                                 );
3106                                         }
3107                                         continue;
3108                                 }
3109
3110                                 $datarray['parent-uri'] = $parent_uri;
3111                                 $datarray['uid'] = $importer['importer_uid'];
3112                                 $datarray['contact-id'] = $importer['id'];
3113                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
3114                                         $datarray['type'] = 'activity';
3115                                         $datarray['gravity'] = GRAVITY_LIKE;
3116                                         // only one like or dislike per person
3117                                         $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`parent-uri` = '%s' OR `thr-parent` = '%s') limit 1",
3118                                                 intval($datarray['uid']),
3119                                                 intval($datarray['contact-id']),
3120                                                 dbesc($datarray['verb']),
3121                                                 dbesc($parent_uri),
3122                                                 dbesc($parent_uri)
3123                                         );
3124                                         if($r && count($r))
3125                                                 continue;
3126
3127                                 }
3128
3129                                 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
3130
3131                                         $xo = parse_xml_string($datarray['object'],false);
3132                                         $xt = parse_xml_string($datarray['target'],false);
3133
3134                                         if($xt->type == ACTIVITY_OBJ_NOTE) {
3135                                                 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
3136                                                         dbesc($xt->id),
3137                                                         intval($importer['importer_uid'])
3138                                                 );
3139                                                 if(! count($r))
3140                                                         continue;
3141
3142                                                 // extract tag, if not duplicate, add to parent item
3143                                                 if($xo->content) {
3144                                                         if(! (stristr($r[0]['tag'],trim($xo->content)))) {
3145                                                                 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
3146                                                                         dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
3147                                                                         intval($r[0]['id'])
3148                                                                 );
3149                                                                 create_tags_from_item($r[0]['id']);
3150                                                         }
3151                                                 }
3152                                         }
3153                                 }
3154
3155                                 $posted_id = item_store($datarray);
3156
3157                                 // find out if our user is involved in this conversation and wants to be notified.
3158
3159                                 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
3160
3161                                         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
3162                                                 dbesc($top_uri),
3163                                                 intval($importer['importer_uid'])
3164                                         );
3165
3166                                         if(count($myconv)) {
3167                                                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
3168
3169                                                 // first make sure this isn't our own post coming back to us from a wall-to-wall event
3170                                                 if(! link_compare($datarray['author-link'],$importer_url)) {
3171
3172
3173                                                         foreach($myconv as $conv) {
3174
3175                                                                 // now if we find a match, it means we're in this conversation
3176
3177                                                                 if(! link_compare($conv['author-link'],$importer_url))
3178                                                                         continue;
3179
3180                                                                 require_once('include/enotify.php');
3181                                                                 
3182                                                                 $conv_parent = $conv['parent'];
3183
3184                                                                 notification(array(
3185                                                                         'type'         => NOTIFY_COMMENT,
3186                                                                         'notify_flags' => $importer['notify-flags'],
3187                                                                         'language'     => $importer['language'],
3188                                                                         'to_name'      => $importer['username'],
3189                                                                         'to_email'     => $importer['email'],
3190                                                                         'uid'          => $importer['importer_uid'],
3191                                                                         'item'         => $datarray,
3192                                                                         'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3193                                                                         'source_name'  => stripslashes($datarray['author-name']),
3194                                                                         'source_link'  => $datarray['author-link'],
3195                                                                         'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
3196                                                                                 ? $importer['thumb'] : $datarray['author-avatar']),
3197                                                                         'verb'         => ACTIVITY_POST,
3198                                                                         'otype'        => 'item',
3199                                                                         'parent'       => $conv_parent,
3200                                                                         'parent_uri'   => $parent_uri
3201
3202                                                                 ));
3203
3204                                                                 // only send one notification
3205                                                                 break;
3206                                                         }
3207                                                 }
3208                                         }
3209                                 }
3210                                 continue;
3211                         }
3212                 }
3213
3214                 else {
3215
3216                         // Head post of a conversation. Have we seen it? If not, import it.
3217
3218
3219                         $item_id  = $item->get_id();
3220                         $datarray = get_atom_elements($feed,$item);
3221
3222                         if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
3223                                 $ev = bbtoevent($datarray['body']);
3224                                 if(x($ev,'desc') && x($ev,'start')) {
3225                                         $ev['cid'] = $importer['id'];
3226                                         $ev['uid'] = $importer['uid'];
3227                                         $ev['uri'] = $item_id;
3228                                         $ev['edited'] = $datarray['edited'];
3229                                         $ev['private'] = $datarray['private'];
3230
3231                                         $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3232                                                 dbesc($item_id),
3233                                                 intval($importer['uid'])
3234                                         );
3235                                         if(count($r))
3236                                                 $ev['id'] = $r[0]['id'];
3237                                         $xyz = event_store($ev);
3238                                         continue;
3239                                 }
3240                         }
3241
3242                         $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3243                                 dbesc($item_id),
3244                                 intval($importer['importer_uid'])
3245                         );
3246
3247                         // Update content if 'updated' changes
3248
3249                         if(count($r)) {
3250                                 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
3251
3252                                         // do not accept (ignore) an earlier edit than one we currently have.
3253                                         if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
3254                                                 continue;
3255
3256                                         $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3257                                                 dbesc($datarray['title']),
3258                                                 dbesc($datarray['body']),
3259                                                 dbesc($datarray['tag']),
3260                                                 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
3261                                                 dbesc($item_id),
3262                                                 intval($importer['importer_uid'])
3263                                         );
3264                                         create_tags_from_itemuri($item_id, $importer['importer_uid']);
3265                                 }
3266
3267                                 // update last-child if it changes
3268
3269                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
3270                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
3271                                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3272                                                 intval($allow[0]['data']),
3273                                                 dbesc(datetime_convert()),
3274                                                 dbesc($item_id),
3275                                                 intval($importer['importer_uid'])
3276                                         );
3277                                 }
3278                                 continue;
3279                         }
3280
3281                         // This is my contact on another system, but it's really me.
3282                         // Turn this into a wall post.
3283
3284                         if($importer['remote_self'])
3285                                 $datarray['wall'] = 1;
3286
3287                         $datarray['parent-uri'] = $item_id;
3288                         $datarray['uid'] = $importer['importer_uid'];
3289                         $datarray['contact-id'] = $importer['id'];
3290
3291
3292                         if(! link_compare($datarray['owner-link'],$importer['url'])) {
3293                                 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery, 
3294                                 // but otherwise there's a possible data mixup on the sender's system.
3295                                 // the tgroup delivery code called from item_store will correct it if it's a forum,
3296                                 // but we're going to unconditionally correct it here so that the post will always be owned by our contact. 
3297                                 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
3298                                 $datarray['owner-name']   = $importer['senderName'];
3299                                 $datarray['owner-link']   = $importer['url'];
3300                                 $datarray['owner-avatar'] = $importer['thumb'];
3301                         }
3302
3303                         if(($importer['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['importer_uid'],$datarray)))
3304                                 continue;
3305
3306                         $posted_id = item_store($datarray);
3307
3308                         if(stristr($datarray['verb'],ACTIVITY_POKE)) {
3309                                 $verb = urldecode(substr($datarray['verb'],strpos($datarray['verb'],'#')+1));
3310                                 if(! $verb)
3311                                         continue;
3312                                 $xo = parse_xml_string($datarray['object'],false);
3313
3314                                 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
3315
3316                                         // somebody was poked/prodded. Was it me?
3317
3318                                         $links = parse_xml_string("<links>".unxmlify($xo->link)."</links>",false);
3319
3320                                 foreach($links->link as $l) {
3321                                 $atts = $l->attributes();
3322                                 switch($atts['rel']) {
3323                                         case "alternate": 
3324                                                                 $Blink = $atts['href'];
3325                                                                 break;
3326                                                         default:
3327                                                                 break;
3328                                     }
3329                                 }
3330                                         if($Blink && link_compare($Blink,$a->get_baseurl() . '/profile/' . $importer['nickname'])) {
3331
3332                                                 // send a notification
3333                                                 require_once('include/enotify.php');
3334                                                                 
3335                                                 notification(array(
3336                                                         'type'         => NOTIFY_POKE,
3337                                                         'notify_flags' => $importer['notify-flags'],
3338                                                         'language'     => $importer['language'],
3339                                                         'to_name'      => $importer['username'],
3340                                                         'to_email'     => $importer['email'],
3341                                                         'uid'          => $importer['importer_uid'],
3342                                                         'item'         => $datarray,
3343                                                         'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3344                                                         'source_name'  => stripslashes($datarray['author-name']),
3345                                                         'source_link'  => $datarray['author-link'],
3346                                                         'source_photo' => ((link_compare($datarray['author-link'],$importer['url'])) 
3347                                                                 ? $importer['thumb'] : $datarray['author-avatar']),
3348                                                         'verb'         => $datarray['verb'],
3349                                                         'otype'        => 'person',
3350                                                         'activity'     => $verb,
3351
3352                                                 ));
3353                                         }
3354                                 }
3355                         }                       
3356
3357                         continue;
3358                 }
3359         }
3360
3361         return 0;
3362         // NOTREACHED
3363
3364 }
3365
3366
3367 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
3368         $url = notags(trim($datarray['author-link']));
3369         $name = notags(trim($datarray['author-name']));
3370         $photo = notags(trim($datarray['author-avatar']));
3371
3372         $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
3373         if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
3374                 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
3375
3376         if(is_array($contact)) {
3377                 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
3378                         || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
3379                         $r = q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
3380                                 intval(CONTACT_IS_FRIEND),
3381                                 intval($contact['id']),
3382                                 intval($importer['uid'])
3383                         );
3384                 }
3385                 // send email notification to owner?
3386         }
3387         else {
3388
3389                 // create contact record
3390
3391                 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`, 
3392                         `blocked`, `readonly`, `pending`, `writable` )
3393                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
3394                         intval($importer['uid']),
3395                         dbesc(datetime_convert()),
3396                         dbesc($url),
3397                         dbesc(normalise_link($url)),
3398                         dbesc($name),
3399                         dbesc($nick),
3400                         dbesc($photo),
3401                         dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
3402                         intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
3403                 );
3404                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
3405                                 intval($importer['uid']),
3406                                 dbesc($url)
3407                 );
3408                 if(count($r))
3409                                 $contact_record = $r[0];
3410
3411                 // create notification
3412                 $hash = random_string();
3413
3414                 if(is_array($contact_record)) {
3415                         $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
3416                                 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
3417                                 intval($importer['uid']),
3418                                 intval($contact_record['id']),
3419                                 dbesc($hash),
3420                                 dbesc(datetime_convert())
3421                         );
3422                 }
3423                 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3424                         intval($importer['uid'])
3425                 );
3426                 $a = get_app();
3427                 if(count($r)) {
3428
3429                         if(intval($r[0]['def_gid'])) {
3430                                 require_once('include/group.php');
3431                                 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
3432                         }
3433
3434                         if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
3435                                 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
3436                                 $email = replace_macros($email_tpl, array(
3437                                         '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
3438                                         '$url' => $url,
3439                                         '$myname' => $r[0]['username'],
3440                                         '$siteurl' => $a->get_baseurl(),
3441                                         '$sitename' => $a->config['sitename']
3442                                 ));
3443                                 $res = mail($r[0]['email'], 
3444                                         email_header_encode((($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],'UTF-8'),
3445                                         $email,
3446                                         'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
3447                                         . 'Content-type: text/plain; charset=UTF-8' . "\n"
3448                                         . 'Content-transfer-encoding: 8bit' );
3449
3450                         }
3451                 }
3452         }
3453 }
3454
3455 function lose_follower($importer,$contact,$datarray,$item) {
3456
3457         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
3458                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3459                         intval(CONTACT_IS_SHARING),
3460                         intval($contact['id'])
3461                 );
3462         }
3463         else {
3464                 contact_remove($contact['id']);
3465         }
3466 }
3467
3468 function lose_sharer($importer,$contact,$datarray,$item) {
3469
3470         if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
3471                 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3472                         intval(CONTACT_IS_FOLLOWER),
3473                         intval($contact['id'])
3474                 );
3475         }
3476         else {
3477                 contact_remove($contact['id']);
3478         }
3479 }
3480
3481
3482 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
3483
3484         $a = get_app();
3485
3486         if(is_array($importer)) {
3487                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
3488                         intval($importer['uid'])
3489                 );
3490         }
3491
3492         // Diaspora has different message-ids in feeds than they do 
3493         // through the direct Diaspora protocol. If we try and use
3494         // the feed, we'll get duplicates. So don't.
3495
3496         if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
3497                 return;
3498
3499         $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
3500
3501         // Use a single verify token, even if multiple hubs
3502
3503         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
3504
3505         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
3506
3507         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
3508
3509         if(! strlen($contact['hub-verify'])) {
3510                 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
3511                         dbesc($verify_token),
3512                         intval($contact['id'])
3513                 );
3514         }
3515
3516         post_url($url,$params);
3517
3518         logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
3519
3520         return;
3521
3522 }
3523
3524
3525 function atom_author($tag,$name,$uri,$h,$w,$photo) {
3526         $o = '';
3527         if(! $tag)
3528                 return $o;
3529         $name = xmlify($name);
3530         $uri = xmlify($uri);
3531         $h = intval($h);
3532         $w = intval($w);
3533         $photo = xmlify($photo);
3534
3535
3536         $o .= "<$tag>\r\n";
3537         $o .= "<name>$name</name>\r\n";
3538         $o .= "<uri>$uri</uri>\r\n";
3539         $o .= '<link rel="photo"  type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3540         $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3541
3542         call_hooks('atom_author', $o);
3543
3544         $o .= "</$tag>\r\n";
3545         return $o;
3546 }
3547
3548 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
3549
3550         $a = get_app();
3551
3552         if(! $item['parent'])
3553                 return;
3554
3555         if($item['deleted'])
3556                 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
3557
3558
3559         if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
3560                 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
3561         else
3562                 $body = $item['body'];
3563
3564         $o = "\r\n\r\n<entry>\r\n";
3565
3566         if(is_array($author))
3567                 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
3568         else
3569                 $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']));
3570         if(strlen($item['owner-name']))
3571                 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
3572
3573         if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
3574                 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
3575                 $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' .  xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
3576         }
3577
3578         $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
3579         $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
3580         $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
3581         $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
3582         $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
3583         $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
3584         $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
3585         if($comment)
3586                 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
3587
3588         if($item['location']) {
3589                 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
3590                 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
3591         }
3592
3593         if($item['coord'])
3594                 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
3595
3596         if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
3597                 $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
3598
3599         if($item['extid'])
3600                 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
3601         if($item['bookmark'])
3602                 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
3603
3604         if($item['app'])
3605                 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
3606
3607         if($item['guid'])
3608                 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
3609
3610         if($item['signed_text']) {
3611                 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
3612                 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
3613         }
3614
3615         $verb = construct_verb($item);
3616         $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
3617         $actobj = construct_activity_object($item);
3618         if(strlen($actobj))
3619                 $o .= $actobj;
3620         $actarg = construct_activity_target($item);
3621         if(strlen($actarg))
3622                 $o .= $actarg;
3623
3624         $tags = item_getfeedtags($item);
3625         if(count($tags)) {
3626                 foreach($tags as $t) {
3627                         $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
3628                 }
3629         }
3630
3631         $o .= item_getfeedattach($item);
3632
3633         $mentioned = get_mentions($item);
3634         if($mentioned)
3635                 $o .= $mentioned;
3636         
3637         call_hooks('atom_entry', $o);
3638
3639         $o .= '</entry>' . "\r\n";
3640         
3641         return $o;
3642 }
3643
3644 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
3645         $a = get_app();
3646
3647         logger('fix_private_photos', LOGGER_DEBUG);
3648         $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3649
3650         $orig_body = $s;
3651         $new_body = '';
3652
3653         $img_start = strpos($orig_body, '[img');
3654         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3655         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3656         while( ($img_st_close !== false) && ($img_len !== false) ) {
3657
3658                 $img_st_close++; // make it point to AFTER the closing bracket
3659                 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
3660
3661                 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3662
3663
3664                 if(stristr($image , $site . '/photo/')) {
3665                         // Only embed locally hosted photos
3666                         $replace = false;
3667                         $i = basename($image);
3668                         $i = str_replace(array('.jpg','.png'),array('',''),$i);
3669                         $x = strpos($i,'-');
3670
3671                         if($x) {
3672                                 $res = substr($i,$x+1);
3673                                 $i = substr($i,0,$x);
3674                                 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3675                                         dbesc($i),
3676                                         intval($res),
3677                                         intval($uid)
3678                                 );
3679                                 if(count($r)) {
3680
3681                                         // Check to see if we should replace this photo link with an embedded image
3682                                         // 1. No need to do so if the photo is public
3683                                         // 2. If there's a contact-id provided, see if they're in the access list
3684                                         //    for the photo. If so, embed it. 
3685                                         // 3. Otherwise, if we have an item, see if the item permissions match the photo
3686                                         //    permissions, regardless of order but first check to see if they're an exact
3687                                         //    match to save some processing overhead.
3688
3689                                         if(has_permissions($r[0])) {
3690                                                 if($cid) {
3691                                                         $recips = enumerate_permissions($r[0]);
3692                                                         if(in_array($cid, $recips)) {
3693                                                                 $replace = true;        
3694                                                         }
3695                                                 }
3696                                                 elseif($item) {
3697                                                         if(compare_permissions($item,$r[0]))
3698                                                                 $replace = true;
3699                                                 }
3700                                         }
3701                                         if($replace) {
3702                                                 $data = $r[0]['data'];
3703                                                 $type = $r[0]['type'];
3704
3705                                                 // If a custom width and height were specified, apply before embedding
3706                                                 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
3707                                                         logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
3708
3709                                                         $width = intval($match[1]);
3710                                                         $height = intval($match[2]);
3711
3712                                                         $ph = new Photo($data, $type);
3713                                                         if($ph->is_valid()) {
3714                                                                 $ph->scaleImage(max($width, $height));
3715                                                                 $data = $ph->imageString();
3716                                                                 $type = $ph->getType();
3717                                                         }
3718                                                 }
3719
3720                                                 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3721                                                 $image = 'data:' . $type . ';base64,' . base64_encode($data);
3722                                                 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
3723                                         }
3724                                 }
3725                         }
3726                 }       
3727
3728                 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
3729                 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
3730                 if($orig_body === false)
3731                         $orig_body = '';
3732
3733                 $img_start = strpos($orig_body, '[img');
3734                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3735                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3736         }
3737
3738         $new_body = $new_body . $orig_body;
3739
3740         return($new_body);
3741 }
3742
3743
3744 function has_permissions($obj) {
3745         if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3746                 return true;
3747         return false;
3748 }
3749
3750 function compare_permissions($obj1,$obj2) {
3751         // first part is easy. Check that these are exactly the same. 
3752         if(($obj1['allow_cid'] == $obj2['allow_cid'])
3753                 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3754                 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3755                 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3756                 return true;
3757
3758         // This is harder. Parse all the permissions and compare the resulting set.
3759
3760         $recipients1 = enumerate_permissions($obj1);
3761         $recipients2 = enumerate_permissions($obj2);
3762         sort($recipients1);
3763         sort($recipients2);
3764         if($recipients1 == $recipients2)
3765                 return true;
3766         return false;
3767 }
3768
3769 // returns an array of contact-ids that are allowed to see this object
3770
3771 function enumerate_permissions($obj) {
3772         require_once('include/group.php');
3773         $allow_people = expand_acl($obj['allow_cid']);
3774         $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3775         $deny_people  = expand_acl($obj['deny_cid']);
3776         $deny_groups  = expand_groups(expand_acl($obj['deny_gid']));
3777         $recipients   = array_unique(array_merge($allow_people,$allow_groups));
3778         $deny         = array_unique(array_merge($deny_people,$deny_groups));
3779         $recipients   = array_diff($recipients,$deny);
3780         return $recipients;
3781 }
3782
3783 function item_getfeedtags($item) {
3784         $ret = array();
3785         $matches = false;
3786         $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3787         if($cnt) {
3788                 for($x = 0; $x < $cnt; $x ++) {
3789                         if($matches[1][$x])
3790                                 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3791                 }
3792         }
3793         $matches = false; 
3794         $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3795         if($cnt) {
3796                 for($x = 0; $x < $cnt; $x ++) {
3797                         if($matches[1][$x])
3798                                 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3799                 }
3800         } 
3801         return $ret;
3802 }
3803
3804 function item_getfeedattach($item) {
3805         $ret = '';
3806         $arr = explode('[/attach],',$item['attach']);
3807         if(count($arr)) {
3808                 foreach($arr as $r) {
3809                         $matches = false;
3810                         $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
3811                         if($cnt) {
3812                                 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3813                                 if(intval($matches[2]))
3814                                         $ret .= 'length="' . intval($matches[2]) . '" ';
3815                                 if($matches[4] !== ' ')
3816                                         $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3817                                 $ret .= ' />' . "\r\n";
3818                         }
3819                 }
3820         }
3821         return $ret;
3822 }
3823
3824
3825         
3826 function item_expire($uid,$days) {
3827
3828         if((! $uid) || ($days < 1))
3829                 return;
3830
3831         // $expire_network_only = save your own wall posts
3832         // and just expire conversations started by others
3833
3834         $expire_network_only = get_pconfig($uid,'expire','network_only');
3835         $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3836
3837         $r = q("SELECT * FROM `item` 
3838                 WHERE `uid` = %d 
3839                 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY 
3840                 AND `id` = `parent` 
3841                 $sql_extra
3842                 AND `deleted` = 0",
3843                 intval($uid),
3844                 intval($days)
3845         );
3846
3847         if(! count($r))
3848                 return;
3849
3850         $expire_items = get_pconfig($uid, 'expire','items');
3851         $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3852
3853         $expire_notes = get_pconfig($uid, 'expire','notes');
3854         $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3855
3856         $expire_starred = get_pconfig($uid, 'expire','starred');
3857         $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3858
3859         $expire_photos = get_pconfig($uid, 'expire','photos');
3860         $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3861
3862         logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3863
3864         foreach($r as $item) {
3865
3866                 // don't expire filed items
3867
3868                 if(strpos($item['file'],'[') !== false)
3869                         continue;
3870
3871                 // Only expire posts, not photos and photo comments
3872
3873                 if($expire_photos==0 && strlen($item['resource-id']))
3874                         continue;
3875                 if($expire_starred==0 && intval($item['starred']))
3876                         continue;
3877                 if($expire_notes==0 && $item['type']=='note')
3878                         continue;
3879                 if($expire_items==0 && $item['type']!='note')
3880                         continue;
3881
3882                 drop_item($item['id'],false);
3883         }
3884
3885         proc_run('php',"include/notifier.php","expire","$uid");
3886         
3887 }
3888
3889
3890 function drop_items($items) {
3891         $uid = 0;
3892
3893         if(! local_user() && ! remote_user())
3894                 return;
3895
3896         if(count($items)) {
3897                 foreach($items as $item) {
3898                         $owner = drop_item($item,false);
3899                         if($owner && ! $uid)
3900                                 $uid = $owner;
3901                 }
3902         }
3903
3904         // multiple threads may have been deleted, send an expire notification
3905
3906         if($uid)
3907                 proc_run('php',"include/notifier.php","expire","$uid");
3908 }
3909
3910
3911 function drop_item($id,$interactive = true) {
3912
3913         $a = get_app();
3914
3915         // locate item to be deleted
3916
3917         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3918                 intval($id)
3919         );
3920
3921         if(! count($r)) {
3922                 if(! $interactive)
3923                         return 0;
3924                 notice( t('Item not found.') . EOL);
3925                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3926         }
3927
3928         $item = $r[0];
3929
3930         $owner = $item['uid'];
3931
3932         $cid = 0;
3933
3934         // check if logged in user is either the author or owner of this item
3935
3936         if(is_array($_SESSION['remote'])) {
3937                 foreach($_SESSION['remote'] as $visitor) {
3938                         if($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
3939                                 $cid = $visitor['cid'];
3940                                 break;
3941                         }
3942                 }
3943         }
3944
3945
3946         if((local_user() == $item['uid']) || ($cid) || (! $interactive)) {
3947
3948                 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
3949                 // delete the item
3950
3951                 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3952                         dbesc(datetime_convert()),
3953                         dbesc(datetime_convert()),
3954                         intval($item['id'])
3955                 );
3956                 create_tags_from_item($item['id']);
3957
3958                 // clean up categories and tags so they don't end up as orphans
3959
3960                 $matches = false;
3961                 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3962                 if($cnt) {
3963                         foreach($matches as $mtch) {
3964                                 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3965                         }
3966                 }
3967
3968                 $matches = false;
3969
3970                 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3971                 if($cnt) {
3972                         foreach($matches as $mtch) {
3973                                 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3974                         }
3975                 }
3976
3977                 // If item is a link to a photo resource, nuke all the associated photos 
3978                 // (visitors will not have photo resources)
3979                 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3980                 // generate a resource-id and therefore aren't intimately linked to the item. 
3981
3982                 if(strlen($item['resource-id'])) {
3983                         q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3984                                 dbesc($item['resource-id']),
3985                                 intval($item['uid'])
3986                         );
3987                         // ignore the result
3988                 }
3989
3990                 // If item is a link to an event, nuke the event record.
3991
3992                 if(intval($item['event-id'])) {
3993                         q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3994                                 intval($item['event-id']),
3995                                 intval($item['uid'])
3996                         );
3997                         // ignore the result
3998                 }
3999
4000                 // clean up item_id and sign meta-data tables
4001
4002                 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
4003                         intval($item['id']),
4004                         intval($item['uid'])
4005                 );
4006
4007                 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
4008                         intval($item['id']),
4009                         intval($item['uid'])
4010                 );
4011
4012                 // If it's the parent of a comment thread, kill all the kids
4013
4014                 if($item['uri'] == $item['parent-uri']) {
4015                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
4016                                 WHERE `parent-uri` = '%s' AND `uid` = %d ",
4017                                 dbesc(datetime_convert()),
4018                                 dbesc(datetime_convert()),
4019                                 dbesc($item['parent-uri']),
4020                                 intval($item['uid'])
4021                         );
4022                         create_tags_from_item($item['parent-uri'], $item['uid']);
4023                         // ignore the result
4024                 }
4025                 else {
4026                         // ensure that last-child is set in case the comment that had it just got wiped.
4027                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
4028                                 dbesc(datetime_convert()),
4029                                 dbesc($item['parent-uri']),
4030                                 intval($item['uid'])
4031                         );
4032                         // who is the last child now?
4033                         $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",
4034                                 dbesc($item['parent-uri']),
4035                                 intval($item['uid'])
4036                         );
4037                         if(count($r)) {
4038                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
4039                                         intval($r[0]['id'])
4040                                 );
4041                         }
4042
4043                         // Add a relayable_retraction signature for Diaspora.
4044                         store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
4045                 }
4046                 $drop_id = intval($item['id']);
4047
4048                 // send the notification upstream/downstream as the case may be
4049
4050                 proc_run('php',"include/notifier.php","drop","$drop_id");
4051
4052                 if(! $interactive)
4053                         return $owner;
4054                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
4055                 //NOTREACHED
4056         }
4057         else {
4058                 if(! $interactive)
4059                         return 0;
4060                 notice( t('Permission denied.') . EOL);
4061                 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
4062                 //NOTREACHED
4063         }
4064
4065 }
4066
4067
4068 function first_post_date($uid,$wall = false) {
4069         $r = q("select id, created from item 
4070                 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0 
4071                 and id = parent
4072                 order by created asc limit 1",
4073                 intval($uid),
4074                 intval($wall ? 1 : 0)
4075         );
4076         if(count($r)) {
4077 //              logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
4078                 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
4079         }
4080         return false;
4081 }
4082
4083 function posted_dates($uid,$wall) {
4084         $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
4085
4086         $dthen = first_post_date($uid,$wall);
4087         if(! $dthen)
4088                 return array();
4089
4090         // If it's near the end of a long month, backup to the 28th so that in 
4091         // consecutive loops we'll always get a whole month difference.
4092
4093         if(intval(substr($dnow,8)) > 28)
4094                 $dnow = substr($dnow,0,8) . '28';
4095         if(intval(substr($dthen,8)) > 28)
4096                 $dnow = substr($dthen,0,8) . '28';
4097
4098         $ret = array();
4099         // Starting with the current month, get the first and last days of every
4100         // month down to and including the month of the first post
4101         while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
4102                 $dstart = substr($dnow,0,8) . '01';
4103                 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
4104                 $start_month = datetime_convert('','',$dstart,'Y-m-d');
4105                 $end_month = datetime_convert('','',$dend,'Y-m-d');
4106                 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
4107                 $ret[] = array($str,$end_month,$start_month);
4108                 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
4109         }
4110         return $ret;
4111 }
4112
4113
4114 function posted_date_widget($url,$uid,$wall) {
4115         $o = '';
4116
4117         if(! feature_enabled($uid,'archives'))
4118                 return $o;
4119
4120         // For former Facebook folks that left because of "timeline"
4121
4122 /*      if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
4123                 return $o;*/
4124
4125         $ret = posted_dates($uid,$wall);
4126         if(! count($ret))
4127                 return $o;
4128
4129         $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
4130                 '$title' => t('Archives'),
4131                 '$size' => ((count($ret) > 6) ? 6 : count($ret)),
4132                 '$url' => $url,
4133                 '$dates' => $ret
4134         ));
4135         return $o;
4136 }
4137
4138 function store_diaspora_retract_sig($item, $user, $baseurl) {
4139         // Note that we can't add a target_author_signature
4140         // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
4141         // the comment, that means we're the home of the post, and Diaspora will only
4142         // check the parent_author_signature of retractions that it doesn't have to relay further
4143         //
4144         // I don't think this function gets called for an "unlike," but I'll check anyway
4145
4146         $enabled = intval(get_config('system','diaspora_enabled'));
4147         if(! $enabled) {
4148                 logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
4149                 return;
4150         }
4151
4152         logger('drop_item: storing diaspora retraction signature');
4153
4154         $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
4155
4156         if(local_user() == $item['uid']) {
4157
4158                 $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
4159                 $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
4160         }
4161         else {
4162                 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
4163                         $item['contact-id'] // If this function gets called, drop_item() has already checked remote_user() == $item['contact-id']
4164                 );
4165                 if(count($r)) {
4166                         // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
4167                         // only handles DFRN deletes
4168                         $handle_baseurl_start = strpos($r['url'],'://') + 3;
4169                         $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
4170                         $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
4171                         $authorsig = '';
4172                 }
4173         }
4174
4175         if(isset($handle))
4176                 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
4177                         intval($item['id']),
4178                         dbesc($signed_text),
4179                         dbesc($authorsig),
4180                         dbesc($handle)
4181                 );
4182
4183         return;
4184 }