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