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