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