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