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