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