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