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