]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Merge branch 'pull'
[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         if(($api_source) 
207                 && (! array_key_exists('allow_cid',$_REQUEST))
208                 && (! array_key_exists('allow_gid',$_REQUEST))
209                 && (! array_key_exists('deny_cid',$_REQUEST))
210                 && (! array_key_exists('deny_gid',$_REQUEST))) {
211                 $str_group_allow   = $user['allow_gid'];
212                 $str_contact_allow = $user['allow_cid'];
213                 $str_group_deny    = $user['deny_gid'];
214                 $str_contact_deny  = $user['deny_cid'];
215         }
216
217
218         // get contact info for poster
219
220         $author = null;
221         $self   = false;
222
223         if(($_SESSION['uid']) && ($_SESSION['uid'] == $profile_uid)) {
224                 $self = true;
225                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
226                         intval($_SESSION['uid'])
227                 );
228         }
229         else {
230                 if((x($_SESSION,'visitor_id')) && (intval($_SESSION['visitor_id']))) {
231                         $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
232                                 intval($_SESSION['visitor_id'])
233                         );
234                 }
235         }
236
237         if(count($r)) {
238                 $author = $r[0];
239                 $contact_id = $author['id'];
240         }
241
242         // get contact info for owner
243         
244         if($profile_uid == $_SESSION['uid']) {
245                 $contact_record = $author;
246         }
247         else {
248                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
249                         intval($profile_uid)
250                 );
251                 if(count($r))
252                         $contact_record = $r[0];
253         }
254
255
256
257         $post_type = notags(trim($_POST['type']));
258
259         if($post_type === 'net-comment') {
260                 if($parent_item !== null) {
261                         if($parent_item['wall'] == 1)
262                                 $post_type = 'wall-comment';
263                         else
264                                 $post_type = 'remote-comment';
265                 }
266         }
267
268         /**
269          *
270          * When a photo was uploaded into the message using the (profile wall) ajax 
271          * uploader, The permissions are initially set to disallow anybody but the
272          * owner from seeing it. This is because the permissions may not yet have been
273          * set for the post. If it's private, the photo permissions should be set
274          * appropriately. But we didn't know the final permissions on the post until
275          * now. So now we'll look for links of uploaded messages that are in the
276          * post and set them to the same permissions as the post itself.
277          *
278          */
279
280         $match = null;
281
282         if(preg_match_all("/\[img\](.*?)\[\/img\]/",$body,$match)) {
283                 $images = $match[1];
284                 if(count($images)) {
285                         foreach($images as $image) {
286                                 if(! stristr($image,$a->get_baseurl() . '/photo/'))
287                                         continue;
288                                 $image_uri = substr($image,strrpos($image,'/') + 1);
289                                 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
290                                 if(! strlen($image_uri))
291                                         continue;
292                                 $srch = '<' . intval($profile_uid) . '>';
293                                 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
294                                         AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
295                                         dbesc($srch),
296                                         dbesc($image_uri),
297                                         intval($profile_uid)
298                                 );
299                                 if(! count($r))
300                                         continue;
301  
302
303                                 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
304                                         WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
305                                         dbesc($str_contact_allow),
306                                         dbesc($str_group_allow),
307                                         dbesc($str_contact_deny),
308                                         dbesc($str_group_deny),
309                                         dbesc($image_uri),
310                                         intval($profile_uid),
311                                         dbesc( t('Wall Photos'))
312                                 );
313  
314                         }
315                 }
316         }
317
318
319         /**
320          * Next link in any attachment references we find in the post.
321          */
322
323         $match = false;
324
325         if(preg_match_all("/\[attachment\](.*?)\[\/attachment\]/",$body,$match)) {
326                 $attaches = $match[1];
327                 if(count($attaches)) {
328                         foreach($attaches as $attach) {
329                                 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
330                                         intval($profile_uid),
331                                         intval($attach)
332                                 );                              
333                                 if(count($r)) {
334                                         $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
335                                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
336                                                 dbesc($str_contact_allow),
337                                                 dbesc($str_group_allow),
338                                                 dbesc($str_contact_deny),
339                                                 dbesc($str_group_deny),
340                                                 intval($profile_uid),
341                                                 intval($attach)
342                                         );
343                                 }
344                         }
345                 }
346         }
347
348         // embedded bookmark in post? set bookmark flag
349
350         $bookmark = 0;
351         if(preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$body,$match,PREG_SET_ORDER)) {
352                 $bookmark = 1;
353 //              foreach($match as $mtch) {
354 //                      $body = str_replace(
355 //                              '[bookmark=' . $mtch[1] . ']' . $mtch[2] . '[/bookmark]',
356 //                              '[url=' . $mtch[1] . ']' . $mtch[2] . '[/url]',
357 //                              $body
358 //                      );
359 //              }
360         }
361
362         $body = bb_translate_video($body);
363
364         /**
365          * Fold multi-line [code] sequences
366          */
367
368         $body = preg_replace('/\[\/code\]\s*\[code\]/ism',"\n",$body); 
369
370         /**
371          * Look for any tags and linkify them
372          */
373
374         $str_tags = '';
375         $inform   = '';
376
377
378         $tags = get_tags($body);
379
380         /**
381          * add a statusnet style reply tag if the original post was from there
382          * and we are replying, and there isn't one already
383          */
384
385         if(($parent_contact) && ($parent_contact['network'] === NETWORK_OSTATUS) 
386                 && ($parent_contact['nick']) && (! in_array('@' . $parent_contact['nick'],$tags))) {
387                 $body = '@' . $parent_contact['nick'] . ' ' . $body;
388                 $tags[] = '@' . $parent_contact['nick'];
389         }               
390
391         if(count($tags)) {
392                 foreach($tags as $tag) {
393                         
394                         if(isset($profile))
395                                 unset($profile);
396                         if(strpos($tag,'#') === 0) {
397                                 if(strpos($tag,'[url='))
398                                         continue;
399                                 $basetag = str_replace('_',' ',substr($tag,1));
400                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
401                                 if(strlen($str_tags))
402                                         $str_tags .= ',';
403                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
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
587         call_hooks('post_local',$datarray);
588
589
590         if($orig_post) {
591                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
592                         dbesc($body),
593                         dbesc(datetime_convert()),
594                         intval($post_id),
595                         intval($profile_uid)
596                 );
597
598                 proc_run('php', "include/notifier.php", 'edit_post', "$post_id");
599                 if((x($_POST,'return')) && strlen($return_path)) {
600                         logger('return: ' . $return_path);
601                         goaway($a->get_baseurl() . "/" . $return_path );
602                 }
603                 killme();
604         }
605         else
606                 $post_id = 0;
607
608
609         $r = q("INSERT INTO `item` (`guid`, `uid`,`type`,`wall`,`gravity`,`contact-id`,`owner-name`,`owner-link`,`owner-avatar`, 
610                 `author-name`, `author-link`, `author-avatar`, `created`, `edited`, `commented`, `received`, `changed`, `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`, 
611                 `tag`, `inform`, `verb`, `postopts`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`, `pubmail`, `attach`, `bookmark`,`origin` )
612                 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 )",
613                 dbesc($datarray['guid']),
614                 intval($datarray['uid']),
615                 dbesc($datarray['type']),
616                 intval($datarray['wall']),
617                 intval($datarray['gravity']),
618                 intval($datarray['contact-id']),
619                 dbesc($datarray['owner-name']),
620                 dbesc($datarray['owner-link']),
621                 dbesc($datarray['owner-avatar']),
622                 dbesc($datarray['author-name']),
623                 dbesc($datarray['author-link']),
624                 dbesc($datarray['author-avatar']),
625                 dbesc($datarray['created']),
626                 dbesc($datarray['edited']),
627                 dbesc($datarray['commented']),
628                 dbesc($datarray['received']),
629                 dbesc($datarray['changed']),
630                 dbesc($datarray['uri']),
631                 dbesc($datarray['thr-parent']),
632                 dbesc($datarray['title']),
633                 dbesc($datarray['body']),
634                 dbesc($datarray['app']),
635                 dbesc($datarray['location']),
636                 dbesc($datarray['coord']),
637                 dbesc($datarray['tag']),
638                 dbesc($datarray['inform']),
639                 dbesc($datarray['verb']),
640                 dbesc($datarray['postopts']),
641                 dbesc($datarray['allow_cid']),
642                 dbesc($datarray['allow_gid']),
643                 dbesc($datarray['deny_cid']),
644                 dbesc($datarray['deny_gid']),
645                 intval($datarray['private']),
646                 intval($datarray['pubmail']),
647                 dbesc($datarray['attach']),
648                 intval($datarray['bookmark']),
649                 intval($datarray['origin'])
650         );
651
652         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
653                 dbesc($datarray['uri']));
654         if(count($r)) {
655                 $post_id = $r[0]['id'];
656                 logger('mod_item: saved item ' . $post_id);
657
658                 if($parent) {
659
660                         // This item is the last leaf and gets the comment box, clear any ancestors
661                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d ",
662                                 dbesc(datetime_convert()),
663                                 intval($parent)
664                         );
665
666                         // Inherit ACL's from the parent item.
667
668                         $r = q("UPDATE `item` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d
669                                 WHERE `id` = %d LIMIT 1",
670                                 dbesc($parent_item['allow_cid']),
671                                 dbesc($parent_item['allow_gid']),
672                                 dbesc($parent_item['deny_cid']),
673                                 dbesc($parent_item['deny_gid']),
674                                 intval($parent_item['private']),
675                                 intval($post_id)
676                         );
677
678                         // Send a notification email to the conversation owner, unless the owner is me and I wrote this item
679                         if(($user['notify-flags'] & NOTIFY_COMMENT) && ($contact_record != $author)) {
680                                 push_lang($user['language']);
681                                 require_once('bbcode.php');
682                                 $from = $author['name'];
683
684                                 // name of the automated email sender
685                                 $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
686                                 // noreply address to send from
687                                 $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
688
689                                 // text version
690                                 // process the message body to display properly in text mode
691                                 $msg['textversion']
692                                         = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
693                                 
694                                 // html version
695                                 // process the message body to display properly in text mode
696                                 $msg['htmlversion']     
697                                         = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
698
699                                 // load the template for private message notifications
700                                 $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
701                                 $email_html_body_tpl = replace_macros($tpl,array(
702                                         '$username'     => $user['username'],
703                                         '$sitename'             => $a->config['sitename'],                              // name of this site
704                                         '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
705                                         '$thumb'                => $author['thumb'],                                    // thumbnail url for sender icon
706                                         '$email'                => $importer['email'],                                  // email address to send to
707                                         '$url'                  => $author['url'],                                              // full url for the site
708                                         '$from'                 => $from,                                                               // name of the person sending the message
709                                         '$body'                 => $msg['htmlversion'],                                 // html version of the message
710                                         '$display'              => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
711                                 ));
712                         
713                                 // load the template for private message notifications
714                                 $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
715                                 $email_text_body_tpl = replace_macros($tpl,array(
716                                         '$username'     => $user['username'],
717                                         '$sitename'             => $a->config['sitename'],                              // name of this site
718                                         '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
719                                         '$thumb'                => $author['thumb'],                                    // thumbnail url for sender icon
720                                         '$email'                => $importer['email'],                                  // email address to send to
721                                         '$url'                  => $author['url'],                                              // profile url for the author
722                                         '$from'                 => $from,                                                               // name of the person sending the message
723                                         '$body'                 => $msg['textversion'],                                 // text version of the message
724                                         '$display'              => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
725                                 ));
726
727                                 // use the EmailNotification library to send the message
728                                 require_once("include/EmailNotification.php");
729                                 EmailNotification::sendTextHtmlEmail(
730                                         $msg['notificationfromname'],
731                                         t("Administrator@") . $a->get_hostname(),
732                                         t("noreply") . '@' . $a->get_hostname(),
733                                         $user['email'],
734                                         sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
735                                         $email_html_body_tpl,
736                                         $email_text_body_tpl
737                                 );
738
739                                 pop_lang();
740                         }
741
742                         // We won't be able to sign Diaspora comments for authenticated visitors - we don't have their private key
743
744                         if($self) {
745                                 require_once('include/bb2diaspora.php');
746                                 $signed_body = html_entity_decode(bb2diaspora($datarray['body']));
747                                 $myaddr = $a->user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
748                                 if($datarray['verb'] === ACTIVITY_LIKE) 
749                                         $signed_text = $datarray['guid'] . ';' . 'Post' . ';' . $parent_item['guid'] . ';' . 'true' . ';' . $myaddr;
750                                 else
751                                 $signed_text = $datarray['guid'] . ';' . $parent_item['guid'] . ';' . $signed_body . ';' . $myaddr;
752
753                                 $authorsig = base64_encode(rsa_sign($signed_text,$a->user['prvkey'],'sha256'));
754
755                                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
756                                         intval($post_id),
757                         dbesc($signed_text),
758                         dbesc(base64_encode($authorsig)),
759                         dbesc($myaddr)
760                         );
761                         }
762                 }
763                 else {
764                         $parent = $post_id;
765
766                         // let me know if somebody did a wall-to-wall post on my profile
767
768                         if(($user['notify-flags'] & NOTIFY_WALL) && ($contact_record != $author)) {
769                                 push_lang($user['language']);
770                                 require_once('bbcode.php');
771                                 $from = $author['name'];
772                                                         
773                                 // name of the automated email sender
774                                 $msg['notificationfromname']    = $from;
775                                 // noreply address to send from
776                                 $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
777
778                                 // text version
779                                 // process the message body to display properly in text mode
780                                 $msg['textversion']
781                                         = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
782                                 
783                                 // html version
784                                 // process the message body to display properly in text mode
785                                 $msg['htmlversion']     
786                                         = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
787
788                                 // load the template for private message notifications
789                                 $tpl = load_view_file('view/wall_received_html_body_eml.tpl');
790                                 $email_html_body_tpl = replace_macros($tpl,array(
791                                         '$username'     => $user['username'],
792                                         '$sitename'             => $a->config['sitename'],                              // name of this site
793                                         '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
794                                         '$thumb'                => $author['thumb'],                                    // thumbnail url for sender icon
795                                         '$url'                  => $author['url'],                                              // full url for the site
796                                         '$from'                 => $from,                                                               // name of the person sending the message
797                                         '$body'                 => $msg['htmlversion'],                                 // html version of the message
798                                         '$display'              => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
799                                 ));
800                         
801                                 // load the template for private message notifications
802                                 $tpl = load_view_file('view/wall_received_text_body_eml.tpl');
803                                 $email_text_body_tpl = replace_macros($tpl,array(
804                                         '$username'     => $user['username'],
805                                         '$sitename'             => $a->config['sitename'],                              // name of this site
806                                         '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
807                                         '$thumb'                => $author['thumb'],                                    // thumbnail url for sender icon
808                                         '$url'                  => $author['url'],                                              // full url for the site
809                                         '$from'                 => $from,                                                               // name of the person sending the message
810                                         '$body'                 => $msg['textversion'],                                 // text version of the message
811                                         '$display'              => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
812                                 ));
813
814                                 // use the EmailNotification library to send the message
815                                 require_once("include/EmailNotification.php");
816                                 EmailNotification::sendTextHtmlEmail(
817                                         $msg['notificationfromname'],
818                                         t("Administrator@") . $a->get_hostname(),
819                                         t("noreply") . '@' . $a->get_hostname(),
820                                         $user['email'],
821                                         sprintf( t('%s posted to your profile wall at %s') , $from , $a->config['sitename']),
822                                         $email_html_body_tpl,
823                                         $email_text_body_tpl
824                                 );
825                                 pop_lang();
826                         }
827                 }
828
829                 // fallback so that parent always gets set to non-zero.
830
831                 if(! $parent)
832                         $parent = $post_id;
833
834                 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `plink` = '%s', `changed` = '%s', `last-child` = 1, `visible` = 1
835                         WHERE `id` = %d LIMIT 1",
836                         intval($parent),
837                         dbesc(($parent == $post_id) ? $uri : $parent_item['uri']),
838                         dbesc($a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id),
839                         dbesc(datetime_convert()),
840                         intval($post_id)
841                 );
842
843                 // photo comments turn the corresponding item visible to the profile wall
844                 // This way we don't see every picture in your new photo album posted to your wall at once.
845                 // They will show up as people comment on them.
846
847                 if(! $parent_item['visible']) {
848                         $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d LIMIT 1",
849                                 intval($parent_item['id'])
850                         );
851                 }
852         }
853         else {
854                 logger('mod_item: unable to retrieve post that was just stored.');
855                 notify( t('System error. Post not saved.'));
856                 goaway($a->get_baseurl() . "/" . $return_path );
857                 // NOTREACHED
858         }
859
860         // update the commented timestamp on the parent
861
862         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
863                 dbesc(datetime_convert()),
864                 dbesc(datetime_convert()),
865                 intval($parent)
866         );
867
868         $datarray['id']    = $post_id;
869         $datarray['plink'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id;
870
871         call_hooks('post_local_end', $datarray);
872
873         if(strlen($emailcc) && $profile_uid == local_user()) {
874                 $erecips = explode(',', $emailcc);
875                 if(count($erecips)) {
876                         foreach($erecips as $recip) {
877                                 $addr = trim($recip);
878                                 if(! strlen($addr))
879                                         continue;
880                                 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'),$a->user['username']) 
881                                         . '<br />';
882                                 $disclaimer .= sprintf( t('You may visit them online at %s'), $a->get_baseurl() . '/profile/' . $a->user['nickname']) . EOL;
883                                 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL; 
884
885                                 $subject  = '[Friendica]' . ' ' . sprintf( t('%s posted an update.'),$a->user['username']);
886                                 $headers  = 'From: ' . $a->user['username'] . ' <' . $a->user['email'] . '>' . "\n";
887                                 $headers .= 'MIME-Version: 1.0' . "\n";
888                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
889                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
890                                 $link = '<a href="' . $a->get_baseurl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
891                                 $html    = prepare_body($datarray);
892                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
893                                 @mail($addr, $subject, $message, $headers);
894                         }
895                 }
896         }
897
898         // This is a real juggling act on shared hosting services which kill your processes
899         // e.g. dreamhost. We used to start delivery to our native delivery agents in the background
900         // and then run our plugin delivery from the foreground. We're now doing plugin delivery first,
901         // because as soon as you start loading up a bunch of remote delivey processes, *this* page is
902         // likely to get killed off. If you end up looking at an /item URL and a blank page,
903         // it's very likely the delivery got killed before all your friends could be notified.
904         // Currently the only realistic fixes are to use a reliable server - which precludes shared hosting,
905         // or cut back on plugins which do remote deliveries.  
906
907         proc_run('php', "include/notifier.php", $notify_type, "$post_id");
908
909         logger('post_complete');
910
911         // figure out how to return, depending on from whence we came
912
913         if($api_source)
914                 return;
915
916         if($return_path) {
917                 goaway($a->get_baseurl() . "/" . $return_path);
918         }
919
920         $json = array('success' => 1);
921         if(x($_POST,'jsreload') && strlen($_POST['jsreload']))
922                 $json['reload'] = $a->get_baseurl() . '/' . $_POST['jsreload'];
923
924         logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
925
926         echo json_encode($json);
927         killme();
928         // NOTREACHED
929 }
930
931
932
933
934
935 function item_content(&$a) {
936
937         if((! local_user()) && (! remote_user()))
938                 return;
939
940         require_once('include/security.php');
941
942         if(($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
943                 require_once('include/items.php');
944                 drop_item($a->argv[2]);
945         }
946 }