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