CI PHP if statement w/ sql syntax - sql

This is a quick syntax question...
I need to block out an HTML element if two SQL statements are true w/ php.
If the status = 'closed', and if the current user is logged in. I can figure out the calls, I just need to see an example of the syntax. :)
So, If SQL status=closed, and if current_user=is_logged_in()...something like that.

I'll assume you're trying to block out a login box if the user is logged in. Here's what you'll need to do:
In the view:
<?php if ($show_login): ?>
<!-- login box code here -->
<?php endif; ?>
In the controller's action that calls the view:
if (is_logged_in() && $this->my_model->check_something()) {
$data['show_login'] = false;
}
else {
$data['show_login'] = true;
}
$this->load->view('myview', $data);
In the model:
function check_something() {
// execute the SQL statements
// and return true/false depending on what you get
}
Refer to CodeIgniter's Active Record documentation to figure out how to setup your SQL statements.
If this isn't what you were looking for, try making your question more detailed, maybe with whatever code you have.

figured it out:
I forgot that I had already called my $data...
<?php
if ($row['status'] == 'closed' && is_logged_in()) { ?>
I feel like a dummy... :)

if($status == "closed" && is_logged_in() == true)
{
// Do Stuff
}
Where is_logged_in() returns true if the user is logged in, or false if the user is not logged in. $status is the value of the MySQL status, which should be either true or false.

if (is_status_closed() && is_logged_in($current_user)) {
// Block this HTML element
elem->block();
}
is_status_closed() would return true if status is equal to "closed".
is_logged_in($current_user) would return true if the user referred to by $current_user is logged in.
The && lets you join two conditional statements together, and can be read as the word "and".
This seems to be a simple question though; is this what you are asking how to do?

Related

Alternatives to conditional statements while writing Cypress custom commands? test-of-tests

This is more of an open ended question. Apologies for asking, however, I cant seem to find a good explanation in online searches, and this community has been one of the important learning resources.
I am writing end to end tests for a complex web application. In a nutshell, it involves...
Creating an application by giving specific inputs
Filling out a series of forms, which differ according to the input given during application creation.
Since the main concept of Cypress is to keep the spec file clean and add all the code in a custom command, and call the custom command in the spec file, I have been writing a lot of if-else conditional statements. For example...
//spec
describe("Test scenario 1", () => {
it("test case 1", function () {
cy.CustomCommand1(arg1,arg2) //arguments are fetched from a fixture file, which acts like input data. Fixture file changes for various test to cover multiple scenario.
})
})
//CustomCommand1
Cypress.Commands.Add('CustomCommand1',(arg1,arg2) => {
if(arg1==xyz || arg2==abc){
//fill some fields
//assert on things in the form and so on...
}
else{
//do something else
//assert on something else and so on...
}
})
This is how I have been using a single command for a single page on my web app, and adding logic for the appearance of various form fields and check boxes etc, filling them and asserting.
I have multiple pages and each displaying different set of fields on the basis of the input data while creation of application. Every page has its own custom command and there is hell of a logic built in there. A real custom command from my project looks like this...
Cypress.Commands.add('addEmployers', (employer) => {
cy.location('pathname').should('eq', '/welcome/employers')
cy.get('[data-testid="add-employer"]').click()
cy.get('#company_name').type(employer.company)
cy.get('#position').type(employer.position)
cy.get('#current').click()
cy.get(`[data-testid="${employer.type}"]`).click()
cy.get('#start_date').parent().type(`${employer.sdate}{enter}`)
if (employer.type == 'not_current') {
cy.get('#end_date').parent().type(`${employer.edate}{enter}`)
}
cy.get('[data-testid="street_address"]').type(employer.addr.street)
cy.selectCountry('#country',employer.addr.country)
if ((['Canada','United States'].includes(employer.addr.country))) {
cy.dropdownWithText('#province_state',employer.addr.province)
}
else {
cy.selectOTProvince('#other_province_state',employer.addr)
}
cy.get('#city').type(employer.addr.city)
cy.get('#postal_code').type(employer.addr.postal)
if(employer.type == 'yes_current' && employer.empcontact == 'Y') {
cy.get('#can_contact').click()
cy.get('[data-testid="can_contact_employer"]').click()
}
if(employer.type == 'yes_current' && employer.empcontact == 'N') {
cy.get('#can_contact').click()
cy.get('[data-testid="cannot_contact_employer"]').click()
}
if(employer.type == 'not_current' || (employer.type == 'yes_current' && employer.empcontact == 'Y')){
cy.ClickNext()
cy.get('#contact_first_name').type(employer.emp.fname)
cy.get('#contact_last_name').type(employer.emp.lname)
cy.EmailGen('employer').then(email => {
cy.wrap(email).as('employerEmail')
})
cy.get('#employerEmail').then(email =>{
cy.get('#contact_email').type(`${email}`)
cy.wrap(email).as('empemail')
})
})
}
})
And then I get to know that if we have conditional statements in a test, they would require tests too. (Test of Tests :shrug:)
Is there something fundamentally wrong in my approach. If yes, what changes should I bring to my approach to keep spec files clean and do bulk of the jobs in custom command?
Do let me know if any more details are required!

Make menu tab on user profile visible only to profile owner

I made a "My bookmarks" tab on the user profile page using Views. The tab shows nodes the user has flagged.
However - "My bookmarks" should only be visible on the user's own profile page and at the moment the "My bookmarks" tab is visible on every profile a user visits. How do I check whether the current user matches the profile being viewed? I tried that from the View interface, but the access permissions don't have any options that work.
EDIT:
I think it is this code, but I still need some guidelines as to how to implement that:
<?php
global $user;
if (arg(0) == 'user' && $user->uid == arg(1)){
return TRUE;
}
else {
return FALSE;
}
?>
I also found this module, I think it helps a lot Views Access Callback
I managed to solve this using the code and module from above.
The custom module contains this code
<?php
function MYMODULE_views_access_callbacks() {
return array(
'MYCALLBACK_user_has_access' => t('User can only see tab on his own profile'));
}
function MYCALLBACK_user_has_access() {
global $user;
if (arg(0) == 'user' && $user->uid == arg(1)){
return TRUE;
}
else {
return FALSE;
}
}
?>
The Views Access Callback module adds your callback to the Views interface and from there, you can use it for your own view.

implement a simple inbox with notifications in yii

I want to implement a simple inbox in yii. it reads messages from a database table and show it.
but i don't know how i should show read and unread messages in different styles and how i can implement a notification for new messages.
i searched a lot but only found some extensions and i don't want to use them.
it is so important to find how i can show unread messages in a different way
any initial idea would help me
a part of mailbox extension code :
public function actionInbox($ajax=null)
{
$this->module->registerConfig($this->getAction()->getId());
$cs =& $this->module->getClientScript();
$cs->registerScriptFile($this->module->getAssetsUrl().'/js/mailbox.js',CClientScript::POS_END);
//$js = '$("#mailbox-list").yiiMailboxList('.$this->module->getOptions().');console.log(1)';
//$cs->registerScript('mailbox-js',$js,CClientScript::POS_READY);
if(isset($_POST['convs']))
{
$this->buttonAction('inbox');
}
$dataProvider = new CActiveDataProvider( Mailbox::model()->inbox($this->module->getUserId()) );
if(isset($ajax))
$this->renderPartial('_mailbox',array('dataProvider'=>$dataProvider));
else{
if(!isset($_GET['Mailbox_sort']))
$_GET['Mailbox_sort'] = 'modified.desc';
$this->render('mailbox',array('dataProvider'=>$dataProvider));
}
}
First of all the scripts things should be in the view. For you problem I would do something like
In the controller
$mailbox = Mailbox::model()->inbox($this->module->getUserId()); //I assume this returns the mailbox from that user?
$this->renderPartial('_mailbox',compact('mailbox ')); //compact is the same as array('mailbox'=>$mailbox) so use whatever you prefer.
In the view I would simply do something like this
<?php foreach($mailbox->messages as $message):
$class = ''; //order unread if you want to give both a different class name
if($message->read): //if this is true
$class = 'read';
endif; ?>
<div id='<?= $message->id ?>'class='message $class'> <!-- insert whatever info from the message --></div>
<?php endforeach; ?>
So now it will add the class read to every message that has been read. Then in CSS you can simply change it style. I hope this is enough information? I use foreach(): endforeach; and if(): endif; in the view files, but you could use foreach() {}, but I prefer foreach, as it looks better combined with HTML.
EDIT about you second question, how do they become read. This you could do with JQUERY. example.
$(".message").on("click", function() {
var id = $(this).attr('id');
$.ajax {
type:"POST",
url: "controller/action/"+id; //the controller action that fetches the message, the Id is the action variable (ex: public function actionGetMessage($id) {})
completed: function(data) {
//data = the message information, you might do type: 'JSON' instead. Use it however you want it.
if(!$(this).hasClass("read"))
$(this).addClass("read"); //give it the class read if it does not have it already
}
}
});
This simply gives the div the class read and it should look like the other items with the class read.

Yii: Using an authorization hierarchy correctly

I am attempting to validate if a user, who belongs to a company, can view an item that belongs to a company...in other words, if they are an employee they should be able to view the company's items.
I'm trying to follow the example provided here:
http://www.yiiframework.com/doc/guide/1.1/en/topics.auth
This is the code I generated (run one time):
$auth=Yii::app()->authManager;
$auth->createOperation('viewItem','view an item');
$bizRule = 'return User::model()->findByPk(Yii::app()->user->getId())->company->id==$params["item"]->company->id';
$task=$auth->createTask('companyOwnedItem','view a company-owned item',$bizRule);
$task->addChild('viewItem');
This is the code in main.php:
'authManager'=>array(
'class'=>'CDbAuthManager',
'connectionID'=>'db',
This is the authorization piece used in my controller:
if (Yii::app()->user->checkAccess('companyOwnedItem',array('item'=>$item))) {
echo 'YES';
} else echo 'NO';
I always get 'NO' on the screen.
However if I use this code:
if (User::model()->findByPk(Yii::app()->user->getId())->company->id==$item->company->id)
Then I get 'YES' on the screen. What am I doing wrong and how do I use Yii's built-in authManager to make it work?
Best guess is that the item in items array isn't working properly. Have you turned on debugging for your auth manager? Forgot the property, but there is one to turn on in case of bizRule errors.
Other than that, it looks right. Also, FYI, after Yii 1.1.11, there is a $param['userId'] option so that you don't need to look up the current user's ID.
I ended up using the following and it worked:
In my config:
'authManager'=>array(
'class'=>'CDbAuthManager',
'connectionID'=>'db',
'defaultRoles'=>array('authenticated'),
'showErrors'=>true,
),
My authManager code:
$auth=Yii::app()->authManager;
$bizRule = 'return User::model()->findByPk(Yii::app()->user->getId())->company->id==$params["item"]->company->id;';
$auth->createOperation('companyOwnedItem','view a company-owned item',$bizRule);
$role = $auth->createRole('authenticated');
$role->addChild('companyOwnedItem');
Then in my controller:
if (Yii::app()->user->checkAccess('companyOwnedItem',array('item'=>$item))) {
echo 'YES';
} else {echo 'NO';}
And it works now!

Confirm Message on DropDown Select Change

I need to show a Confirm message when the value Hiring is selected in the dropdown. How can I do that?
if (Status.SelectedValue == "HIRING")
{
Status.Attributes.Add("onChange", "javascript:return DisplayConfirmation();");
}
I have the function DisplayConfirmation in aspx page. This does not work.
Alter the DisplayConfirmation() javascript function to include a parameter for the selected value, and handle the logic inside the function.
In the Code behind, replace your code with this:
Status.Attributes.Add("OnChange", string.Format("DisplayConfirmation('{0}');", Status.SelectedValue));
So, you can change your javascript to be
function DisplayConfirmation(Status) {
if(Status == "HIRING")
{
if (confirm('Are you sure you want to do this?')) { __doPostback('Status', ''); }
}}