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