PyroCMS/Codeigniter database issue - php

I may well be missing something quite obvious, but I'm still a bit lost. The actual database interaction seems to be the catch. I mean, the table is created on installation, but actually sending the information doesn't seem to work as it triggers the validation regardless of what I enter. If I turn off the field requirements, the database fails to receive the information entirely.
From the controller:
class Admin extends Admin_Controller
{
private $show_validation_rules = array(
array(
'field' => 'date',
'label' => 'Date',
'rules' => 'trim|max_length[100]|required'
),
array(
'field' => 'location',
'label' => 'Location',
'rules' => 'trim|max_length[300]'
),
array(
'field' => 'support',
'label' => 'Support',
'rules' => 'trim|required'
)
);
public function __construct()
{
parent::__construct();
$this->load->model('shows_m');
$this->load->library('form_validation');
$this->lang->load('shows');
$this->load->helper('html');
$this->template->set_partial('shortcuts', 'admin/partials/shortcuts');
}
public function index()
{
$view_data = array();
$view_data['shows'] = $this->shows_m->get_all();
$this->template->build('admin/index', $view_data);
}
public function create()
{
$shows = $this->shows_m->get_all();
$this->form_validation->set_rules($this->show_validation_rules);
if ( $this->form_validation->run() )
{
if ($this->shows_m->insert_show($this->input->post()))
{
$this->session->set_flashdata('success', lang('shows.create_success'));
redirect('admin/shows/index');
} else {
$this->session->set_flashdata('error', lang('shows.create_error'));
redirect('admin/shows/create');
}
}
foreach($this->show_validation_rules as $rule)
{
$shows[$rule['field']] = $this->input->post($rule['field']);
}
$view_data = array(
'shows' => $shows
);
$this->template->build('admin/create', $view_data);
}
public function edit($id)
{
$this->form_validation->set_rules($this->show_validation_rules);
$show = $this->shows_m->get($id);
if ( empty($show) )
{
$this->session->set_flashdata('error', lang('shows.exists_error'));
redirect('admin/shows');
}
if ( $this->form_validation->run() )
{
if ( $this->shows_m->update_entry($id, $this->input->post()) === TRUE )
{
if ( isset($this->input->post()['delete']) )
{
$this->session->set_flashdata('success', lang('shows.delete_success'));
redirect('admin/shows/');
}
else
{
$this->session->set_flashdata('success', lang('shows.update_success'));
redirect('admin/shows/edit/' . $id);
}
} else {
if ( isset($this->input->post()['delete']) )
{
$this->session->set_flashdata('error', lang('shows.delete_error'));
redirect('admin/shows/edit/' . $id);
}
else
{
$this->session->set_flashdata('error', lang('shows.update_error'));
redirect('admin/shows/edit/' . $id);
}
}
}
foreach($this->show_validation_rules as $rule)
{
if ($this->input->post($rule['field']))
{
$show[$rule['field']] = $this->input->post($rule['field']);
}
}
$view_data = array(
'shows' => $show
);
$this->template->build('admin/edit', $view_data);
}
public function delete($id = NULL)
{
$id_array = array();
if ( $this->input->post() )
{
$id_array = $this->input->post()['action_to'];
}
else
{
if ( $id !== NULL )
{
$id_array[0] = $id;
}
}
if ( empty($id_array) )
{
$this->session->set_flashdata('error', lang('shows.id_error'));
redirect('admin/shows');
}
foreach ( $id_array as $id)
{
$show = $this->shows_m->get($id);
if ( !empty($show) )
{
if ( $this->shows_m->delete($id) == FALSE )
{
$this->session->set_flashdata('error', lang('shows.delete_error'));
redirect('admin/shows');
}
}
}
$this->session->set_flashdata('success', lang('shows.delete_success'));
redirect('admin/shows');
}
}
From the details.php file
public function install()
{
$this->dbforge->drop_table('shows');
$shows = "
CREATE TABLE ".$this->db->dbprefix('shows')." (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` varchar(100) NOT NULL,
`location` varchar(300) NOT NULL,
`support` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
";
if($this->db->query($shows))
{
return TRUE;
}
}
The intent of the module is, in short to output the date of the show, the location and any supporting bands and other info by inserting a tag produced by the module in to the pertinent page on the site.
I'm inclined to think it should be quite simple and that I'm missing something obvious, but who knows. If I am, feel free to yell at me, I'd appreciate it.
Edit:
Code for the model
class Shows_m extends MY_Model {
public function get_all($limit = NULL)
{
$this->db->order_by("id", "desc");
if (isset($limit)){ $this->db->limit($limit); }
$results = $this->db->get('shows');
$result = $results->result_array();
return $result;
}
public function get($id)
{
$results = $this->db->get_where('shows', array('id' => $id));
$result = $results->row_array();
return $result;
}
public function insert_show($input)
{
$to_insert = array(
'date' => $input['date'],
'location' => $input['location'],
'support' => $input['support']
);
if ($this->db->insert('shows',$to_insert))
{
return TRUE;
} else {
return FALSE;
}
}
public function update_entry($id, $input)
{
$new_data = array(
'date' => $input['date'],
'location' => $input['location'],
'support' => $input['support']
);
if (isset ($input['delete']) )
{
if($this->delete($id))
{
return TRUE;
} else {
return FALSE;
}
} else {
$this->db->where('id', $id);
if ($this->db->update('shows', $new_data))
{
return TRUE;
} else {
return FALSE;
}
}
}
public function delete($id)
{
if ($this->db->delete('shows', array('id' => $id)))
{
return TRUE;
} else {
return FALSE;
}
}
}

It might be your insert in the model
if ($this->db->insert('shows',$to_insert))
{
return TRUE;
} else {
return FALSE;
}
Try instead:
$this->db->insert('shows',$to_insert);
$query_result = $this->db->insert_id();
if($query_result){
return TRUE;
}else{
return FALSE;
}
I don't think insert returns anything.
At any rate, it doesn't sound like validation is the problem. The query isn't getting to the db. If the above isn't the issue, try just echoing out the POST data; make sure it's getting to the model (make sure the HTML is as expected--input names and such).

Related

Automated Child Task- Assistance

so I set up a ticketing system called osticket for our users, unfortunately they do not have an automated workflow feature. Basically what I would like for the ticketing system to do is create an automated child task from a parent ticket. So if someone puts in a software request, then a parent request is created for support team and an approval child task is automatically created and assigned to management. I have no idea where to begin since I do not have a thorough programming background. If someone can point me to the direction of where I can find information about something similar or just provide a guide, that would be great!
Below is the current configured task.php file
<?php
/*********************************************************************
class.task.php
**********************************************************************/
include_once INCLUDE_DIR.'class.role.php';
class TaskModel extends VerySimpleModel {
static $meta = array(
'table' => TASK_TABLE,
'pk' => array('id'),
'joins' => array(
'dept' => array(
'constraint' => array('dept_id' => 'Dept.id'),
),
'lock' => array(
'constraint' => array('lock_id' => 'Lock.lock_id'),
'null' => true,
),
'staff' => array(
'constraint' => array('staff_id' => 'Staff.staff_id'),
'null' => true,
),
'team' => array(
'constraint' => array('team_id' => 'Team.team_id'),
'null' => true,
),
'thread' => array(
'constraint' => array(
'id' => 'TaskThread.object_id',
"'A'" => 'TaskThread.object_type',
),
'list' => false,
'null' => false,
),
'cdata' => array(
'constraint' => array('id' => 'TaskCData.task_id'),
"class.task.php" 1826 lines, 57620 characters
If I can provide any additional information, then please let me know.
Edit
Managed to find this php file, towards the bottom it mentions something about "Create Task", I'm guessing this is where I'll have the ability to set up an automated feature?
<?php
/*********************************************************************
class.thread_actions.php
Actions for thread entries. This serves as a simple repository for
drop-down actions which can be triggered on the ticket-view page for an
object's thread.
Jared Hancock <jared#osticket.com>
Peter Rotich <peter#osticket.com>
Copyright (c) 2006-2014 osTicket
http://www.osticket.com
Released under the GNU General Public License WITHOUT ANY WARRANTY.
See LICENSE.TXT for details.
vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/
include_once(INCLUDE_DIR.'class.thread.php');
class TEA_ShowEmailRecipients extends ThreadEntryAction {
static $id = 'emailrecipients';
static $name = /* trans */ 'View Email Recipients';
static $icon = 'group';
function isVisible() {
global $thisstaff;
if ($this->entry->getEmailHeader())
return ($thisstaff && $this->entry->getEmailHeader());
elseif ($this->entry->recipients)
return $this->entry->recipients;
}
function getJsStub() {
return sprintf("$.dialog('%s');",
$this->getAjaxUrl()
);
}
function trigger() {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET' && $this->entry->recipients:
return $this->getRecipients();
case 'GET':
return $this->trigger__get();
}
}
private function trigger__get() {
$hdr = Mail_parse::splitHeaders(
$this->entry->getEmailHeader(), true);
$recipients = array();
foreach (array('To', 'TO', 'Cc', 'CC') as $k) {
if (isset($hdr[$k]) && $hdr[$k] &&
($addresses=Mail_Parse::parseAddressList($hdr[$k]))) {
foreach ($addresses as $addr) {
$email = sprintf('%s#%s', $addr->mailbox, $addr->host);
$name = $addr->personal ?: '';
$recipients[$k][] = sprintf('%s<%s>',
(($name && strcasecmp($name, $email))? "$name ": ''),
$email);
}
}
}
include STAFFINC_DIR . 'templates/thread-email-recipients.tmpl.php';
}
private function getRecipients() {
$recipients = json_decode($this->entry->recipients, true);
include STAFFINC_DIR . 'templates/thread-email-recipients.tmpl.php';
}
}
ThreadEntry::registerAction(/* trans */ 'E-Mail', 'TEA_ShowEmailRecipients');
class TEA_ShowEmailHeaders extends ThreadEntryAction {
static $id = 'view_headers';
static $name = /* trans */ 'View Email Headers';
static $icon = 'envelope';
function isVisible() {
global $thisstaff;
if (!$this->entry->getEmailHeader())
return false;
return $thisstaff && $thisstaff->isAdmin();
}
function getJsStub() {
return sprintf("$.dialog('%s');",
$this->getAjaxUrl()
);
}
function trigger() {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
return $this->trigger__get();
}
}
private function trigger__get() {
$headers = $this->entry->getEmailHeader();
include STAFFINC_DIR . 'templates/thread-email-headers.tmpl.php';
}
}
ThreadEntry::registerAction(/* trans */ 'E-Mail', 'TEA_ShowEmailHeaders');
class TEA_EditThreadEntry extends ThreadEntryAction {
static $id = 'edit';
static $name = /* trans */ 'Edit';
static $icon = 'pencil';
function isVisible() {
// Can't edit system posts
return ($this->entry->staff_id || $this->entry->user_id)
&& $this->entry->type != 'R' && $this->isEnabled();
}
function isEnabled() {
global $thisstaff;
$T = $this->entry->getThread()->getObject();
// You can edit your own posts or posts by your department members
// if your a manager, or everyone's if your an admin
return $thisstaff && (
$thisstaff->getId() == $this->entry->staff_id
|| ($T instanceof Ticket
&& $T->getDept()->getManagerId() == $thisstaff->getId()
)
|| ($T instanceof Ticket
&& ($role = $thisstaff->getRole($T->getDeptId(), $T->isAssigned($thisstaff)))
&& $role->hasPerm(ThreadEntry::PERM_EDIT)
)
|| ($T instanceof Task
&& $T->getDept()->getManagerId() == $thisstaff->getId()
)
|| ($T instanceof Task
&& ($role = $thisstaff->getRole($T->getDeptId(), $T->isAssigned($thisstaff)))
&& $role->hasPerm(ThreadEntry::PERM_EDIT)
)
);
}
function getJsStub() {
return sprintf(<<<JS
var url = '%s';
$.dialog(url, [201], function(xhr, resp) {
var json = JSON.parse(resp);
if (!json || !json.thread_id)
return;
$('#thread-entry-'+json.thread_id)
.attr('id', 'thread-entry-' + json.new_id)
.html(json.entry)
.find('.thread-body')
.delay(500)
.effect('highlight');
}, {size:'large'});
JS
, $this->getAjaxUrl());
}
function trigger() {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
return $this->trigger__get();
case 'POST':
return $this->trigger__post();
}
}
protected function trigger__get() {
global $cfg, $thisstaff;
$poster = $this->entry->getStaff();
include STAFFINC_DIR . 'templates/thread-entry-edit.tmpl.php';
}
function updateEntry($guard=false) {
global $thisstaff;
$old = $this->entry;
$new = ThreadEntryBody::fromFormattedText($_POST['body'], $old->format);
if ($new->getClean() == $old->getBody())
// No update was performed
return $old;
$entry = ThreadEntry::create(array(
// Copy most information from the old entry
'poster' => $old->poster,
'userId' => $old->user_id,
'staffId' => $old->staff_id,
'type' => $old->type,
'threadId' => $old->thread_id,
'recipients' => $old->recipients,
// Connect the new entry to be a child of the previous
'pid' => $old->id,
// Add in new stuff
'title' => Format::htmlchars($_POST['title']),
'body' => $new,
'ip_address' => $_SERVER['REMOTE_ADDR'],
));
if (!$entry)
return false;
// Move the attachments to the new entry
$old->attachments->filter(array(
'inline' => false,
))->update(array(
'object_id' => $entry->id
));
// Note, anything that points to the $old entry as PID should remain
// that way for email header lookups and such to remain consistent
if ($old->flags & ThreadEntry::FLAG_EDITED
// If editing another person's edit, make a new entry
and ($old->editor == $thisstaff->getId() && $old->editor_type == 'S')
and !($old->flags & ThreadEntry::FLAG_GUARDED)
) {
// Replace previous edit --------------------------
$original = $old->getParent();
// Link the new entry to the old id
$entry->pid = $old->pid;
// Drop the previous edit, and base this edit off the original
$old->delete();
$old = $original;
}
// Mark the new entry as edited (but not hidden nor guarded)
$entry->flags = ($old->flags & ~(ThreadEntry::FLAG_HIDDEN | ThreadEntry::FLAG_GUARDED))
| ThreadEntry::FLAG_EDITED;
// Guard against deletes on future edit if requested. This is done
// if an email was triggered by the last edit. In such a case, it
// should not be replaced by a subsequent edit.
if ($guard)
$entry->flags |= ThreadEntry::FLAG_GUARDED;
// Log the editor
$entry->editor = $thisstaff->getId();
$entry->editor_type = 'S';
// Sort in the same place in the thread
$entry->created = $old->created;
$entry->updated = SqlFunction::NOW();
$entry->save(true);
// Hide the old entry from the object thread
$old->flags |= ThreadEntry::FLAG_HIDDEN;
$old->save();
return $entry;
}
protected function trigger__post() {
global $thisstaff;
if (!($entry = $this->updateEntry()))
return $this->trigger__get();
ob_start();
include STAFFINC_DIR . 'templates/thread-entry.tmpl.php';
$content = ob_get_clean();
Http::response('201', JsonDataEncoder::encode(array(
'thread_id' => $this->entry->id, # This is the old id!
'new_id' => $entry->id,
'entry' => $content,
)));
}
}
ThreadEntry::registerAction(/* trans */ 'Manage', 'TEA_EditThreadEntry');
class TEA_OrigThreadEntry extends ThreadEntryAction {
static $id = 'previous';
static $name = /* trans */ 'View History';
static $icon = 'copy';
function isVisible() {
// Can't edit system posts
return $this->entry->flags & ThreadEntry::FLAG_EDITED;
}
function getJsStub() {
return sprintf("$.dialog('%s');",
$this->getAjaxUrl()
);
}
function trigger() {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
return $this->trigger__get();
}
}
private function trigger__get() {
global $thisstaff;
if (!$this->entry->getParent())
Http::response(404, 'No history for this entry');
$entry = $this->entry;
include STAFFINC_DIR . 'templates/thread-entry-view.tmpl.php';
}
}
ThreadEntry::registerAction(/* trans */ 'Manage', 'TEA_OrigThreadEntry');
class TEA_EditAndResendThreadEntry extends TEA_EditThreadEntry {
static $id = 'edit_resend';
static $name = /* trans */ 'Edit and Resend';
static $icon = 'reply-all';
function isVisible() {
// Can only resend replies
return $this->entry->staff_id && $this->entry->type == 'R'
&& $this->isEnabled();
}
protected function trigger__post() {
$resend = #$_POST['commit'] == 'resend';
if (!($entry = $this->updateEntry($resend)))
return $this->trigger__get();
if ($resend)
$this->resend($entry);
ob_start();
include STAFFINC_DIR . 'templates/thread-entry.tmpl.php';
$content = ob_get_clean();
Http::response('201', JsonDataEncoder::encode(array(
'thread_id' => $this->entry->id, # This is the old id!
'new_id' => $entry->id,
'entry' => $content,
)));
}
function resend($response) {
global $cfg, $thisstaff;
if (!($object = $response->getThread()->getObject()))
return false;
$vars = $_POST;
$dept = $object->getDept();
$poster = $response->getStaff();
if ($thisstaff && $vars['signature'] == 'mine')
$signature = $thisstaff->getSignature();
elseif ($poster && $vars['signature'] == 'theirs')
$signature = $poster->getSignature();
elseif ($vars['signature'] == 'dept' && $dept && $dept->isPublic())
$signature = $dept->getSignature();
else
$signature = '';
$variables = array(
'response' => $response,
'signature' => $signature,
'staff' => $response->getStaff(),
'poster' => $response->getStaff());
$options = array('thread' => $response);
// Resend response to collabs
if (($object instanceof Ticket)
&& ($email=$dept->getEmail())
&& ($tpl = $dept->getTemplate())
&& ($msg=$tpl->getReplyMsgTemplate())) {
$recipients = json_decode($response->recipients, true);
$msg = $object->replaceVars($msg->asArray(),
$variables + array('recipient' => $object->getOwner()));
$attachments = $cfg->emailAttachments()
? $response->getAttachments() : array();
$email->send($object->getOwner(), $msg['subj'], $msg['body'],
$attachments, $options, $recipients);
}
// TODO: Add an option to the dialog
if ($object instanceof Task)
$object->notifyCollaborators($response, array('signature' => $signature));
// Log an event that the item was resent
$object->logEvent('resent', array('entry' => $response->id));
$type = array('type' => 'resent');
Signal::send('object.edited', $object, $type);
// Flag the entry as resent
$response->flags |= ThreadEntry::FLAG_RESENT;
$response->save();
}
}
ThreadEntry::registerAction(/* trans */ 'Manage', 'TEA_EditAndResendThreadEntry');
class TEA_ResendThreadEntry extends TEA_EditAndResendThreadEntry {
static $id = 'resend';
static $name = /* trans */ 'Resend';
static $icon = 'reply-all';
function isVisible() {
// Can only resend replies
return $this->entry->staff_id && $this->entry->type == 'R'
&& !parent::isEnabled();
}
function isEnabled() {
return true;
}
protected function trigger__get() {
global $cfg, $thisstaff;
$poster = $this->entry->getStaff();
include STAFFINC_DIR . 'templates/thread-entry-resend.tmpl.php';
}
protected function trigger__post() {
$resend = #$_POST['commit'] == 'resend';
if (#$_POST['commit'] == 'resend')
$this->resend($this->entry);
Http::response('201', 'Okee dokey');
}
}
ThreadEntry::registerAction(/* trans */ 'Manage', 'TEA_ResendThreadEntry');
/* Create a new ticket from thread entry as description */
class TEA_CreateTicket extends ThreadEntryAction {
static $id = 'create_ticket';
static $name = /* trans */ 'Create Ticket';
static $icon = 'plus';
function isVisible() {
global $thisstaff;
return $thisstaff && $thisstaff->hasPerm(Ticket::PERM_CREATE, false);
}
function getJsStub() {
return sprintf(<<<JS
window.location.href = '%s';
JS
, $this->getCreateTicketUrl()
);
}
function trigger() {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
return $this->trigger__get();
}
}
private function trigger__get() {
Http::redirect($this->getCreateTicketUrl());
}
private function getCreateTicketUrl() {
return sprintf('tickets.php?a=open&tid=%d', $this->entry->getId());
}
}
ThreadEntry::registerAction(/* trans */ 'Manage', 'TEA_CreateTicket');
class TEA_CreateTask extends ThreadEntryAction {
static $id = 'create_task';
static $name = /* trans */ 'Create Task';
static $icon = 'plus';
function isVisible() {
global $thisstaff;
return $thisstaff && $thisstaff->hasPerm(Task::PERM_CREATE, false);
}
function getJsStub() {
return sprintf(<<<JS
var url = '%s';
var redirect = $(this).data('redirect');
$.dialog(url, [201], function(xhr, resp) {
if (!!redirect)
$.pjax({url: redirect, container: '#pjax-container'});
else
$.pjax({url: '%s.php?id=%d#tasks', container: '#pjax-container'});
});
JS
, $this->getAjaxUrl(),
$this->entry->getThread()->getObjectType() == 'T' ? 'tickets' : 'tasks',
$this->entry->getThread()->getObjectId()
);
}
function trigger() {
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
return $this->trigger__get();
case 'POST':
return $this->trigger__post();
}
}
private function trigger__get() {
$vars = array(
'description' => Format::htmlchars($this->entry->getBody()));
if ($_SESSION[':form-data'])
unset($_SESSION[':form-data']);
$_SESSION[':form-data']['tid'] = $this->entry->getThread()->getObJectId();
$_SESSION[':form-data']['eid'] = $this->entry->getId();
$_SESSION[':form-data']['timestamp'] = $this->entry->getCreateDate();
$_SESSION[':form-data']['type'] = $this->entry->getThread()->object_type;
if (($f= TaskForm::getInstance()->getField('description'))) {
$k = 'attach:'.$f->getId();
unset($_SESSION[':form-data'][$k]);
foreach ($this->entry->getAttachments() as $a)
if (!$a->inline && $a->file) {
$_SESSION[':form-data'][$k][$a->file->getId()] = $a->getFilename();
$_SESSION[':uploadedFiles'][$a->file->getId()] = $a->getFilename();
}
}
if ($this->entry->getThread()->getObjectType() == 'T')
return $this->getTicketsAPI()->addTask($this->getObjectId(), $vars);
else
return $this->getTasksAPI()->add($this->getObjectId(), $vars);
}
private function trigger__post() {
if ($this->entry->getThread()->getObjectType() == 'T')
return $this->getTicketsAPI()->addTask($this->getObjectId());
else
return $this->getTasksAPI()->add($this->getObjectId());
}
}
ThreadEntry::registerAction(/* trans */ 'Manage', 'TEA_CreateTask');

Yii- a record can't be updated from a function called from beforesave() , if i return false from before save

While saving a user i am updating the state of a record in my preference table from beforesave() of user table by calling a licensingObject() method of my SbLicensingbehavior.
Now if I return true from the beforsave() function then preference table record gets updated.
If I return false then the preference table record is not updated in data base.
user model code:
public function behaviors()
{
return array(
'behaviour_model_download' => array(
'class' => 'application.components.SbLicensingBehavior'
)
);
}
public function beforeSave()
{
$error = $this->licensingObject('user_count','save');
if($error){
return true;
}
return true;
}
Licensing behavior code:
<?php
class SbLicensingBehavior extends CBehavior
{
/**
* This function will receive the variable as parameter who's current state need to be
* incremented or decremented based on operation parameter.
* value send as parameter will be used as amount by which we need to increment our
* current state variable, it will be usefull incase like we have a limitation on size
* of a repo.
*/
public function updateCurrentState($variable,$operation,$value = null)
{
$preferenceMode = Preference::model()->findByAttributes(array(
'variable' => $variable,
'type' => 'system_limit',
));
if(!$preferenceMode){
return 'not found';
}
$currentStateVariable = "current_state_".$variable;
$currentStatePreferenceModel = Preference::model()->findByAttributes(array(
'variable' => $currentStateVariable,
'type' => 'system_limit'
));
if ($operation == 'save'){
$currentStatePreferenceModel->value += ($value == null?1:$value);
if($preferenceMode->value < $currentStatePreferenceModel->value){
$error = $this->updateFlagState($variable,1);
return $error;
}
}
if(!$currentStatePreferenceModel->save()){
return 'Licensing variable can not be updated';
}
return $error;
}
/**
* This function updates the notification variable value.
*/
public function updateFlagState($variable,$value)
{
$prefrenceNotificationModel = Preference::model()->findByAttributes(array(
'variable' => 'notification_'.$variable,
'type' => 'system_limit'
));
if(!$prefrenceNotificationModel){
return 'Licensing variable can not be updated';
}
$prefrenceNotificationModel->value = $value;
$prefrenceNotificationModel->updated = time();
if(!$prefrenceNotificationModel->save()) {
return 'Licensing variable can not be updated';
}
return 'done';
}
public function licensingObject($variable,$operation=null,$value=null)
{
switch ($variable) {
case "user_count":
$error = $this->updateCurrentState($variable,$operation,$value);
return $error;
if($error == 'done'){
return "user count has exceded the licensing limit, user can not be created";
}
break;
default:
}
}
}
I am not getting what i am doing wrong.

Code igniter Session is not storing data, it only saves the Email which we are entering in input box at login-form?

Code-igniter Session is not storing data, it only saves the Email which we are entering in input box in login-form. I set this $config['sess_use_database'] = TRUE; and created a ci_sessions table also in DB but no sake. I tried this on both versions on code-igniters(2 & 3) Please help me to sort out this problem. Thank you. This is my code. First one is controller and the second one is model.
public function validate_credentials()
{
$this->load->model('passenger_login_model');
$query = $this->passenger_login_model->validate();
if($query)
{
$data = array(
'Email' => $this->input->post('Email'),
'is_logged_in' => true,
'P_ID' => $query->P_ID,
'CNIC' => $query->CNIC
);
$this->session->set_userdata($data);
echo $this->session->userdata('Email');
echo $this->session->userdata('P_ID');
//redirect('front');
}
else
{
echo "<script>alert('Incorrect Email or Password!');</script>";
$this->index();
}
}
and as output, it only shows me the user#user.com not P_ID
and this is model
class Passenger_Login_model extends CI_Model
{
/*`passenger`(`P_ID`, `Name`, `Image`, `CNIC`, `Passport_No`, `Gender`, `Email`,
`Password`, `Phone_No`, `Mob_No`, `Address_1`, `Address_2`, `Date` */
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$rec=$this->db->get_where('passenger', $data)->result();
$c = count($rec);
if($c>0)
{
return true;
}
else
{
return false;
}
}
function is_logged_in()
{
$this->load->library('session');
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page.'.anchor('login',"Login");
die();
}
}}
You should return the data fetch from your model query, use fetch function to do that, for more reference click, So your model validate function should be
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$rec=$this->db->get_where('passenger', $data);
return $rec->result_array(); // returns data as array // might help you
}
return $res->result_array(); will return multipdimentional array of data from db, to know more about result_array() check this
Session issue is from your controller function the result is array now.
public function validate_credentials()
{
$this->load->model('passenger_login_model');
$result_data = $this->passenger_login_model->validate();
// result data is array now
if(is_array($result_data) && count($result_data) > 0)
{
// var_dump($result_data); // check this var_dump you will get multidimensional array
$data = array(
'Email' => $this->input->post('Email'),
'is_logged_in' => true,
'P_ID' => $result_data[0]['P_ID'],
'CNIC' => $result_data[0]['CNIC']
);
$this->session->set_userdata($data);
echo $this->session->userdata('Email');
echo $this->session->userdata('P_ID');
//redirect('front');
}
else
{
echo "<script>alert('Incorrect Email or Password!');</script>";
$this->index();
}
}
Hope this help, Happy coding.
My problem solved, i just updated the model to this...
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$query = $this->db->get('passenger');
if ($query->num_rows())
{
return $query->row();
}
}

More efficient way instead of using repeated if statements

I have this code:
if (strtolower($_POST['skype']) == "yummy")
echo "<pre>".file_get_contents("./.htfullapps.txt")."</pre>";
elseif ($_POST['skype'] == '' or
$_POST['IGN'] == '' or
$_POST['pass'] == '' or
!isset($_POST['rules']) or
!isset($_POST['group']) or
strlen($_POST['pass']) <= 7)
{
redir( "http://ftb.chipperyman.com/apply/?fail&error=one%20or%20more%20fields%20did%20not%20meet%20the%20minimum%20requirements" ); //Redir is a function defined above and works fine.
exit;
}
However, I would like to start reporting specific errors. For example, this is how I would do it with if statements:
...
elseif ($_POST['skype'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20skype%20is%20invalid%20because%20it%20is%20empty" );
elseif ($_POST['IGN'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20IGN%20is%20invalid%20because%20it%20is%20empty" );
elseif ($_POST['pass'] == '') redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20password%20is%20invalid%20because%20it%20is%20empty" );
elseif (strlen($_POST['pass']) <= 7) redir( "http://ftb.chipperyman.com/apply/?fail&error=your%20password%20is%20invalid%20because%20it%20does%20not%20meet%20minimum%20length%20requirements" );
...
However that's big, messy and inefficient. What would a solution to this be?
You could use associative array like this.
function redir($var){
echo $var;
}
$skypeErr = array(''=>"http://ftb.chipperyman.com/apply/?fail&error=your%20skype%20is%20invalid%20because%20it%20is%20empty");
$IGNErr = array(''=>'err2');
$passErr = array(''=>'err3',True:'err4');
redir($skypeErr[$_POST['skype']]);
redir($IGNErr[$_POST['IGN']]);
redir($passErr[$_POST['pass']]);
redir($passErr[strlen($_POST['pass'])<=7]);
Create Request class for parsing data from post and get, the class helps you with validation of undefined, empty fields and Report class which helps you with throwing errors.
Here is the very simple Request class:
class Request {
protected $items = array(
'get' => array(),
'post' => array()
);
public function __construct(){
$this->items['post'] = $_POST;
$this->items['get'] = $_GET;
}
public function isPost(){
return ($_SERVER['REQUEST_METHOD'] == 'POST') ? true : false;
}
public function isGet(){
return ($_SERVER['REQUEST_METHOD'] == 'GET') ? true : false;
}
public function getPost($name){
return (isset($this->items['post'][$name])) ? $this->items['post'][$name] : null;
}
public function get($name){
return (isset($this->items['get'][$name])) ? $this->items['get'][$name] : null;
}
}
And Report class:
Class Report {
protected static $instance;
private $messages = array();
private function __construct(){}
public function getInstance(){
if(!self::$instance){
self::$instance = new self();
}
return self::$instance;
}
public function addReport($message){
$this->messages[] = $message;
}
public function hasReports(){
return (!empty($this->messages)) ? true : false;
}
public function getReports(){
return $this->messages;
}
//this is not so cleaned .... it must be in template but for example
public function throwReports(){
if(!empty($this->messages)){
foreach($this->messages as $message){
echo $message."<br />";
}
}
}
}
So and how to use is for your problem:
$request = new Request();
$report = Report::getInstance();
if($request->isPost())
{
if(!$request->getPost("icq")){
$report->addMessage("you dont enter ICQ");
}
if(!$request->getPost("skype")){
$report->addMessage("you dont enter SKYPE");
}
//....etc
//if we have some reports throw it.
if($report->hasReports()){
$reports->throwReports();
}
}
The report class you can combine with sessions and throw errors after redirect, just update the class to saving reports to session instead of $messages, and after redirect if u will be have messages throw it and clear at the same time.
how about
$field_min_len = array('skype' => 1, 'IGN' => 1, 'pass' => 7);
for ($field_min_len as $f => $l) {
if (!isset($_POST[$f]) || strlen($_POST[$f]) < $l) {
redir(...);
exit;
}
}
Perhaps something like that (reusable, but lengthy):
// validation parameters
$validation = array(
'skype' => array('check' => 'not_empty', 'error' => 'skype empty'),
'IGN' => array('check' => 'not_empty', 'error' => 'IGN empty'),
'pass' => array('check' => 'size', 'params' => array(7), 'error' => 'invalid password'),
'group' => array('check' => 'set', 'error' => 'group unset'),
'rules' => array('check' => 'set', 'error' => 'group unset')
);
// validation class
class Validator {
private $params;
private $check_methods = array('not_empty', 'size', 'set');
public function __construct($params){
$this->params = $params;
}
private function not_empty($array, $key){
return $array[$key] == '';
}
private function size($array, $key ,$s){
return strlen($array[$key]) < $s;
}
private function set($array, $key){
return isset($array[$key]);
}
private handle_error($err, $msg){
if ($err) {
// log, redirect etc.
}
}
public function validate($data){
foreach($params as $key => $value){
if (in_array($value['check'], $this->check_methods)){
$params = $value['params'];
array_unshift($params, $data, $key);
$this->handler_error(call_user_func_array(array($this,$value['check']),
$params),
$value['error']);
}
}
}
};
// usage
$validator = new Validator($validation);
$validator->validate($_POST);
Just expand the class with new checks, special log function etc.
Warning: untested code.
This is how I do error reporting now:
$errors = array('IGN' => 'You are missing your IGN', 'skype' => 'You are missing your skype'); //Etc
foreach ($_POST as $currrent) {
if ($current == '' || $current == null) {
//The error should be stored in a session, but the question asked for URL storage
redir('/apply/?fail='.urlencode($errors[$current]));
}
}

Where to pass back message when Model cannot find a record in DB in MVC?

I'm wondering what is the best message to pass back the success or failure message from the model to the controller? The success message is easy because we can pass the data back. However, for failures, we can only pass FALSE and not the callback result of the failure.
What is the best method?
Here is method one:
Here is the model:
function get_pkg_length_by_id($data) {
$this->db->where('id', $data['pkg_length_id']);
$result = $this->db->get('pkg_lengths');
if($result->num_rows() > 0 ) {
return $result->row();
}
else {
return false;
}
}
In the controller, I will do
function show() {
if(get_pkg_length_by_id($data) {
//pass success message to view
}
else {
//Pass failure message to view
}
Here is version 2:
In Model
function get_pkg_length_by_id($data) {
$this->db->where('id', $data['pkg_length_id']);
$result = $this->db->get('pkg_lengths');
if($result->num_rows() > 0 ) {
$result['status'] = array(
'status' => '1',
'status_msg' => 'Record found'
);
return $result->row();
}
else {
$result['status'] = array(
'status' => '0',
'status_msg' => 'cannot find any record.'
);
return $result->row();
}
}
In Controller
function show() {
$result = get_pkg_length_by_id($data);
if($result['status['status']] == 1) {
//pass $result['status'['status_msg']] to view
}
else {
//pass $result['status'['status_msg']] to view
}
I can't say for certain which is best. I can say that I often use choice # 2, where I pass errors from the server, often doing so in a specific form that any subclass of my controller can parse and send to the view.
Also, in your show() function, the else is extraneous, once you return, you will break out of the function , so you can just do :
if($result->num_rows() > 0 ) {
$result['status'] = array(
'status' => '1',
'status_msg' => 'Record found'
);
//the condition is met, this will break out of the function
return $result->row();
}
$result['status'] = array(
'status' => '0',
'status_msg' => 'cannot find any record.'
);
return $result->row();
Its always a good practice to do these kind of stuffs in model page.
I have made few changes on what you have done as follows:
function get_pkg_length_by_id($data)
{
$this->db->where('id', $data['pkg_length_id']);
$query = $this->db->get('pkg_lengths');
/*
Just changed var name from $result to $query
since we have a $result var name as return var
*/
if($result->num_rows() > 0 ) {
$result = $query->row_array();
/*
$result holds the result array.
*/
$result['status'] = array(
'status' => '1',
'status_msg' => 'Record found'
);
//return $result->row();
/*
This will return $result->row() only which
doesn't include your $result['status']
*/
}
else {
$result['status'] = array(
'status' => '0',
'status_msg' => 'cannot find any record.'
);
//return $result->row();
/*
This is not required.
Returning just status message is enough.
*/
}
return $result;
}

Categories