]> git.mxchange.org Git - friendica.git/blob - mod/item.php
5fb0ef43700e665e00484ba3750439e6fdcc8435
[friendica.git] / mod / item.php
1 <?php
2
3 /**
4  *
5  * This is the POST destination for most all locally posted
6  * text stuff. This function handles status, wall-to-wall status, 
7  * local comments, and remote coments - that are posted on this site 
8  * (as opposed to being delivered in a feed).
9  * Also processed here are posts and comments coming through the 
10  * statusnet/twitter API. 
11  * All of these become an "item" which is our basic unit of 
12  * information.
13  * Posts that originate externally or do not fall into the above 
14  * posting categories go through item_store() instead of this function. 
15  *
16  */  
17
18 require_once('include/crypto.php');
19 require_once('include/enotify.php');
20
21 function item_post(&$a) {
22
23         if((! local_user()) && (! remote_user()))
24                 return;
25
26         require_once('include/security.php');
27
28         $uid = local_user();
29
30         if(x($_POST,'dropitems')) {
31                 require_once('include/items.php');
32                 $arr_drop = explode(',',$_POST['dropitems']);
33                 drop_items($arr_drop);
34                 $json = array('success' => 1);
35                 echo json_encode($json);
36                 killme();
37         }
38
39         call_hooks('post_local_start', $_POST);
40 //      logger('postinput ' . file_get_contents('php://input'));
41         logger('postvars' . print_r($_POST,true), LOGGER_DATA);
42
43         $api_source = ((x($_POST,'api_source') && $_POST['api_source']) ? true : false);
44         $return_path = ((x($_POST,'return')) ? $_POST['return'] : '');
45
46         /**
47          * Is this a reply to something?
48          */
49
50         $parent = ((x($_POST,'parent')) ? intval($_POST['parent']) : 0);
51         $parent_uri = ((x($_POST,'parent_uri')) ? trim($_POST['parent_uri']) : '');
52
53         $parent_item = null;
54         $parent_contact = null;
55         $thr_parent = '';
56         $parid = 0;
57         $r = false;
58
59         $preview = ((x($_POST,'preview')) ? intval($_POST['preview']) : 0);
60
61         if($parent || $parent_uri) {
62
63                 if(! x($_POST,'type'))
64                         $_POST['type'] = 'net-comment';
65
66                 if($parent) {
67                         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
68                                 intval($parent)
69                         );
70                 }
71                 elseif($parent_uri && local_user()) {
72                         // This is coming from an API source, and we are logged in
73                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
74                                 dbesc($parent_uri),
75                                 intval(local_user())
76                         );
77                 }
78                 // if this isn't the real parent of the conversation, find it
79                 if($r !== false && count($r)) {
80                         $parid = $r[0]['parent'];
81                         if($r[0]['id'] != $r[0]['parent']) {
82                                 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
83                                         intval($parid)
84                                 );
85                         }
86                 }
87
88                 if(($r === false) || (! count($r))) {
89                         notice( t('Unable to locate original post.') . EOL);
90                         if(x($_POST,'return')) 
91                                 goaway($a->get_baseurl() . "/" . $return_path );
92                         killme();
93                 }
94                 $parent_item = $r[0];
95                 $parent = $r[0]['id'];
96
97                 // multi-level threading - preserve the info but re-parent to our single level threading
98                 if(($parid) && ($parid != $parent))
99                         $thr_parent = $parent_uri;
100
101                 if($parent_item['contact-id'] && $uid) {
102                         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
103                                 intval($parent_item['contact-id']),
104                                 intval($uid)
105                         );
106                         if(count($r))
107                                 $parent_contact = $r[0];
108                 }
109         }
110
111         if($parent) logger('mod_post: parent=' . $parent);
112
113         $profile_uid = ((x($_POST,'profile_uid')) ? intval($_POST['profile_uid']) : 0);
114         $post_id     = ((x($_POST['post_id']))    ? intval($_POST['post_id'])     : 0);
115         $app         = ((x($_POST['source']))     ? strip_tags($_POST['source'])  : '');
116
117         if(! can_write_wall($a,$profile_uid)) {
118                 notice( t('Permission denied.') . EOL) ;
119                 if(x($_POST,'return')) 
120                         goaway($a->get_baseurl() . "/" . $return_path );
121                 killme();
122         }
123
124
125         // is this an edited post?
126
127         $orig_post = null;
128
129         if($post_id) {
130                 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
131                         intval($profile_uid),
132                         intval($post_id)
133                 );
134                 if(! count($i))
135                         killme();
136                 $orig_post = $i[0];
137         }
138
139         $user = null;
140
141         $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
142                 intval($profile_uid)
143         );
144         if(count($r))
145                 $user = $r[0];
146
147         if($orig_post) {
148                 $str_group_allow   = $orig_post['allow_gid'];
149                 $str_contact_allow = $orig_post['allow_cid'];
150                 $str_group_deny    = $orig_post['deny_gid'];
151                 $str_contact_deny  = $orig_post['deny_cid'];
152                 $title             = $orig_post['title'];
153                 $location          = $orig_post['location'];
154                 $coord             = $orig_post['coord'];
155                 $verb              = $orig_post['verb'];
156                 $emailcc           = $orig_post['emailcc'];
157                 $app                       = $orig_post['app'];
158
159                 $body              = escape_tags(trim($_POST['body']));
160                 $private           = $orig_post['private'];
161                 $pubmail_enable    = $orig_post['pubmail'];
162         }
163         else {
164                 $str_group_allow   = perms2str($_POST['group_allow']);
165                 $str_contact_allow = perms2str($_POST['contact_allow']);
166                 $str_group_deny    = perms2str($_POST['group_deny']);
167                 $str_contact_deny  = perms2str($_POST['contact_deny']);
168                 $title             = notags(trim($_POST['title']));
169                 $location          = notags(trim($_POST['location']));
170                 $coord             = notags(trim($_POST['coord']));
171                 $verb              = notags(trim($_POST['verb']));
172                 $emailcc           = notags(trim($_POST['emailcc']));
173
174                 $body              = escape_tags(trim($_POST['body']));
175                 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
176
177                 if(($parent_item) && 
178                         (($parent_item['private']) 
179                                 || strlen($parent_item['allow_cid']) 
180                                 || strlen($parent_item['allow_gid']) 
181                                 || strlen($parent_item['deny_cid']) 
182                                 || strlen($parent_item['deny_gid'])
183                         )) {
184                         $private = 1;
185                 }
186         
187                 $pubmail_enable    = ((x($_POST,'pubmail_enable') && intval($_POST['pubmail_enable']) && (! $private)) ? 1 : 0);
188
189                 // if using the API, we won't see pubmail_enable - figure out if it should be set
190
191                 if($api_source && $profile_uid && $profile_uid == local_user() && (! $private)) {
192                         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
193                         if(! $mail_disabled) {
194                                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
195                                         intval(local_user())
196                                 );
197                                 if(count($r) && intval($r[0]['pubmail']))
198                                         $pubmail_enabled = true;
199                         }
200                 }
201
202
203                 if(! strlen($body)) {
204                         if($preview)
205                                 killme();
206                         info( t('Empty post discarded.') . EOL );
207                         if(x($_POST,'return')) 
208                                 goaway($a->get_baseurl() . "/" . $return_path );
209                         killme();
210                 }
211         }
212
213         if(($api_source) 
214                 && (! array_key_exists('contact_allow',$_REQUEST))
215                 && (! array_key_exists('group_allow',$_REQUEST))
216                 && (! array_key_exists('contact_deny',$_REQUEST))
217                 && (! array_key_exists('group_deny',$_REQUEST))) {
218                 $str_group_allow   = $user['allow_gid'];
219                 $str_contact_allow = $user['allow_cid'];
220                 $str_group_deny    = $user['deny_gid'];
221                 $str_contact_deny  = $user['deny_cid'];
222         }
223
224
225         // get contact info for poster
226
227         $author = null;
228         $self   = false;
229
230         if(($_SESSION['uid']) && ($_SESSION['uid'] == $profile_uid)) {
231                 $self = true;
232                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
233                         intval($_SESSION['uid'])
234                 );
235         }
236         else {
237                 if((x($_SESSION,'visitor_id')) && (intval($_SESSION['visitor_id']))) {
238                         $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
239                                 intval($_SESSION['visitor_id'])
240                         );
241                 }
242         }
243
244         if(count($r)) {
245                 $author = $r[0];
246                 $contact_id = $author['id'];
247         }
248
249         // get contact info for owner
250         
251         if($profile_uid == $_SESSION['uid']) {
252                 $contact_record = $author;
253         }
254         else {
255                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
256                         intval($profile_uid)
257                 );
258                 if(count($r))
259                         $contact_record = $r[0];
260         }
261
262
263
264         $post_type = notags(trim($_POST['type']));
265
266         if($post_type === 'net-comment') {
267                 if($parent_item !== null) {
268                         if($parent_item['wall'] == 1)
269                                 $post_type = 'wall-comment';
270                         else
271                                 $post_type = 'remote-comment';
272                 }
273         }
274
275         /**
276          *
277          * When a photo was uploaded into the message using the (profile wall) ajax 
278          * uploader, The permissions are initially set to disallow anybody but the
279          * owner from seeing it. This is because the permissions may not yet have been
280          * set for the post. If it's private, the photo permissions should be set
281          * appropriately. But we didn't know the final permissions on the post until
282          * now. So now we'll look for links of uploaded messages that are in the
283          * post and set them to the same permissions as the post itself.
284          *
285          */
286
287         $match = null;
288
289         if((! $preview) && preg_match_all("/\[img\](.*?)\[\/img\]/",$body,$match)) {
290                 $images = $match[1];
291                 if(count($images)) {
292                         foreach($images as $image) {
293                                 if(! stristr($image,$a->get_baseurl() . '/photo/'))
294                                         continue;
295                                 $image_uri = substr($image,strrpos($image,'/') + 1);
296                                 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
297                                 if(! strlen($image_uri))
298                                         continue;
299                                 $srch = '<' . intval($profile_uid) . '>';
300                                 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
301                                         AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
302                                         dbesc($srch),
303                                         dbesc($image_uri),
304                                         intval($profile_uid)
305                                 );
306                                 if(! count($r))
307                                         continue;
308  
309
310                                 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
311                                         WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
312                                         dbesc($str_contact_allow),
313                                         dbesc($str_group_allow),
314                                         dbesc($str_contact_deny),
315                                         dbesc($str_group_deny),
316                                         dbesc($image_uri),
317                                         intval($profile_uid),
318                                         dbesc( t('Wall Photos'))
319                                 );
320  
321                         }
322                 }
323         }
324
325
326         /**
327          * Next link in any attachment references we find in the post.
328          */
329
330         $match = false;
331
332         if((! $preview) && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/",$body,$match)) {
333                 $attaches = $match[1];
334                 if(count($attaches)) {
335                         foreach($attaches as $attach) {
336                                 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
337                                         intval($profile_uid),
338                                         intval($attach)
339                                 );                              
340                                 if(count($r)) {
341                                         $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
342                                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
343                                                 dbesc($str_contact_allow),
344                                                 dbesc($str_group_allow),
345                                                 dbesc($str_contact_deny),
346                                                 dbesc($str_group_deny),
347                                                 intval($profile_uid),
348                                                 intval($attach)
349                                         );
350                                 }
351                         }
352                 }
353         }
354
355         // embedded bookmark in post? set bookmark flag
356
357         $bookmark = 0;
358         if(preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$body,$match,PREG_SET_ORDER)) {
359                 $bookmark = 1;
360         }
361
362         $body = bb_translate_video($body);
363
364         /**
365          * Fold multi-line [code] sequences
366          */
367
368         $body = preg_replace('/\[\/code\]\s*\[code\]/ism',"\n",$body); 
369
370         /**
371          * Look for any tags and linkify them
372          */
373
374         $str_tags = '';
375         $inform   = '';
376
377
378         $tags = get_tags($body);
379
380         /**
381          * add a statusnet style reply tag if the original post was from there
382          * and we are replying, and there isn't one already
383          */
384
385         if(($parent_contact) && ($parent_contact['network'] === NETWORK_OSTATUS) 
386                 && ($parent_contact['nick']) && (! in_array('@' . $parent_contact['nick'],$tags))) {
387                 $body = '@' . $parent_contact['nick'] . ' ' . $body;
388                 $tags[] = '@' . $parent_contact['nick'];
389         }               
390
391         if(count($tags)) {
392                 foreach($tags as $tag) {
393                         
394                         if(isset($profile))
395                                 unset($profile);
396                         if(strpos($tag,'#') === 0) {
397                                 if(strpos($tag,'[url='))
398                                         continue;
399                                 $basetag = str_replace('_',' ',substr($tag,1));
400                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
401
402                                 $newtag = '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
403                                 if(! stristr($str_tags,$newtag)) {
404                                         if(strlen($str_tags))
405                                                 $str_tags .= ',';
406                                         $str_tags .= $newtag;
407                                 } 
408                                 continue;
409                         }
410                         if(strpos($tag,'@') === 0) {
411                                 if(strpos($tag,'[url='))
412                                         continue;
413                                 $stat = false;
414                                 $name = substr($tag,1);
415                                 if((strpos($name,'@')) || (strpos($name,'http://'))) {
416                                         $newname = $name;
417                                         $links = @lrdd($name);
418                                         if(count($links)) {
419                                                 foreach($links as $link) {
420                                                         if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
421                                         $profile = $link['@attributes']['href'];
422                                                         if($link['@attributes']['rel'] === 'salmon') {
423                                                                 if(strlen($inform))
424                                                                         $inform .= ',';
425                                         $inform .= 'url:' . str_replace(',','%2c',$link['@attributes']['href']);
426                                                         }
427                                                 }
428                                         }
429                                 }
430                                 else {
431                                         $newname = $name;
432                                         $alias = '';
433                                         $tagcid = 0;
434                                         if(strrpos($newname,'+')) {
435                                                 $tagcid = intval(substr($newname,strrpos($newname,'+') + 1));
436                                                 if(strpos($name,' '))
437                                                         $name = substr($name,0,strpos($name,' '));
438                                         }       
439                                         if($tagcid) {
440                                                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
441                                                         intval($tagcid),
442                                                         intval($profile_uid)
443                                                 );
444                                         }
445                                         elseif(strstr($name,'_') || strstr($name,' ')) {
446                                                 $newname = str_replace('_',' ',$name);
447                                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
448                                                         dbesc($newname),
449                                                         intval($profile_uid)
450                                                 );
451                                         }
452                                         else {
453                                                 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
454                                                         dbesc($name),
455                                                         dbesc($name),
456                                                         intval($profile_uid)
457                                                 );
458                                         }
459                                         if(count($r)) {
460                                                 $profile = $r[0]['url'];
461                                                 if($r[0]['network'] === 'stat') {
462                                                         $newname = $r[0]['nick'];
463                                                         $stat = true;
464                                                         if($r[0]['alias'])
465                                                                 $alias = $r[0]['alias'];
466                                                 }
467                                                 else
468                                                         $newname = $r[0]['name'];
469                                                 if(strlen($inform))
470                                                         $inform .= ',';
471                                                 $inform .= 'cid:' . $r[0]['id'];
472                                         }
473                                 }
474                                 if($profile) {
475                                         $body = str_replace('@' . $name, '@' . '[url=' . $profile . ']' . $newname      . '[/url]', $body);
476                                         $profile = str_replace(',','%2c',$profile);
477                                         $newtag = '@[url=' . $profile . ']' . $newname  . '[/url]';
478                                         if(! stristr($str_tags,$newtag)) {
479                                                 if(strlen($str_tags))
480                                                         $str_tags .= ',';
481                                                 $str_tags .= $newtag;
482                                         }
483
484                                         // Status.Net seems to require the numeric ID URL in a mention if the person isn't 
485                                         // subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both. 
486
487                                         if(strlen($alias)) {
488                                                 $newtag = '@[url=' . $alias . ']' . $newname    . '[/url]';
489                                                 if(! stristr($str_tags,$newtag)) {
490                                                         if(strlen($str_tags))
491                                                                 $str_tags .= ',';
492                                                         $str_tags .= $newtag;
493                                                 }
494                                         }
495                                 }
496                         }
497                 }
498         }
499
500         $attachments = '';
501         $match = false;
502
503         if(preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
504                 foreach($match[2] as $mtch) {
505                         $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
506                                 intval($profile_uid),
507                                 intval($mtch)
508                         );
509                         if(count($r)) {
510                                 if(strlen($attachments))
511                                         $attachments .= ',';
512                                 $attachments .= '[attach]href="' . $a->get_baseurl() . '/attach/' . $r[0]['id'] . '" length="' . $r[0]['filesize'] . '" type="' . $r[0]['filetype'] . '" title="' . (($r[0]['filename']) ? $r[0]['filename'] : '') . '"[/attach]'; 
513                         }
514                         $body = str_replace($match[1],'',$body);
515                 }
516         }
517
518         $wall = 0;
519
520         if($post_type === 'wall' || $post_type === 'wall-comment')
521                 $wall = 1;
522
523         if(! strlen($verb))
524                 $verb = ACTIVITY_POST ;
525
526         $gravity = (($parent) ? 6 : 0 );
527
528         // even if the post arrived via API we are considering that it 
529         // originated on this site by default for determining relayability.
530
531         $origin = ((x($_REQUEST,'origin')) ? intval($_REQUEST['origin']) : 1);
532         
533         $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
534
535         $uri = item_new_uri($a->get_hostname(),$profile_uid);
536
537         $datarray = array();
538         $datarray['uid']           = $profile_uid;
539         $datarray['type']          = $post_type;
540         $datarray['wall']          = $wall;
541         $datarray['gravity']       = $gravity;
542         $datarray['contact-id']    = $contact_id;
543         $datarray['owner-name']    = $contact_record['name'];
544         $datarray['owner-link']    = $contact_record['url'];
545         $datarray['owner-avatar']  = $contact_record['thumb'];
546         $datarray['author-name']   = $author['name'];
547         $datarray['author-link']   = $author['url'];
548         $datarray['author-avatar'] = $author['thumb'];
549         $datarray['created']       = datetime_convert();
550         $datarray['edited']        = datetime_convert();
551         $datarray['commented']     = datetime_convert();
552         $datarray['received']      = datetime_convert();
553         $datarray['changed']       = datetime_convert();
554         $datarray['uri']           = $uri;
555         $datarray['title']         = $title;
556         $datarray['body']          = $body;
557         $datarray['app']           = $app;
558         $datarray['location']      = $location;
559         $datarray['coord']         = $coord;
560         $datarray['tag']           = $str_tags;
561         $datarray['inform']        = $inform;
562         $datarray['verb']          = $verb;
563         $datarray['allow_cid']     = $str_contact_allow;
564         $datarray['allow_gid']     = $str_group_allow;
565         $datarray['deny_cid']      = $str_contact_deny;
566         $datarray['deny_gid']      = $str_group_deny;
567         $datarray['private']       = $private;
568         $datarray['pubmail']       = $pubmail_enable;
569         $datarray['attach']        = $attachments;
570         $datarray['bookmark']      = intval($bookmark);
571         $datarray['thr-parent']    = $thr_parent;
572         $datarray['postopts']      = '';
573         $datarray['origin']        = $origin;
574
575         /**
576          * These fields are for the convenience of plugins...
577          * 'self' if true indicates the owner is posting on their own wall
578          * If parent is 0 it is a top-level post.
579          */
580
581         $datarray['parent']        = $parent;
582         $datarray['self']          = $self;
583 //      $datarray['prvnets']       = $user['prvnets'];
584
585         if($orig_post)
586                 $datarray['edit']      = true;
587         else
588                 $datarray['guid']      = get_guid();
589
590         // preview mode - prepare the body for display and send it via json
591
592         if($preview) {
593                 require_once('include/conversation.php');
594                 $o = conversation(&$a,array(array_merge($contact_record,$datarray)),'search',false,true);
595                 logger('preview: ' . $o);
596                 echo json_encode(array('preview' => $o));
597                 killme();
598         }
599
600
601         call_hooks('post_local',$datarray);
602
603
604         if($orig_post) {
605                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
606                         dbesc($body),
607                         dbesc(datetime_convert()),
608                         intval($post_id),
609                         intval($profile_uid)
610                 );
611
612                 proc_run('php', "include/notifier.php", 'edit_post', "$post_id");
613                 if((x($_POST,'return')) && strlen($return_path)) {
614                         logger('return: ' . $return_path);
615                         goaway($a->get_baseurl() . "/" . $return_path );
616                 }
617                 killme();
618         }
619         else
620                 $post_id = 0;
621
622
623         $r = q("INSERT INTO `item` (`guid`, `uid`,`type`,`wall`,`gravity`,`contact-id`,`owner-name`,`owner-link`,`owner-avatar`, 
624                 `author-name`, `author-link`, `author-avatar`, `created`, `edited`, `commented`, `received`, `changed`, `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`, 
625                 `tag`, `inform`, `verb`, `postopts`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`, `pubmail`, `attach`, `bookmark`,`origin` )
626                 VALUES( '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d )",
627                 dbesc($datarray['guid']),
628                 intval($datarray['uid']),
629                 dbesc($datarray['type']),
630                 intval($datarray['wall']),
631                 intval($datarray['gravity']),
632                 intval($datarray['contact-id']),
633                 dbesc($datarray['owner-name']),
634                 dbesc($datarray['owner-link']),
635                 dbesc($datarray['owner-avatar']),
636                 dbesc($datarray['author-name']),
637                 dbesc($datarray['author-link']),
638                 dbesc($datarray['author-avatar']),
639                 dbesc($datarray['created']),
640                 dbesc($datarray['edited']),
641                 dbesc($datarray['commented']),
642                 dbesc($datarray['received']),
643                 dbesc($datarray['changed']),
644                 dbesc($datarray['uri']),
645                 dbesc($datarray['thr-parent']),
646                 dbesc($datarray['title']),
647                 dbesc($datarray['body']),
648                 dbesc($datarray['app']),
649                 dbesc($datarray['location']),
650                 dbesc($datarray['coord']),
651                 dbesc($datarray['tag']),
652                 dbesc($datarray['inform']),
653                 dbesc($datarray['verb']),
654                 dbesc($datarray['postopts']),
655                 dbesc($datarray['allow_cid']),
656                 dbesc($datarray['allow_gid']),
657                 dbesc($datarray['deny_cid']),
658                 dbesc($datarray['deny_gid']),
659                 intval($datarray['private']),
660                 intval($datarray['pubmail']),
661                 dbesc($datarray['attach']),
662                 intval($datarray['bookmark']),
663                 intval($datarray['origin'])
664         );
665
666         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
667                 dbesc($datarray['uri']));
668         if(count($r)) {
669                 $post_id = $r[0]['id'];
670                 logger('mod_item: saved item ' . $post_id);
671
672                 if($parent) {
673
674                         // This item is the last leaf and gets the comment box, clear any ancestors
675                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d ",
676                                 dbesc(datetime_convert()),
677                                 intval($parent)
678                         );
679
680                         // Inherit ACL's from the parent item.
681
682                         $r = q("UPDATE `item` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d
683                                 WHERE `id` = %d LIMIT 1",
684                                 dbesc($parent_item['allow_cid']),
685                                 dbesc($parent_item['allow_gid']),
686                                 dbesc($parent_item['deny_cid']),
687                                 dbesc($parent_item['deny_gid']),
688                                 intval($parent_item['private']),
689                                 intval($post_id)
690                         );
691
692                         if($contact_record != $author) {
693                                 notification(array(
694                                         'type'         => NOTIFY_COMMENT,
695                                         'notify_flags' => $user['notify-flags'],
696                                         'language'     => $user['language'],
697                                         'to_name'      => $user['username'],
698                                         'to_email'     => $user['email'],
699                                         'item'         => $datarray,
700                                         'link'             => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
701                                         'source_name'  => $datarray['author-name'],
702                                         'source_link'  => $datarray['author-link'],
703                                         'source_photo' => $datarray['author-avatar'],
704                                         'verb'         => ACTIVITY_POST,
705                                         'otype'        => 'item'
706                                 ));
707                         
708                         }
709
710                         // We won't be able to sign Diaspora comments for authenticated visitors - we don't have their private key
711
712                         if($self) {
713                                 require_once('include/bb2diaspora.php');
714                                 $signed_body = html_entity_decode(bb2diaspora($datarray['body']));
715                                 $myaddr = $a->user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
716                                 if($datarray['verb'] === ACTIVITY_LIKE) 
717                                         $signed_text = $datarray['guid'] . ';' . 'Post' . ';' . $parent_item['guid'] . ';' . 'true' . ';' . $myaddr;
718                                 else
719                                 $signed_text = $datarray['guid'] . ';' . $parent_item['guid'] . ';' . $signed_body . ';' . $myaddr;
720
721                                 $authorsig = base64_encode(rsa_sign($signed_text,$a->user['prvkey'],'sha256'));
722
723                                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
724                                         intval($post_id),
725                         dbesc($signed_text),
726                         dbesc(base64_encode($authorsig)),
727                         dbesc($myaddr)
728                         );
729                         }
730                 }
731                 else {
732                         $parent = $post_id;
733
734                         if($contact_record != $author) {
735                                 notification(array(
736                                         'type'         => NOTIFY_WALL,
737                                         'notify_flags' => $user['notify-flags'],
738                                         'language'     => $user['language'],
739                                         'to_name'      => $user['username'],
740                                         'to_email'     => $user['email'],
741                                         'item'         => $datarray,
742                                         'link'             => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
743                                         'source_name'  => $datarray['author-name'],
744                                         'source_link'  => $datarray['author-link'],
745                                         'source_photo' => $datarray['author-avatar'],
746                                         'verb'         => ACTIVITY_POST,
747                                         'otype'        => 'item'
748                                 ));
749                         }
750                 }
751
752                 // fallback so that parent always gets set to non-zero.
753
754                 if(! $parent)
755                         $parent = $post_id;
756
757                 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `plink` = '%s', `changed` = '%s', `last-child` = 1, `visible` = 1
758                         WHERE `id` = %d LIMIT 1",
759                         intval($parent),
760                         dbesc(($parent == $post_id) ? $uri : $parent_item['uri']),
761                         dbesc($a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id),
762                         dbesc(datetime_convert()),
763                         intval($post_id)
764                 );
765
766                 // photo comments turn the corresponding item visible to the profile wall
767                 // This way we don't see every picture in your new photo album posted to your wall at once.
768                 // They will show up as people comment on them.
769
770                 if(! $parent_item['visible']) {
771                         $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d LIMIT 1",
772                                 intval($parent_item['id'])
773                         );
774                 }
775         }
776         else {
777                 logger('mod_item: unable to retrieve post that was just stored.');
778                 notify( t('System error. Post not saved.'));
779                 goaway($a->get_baseurl() . "/" . $return_path );
780                 // NOTREACHED
781         }
782
783         // update the commented timestamp on the parent
784
785         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
786                 dbesc(datetime_convert()),
787                 dbesc(datetime_convert()),
788                 intval($parent)
789         );
790
791         $datarray['id']    = $post_id;
792         $datarray['plink'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id;
793
794         call_hooks('post_local_end', $datarray);
795
796         if(strlen($emailcc) && $profile_uid == local_user()) {
797                 $erecips = explode(',', $emailcc);
798                 if(count($erecips)) {
799                         foreach($erecips as $recip) {
800                                 $addr = trim($recip);
801                                 if(! strlen($addr))
802                                         continue;
803                                 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'),$a->user['username']) 
804                                         . '<br />';
805                                 $disclaimer .= sprintf( t('You may visit them online at %s'), $a->get_baseurl() . '/profile/' . $a->user['nickname']) . EOL;
806                                 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL; 
807
808                                 $subject  = '[Friendica]' . ' ' . sprintf( t('%s posted an update.'),$a->user['username']);
809                                 $headers  = 'From: ' . $a->user['username'] . ' <' . $a->user['email'] . '>' . "\n";
810                                 $headers .= 'MIME-Version: 1.0' . "\n";
811                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
812                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
813                                 $link = '<a href="' . $a->get_baseurl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
814                                 $html    = prepare_body($datarray);
815                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
816                                 @mail($addr, $subject, $message, $headers);
817                         }
818                 }
819         }
820
821         // This is a real juggling act on shared hosting services which kill your processes
822         // e.g. dreamhost. We used to start delivery to our native delivery agents in the background
823         // and then run our plugin delivery from the foreground. We're now doing plugin delivery first,
824         // because as soon as you start loading up a bunch of remote delivey processes, *this* page is
825         // likely to get killed off. If you end up looking at an /item URL and a blank page,
826         // it's very likely the delivery got killed before all your friends could be notified.
827         // Currently the only realistic fixes are to use a reliable server - which precludes shared hosting,
828         // or cut back on plugins which do remote deliveries.  
829
830         proc_run('php', "include/notifier.php", $notify_type, "$post_id");
831
832         logger('post_complete');
833
834         // figure out how to return, depending on from whence we came
835
836         if($api_source)
837                 return;
838
839         if($return_path) {
840                 goaway($a->get_baseurl() . "/" . $return_path);
841         }
842
843         $json = array('success' => 1);
844         if(x($_POST,'jsreload') && strlen($_POST['jsreload']))
845                 $json['reload'] = $a->get_baseurl() . '/' . $_POST['jsreload'];
846
847         logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
848
849         echo json_encode($json);
850         killme();
851         // NOTREACHED
852 }
853
854
855
856
857
858 function item_content(&$a) {
859
860         if((! local_user()) && (! remote_user()))
861                 return;
862
863         require_once('include/security.php');
864
865         if(($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
866                 require_once('include/items.php');
867                 drop_item($a->argv[2]);
868         }
869 }