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