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