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