]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Merge pull request #616 from fabrixxm/master
[friendica.git] / mod / item.php
1 <?php
2
3 /**
4  *
5  * This is the POST destination for most all locally posted
6  * text stuff. This function handles status, wall-to-wall status, 
7  * local comments, and remote coments that are posted on this site 
8  * (as opposed to being delivered in a feed).
9  * Also processed here are posts and comments coming through the 
10  * statusnet/twitter API. 
11  * All of these become an "item" which is our basic unit of 
12  * information.
13  * Posts that originate externally or do not fall into the above 
14  * posting categories go through item_store() instead of this function. 
15  *
16  */  
17
18 require_once('include/crypto.php');
19 require_once('include/enotify.php');
20 require_once('include/email.php');
21 require_once('library/langdet/Text/LanguageDetect.php');
22
23 function item_post(&$a) {
24
25         if((! local_user()) && (! remote_user()) && (! x($_REQUEST,'commenter')))
26                 return;
27
28         require_once('include/security.php');
29
30         $uid = local_user();
31
32         if(x($_REQUEST,'dropitems')) {
33                 require_once('include/items.php');
34                 $arr_drop = explode(',',$_REQUEST['dropitems']);
35                 drop_items($arr_drop);
36                 $json = array('success' => 1);
37                 echo json_encode($json);
38                 killme();
39         }
40
41         call_hooks('post_local_start', $_REQUEST);
42 //      logger('postinput ' . file_get_contents('php://input'));
43         logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
44
45         $api_source = ((x($_REQUEST,'api_source') && $_REQUEST['api_source']) ? true : false);
46         $return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : '');
47         $preview = ((x($_REQUEST,'preview')) ? intval($_REQUEST['preview']) : 0);
48
49
50         // Check for doubly-submitted posts, and reject duplicates
51         // Note that we have to ignore previews, otherwise nothing will post
52         // after it's been previewed
53         if(!$preview && x($_REQUEST['post_id_random'])) {
54                 if(x($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
55                         logger("item post: duplicate post", LOGGER_DEBUG);
56                         item_post_return($a->get_baseurl(), $api_source, $return_path);
57                 }
58                 else
59                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
60         }
61
62         /**
63          * Is this a reply to something?
64          */
65
66         $parent = ((x($_REQUEST,'parent')) ? intval($_REQUEST['parent']) : 0);
67         $parent_uri = ((x($_REQUEST,'parent_uri')) ? trim($_REQUEST['parent_uri']) : '');
68
69         $parent_item = null;
70         $parent_contact = null;
71         $thr_parent = '';
72         $parid = 0;
73         $r = false;
74
75         if($parent || $parent_uri) {
76
77                 if(! x($_REQUEST,'type'))
78                         $_REQUEST['type'] = 'net-comment';
79
80                 if($parent) {
81                         $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
82                                 intval($parent)
83                         );
84                 }
85                 elseif($parent_uri && local_user()) {
86                         // This is coming from an API source, and we are logged in
87                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
88                                 dbesc($parent_uri),
89                                 intval(local_user())
90                         );
91                 }
92                 // if this isn't the real parent of the conversation, find it
93                 if($r !== false && count($r)) {
94                         $parid = $r[0]['parent'];
95                         $parent_uri = $r[0]['uri'];
96                         if($r[0]['id'] != $r[0]['parent']) {
97                                 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
98                                         intval($parid)
99                                 );
100                         }
101                 }
102
103                 if(($r === false) || (! count($r))) {
104                         notice( t('Unable to locate original post.') . EOL);
105                         if(x($_REQUEST,'return')) 
106                                 goaway($a->get_baseurl() . "/" . $return_path );
107                         killme();
108                 }
109                 $parent_item = $r[0];
110                 $parent = $r[0]['id'];
111
112                 // multi-level threading - preserve the info but re-parent to our single level threading
113                 //if(($parid) && ($parid != $parent))
114                 $thr_parent = $parent_uri;
115
116                 if($parent_item['contact-id'] && $uid) {
117                         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
118                                 intval($parent_item['contact-id']),
119                                 intval($uid)
120                         );
121                         if(count($r))
122                                 $parent_contact = $r[0];
123                 }
124         }
125
126         if($parent) logger('mod_item: item_post parent=' . $parent);
127
128         $profile_uid = ((x($_REQUEST,'profile_uid')) ? intval($_REQUEST['profile_uid']) : 0);
129         $post_id     = ((x($_REQUEST,'post_id'))     ? intval($_REQUEST['post_id'])     : 0);
130         $app         = ((x($_REQUEST,'source'))      ? strip_tags($_REQUEST['source'])  : '');
131
132         $allow_moderated = false;
133
134         // here is where we are going to check for permission to post a moderated comment.
135
136         // First check that the parent exists and it is a wall item.
137
138         if((x($_REQUEST,'commenter')) && ((! $parent) || (! $parent_item['wall']))) {
139                 notice( t('Permission denied.') . EOL) ;
140                 if(x($_REQUEST,'return')) 
141                         goaway($a->get_baseurl() . "/" . $return_path );
142                 killme();
143         }
144
145         // Now check that it is a page_type of PAGE_BLOG, and that valid personal details
146         // have been provided, and run any anti-spam plugins
147
148
149         // TODO
150
151
152
153
154         if((! can_write_wall($a,$profile_uid)) && (! $allow_moderated)) {
155                 notice( t('Permission denied.') . EOL) ;
156                 if(x($_REQUEST,'return')) 
157                         goaway($a->get_baseurl() . "/" . $return_path );
158                 killme();
159         }
160
161
162         // is this an edited post?
163
164         $orig_post = null;
165
166         if($post_id) {
167                 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
168                         intval($profile_uid),
169                         intval($post_id)
170                 );
171                 if(! count($i))
172                         killme();
173                 $orig_post = $i[0];
174         }
175
176         $user = null;
177
178         $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
179                 intval($profile_uid)
180         );
181         if(count($r))
182                 $user = $r[0];
183
184         if($orig_post) {
185                 $str_group_allow   = $orig_post['allow_gid'];
186                 $str_contact_allow = $orig_post['allow_cid'];
187                 $str_group_deny    = $orig_post['deny_gid'];
188                 $str_contact_deny  = $orig_post['deny_cid'];
189                 $location          = $orig_post['location'];
190                 $coord             = $orig_post['coord'];
191                 $verb              = $orig_post['verb'];
192                 $emailcc           = $orig_post['emailcc'];
193                 $app                       = $orig_post['app'];
194                 $categories        = $orig_post['file'];
195                 $title             = notags(trim($_REQUEST['title']));
196                 $body              = escape_tags(trim($_REQUEST['body']));
197                 $private           = $orig_post['private'];
198                 $pubmail_enable    = $orig_post['pubmail'];
199
200         }
201         else {
202
203                 // if coming from the API and no privacy settings are set, 
204                 // use the user default permissions - as they won't have
205                 // been supplied via a form.
206
207                 if(($api_source) 
208                         && (! array_key_exists('contact_allow',$_REQUEST))
209                         && (! array_key_exists('group_allow',$_REQUEST))
210                         && (! array_key_exists('contact_deny',$_REQUEST))
211                         && (! array_key_exists('group_deny',$_REQUEST))) {
212                         $str_group_allow   = $user['allow_gid'];
213                         $str_contact_allow = $user['allow_cid'];
214                         $str_group_deny    = $user['deny_gid'];
215                         $str_contact_deny  = $user['deny_cid'];
216                 }
217                 else {
218
219                         // use the posted permissions
220
221                         $str_group_allow   = perms2str($_REQUEST['group_allow']);
222                         $str_contact_allow = perms2str($_REQUEST['contact_allow']);
223                         $str_group_deny    = perms2str($_REQUEST['group_deny']);
224                         $str_contact_deny  = perms2str($_REQUEST['contact_deny']);
225                 }
226
227                 $title             = notags(trim($_REQUEST['title']));
228                 $location          = notags(trim($_REQUEST['location']));
229                 $coord             = notags(trim($_REQUEST['coord']));
230                 $verb              = notags(trim($_REQUEST['verb']));
231                 $emailcc           = notags(trim($_REQUEST['emailcc']));
232                 $body              = escape_tags(trim($_REQUEST['body']));
233
234
235                 $naked_body = preg_replace('/\[(.+?)\]/','',$body);
236
237                 if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
238                         $l = new Text_LanguageDetect;
239                         $lng = $l->detectConfidence($naked_body);
240
241                         $postopts = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
242
243                         logger('mod_item: detect language' . print_r($lng,true) . $naked_body, LOGGER_DATA);
244                 }
245                 else
246                         $postopts = '';
247
248
249                 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
250
251
252                 if($user['hidewall'])
253                         $private = 2;
254
255                 // If this is a comment, set the permissions from the parent.
256
257                 if($parent_item) {
258                         $private = 0;
259
260                         if(($parent_item['private']) 
261                                 || strlen($parent_item['allow_cid']) 
262                                 || strlen($parent_item['allow_gid']) 
263                                 || strlen($parent_item['deny_cid']) 
264                                 || strlen($parent_item['deny_gid'])) {
265                                 $private = (($parent_item['private']) ? $parent_item['private'] : 1);
266                         }
267
268                         $str_contact_allow = $parent_item['allow_cid'];
269                         $str_group_allow   = $parent_item['allow_gid'];
270                         $str_contact_deny  = $parent_item['deny_cid'];
271                         $str_group_deny    = $parent_item['deny_gid'];
272                 }
273         
274                 $pubmail_enable    = ((x($_REQUEST,'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && (! $private)) ? 1 : 0);
275
276                 // if using the API, we won't see pubmail_enable - figure out if it should be set
277
278                 if($api_source && $profile_uid && $profile_uid == local_user() && (! $private)) {
279                         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
280                         if(! $mail_disabled) {
281                                 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
282                                         intval(local_user())
283                                 );
284                                 if(count($r) && intval($r[0]['pubmail']))
285                                         $pubmail_enabled = true;
286                         }
287                 }
288
289                 if(! strlen($body)) {
290                         if($preview)
291                                 killme();
292                         info( t('Empty post discarded.') . EOL );
293                         if(x($_REQUEST,'return')) 
294                                 goaway($a->get_baseurl() . "/" . $return_path );
295                         killme();
296                 }
297         }
298
299         if(strlen($categories)) {
300                 // get the "fileas" tags for this post
301                 $filedas = file_tag_file_to_list($categories, 'file');
302         }
303         // save old and new categories, so we can determine what needs to be deleted from pconfig
304         $categories_old = $categories;
305         $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
306         $categories_new = $categories;
307         if(strlen($filedas)) {
308                 // append the fileas stuff to the new categories list
309                 $categories .= file_tag_list_to_file($filedas, 'file');
310         }
311
312         // Work around doubled linefeeds in Tinymce 3.5b2
313         // First figure out if it's a status post that would've been
314         // created using tinymce. Otherwise leave it alone. 
315
316 /*      $plaintext = (local_user() ? intval(get_pconfig(local_user(),'system','plaintext')) || !feature_enabled($profile_uid,'richtext') : 0);
317         if((! $parent) && (! $api_source) && (! $plaintext)) {
318                 $body = fix_mce_lf($body);
319         }*/
320         $plaintext = (local_user() ? !feature_enabled($profile_uid,'richtext') : 0);
321         if((! $parent) && (! $api_source) && (! $plaintext)) {
322                 $body = fix_mce_lf($body);
323         }
324
325
326         // get contact info for poster
327
328         $author = null;
329         $self   = false;
330         $contact_id = 0;
331
332         if((local_user()) && (local_user() == $profile_uid)) {
333                 $self = true;
334                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
335                         intval($_SESSION['uid'])
336                 );
337         }
338         elseif(remote_user()) {
339                 if(is_array($_SESSION['remote'])) {
340                         foreach($_SESSION['remote'] as $v) {
341                                 if($v['uid'] == $profile_uid) {
342                                         $contact_id = $v['cid'];
343                                         break;
344                                 }
345                         }
346                 }                               
347                 if($contact_id) {
348                         $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
349                                 intval($contact_id)
350                         );
351                 }
352         }
353
354         if(count($r)) {
355                 $author = $r[0];
356                 $contact_id = $author['id'];
357         }
358
359         // get contact info for owner
360         
361         if($profile_uid == local_user()) {
362                 $contact_record = $author;
363         }
364         else {
365                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
366                         intval($profile_uid)
367                 );
368                 if(count($r))
369                         $contact_record = $r[0];
370         }
371
372         $post_type = notags(trim($_REQUEST['type']));
373
374         if($post_type === 'net-comment') {
375                 if($parent_item !== null) {
376                         if($parent_item['wall'] == 1)
377                                 $post_type = 'wall-comment';
378                         else
379                                 $post_type = 'remote-comment';
380                 }
381         }
382
383         /**
384          *
385          * When a photo was uploaded into the message using the (profile wall) ajax 
386          * uploader, The permissions are initially set to disallow anybody but the
387          * owner from seeing it. This is because the permissions may not yet have been
388          * set for the post. If it's private, the photo permissions should be set
389          * appropriately. But we didn't know the final permissions on the post until
390          * now. So now we'll look for links of uploaded messages that are in the
391          * post and set them to the same permissions as the post itself.
392          *
393          */
394
395         $match = null;
396
397         if((! $preview) && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
398                 $images = $match[2];
399                 if(count($images)) {
400                         foreach($images as $image) {
401                                 if(! stristr($image,$a->get_baseurl() . '/photo/'))
402                                         continue;
403                                 $image_uri = substr($image,strrpos($image,'/') + 1);
404                                 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
405                                 if(! strlen($image_uri))
406                                         continue;
407                                 $srch = '<' . intval($contact_id) . '>';
408
409                                 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
410                                         AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
411                                         dbesc($srch),
412                                         dbesc($image_uri),
413                                         intval($profile_uid)
414                                 );
415
416                                 if(! count($r))
417                                         continue;
418  
419
420                                 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
421                                         WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
422                                         dbesc($str_contact_allow),
423                                         dbesc($str_group_allow),
424                                         dbesc($str_contact_deny),
425                                         dbesc($str_group_deny),
426                                         dbesc($image_uri),
427                                         intval($profile_uid),
428                                         dbesc( t('Wall Photos'))
429                                 );
430  
431                         }
432                 }
433         }
434
435
436         /**
437          * Next link in any attachment references we find in the post.
438          */
439
440         $match = false;
441
442         if((! $preview) && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/",$body,$match)) {
443                 $attaches = $match[1];
444                 if(count($attaches)) {
445                         foreach($attaches as $attach) {
446                                 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
447                                         intval($profile_uid),
448                                         intval($attach)
449                                 );                              
450                                 if(count($r)) {
451                                         $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
452                                                 WHERE `uid` = %d AND `id` = %d LIMIT 1",
453                                                 dbesc($str_contact_allow),
454                                                 dbesc($str_group_allow),
455                                                 dbesc($str_contact_deny),
456                                                 dbesc($str_group_deny),
457                                                 intval($profile_uid),
458                                                 intval($attach)
459                                         );
460                                 }
461                         }
462                 }
463         }
464
465         // embedded bookmark in post? set bookmark flag
466
467         $bookmark = 0;
468         if(preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$body,$match,PREG_SET_ORDER)) {
469                 $bookmark = 1;
470         }
471
472         $body = bb_translate_video($body);
473
474
475         /**
476          * Fold multi-line [code] sequences
477          */
478
479         $body = preg_replace('/\[\/code\]\s*\[code\]/ism',"\n",$body); 
480
481         $body = scale_external_images($body,false);
482
483
484
485         /**
486          * Look for any tags and linkify them
487          */
488
489         $str_tags = '';
490         $inform   = '';
491
492
493         $tags = get_tags($body);
494
495         /**
496          * add a statusnet style reply tag if the original post was from there
497          * and we are replying, and there isn't one already
498          */
499
500         if(($parent_contact) && ($parent_contact['network'] === NETWORK_OSTATUS) 
501                 && ($parent_contact['nick']) && (! in_array('@' . $parent_contact['nick'],$tags))) {
502                 $body = '@' . $parent_contact['nick'] . ' ' . $body;
503                 $tags[] = '@' . $parent_contact['nick'];
504         }               
505
506         $tagged = array();
507
508         $private_forum = false;
509
510         if(count($tags)) {
511                 foreach($tags as $tag) {
512
513                         // If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
514                         // Robert Johnson should be first in the $tags array
515
516                         $fullnametagged = false;
517                         for($x = 0; $x < count($tagged); $x ++) {
518                                 if(stristr($tagged[$x],$tag . ' ')) {
519                                         $fullnametagged = true;
520                                         break;
521                                 }
522                         }
523                         if($fullnametagged)
524                                 continue;
525
526                         $success = handle_tag($a, $body, $inform, $str_tags, (local_user()) ? local_user() : $profile_uid , $tag); 
527                         if($success['replaced'])
528                                 $tagged[] = $tag;
529                         if(is_array($success['contact']) && intval($success['contact']['prv'])) {
530                                 $private_forum = true;
531                                 $private_id = $success['contact']['id'];
532                         }
533                 }
534         }
535
536         if(($private_forum) && (! $parent) && (! $private)) {
537                 // we tagged a private forum in a top level post and the message was public.
538                 // Restrict it.
539                 $private = 1;
540                 $str_contact_allow = '<' . $private_id . '>'; 
541         }
542
543         $attachments = '';
544         $match = false;
545
546         if(preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
547                 foreach($match[2] as $mtch) {
548                         $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
549                                 intval($profile_uid),
550                                 intval($mtch)
551                         );
552                         if(count($r)) {
553                                 if(strlen($attachments))
554                                         $attachments .= ',';
555                                 $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]'; 
556                         }
557                         $body = str_replace($match[1],'',$body);
558                 }
559         }
560
561         $wall = 0;
562
563         if($post_type === 'wall' || $post_type === 'wall-comment')
564                 $wall = 1;
565
566         if(! strlen($verb))
567                 $verb = ACTIVITY_POST ;
568
569         $gravity = (($parent) ? 6 : 0 );
570
571         // even if the post arrived via API we are considering that it 
572         // originated on this site by default for determining relayability.
573
574         $origin = ((x($_REQUEST,'origin')) ? intval($_REQUEST['origin']) : 1);
575         
576         $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
577
578         $uri = item_new_uri($a->get_hostname(),$profile_uid);
579
580         // Fallback so that we alway have a thr-parent
581         if(!$thr_parent)
582                 $thr_parent = $uri;
583
584         $datarray = array();
585         $datarray['uid']           = $profile_uid;
586         $datarray['type']          = $post_type;
587         $datarray['wall']          = $wall;
588         $datarray['gravity']       = $gravity;
589         $datarray['contact-id']    = $contact_id;
590         $datarray['owner-name']    = $contact_record['name'];
591         $datarray['owner-link']    = $contact_record['url'];
592         $datarray['owner-avatar']  = $contact_record['thumb'];
593         $datarray['author-name']   = $author['name'];
594         $datarray['author-link']   = $author['url'];
595         $datarray['author-avatar'] = $author['thumb'];
596         $datarray['created']       = datetime_convert();
597         $datarray['edited']        = datetime_convert();
598         $datarray['commented']     = datetime_convert();
599         $datarray['received']      = datetime_convert();
600         $datarray['changed']       = datetime_convert();
601         $datarray['uri']           = $uri;
602         $datarray['title']         = $title;
603         $datarray['body']          = $body;
604         $datarray['app']           = $app;
605         $datarray['location']      = $location;
606         $datarray['coord']         = $coord;
607         $datarray['tag']           = $str_tags;
608         $datarray['file']          = $categories;
609         $datarray['inform']        = $inform;
610         $datarray['verb']          = $verb;
611         $datarray['allow_cid']     = $str_contact_allow;
612         $datarray['allow_gid']     = $str_group_allow;
613         $datarray['deny_cid']      = $str_contact_deny;
614         $datarray['deny_gid']      = $str_group_deny;
615         $datarray['private']       = $private;
616         $datarray['pubmail']       = $pubmail_enable;
617         $datarray['attach']        = $attachments;
618         $datarray['bookmark']      = intval($bookmark);
619         $datarray['thr-parent']    = $thr_parent;
620         $datarray['postopts']      = $postopts;
621         $datarray['origin']        = $origin;
622         $datarray['moderated']     = $allow_moderated;
623
624         /**
625          * These fields are for the convenience of plugins...
626          * 'self' if true indicates the owner is posting on their own wall
627          * If parent is 0 it is a top-level post.
628          */
629
630         $datarray['parent']        = $parent;
631         $datarray['self']          = $self;
632 //      $datarray['prvnets']       = $user['prvnets'];
633
634         if($orig_post)
635                 $datarray['edit']      = true;
636         else
637                 $datarray['guid']      = get_guid();
638
639         // preview mode - prepare the body for display and send it via json
640
641         if($preview) {
642                 require_once('include/conversation.php');
643                 $o = conversation($a,array(array_merge($contact_record,$datarray)),'search', false, true);
644                 logger('preview: ' . $o);
645                 echo json_encode(array('preview' => $o));
646                 killme();
647         }
648
649
650         call_hooks('post_local',$datarray);
651
652         if(x($datarray,'cancel')) {
653                 logger('mod_item: post cancelled by plugin.');
654                 if($return_path) {
655                         goaway($a->get_baseurl() . "/" . $return_path);
656                 }
657
658                 $json = array('cancel' => 1);
659                 if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
660                         $json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload'];
661
662                 echo json_encode($json);
663                 killme();
664         }
665
666
667         if($orig_post) {
668                 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `attach` = '%s', `file` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
669                         dbesc($datarray['title']),
670                         dbesc($datarray['body']),
671                         dbesc($datarray['tag']),
672                         dbesc($datarray['attach']),
673                         dbesc($datarray['file']),
674                         dbesc(datetime_convert()),
675                         intval($post_id),
676                         intval($profile_uid)
677                 );
678
679                 // update filetags in pconfig
680                 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
681
682                 proc_run('php', "include/notifier.php", 'edit_post', "$post_id");
683                 if((x($_REQUEST,'return')) && strlen($return_path)) {
684                         logger('return: ' . $return_path);
685                         goaway($a->get_baseurl() . "/" . $return_path );
686                 }
687                 killme();
688         }
689         else
690                 $post_id = 0;
691
692
693         $r = q("INSERT INTO `item` (`guid`, `uid`,`type`,`wall`,`gravity`,`contact-id`,`owner-name`,`owner-link`,`owner-avatar`, 
694                 `author-name`, `author-link`, `author-avatar`, `created`, `edited`, `commented`, `received`, `changed`, `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`, 
695                 `tag`, `inform`, `verb`, `postopts`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`, `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file` )
696                 VALUES( '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, %d, '%s' )",
697                 dbesc($datarray['guid']),
698                 intval($datarray['uid']),
699                 dbesc($datarray['type']),
700                 intval($datarray['wall']),
701                 intval($datarray['gravity']),
702                 intval($datarray['contact-id']),
703                 dbesc($datarray['owner-name']),
704                 dbesc($datarray['owner-link']),
705                 dbesc($datarray['owner-avatar']),
706                 dbesc($datarray['author-name']),
707                 dbesc($datarray['author-link']),
708                 dbesc($datarray['author-avatar']),
709                 dbesc($datarray['created']),
710                 dbesc($datarray['edited']),
711                 dbesc($datarray['commented']),
712                 dbesc($datarray['received']),
713                 dbesc($datarray['changed']),
714                 dbesc($datarray['uri']),
715                 dbesc($datarray['thr-parent']),
716                 dbesc($datarray['title']),
717                 dbesc($datarray['body']),
718                 dbesc($datarray['app']),
719                 dbesc($datarray['location']),
720                 dbesc($datarray['coord']),
721                 dbesc($datarray['tag']),
722                 dbesc($datarray['inform']),
723                 dbesc($datarray['verb']),
724                 dbesc($datarray['postopts']),
725                 dbesc($datarray['allow_cid']),
726                 dbesc($datarray['allow_gid']),
727                 dbesc($datarray['deny_cid']),
728                 dbesc($datarray['deny_gid']),
729                 intval($datarray['private']),
730                 intval($datarray['pubmail']),
731                 dbesc($datarray['attach']),
732                 intval($datarray['bookmark']),
733                 intval($datarray['origin']),
734                 intval($datarray['moderated']),
735                 dbesc($datarray['file'])
736                );
737
738         $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
739                 dbesc($datarray['uri']));
740         if(count($r)) {
741                 $post_id = $r[0]['id'];
742                 logger('mod_item: saved item ' . $post_id);
743
744                 // update filetags in pconfig
745                 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
746
747                 if($parent) {
748
749                         // This item is the last leaf and gets the comment box, clear any ancestors
750                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d ",
751                                 dbesc(datetime_convert()),
752                                 intval($parent)
753                         );
754
755                         // Inherit ACL's from the parent item.
756
757                         $r = q("UPDATE `item` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d
758                                 WHERE `id` = %d LIMIT 1",
759                                 dbesc($parent_item['allow_cid']),
760                                 dbesc($parent_item['allow_gid']),
761                                 dbesc($parent_item['deny_cid']),
762                                 dbesc($parent_item['deny_gid']),
763                                 intval($parent_item['private']),
764                                 intval($post_id)
765                         );
766
767                         if($contact_record != $author) {
768                                 notification(array(
769                                         'type'         => NOTIFY_COMMENT,
770                                         'notify_flags' => $user['notify-flags'],
771                                         'language'     => $user['language'],
772                                         'to_name'      => $user['username'],
773                                         'to_email'     => $user['email'],
774                                         'uid'          => $user['uid'],
775                                         'item'         => $datarray,
776                                         'link'             => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
777                                         'source_name'  => $datarray['author-name'],
778                                         'source_link'  => $datarray['author-link'],
779                                         'source_photo' => $datarray['author-avatar'],
780                                         'verb'         => ACTIVITY_POST,
781                                         'otype'        => 'item',
782                                         'parent'       => $parent,
783                                         'parent_uri'   => $parent_item['uri']
784                                 ));
785                         
786                         }
787
788
789                         // Store the comment signature information in case we need to relay to Diaspora
790                         store_diaspora_comment_sig($datarray, $author, ($self ? $a->user['prvkey'] : false), $parent_item, $post_id);
791
792                 }
793                 else {
794                         $parent = $post_id;
795
796                         if($contact_record != $author) {
797                                 notification(array(
798                                         'type'         => NOTIFY_WALL,
799                                         'notify_flags' => $user['notify-flags'],
800                                         'language'     => $user['language'],
801                                         'to_name'      => $user['username'],
802                                         'to_email'     => $user['email'],
803                                         'uid'          => $user['uid'],
804                                         'item'         => $datarray,
805                                         'link'             => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
806                                         'source_name'  => $datarray['author-name'],
807                                         'source_link'  => $datarray['author-link'],
808                                         'source_photo' => $datarray['author-avatar'],
809                                         'verb'         => ACTIVITY_POST,
810                                         'otype'        => 'item'
811                                 ));
812                         }
813                 }
814
815                 // fallback so that parent always gets set to non-zero.
816
817                 if(! $parent)
818                         $parent = $post_id;
819
820                 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `plink` = '%s', `changed` = '%s', `last-child` = 1, `visible` = 1
821                         WHERE `id` = %d LIMIT 1",
822                         intval($parent),
823                         dbesc(($parent == $post_id) ? $uri : $parent_item['uri']),
824                         dbesc($a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id),
825                         dbesc(datetime_convert()),
826                         intval($post_id)
827                 );
828
829                 // photo comments turn the corresponding item visible to the profile wall
830                 // This way we don't see every picture in your new photo album posted to your wall at once.
831                 // They will show up as people comment on them.
832
833                 if(! $parent_item['visible']) {
834                         $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d LIMIT 1",
835                                 intval($parent_item['id'])
836                         );
837                 }
838         }
839         else {
840                 logger('mod_item: unable to retrieve post that was just stored.');
841                 notice( t('System error. Post not saved.') . EOL);
842                 goaway($a->get_baseurl() . "/" . $return_path );
843                 // NOTREACHED
844         }
845
846         // update the commented timestamp on the parent
847
848         q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
849                 dbesc(datetime_convert()),
850                 dbesc(datetime_convert()),
851                 intval($parent)
852         );
853
854         $datarray['id']    = $post_id;
855         $datarray['plink'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id;
856
857         call_hooks('post_local_end', $datarray);
858
859         if(strlen($emailcc) && $profile_uid == local_user()) {
860                 $erecips = explode(',', $emailcc);
861                 if(count($erecips)) {
862                         foreach($erecips as $recip) {
863                                 $addr = trim($recip);
864                                 if(! strlen($addr))
865                                         continue;
866                                 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'),$a->user['username']) 
867                                         . '<br />';
868                                 $disclaimer .= sprintf( t('You may visit them online at %s'), $a->get_baseurl() . '/profile/' . $a->user['nickname']) . EOL;
869                                 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL; 
870
871                                 $subject  = email_header_encode('[Friendica]' . ' ' . sprintf( t('%s posted an update.'),$a->user['username']),'UTF-8');
872                                 $headers  = 'From: ' . email_header_encode($a->user['username'],'UTF-8') . ' <' . $a->user['email'] . '>' . "\n";
873                                 $headers .= 'MIME-Version: 1.0' . "\n";
874                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
875                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
876                                 $link = '<a href="' . $a->get_baseurl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
877                                 $html    = prepare_body($datarray);
878                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
879                                 @mail($addr, $subject, $message, $headers);
880                         }
881                 }
882         }
883
884         // This is a real juggling act on shared hosting services which kill your processes
885         // e.g. dreamhost. We used to start delivery to our native delivery agents in the background
886         // and then run our plugin delivery from the foreground. We're now doing plugin delivery first,
887         // because as soon as you start loading up a bunch of remote delivey processes, *this* page is
888         // likely to get killed off. If you end up looking at an /item URL and a blank page,
889         // it's very likely the delivery got killed before all your friends could be notified.
890         // Currently the only realistic fixes are to use a reliable server - which precludes shared hosting,
891         // or cut back on plugins which do remote deliveries.  
892
893         proc_run('php', "include/notifier.php", $notify_type, "$post_id");
894
895         logger('post_complete');
896
897         item_post_return($a->get_baseurl(), $api_source, $return_path);
898         // NOTREACHED
899 }
900
901 function item_post_return($baseurl, $api_source, $return_path) {
902         // figure out how to return, depending on from whence we came
903
904         if($api_source)
905                 return;
906
907         if($return_path) {
908                 goaway($baseurl . "/" . $return_path);
909         }
910
911         $json = array('success' => 1);
912         if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
913                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
914
915         logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
916
917         echo json_encode($json);
918         killme();
919 }
920
921
922
923 function item_content(&$a) {
924
925         if((! local_user()) && (! remote_user()))
926                 return;
927
928         require_once('include/security.php');
929
930         $o = '';
931         if(($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
932                 require_once('include/items.php'); 
933                 $o = drop_item($a->argv[2], !is_ajax());
934                 if (is_ajax()){
935                         // ajax return: [<item id>, 0 (no perm) | <owner id>] 
936                         echo json_encode(array(intval($a->argv[2]), intval($o)));
937                         kllme();
938                 }
939         }
940         return $o;
941 }
942
943 /**
944  * This function removes the tag $tag from the text $body and replaces it with 
945  * the appropiate link. 
946  * 
947  * @param unknown_type $body the text to replace the tag in
948  * @param unknown_type $inform a comma-seperated string containing everybody to inform
949  * @param unknown_type $str_tags string to add the tag to
950  * @param unknown_type $profile_uid
951  * @param unknown_type $tag the tag to replace
952  *
953  * @return boolean true if replaced, false if not replaced
954  */
955 function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag) {
956
957         $replaced = false;
958         $r = null;
959
960         //is it a hash tag? 
961         if(strpos($tag,'#') === 0) {
962                 //if the tag is replaced...
963                 if(strpos($tag,'[url='))
964                         //...do nothing
965                         return $replaced;
966                 //base tag has the tags name only
967                 $basetag = str_replace('_',' ',substr($tag,1));
968                 //create text for link
969                 $newtag = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
970                 //replace tag by the link
971                 $body = str_replace($tag, $newtag, $body);
972                 $replaced = true;
973
974                 //is the link already in str_tags?
975                 if(! stristr($str_tags,$newtag)) {
976                         //append or set str_tags
977                         if(strlen($str_tags))
978                                 $str_tags .= ',';
979                         $str_tags .= $newtag;
980                 }
981                 return $replaced;
982         }
983         //is it a person tag? 
984         if(strpos($tag,'@') === 0) {
985                 //is it already replaced? 
986                 if(strpos($tag,'[url='))
987                         return $replaced;
988                 $stat = false;
989                 //get the person's name
990                 $name = substr($tag,1);
991                 //is it a link or a full dfrn address? 
992                 if((strpos($name,'@')) || (strpos($name,'http://'))) {
993                         $newname = $name;
994                         //get the profile links
995                         $links = @lrdd($name);
996                         if(count($links)) {
997                                 //for all links, collect how is to inform and how's profile is to link
998                                 foreach($links as $link) {
999                                         if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
1000                                                 $profile = $link['@attributes']['href'];
1001                                         if($link['@attributes']['rel'] === 'salmon') {
1002                                                 if(strlen($inform))
1003                                                         $inform .= ',';
1004                                                 $inform .= 'url:' . str_replace(',','%2c',$link['@attributes']['href']);
1005                                         }
1006                                 }
1007                         }
1008                 } else { //if it is a name rather than an address
1009                         $newname = $name;
1010                         $alias = '';
1011                         $tagcid = 0;
1012                         //is it some generated name?
1013                         if(strrpos($newname,'+')) {
1014                                 //get the id
1015                                 $tagcid = intval(substr($newname,strrpos($newname,'+') + 1));
1016                                 //remove the next word from tag's name
1017                                 if(strpos($name,' ')) {
1018                                         $name = substr($name,0,strpos($name,' '));
1019                                 }
1020                         }
1021                         if($tagcid) { //if there was an id
1022                                 //select contact with that id from the logged in user's contact list
1023                                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1024                                                 intval($tagcid),
1025                                                 intval($profile_uid)
1026                                 );
1027                         }
1028                         else {
1029                                 $newname = str_replace('_',' ',$name);
1030
1031                                 //select someone from this user's contacts by name
1032                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1033                                                 dbesc($newname),
1034                                                 intval($profile_uid)
1035                                 );
1036
1037                                 if(! $r) {
1038                                         //select someone by attag or nick and the name passed in
1039                                         $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1040                                                         dbesc($name),
1041                                                         dbesc($name),
1042                                                         intval($profile_uid)
1043                                         );
1044                                 }
1045                         }
1046 /*                      } elseif(strstr($name,'_') || strstr($name,' ')) { //no id
1047                                 //get the real name
1048                                 $newname = str_replace('_',' ',$name);
1049                                 //select someone from this user's contacts by name
1050                                 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1051                                                 dbesc($newname),
1052                                                 intval($profile_uid)
1053                                 );
1054                         } else {
1055                                 //select someone by attag or nick and the name passed in
1056                                 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1057                                                 dbesc($name),
1058                                                 dbesc($name),
1059                                                 intval($profile_uid)
1060                                 );
1061                         }*/
1062                         //$r is set, if someone could be selected
1063                         if(count($r)) {
1064                                 $profile = $r[0]['url'];
1065                                 //set newname to nick, find alias
1066                                 if($r[0]['network'] === 'stat') {
1067                                         $newname = $r[0]['nick'];
1068                                         $stat = true;
1069                                         if($r[0]['alias'])
1070                                                 $alias = $r[0]['alias'];
1071                                 }
1072                                 else
1073                                         $newname = $r[0]['name'];
1074                                 //add person's id to $inform
1075                                 if(strlen($inform))
1076                                         $inform .= ',';
1077                                 $inform .= 'cid:' . $r[0]['id'];
1078                         }
1079                 }
1080                 //if there is an url for this persons profile
1081                 if(isset($profile)) {
1082                         $replaced = true;
1083                         //create profile link
1084                         $profile = str_replace(',','%2c',$profile);
1085                         $newtag = '@[url=' . $profile . ']' . $newname  . '[/url]';
1086                         $body = str_replace('@' . $name, $newtag, $body);
1087                         //append tag to str_tags
1088                         if(! stristr($str_tags,$newtag)) {
1089                                 if(strlen($str_tags))
1090                                         $str_tags .= ',';
1091                                 $str_tags .= $newtag;
1092                         }
1093         
1094                         // Status.Net seems to require the numeric ID URL in a mention if the person isn't
1095                         // subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1096         
1097                         if(strlen($alias)) {
1098                                 $newtag = '@[url=' . $alias . ']' . $newname    . '[/url]';
1099                                 if(! stristr($str_tags,$newtag)) {
1100                                         if(strlen($str_tags))
1101                                                 $str_tags .= ',';
1102                                         $str_tags .= $newtag;
1103                                 }
1104                         }
1105                 }
1106         }
1107
1108         return array('replaced' => $replaced, 'contact' => $r[0]);      
1109 }
1110
1111
1112 function store_diaspora_comment_sig($datarray, $author, $uprvkey, $parent_item, $post_id) {
1113         // We won't be able to sign Diaspora comments for authenticated visitors - we don't have their private key
1114
1115         $enabled = intval(get_config('system','diaspora_enabled'));
1116         if(! $enabled) {
1117                 logger('mod_item: diaspora support disabled, not storing comment signature', LOGGER_DEBUG);
1118                 return;
1119         }
1120
1121
1122         logger('mod_item: storing diaspora comment signature');
1123
1124         require_once('include/bb2diaspora.php');
1125         $signed_body = html_entity_decode(bb2diaspora($datarray['body']));
1126
1127         // Only works for NETWORK_DFRN
1128         $contact_baseurl_start = strpos($author['url'],'://') + 3;
1129         $contact_baseurl_length = strpos($author['url'],'/profile') - $contact_baseurl_start;
1130         $contact_baseurl = substr($author['url'], $contact_baseurl_start, $contact_baseurl_length);
1131         $diaspora_handle = $author['nick'] . '@' . $contact_baseurl;
1132
1133         $signed_text = $datarray['guid'] . ';' . $parent_item['guid'] . ';' . $signed_body . ';' . $diaspora_handle;
1134
1135         if( $uprvkey !== false )
1136                 $authorsig = base64_encode(rsa_sign($signed_text,$uprvkey,'sha256'));
1137         else
1138                 $authorsig = '';
1139
1140         q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1141                 intval($post_id),
1142                 dbesc($signed_text),
1143                 dbesc(base64_encode($authorsig)),
1144                 dbesc($diaspora_handle)
1145         );
1146
1147         return;
1148 }