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