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