More efficient way instead of using repeated if statements - php

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]));
}
}

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');

What would make a good PHP validaton class?

I would like to read about your opinions on what the best way to create a validation class is.
Below i pasted in my version, it's not really extensive yet, but is it the right approach so far?
I want every element which could appear in a form and which should be validated to have its own properties, in terms of string length for strings or file size for images or files in general (see below).
Also, is it better to declare these rules as nested arrays or should I put them in one big string, which would then be split up during the process?
mb_internal_encoding("UTF-8");
class Phrase {
//creates parts of sentences, not important
static function additive(array $limbs) {
return implode(' and ', array_filter([implode(', ', array_slice($limbs, 0, -1)), end($limbs)], 'strlen'));
}
}
class Text {
static function validate($item) {
$err = array();
$value = $_POST[$item] ?? $_GET[$item];
$criteria = FormProcess::$criteria[$item];
foreach($criteria as $critKey => $critVal) {
if($critKey === 'required' && empty($value)) {
$err[] = "is required";
} else if(!empty($value)) {
switch($critKey) {
case 'length':
if(is_array($critVal)) {
//min and max set
if(mb_strlen($value) < $critVal[0] || mb_strlen($value) > $critVal[1]) {
$this->err[] = "must contain between {$critVal[0]} and {$critVal[1]} characters";
}
} else {
//max set only
if(mb_strlen($value) > $critVal) {
$err[] = "must contain a maximum of $critVal characters";
}
}
break;
case 'pattern':
if(!preg_match($critVal[0], $value)) {
$err[] = "may consist of {$critVal[1]} only";
}
break;
case 'function':
$result = static::$critVal($value);
if($result) {
$err[] = $result;
}
break;
}
}
}
if(!empty($err)) {
return "{$criteria['name']} " . Phrase::additive($err) . "!";
}
return false;
}
private static function email($email) {
//checks if given string is a valid email address
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return "is invalid";
}
return false;
}
}
class File {
//checks for aspects like filesize...
static function validate() {
//...
}
}
class Image extends File {
static function validate() {
parent::validate(); //perform general file checks first
//...checks for images specifically
}
}
class Video extends File {
static function validate() {
parent::validate(); //perform general file checks first
//...checks for videos specifically
}
}
class FormProcess {
public $errors;
//declare, what kind of requirements the items must meet
static $criteria = array(
'email' => array(
'type' => 'Text',
'required' => true,
'name' => 'Email',
'length' => 48,
'function' => 'email',
),
'username' => array(
'type' => 'Text',
'required' => true,
'name' => 'Username',
'length' => [4, 24],
'pattern' => ['/^[-\w]+$/', "alphanumeric characters, underscores and hyphens"],
),
'password' => array(
'type' => 'Text',
'required' => true,
'name' => 'Password',
'length' => [6, 100],
'pattern' => ['/^[\S]+$/', "non-whitespace characters"],
),
);
//runs the validate function on each item while storing occuring errors
function __construct(array $items) {
foreach($items as $item) {
$class = self::$criteria[$item]['type'];
$result = $class::validate($item);
if($result) {
$this->errors[] = $result;
}
}
}
}
Then all you had to do, is, naming all expected items (by their html 'name' attribute in the form) in an array and pass it through the constructor, which would then run the appropriate validation function on each item.
$expected = ['username', 'password'];
$signup = new FormProcess($expected);
if($signup->errors) {
?>
There was something wrong with your request:
<ul>
<?php foreach($signup->errors as $error) { ?>
<li><?= $error ?></li>
<?php } ?>
</ul>
<?php
}
I hope to learn from mistakes and make improvements to the code from you where they are needed.
Thank you in advance!

Var_dump changes "something" in my variable?

So I am currently coding a user registration in PHP 5.6.10 and just discovered something weird: The function Token::check(Input::get('token')) returns a boolean. If it returns true, the if-statement is getting executed. Works fine so far, however when I var_dump it previous to the if-statement, the if-statement is not being executed.
Is there any explanation for this behaviour?
var_dump(Token::check(Input::get('token')));
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
echo "Loop.";
$validate = new Validate();
$validation = $validate->check($_POST, array(
'first_name' => array(
'required' => true,
'min' => 1,
'max' => 50
)
));
if($validation->passed()) {
echo "Die Eingaben waren korrekt.";
} else {
foreach ($validation->errors() as $error) {
echo $error,"<br>";
}
echo "<br>";
}
}
}
(I hope I didn't make a typo when shortening the code)
Here is the check()-function as requested:
public static function check($token) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)) {
Session::delete($tokenName);
return true;
}
return false;
}
Based on the code from the check method:
public static function check($token) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)){
Session::delete($tokenName);
return true;
}
return false;
}
In the first time that you call:
var_dump(Token::check(Input::get('token')));
it deletes the token from the session, preventing the condition:
if(Token::check(Input::get('token'))) to be met.
Maybe you can put an extra param in the check function just to help you debug and not delete the token:
public static function check($token, $test = false) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)){
if (!$test) {
Session::delete($tokenName);
}
return true;
}
return false;
}

How to use REST with MVC when there is no Database?

I have two servers, the first works using REST and other Webs pages that are built using MVC.
I usually always run REST commands in the Controller layer, however I am with a doubt, assuming that my project (using MVC) does not use database and I'm using Controllers only to send commands to the webservice to send and receive information.
The REST this case would be the like Model?
In this case I should call the Rest within the Controllers and not create Models. eg .:
public function createProductAction() {
$rest = Rest('ws.example.com', 'PUT /items/', array(
'price' => $price,
'description' => $descricao
));
if ($response->status === 200) {
View::show('success.tpl');
} else {
View::show('error.tpl', $rest->error());
}
}
public function viewProductAction() {
$rest = Rest('ws.example.com', 'GET /items/{id}', array(
'id' => $_GET['id']
));
$response = json_decode($rest->getRespose());
if ($response->status() === 200) {
View::show('product.tpl', $response);
} else {
View::show('error.tpl', $rest->error());
}
}
or
I would have to create Models to make the calls to REST?
For example:
class ProductsModel
{
public function putItem($preco, $descricao)
{
$rest = Rest('ws.example.com', 'PUT /items/', array(
'price' => $price,
'description' => $descricao
));
//If status=200 new product is added
return $response->status() === 200;
}
public function deleteItem($id)
{
$rest = Rest('ws.example.com', 'DELETE /items/{id}', array(
'id' => $id
));
//If status=200 product is deleted
return $rest->status() === 200;
}
public function getItem($id)
{
$rest = Rest('ws.example.com', 'GET /items/{id}', array(
'id' => $id
));
if ($rest->status() === 200) {
//If status=200 return data
return json_decode($rest->getRespose());
}
return NULL;
}
}
How should I proceed?

PyroCMS/Codeigniter database issue

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).

Categories