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