How to change bb press forum roles programmatically? - bbpress

I have two user role
1)student
2)paid student
I have situation after the payment i am changing role student to paid student it work good but here i have also change the forum role programmatically to participant for paid student here . How do i change forum role programmatically using query, function anything.
Below code i have used to change user roles programmatically it works good but i am stuck d in changing forum role. i am looking something like this.
$user_id = get_current_user_id();
$oldrole=implode(', ', $user_id->roles);
if($oldrole=="student")
{
$u = new WP_User($user_id);
// Remove role
$u->remove_role('student');
$newrole="paid_student";
// Add role
$u->add_role( $newrole );
}

Finally i have got the answer.
Bellow are the step.
1) Get user current user id.
<?php $user_id = get_current_user_id(); ?>
2)set new user forum role you wish to change
<?php $new_role_forum_role="bbp_participant"; ?>
3)fire function.
<?php bbp_set_user_role( $user_id, $new_role_forum_role );?>
now check your user in back end and see forum user role.
Full snippet code
<?php
$user_id = get_current_user_id();
$new_role_forum_role="bbp_participant";
bbp_set_user_role( $user_id, $new_role_forum_role );
?>

Related

Way to hide some form fields for user xyz

at the moment I'm using this way to get the 'role' of an user in a ZEND_FORM.
$identity = Zend_Auth::getInstance()->getIdentity();
For every form field I check for the role in front of adding the form field like:
if($identity->role=='admin') $form->addElement...
Is there a smarter way to do this? Such as an option for the addElement?
Best Regards
Frgtv10
The way you do it could get messy. Its possible you could use 2 forms here. One main one containing what is common to everyone and one that inherits from the first one and adds fonctionnality for admins. This would be much easier to maintain since you would just instantiate the right form depending on role so one check for role instead of a ton everywhere in your form.
So in your controller you would :
if($identity->role=='admin'){
$form = new Form_WhateverAdmin();
} else {
$form = new Form_WhateverNotAdmin();
}
And where
Form_WhateverNotAdmin extends Zend_Form
and
Form_WhateverAdmin extends Form_WhateverNotAdmin
You also can delete existing elemets:
if($identity->role != 'admin') $form->removeElement('name');

Joomla Form Field User Front End

I am trying to use JFormFieldUser::getInput as an input to my Joomla forms.
In the backend (logged in with the super user), when I call this method, it produces a nice 'select user' box when clicked displays a list of all users to chose from.
I have been trying to use the User form field on a front end form (logged in with the super user). The result is some what confusing and undesirable. A 'select user' link is produced, but when clicking on it, the result is that the super users, 'User profile' is loaded up: not a list of all users.
Why is this, and how can i make 'select user' show the full list of users like it does in the backend.
Joomla 3 (from your field definitions):
<field name="field_name" type="sql" label="COM_FIELD_LABEL"
sql_select="id,name"
sql_from="#__users"
value_field="name"
key_field="id"
description=""
header="DROP_DOWN_HEADER"
required="false" />
Apparently it can't be done
The JForm (Joomla) User field is the Joomla core field that you can
see in Joomla article form to select a user (lightbox with list of
user). Becareful this field can not be used on front-end because
Joomla core don't manage it on front-end... Often we replace this
field on front end with a select dynamic field.
I didn't have much luck with this. Instead I created my own component and added in the content from com_users. Worked a treat.
Can be done fairly simply but with some significant limitations - depending on your use case.
User must be logged in to backend (even if you are trying to access the information frontend). If they are not logged in, it will prompt for log in and break out of the modal :(
User must have permissions for User Manager
Then duplicate the \libraries\cms\form\field\user.php to a fields location of your choice (in a modal subdirectory) and rename it to something like user2.php. Make the class name JFormFieldModal_Users2 and the $type='Modal_Users2'.
Don't forget to add the new path to your form .xml if required. The type will be "modal_users2".
Last step. In user2.php, change:
$link = 'index.php?option=com_users&view=users&layout=modal&tmpl=component&field=' . $this->id
. (isset($groups) ? ('&groups=' . base64_encode(json_encode($groups))) : '')
. (isset($excluded) ? ('&excluded=' . base64_encode(json_encode($excluded))) : '');
to
$link = 'administrator/index.php?option=com_users&view=users&layout=modal&tmpl=component&field=' . $this->id
. (isset($groups) ? ('&groups=' . base64_encode(json_encode($groups))) : '')
. (isset($excluded) ? ('&excluded=' . base64_encode(json_encode($excluded))) : '');
A bit hacky, but served my purposes.
Less hacky, but less glamorous solution here: The SQL formfield type

Cakephp 2 security in forms

I have a question about the cakephp2 forms security. Let's assume that we have the Security Component enabled and have already build users authentication, permissions, and product management system.
We need to create an Offer Request feature, which allows users to ask for an offer for a specific product.
The user is logged in and clicks on "ask" and goes to /offer_requests/add/product_id
Scenario 1:
In the /Views/OfferRequests/add.ctp:
<?php
echo $this->Form->create('OfferRequest');
echo $this->Form->input('user_id',
array('value' => $this->Session->read('Auth.User.id'),
'type' => 'hidden' ));
echo $this->Form->input('product_id');
echo $this->Form->input('quantity');
echo $this->Form->end(__('Submit'));
?>
Scenario 2:
In the /Views/OfferRequests/add.ctp:
<?php
echo $this->Form->create('OfferRequest');
echo $this->Form->input('product_id');
echo $this->Form->input('quantity');
echo $this->Form->end(__('Submit'));
?>
And in the OfferRequestsController add():
<?php
$this->request->data['OfferRequest']['user_id'] = $this->Session->read('Auth.User.id');
?>
My question is which scenario is more safe, for example against making false requests as other user. For scenario 1, does the Security Component allow manipulating input values through Firebug or some other software?
Yes, the security component adds automatic prevention of form tampering:
From the docs:
By using the Security Component you automatically get CSRF and form
tampering protection. Hidden token fields will automatically be
inserted into forms and checked by the Security component. Among other
things, a form submission will not be accepted after a certain period
of inactivity, which is controlled by the csrfExpires time.
As stated in the other answer, you can use the fieldsList option when saving your data instead. With the security component, however, you would be able to add the user_id as a hidden field (scenario 1) and not worry about its value being tampered with. This would prevent the necessity to set it in the controller (scenario 2).

How to reuse codeigniter form on multiple pages

I have a simple search form I want to reuse across multiple pages in my codeigniter application. For example, right now I have a search form in the sidebar and I'm planning on displaying that sidebar on the index, about, and other pages.
I want to have the form validation display errors on the same page the users submits the form from.
For example:
User is on About page.
User submits form with invalid data
User sees error in the sidebar on the About page
and
User is on Index page.
User submits form with invalid data
User sees error in the sidebar on the Index page
But I'd like to reuse that form validation logic. I just want it to display the error on whichever page the user posted from.
Any ideas how to do that? Sorry for the noob question, I'm pretty new to CI.
Here you have to think globally.
Step.1 : Make one view file : display.php
which contains :
<div id = "main">
<div id = "header">
[load header file here]
</div>
<?php
if(validation_errors() != '') {
?>
<div id = "error">
<?=validation_errors()?>
</div>
<?php
}
?>
<div id = "content">
<?=$page?>
</div>
<div id = "footer">
[load footer file here]
</div>
</div>
Step.2 : About us Page.(controlller)
.... Your data ....
at end of controller function
$data['page'] = 'aboutus';
$this->load->view('display',$data);
With regards to your comment on the above question you could use Flash data
With the assumption that you have the session library loaded, here is a helper function.
function last_page($page = null){
$ci = get_instance();
if($page === null)
return $ci->session->flashdata('last_page');
$ci->session->set_flashdata('last_page', $page);
}
then you can call last_page('about'); at the top of the about page, and then when you want to find out what the last page you were on was you can just call last_page(); with no params.
In the User Guide, there's different ways to configure sets/groups of rules. Then you can simply have something like:
if ($this->form_validation->run('signup') == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
Which will run your "signup" group of validations. To me, this is the cleanest way to achieve reusable validation rules.
This is a perfectly valid question.
I'm not a PHP expert, nor a CI expert, but the fact is sometimes you want to post to a controller that didn't create the view from which you're posting. Which means posting back to itself is not going to work.
I came across this post on the Ellislab forum:
http://ellislab.com/forums/viewthread/217176/
On this page, There are 2 methods of going about it. Both of which use flashdata and both of which are totally valid, IMHO.
The first: create a helper function
http://ellislab.com/forums/viewreply/1003010/
The second: extend the CI_Form_Validation Class.
http://ellislab.com/forums/viewreply/1047536/
The second is the way I went as it seems cleanest although some may argue whether the form validation class should know anything about flash data.

How do I use CakePHP to append data to database when submitting from a form?

I've been developing this application for use in my biology lab where I require the following:
User adds in data into a text field.
When the user wants to update the text field, s/he cannot update the existing text, and can only append new text to the field.
Therefore, the form must contain a blank text field that the user can input text to append to the existing entry.
Ideally, I'd also like to append the timestamp for when each entry is recorded.
As you can see, it's sort of like a lab notebook, where the integrity of previously-entered data is important.
I'm having trouble with 2nd point, in that I don't know how to create a blank text field that saves the data to the corresponding field in the model.
Here is the code I currently have for the "view":
(I've tried to hide the existing data - "results_summary" - in a "hidden" element.)
<!-- File: /app/View/Experiments/update.ctp -->
<h1>Update Experiment</h1>
<h2>Objective:</h2>
<p><?php echo $experiment['Experiment']['objective']?></p>
<p>Notebook <?php echo $experiment['Experiment']['notebook_number'] ?>, Page <?php echo $experiment['Experiment']['notebook_page'] ?> </p>
<p>Date Started: <?php echo $experiment['Experiment']['date_started']?></p>
<p>Date Ended: <?php echo $experiment['Experiment']['date_ended']?></p>
<p>Project: <?php echo $experiment['Project']['title']?>
<p>Status: <?php echo $experiment['ExperimentStatus']['title']?>
<p>Results Summary:</p>
<p><?php echo $this->Form->create('Experiment', array('action' => 'update'));
echo $this->Form->hidden('results_summary');
echo $this->Form->text('results_summary');
echo $this->Form->end('Update');
//$experiment['Experiment']['results_summary']?></p>
Does anybody have clues as to how I could go about solving this problem? I'm quite lost right now, as I haven't had the experience coding this before.
Based on requirements 3 and 4, I would model the database in a way that each summary entry is stored in a separate row. You'll need a separate table for that, something like this:
id | experiment_id | summary_entry | summary_entry_timestamp
Column experiment_id is a foreign key to the related id on experiments table. Tables/models are related so that Experiment hasMany ExperimentSummaryEntry.
Then, logging to the experiment results summary will be a matter of inserting a new row on that table.
I would have to agree with #bfavaretto
Without seeing your database structure it is hard to be sure.
I suspect that you are doing
Project hasMany Experiment
Experiment hasOne ExperimentStatus
You need an additional
Experiment hasMany ExperimentEntry
the entries table need to have
id int(11), experiment_id int (11), content TEXT, created DATETIME
if you are okay using DATETIME field for timestamp then I suggest using **created because cakephp will auto fill in for you.
instead of update experiment, you do a add experimententry.
in the afterSave method of ExperimentEntry you do a
$this->Experiment->id = $this->data['ExperimentEntry']['experiment_id'];
$latestSummary = $this->Experiment->field('result_summary');
$latestSummary .= $this->data['ExperimentEntry']['content']; // you may need to add a newline before you append. up to you
$this->Experiment->save(array(
'Experiment' => array(
'result_summary' => $latestSummary
)));
Code is not tested so use at own risk.
** no corresponding page in cakephp 2.0 docs for created and modified but definitely this works. I have tried it before.