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