validate() public method

Perform data validation against the provided ruleset.
public validate ( array $input, array $ruleset ) : mixed
$input array
$ruleset array
return mixed
コード例 #1
0
/**
 * Submit Registration
 *
 * Controller for the Authenticate module.
 *
 * @author      Goran Halusa <*****@*****.**>
 * @since       0.1.0
 * @param       array  $route  The route data array
 */
function submit_registration(\Slim\Route $route)
{
    $app = \Slim\Slim::getInstance();
    $final_global_template_vars = $app->config('final_global_template_vars');
    require_once $final_global_template_vars["default_module_list"]["user_account"]["absolute_path_to_this_module"] . "/models/user_account.class.php";
    require_once $final_global_template_vars["default_module_list"]["group"]["absolute_path_to_this_module"] . "/models/group.class.php";
    require_once $_SERVER["PATH_TO_VENDOR"] . "wixel/gump/gump.class.php";
    $env = $app->environment();
    $db_conn = new \PHPSkeleton\models\db($final_global_template_vars["db_connection"]);
    $db_resource = $db_conn->get_resource();
    $user_account = new \PHPSkeleton\UserAccount($db_resource, $final_global_template_vars["session_key"]);
    $gump = new GUMP();
    $errors = array();
    $user_account_id = $_SESSION[$final_global_template_vars["session_key"]]["user_account_id"];
    // Check to see if this user is already assigned to a group - they may have been added by another administrator.
    $current_groups = $user_account->get_user_account_groups($user_account_id);
    if (!$current_groups) {
        // Validate the group that they submitted.
        $rules = array("group" => "required|integer");
        $validated = $gump->validate($app->request()->post(), $rules);
        if ($validated !== true) {
            $errors = \phpskeleton\models\utility::gump_parse_errors($validated);
        }
    }
    // Validate the acceptable use policy.
    $rules = array("acceptable_use_policy" => "required|integer");
    $validated = $gump->validate($app->request()->post(), $rules);
    if ($validated !== true) {
        $errors = array_merge($errors, \phpskeleton\models\utility::gump_parse_errors($validated));
    }
    if (!$errors) {
        // Create the actual user account.
        $user_data = array("group_data" => '{"0":{"group_id":"' . $app->request()->post("group") . '","roles":["' . $final_global_template_vars["default_role_id"] . '"]}}');
        $update_groups = !empty($current_groups) ? false : true;
        // Get the existing user account info.
        $existing_user_data = $user_account->get_user_account_info($user_account_id);
        // Merge the data.
        $user_data = array_merge($user_data, $existing_user_data);
        // Insert/update
        $user_account->insert_update_user_account($user_data, $user_account_id, $update_groups);
        // Update acceptable use policy.
        $user_account->update_acceptable_use_policy($user_account_id, 1);
        $landing_page = $final_global_template_vars['landing_page'];
        if (isset($_COOKIE[$final_global_template_vars["redirect_cookie_key"]]) && $_COOKIE[$final_global_template_vars["redirect_cookie_key"]]) {
            $landing_page = $_COOKIE[$final_global_template_vars["redirect_cookie_key"]];
            setcookie($final_global_template_vars["redirect_cookie_key"], "", time() - 3600, "/");
            unset($_COOKIE[$final_global_template_vars["redirect_cookie_key"]]);
        }
        // Add role list to session.
        $_SESSION[$final_global_template_vars["session_key"]][$final_global_template_vars["current_user_roles_session_key"]] = \phpskeleton\models\utility::array_flatten($user_account->get_user_roles_list($user_account_id));
        // Add group to session.
        $_SESSION[$final_global_template_vars["session_key"]]["associated_groups"] = array((int) $app->request()->post("group"));
        $app->redirect($landing_page);
    } else {
        $env["default_validation_errors"] = $errors;
    }
}
コード例 #2
0
/**
 * Insert/Update Group
 *
 * Controller for the Group module.
 *
 * @param \Slim\Route $route The route data array
 * @return void
 */
function insert_update_group(\Slim\Route $route)
{
    $app = \Slim\Slim::getInstance();
    $final_global_template_vars = $app->config('final_global_template_vars');
    require_once $final_global_template_vars["absolute_path_to_this_module"] . "/models/group.class.php";
    require_once $_SERVER["PATH_TO_VENDOR"] . "wixel/gump/gump.class.php";
    // URL parameters matched in the route.
    $params = $route->getParams();
    $group_id = isset($params["group_id"]) ? $params["group_id"] : false;
    $db_conn = new \PHPSkeleton\models\db($final_global_template_vars["db_connection"]);
    $db_resource = $db_conn->get_resource();
    $group = new \PHPSkeleton\Group($db_resource, $final_global_template_vars["session_key"]);
    $gump = new GUMP();
    $rules = array("name" => "required", "abbreviation" => "required|alpha_numeric", "state" => "alpha_numeric", "zip" => "numeric|exact_len,5", "group_parent" => "numeric");
    $validated = $gump->validate($app->request()->post(), $rules);
    $errors = array();
    if ($validated !== true) {
        $errors = \phpskeleton\models\utility::gump_parse_errors($validated);
    }
    if (!$errors) {
        $group->insert_update_group($app->request()->post(), $group_id);
        // If group_id is true, then the group was modified. Otherwise, it was created.
        if ($group_id) {
            $app->flash('message', 'The group has been successfully modified.');
        } else {
            $app->flash('message', 'New group has been successfully created.');
        }
        $app->redirect($final_global_template_vars["path_to_this_module"]);
    } else {
        $env = $app->environment();
        $env["default_validation_errors"] = $errors;
    }
}
コード例 #3
0
/**
 * Authenticate User
 *
 * Controller for the Authenticate module.
 *
 * @author      Goran Halusa <*****@*****.**>
 * @since       0.1.0
 */
function authenticate_user()
{
    $app = \Slim\Slim::getInstance();
    $final_global_template_vars = $app->config('final_global_template_vars');
    require_once $_SERVER["PATH_TO_VENDOR"] . "wixel/gump/gump.class.php";
    require_once $final_global_template_vars["absolute_path_to_this_module"] . "/models/authenticate.class.php";
    $db_conn = new \PHPSkeleton\models\db($final_global_template_vars["db_connection"]);
    $db_resource = $db_conn->get_resource();
    $authenticate = new \PHPSkeleton\Authenticate($db_resource, $final_global_template_vars["session_key"]);
    $gump = new GUMP();
    $rules = array("user_account_email" => "valid_email", "password" => "min_len,6");
    $validated = $gump->validate($app->request()->post(), $rules);
    if ($validated === true) {
        $validated = array(array("field" => "user_account_email", "value" => "", "rule" => ""));
        // Query the database for the user_account_email and password.
        try {
            $local_validated = $authenticate->authenticate_local($app->request()->post('user_account_email'), $app->request()->post('password'));
        } catch (Exception $e) {
            $local_validated = false;
        }
        if ($local_validated) {
            $validated = true;
            session_regenerate_id();
            foreach ($final_global_template_vars["auth_session_keys"] as $single_key) {
                $_SESSION[$final_global_template_vars["session_key"]][$single_key] = $local_validated[$single_key];
            }
            // Log the successful login attempt.
            $authenticate->log_login_attempt($local_validated["user_account_email"], "succeeded");
        }
    }
    if ($validated === true) {
        // The show_login_form.php redirects to the redirect cookie key instead of doing it here.
    } else {
        // Log the failed login attempt.
        $authenticate->log_login_attempt($app->request()->post("user_account_email"), "failed");
        $env = $app->environment();
        $env["default_validation_errors"] = $validated;
    }
}
コード例 #4
0
#!/usr/bin/php -q
<?php 
require "../gump.class.php";
// Add the custom validator
GUMP::add_validator("is_object", function ($field, $input, $param = NULL) {
    return is_object($input[$field]);
});
// Generic test data
$input_data = array('not_object' => 5, 'valid_object' => new stdClass());
$rules = array('not_object' => "required|is_object", 'valid_object' => "required|is_object");
// METHOD 1 (Long):
$validator = new GUMP();
$validated = $validator->validate($input_data, $rules);
if ($validated === true) {
    echo "Validation passed!";
} else {
    echo $validator->get_readable_errors(true);
}
// METHOD 2 (Short):
$is_valid = GUMP::is_valid($input_data, $rules);
if ($is_valid === true) {
    echo "Validation passed!";
} else {
    print_r($is_valid);
}
コード例 #5
0
 public static function process_submission()
 {
     require_once 'gump.class.php';
     $gump = new GUMP();
     $_POST = $gump->sanitize($_POST);
     global $a;
     $a = AC::load_current_activity();
     if (isset($_POST['waitlist-submit'])) {
         AC::generate_waitlist_fields();
         require_once 'wp-content/themes/vetri-master/lib/ReCaptcha/autoload.php';
         $recaptcha = new \ReCaptcha\ReCaptcha('6LendQoTAAAAABQzKPl_3sLPQQkTKMW4DBnIP37R', new \ReCaptcha\RequestMethod\Curl());
         $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
         if (!$resp->isSuccess()) {
             AC::$errors['recaptcha'] = 'Please verify using the ReCaptcha widget';
             return false;
         }
     } else {
         if (AC::is_active_timer_expired()) {
             AC::$errors[] = 'Your timer has expired. Please start over.';
             AC::reset_all();
             return false;
         }
         AC::generate_fields();
         $step = $_POST['step'];
         foreach ($_POST['form'] as $k => $v) {
             $_SESSION['edgimo-reservation-form']['step-' . $step][$k] = $v;
         }
     }
     if (isset($_POST['activity-center-back'])) {
         $_SESSION['edgimo-reservation-form']['current-step']--;
         if (AC::get_current_step() === 1) {
             AC::reset_timer();
         }
         return true;
     }
     $validation = array();
     $filter = array();
     foreach ($_POST['form'] as $field_name => $field_value) {
         if (isset(AC::$fields[$field_name]['validate'])) {
             $validation[$field_name] = AC::$fields[$field_name]['validate'];
         }
         if (isset(AC::$fields[$field_name]['filter'])) {
             $filter[$field_name] = AC::$fields[$field_name]['filter'];
         }
     }
     $gump->validation_rules($validation);
     $gump->filter_rules($filter);
     $validated_data = $gump->run($_POST['form']);
     if (isset($step) && $step == 1 && !isset($validated_data['terms'])) {
         AC::$errors['terms'] = 'You must agree to the terms of registration in order to register for an event.  If you have questions about the terms, please feel free to contact us at <a href="mailto:' . $a->service_email . '">' . $a->service_email . '</a>';
         return false;
     }
     if ($validated_data === false) {
         $temp = $gump->get_readable_errors();
         $i = 0;
         foreach ($gump->validate($_POST['form'], $validation) as $error) {
             AC::$errors[$error['field']] = $temp[$i];
             $i++;
         }
         return false;
     }
     if (isset($_POST['waitlist-submit'])) {
         $new_waitlist = wp_insert_post(array('post_name' => $validated_data['name'], 'post_title' => $validated_data['name'], 'post_type' => 'waitlist', 'post_status' => 'publish'));
         $meta = array('_waitlist_activity' => $validated_data['activity_id'], '_waitlist_created' => time(), '_waitlist_name' => $validated_data['name'], '_waitlist_desired_seats' => $validated_data['desired_seats'], '_waitlist_phone' => $validated_data['phone_1'] . $validated_data['phone_2'] . $validated_data['phone_3'], '_waitlist_email' => $validated_data['email'], '_waitlist_code' => md5(time() . rand() . $validated_data['name']), '_waitlist_redeemed' => 'false');
         foreach ($meta as $k => $v) {
             add_post_meta($new_waitlist, $k, $v, true);
         }
         require_once 'wp-content/themes/vetri-master/lib/phpmailer/PHPMailerAutoload.php';
         AC::send_admin_waitlist_email($new_waitlist);
         AC::send_waitlist_confirmation_email($new_waitlist);
         $_SESSION['edgimo-reservation-form']['waitlist-success'] = $new_waitlist;
         wp_redirect(AC::get_redirect_url());
         exit;
     }
     switch ($step) {
         case 1:
             //check to see if the capacity went down after submitting registrant count
             if ($a->seats_available < AC::load_saved_data('number_of_registrants') && !AC::current_user_has_pending_reservation() && !AC::valid_waitlist_code()) {
                 AC::$errors['number_of_registrants'] = 'The number of registrants you selected is no longer available. Please select again.';
                 return false;
             }
             $_SESSION['edgimo-reservation-form']['current-step'] = 2;
             //in case user clicked back using browser and not button, pending data will still exist. delete it
             if (AC::current_user_has_pending_reservation()) {
                 AC::reset_timer();
             }
             //by now any old pending data should be gone
             //always initiate a new timer when step 1 is submitted
             AC::init_timer();
             break;
         case 2:
             $_SESSION['edgimo-reservation-form']['current-step'] = 3;
             break;
         case 3:
             $values = AC::get_all_final_values();
             $result = AC::process_transaction($values);
             if ($result['success']) {
                 $new_reservation = wp_insert_post(array('post_name' => $values['registrant_1_last_name'] . ', ' . $values['registrant_1_first_name'], 'post_title' => $values['registrant_1_last_name'] . ', ' . $values['registrant_1_first_name'], 'post_type' => 'reservation', 'post_status' => 'publish'));
                 isset($values['donation']) ? $values['donation'] = $values['donation'] : ($values['donation'] = 0);
                 $meta = array('_reservation_activity' => $a->ID, '_reservation_created' => time(), '_reservation_total' => AC::get_total(), '_reservation_fee' => $a->fee * $values['number_of_registrants'], '_reservation_gratuity' => AC::calculate_gratuity(), '_reservation_tax' => AC::calculate_tax(), '_reservation_donation' => $values['donation'], '_reservation_registrant_count' => $values['number_of_registrants'], '_reservation_optin' => $values['optin'], '_reservation_billing_first_name' => $values['billing_first_name'], '_reservation_billing_last_name' => $values['billing_last_name'], '_reservation_billing_address' => $values['billing_address'], '_reservation_billing_phone' => $values['billing_phone'], '_reservation_billing_city' => $values['billing_city'], '_reservation_billing_state' => $values['billing_state'], '_reservation_billing_zip' => $values['billing_zip'], '_reservation_transaction_id' => $result['RefNum'], '_reservation_auth_code' => $result['AuthCode'], '_reservation_card_type' => AC::card_type($values['cc_number']), '_reservation_last4' => $result['Last4']);
                 $registrants = array();
                 $addons = array();
                 for ($i = 1; $i <= $values['number_of_registrants']; $i++) {
                     $registrants[] = array('first_name' => $values['registrant_' . $i . '_first_name'], 'last_name' => $values['registrant_' . $i . '_last_name'], 'email' => $values['registrant_' . $i . '_email']);
                 }
                 $addon_fees = 0;
                 foreach (AC::get_addons_in_cart() as $tax_status_group) {
                     foreach ($tax_status_group as $addon) {
                         $addons[] = array('title' => $a->addon_group[$addon['index']]['title'], 'cost' => $a->addon_group[$addon['index']]['cost'], 'quantity' => $addon['quantity']);
                         $addon_fees += $addon['total'];
                     }
                 }
                 $meta['_reservation_addon_fees'] = $addon_fees;
                 if (!empty($addons)) {
                     $meta['_reservation_addon_group'] = $addons;
                 }
                 $meta['_reservation_registrant_group'] = $registrants;
                 foreach ($meta as $k => $v) {
                     add_post_meta($new_reservation, $k, $v, true);
                 }
                 //if this was a waitlist code reservation, flag the waitlist as redeemed and set the meta
                 if (AC::valid_waitlist_code()) {
                     $w = AC::get_waitlist_from_code($_GET['v']);
                     update_post_meta($w->ID, '_waitlist_redeemed', 'yes');
                     update_post_meta($w->ID, '_waitlist_reservation', $new_reservation);
                 }
                 if ($values['optin'] === 'yes') {
                     $values['reservation_id'] = $new_reservation;
                     //AC::add_to_mailchimp($values);
                 }
                 require_once 'wp-content/themes/vetri-master/lib/phpmailer/PHPMailerAutoload.php';
                 AC::send_confirmation_email($new_reservation);
                 AC::send_admin_reservation_email($new_reservation);
                 AC::reset_all();
                 $_SESSION['edgimo-reservation-form']['success'] = $new_reservation;
                 wp_redirect(AC::get_redirect_url());
                 exit;
             } else {
                 AC::$transaction_error = $result['message'];
             }
             break;
     }
 }
コード例 #6
0
ファイル: ce-upload.php プロジェクト: chrismademe/php-starter
    # Not logged in
    case !is_loggedin():
        JSON::parse(100, 'negative', 'You\'re not logged in.', null, true);
        break;
        # No data
    # No data
    case !is_form_data():
        JSON::parse(100, 'negative', 'Nothing was submitted.', null, true);
        break;
}
# New GUMP Object
$form = new GUMP();
# Get Input
$data = form_data();
# Validate Input
$form->validate($data, array('files' => 'required'));
# Run GUMP
$response = $form->run($data);
# Get Response
if ($response === false) {
    JSON::parse(100, 'negative', $form->get_readable_errors(true));
} else {
    # Split Base64
    $parts = explode(';', $data['files']);
    # Split Type
    $type = explode('/', $parts[0]);
    # File Extension
    $ext = $type[1];
    # Get File
    $file = base64_decode(preg_replace('#^data:image/\\w+;base64,#i', '', $data['files']));
    # Set filename
コード例 #7
0
/**
 * Update Password
 *
 * Controller for the User Account module.
 *
 * @author      Goran Halusa <*****@*****.**>
 * @since       0.1.0
 */
function update_password()
{
    $app = \Slim\Slim::getInstance();
    $final_global_template_vars = $app->config('final_global_template_vars');
    require_once $_SERVER["PATH_TO_VENDOR"] . "wixel/gump/gump.class.php";
    require_once $final_global_template_vars["absolute_path_to_this_module"] . "/models/register_account.class.php";
    require_once $final_global_template_vars["default_module_list"]["authenticate"]["absolute_path_to_this_module"] . "/models/authenticate.class.php";
    require_once $_SERVER["PATH_TO_VENDOR"] . "phpmailer/phpmailer/PHPMailerAutoload.php";
    $db_conn = new \PHPSkeleton\models\db($final_global_template_vars["db_connection"]);
    $db_resource = $db_conn->get_resource();
    $register_account = new \PHPSkeleton\RegisterAccount($db_resource, $final_global_template_vars["session_key"]);
    $authenticate = new \PHPSkeleton\Authenticate($db_resource, $final_global_template_vars["session_key"]);
    $gump = new GUMP();
    $mail = new PHPMailer();
    $post = $app->request()->post() ? $app->request()->post() : false;
    $account_email_exists = false;
    // Is the email address in the database?
    if ($post) {
        $account_email_exists = $register_account->account_email_exists($post["user_account_email"]);
        if (!$account_email_exists) {
            $app->flash('message', 'The entered email address was not found in our database.');
            $app->redirect($final_global_template_vars["path_to_this_module"] . "/password/");
        }
    }
    $rules = array();
    if ($account_email_exists) {
        $rules = array("user_account_password" => "required|max_len,100|min_len,6", "password_check" => "required|max_len,100|min_len,6");
    }
    $validated = $gump->validate($post, $rules);
    if ($post["user_account_password"] != $post["password_check"]) {
        $validated_password_check = array("field" => "user_account_password_check", "value" => null, "rule" => "validate_required");
        if (is_array($validated)) {
            array_push($validated, $validated_password_check);
        } else {
            $validated = array($validated_password_check);
        }
    }
    $errors = array();
    if ($validated !== true) {
        $errors = \phpskeleton\models\utility::gump_parse_errors($validated);
    }
    if (isset($errors["user_account_password_check"])) {
        $errors["user_account_password_check"] = "Passwords did not match.";
    }
    // If there are no errors, process posted data and email to user
    if (empty($errors) && $post) {
        // Attempt to update the user_account_password and set the account to active (returns boolean)
        $updated = $register_account->update_password($authenticate->generate_hashed_password($post["user_account_password"]), $account_email_exists['user_account_id'], $post["emailed_hash"]);
        if ($updated) {
            // Prepare the email...
            // The email subject.
            $subject = 'Your Password Has Been Reset';
            // The message.
            $message = '<h2>Your Password Has Been Reset</h2>
            <hr>
            <p>If you did not execute this change, please contact the site administrator as soon as possible.</p>';
            // For the ability to send emails from an AWS EC2 instance
            // If you need this functionality, you can configure the settings accordingly in /default_global_settings.php
            if ($final_global_template_vars["hosting_vendor"] && $final_global_template_vars["hosting_vendor"] == "aws_ec2") {
                $email = array();
                require_once $final_global_template_vars["path_to_smtp_settings"];
                // SMTP Settings
                $mail = new PHPMailer();
                $mail->IsSMTP();
                $mail->SMTPAuth = $email['settings']['smtpauth'];
                $mail->SMTPSecure = $email['settings']['smtpsecure'];
                $mail->Host = $email['settings']['host'];
                $mail->Username = $email['settings']['username'];
                $mail->Password = $email['settings']['password'];
            }
            // From (verified email address).
            $mail->SetFrom($final_global_template_vars["send_emails_from"], $final_global_template_vars["site_name"] . ' Accounts');
            // Subject
            $mail->Subject = $subject;
            $mail->MsgHTML($message);
            // Recipient
            $mail->AddAddress($post['user_account_email']);
            // Send the email.
            $mail->Send();
            $app->flash('message', 'Your password has been reset.');
            $app->redirect($final_global_template_vars["path_to_this_module"] . "/password/");
        } else {
            $app->flash('message', 'Processing failed.');
            $app->redirect($final_global_template_vars["path_to_this_module"] . "/password/");
        }
    } else {
        $app->flash('message', $errors["user_account_password"]);
        $app->redirect($final_global_template_vars["path_to_this_module"] . "/reset/?user_account_email=" . $account_email_exists['user_account_email'] . "&emailed_hash=" . $post["emailed_hash"]);
    }
}
コード例 #8
0
ファイル: tests.php プロジェクト: jsnshrmn/Suma
<?php

error_reporting(-1);
ini_set('display_errors', 1);
require "gump.class.php";
$validator = new GUMP();
$rules = array('missing' => 'required', 'email' => 'valid_email', 'max_len' => 'max_len,1', 'min_len' => 'min_len,4', 'exact_len' => 'exact_len,10', 'alpha' => 'alpha', 'alpha_numeric' => 'alpha_numeric', 'alpha_dash' => 'alpha_dash', 'numeric' => 'numeric', 'integer' => 'integer', 'boolean' => 'boolean', 'float' => 'float', 'valid_url' => 'valid_url', 'url_exists' => 'url_exists', 'valid_ip' => 'valid_ip', 'valid_ipv4' => 'valid_ipv4', 'valid_ipv6' => 'valid_ipv6', 'valid_name' => 'valid_name', 'contains' => 'contains,free pro basic');
$invalid_data = array('missing' => '', 'email' => "not a valid email\r\n", 'max_len' => "1234567890", 'min_len' => "1", 'exact_len' => "123456", 'alpha' => "*(^*^*&", 'alpha_numeric' => "abcdefg12345+\r\n\r\n\r\n", 'alpha_dash' => "ab<script>alert(1);</script>cdefg12345-_+", 'numeric' => "one, two\r\n", 'integer' => "1,003\r\n\r\n\r\n\r\n", 'boolean' => "this is not a boolean\r\n\r\n\r\n\r\n", 'float' => "not a float\r\n", 'valid_url' => "\r\n\r\nhttp://add", 'url_exists' => "http://asdasdasd354.gov", 'valid_ip' => "google.com", 'valid_ipv4' => "google.com", 'valid_ipv6' => "google.com", 'valid_name' => '*&((*S))(*09890uiadaiusyd)', 'contains' => 'premium');
$valid_data = array('missing' => 'This is not missing', 'email' => '*****@*****.**', 'max_len' => '1', 'min_len' => '1234', 'exact_len' => '1234567890', 'alpha' => 'ÈÉÊËÌÍÎÏÒÓÔasdasdasd', 'alpha_numeric' => 'abcdefg12345', 'alpha_dash' => 'abcdefg12345-_', 'numeric' => 2.0, 'integer' => 3, 'boolean' => FALSE, 'float' => 10.1, 'valid_url' => 'http://wixel.net', 'url_exists' => 'http://wixel.net', 'valid_ip' => '69.163.138.23', 'valid_ipv4' => "255.255.255.255", 'valid_ipv6' => "2001:0db8:85a3:08d3:1319:8a2e:0370:7334", 'valid_name' => 'Sean Nieuwoudt', 'contains' => 'free');
echo "\nBEFORE SANITIZE:\n\n";
print_r($invalid_data);
echo "\nAFTER SANITIZE:\n\n";
print_r($validator->sanitize($invalid_data));
echo "\nTHESE ALL FAIL:\n\n";
$validator->validate($invalid_data, $rules);
// Print out the errors using the new get_readable_errors() method:
print_r($validator->get_readable_errors());
if ($validator->validate($valid_data, $rules)) {
    echo "\nTHESE ALL SUCCEED:\n\n";
    print_r($valid_data);
}
echo "\nDONE\n\n";
コード例 #9
0
ファイル: validator.php プロジェクト: koutsenko/gb-js2016
<?php

require "gump.class.php";
$validator = new GUMP();
$_POST = $validator->sanitize($_POST);
$rules = array('username' => 'required|alpha_numeric|max_len,100|min_len,6', 'password' => 'required|max_len,100|min_len,6', 'email' => 'required|valid_email', 'gender' => 'required|exact_len,1', 'credit_card' => 'required|valid_cc', 'bio' => 'required', 'birth' => 'required|date');
$validated = @$validator->validate($_POST, $rules);
if ($validated === TRUE) {
    $result["result"] = true;
    die(json_encode($result));
} else {
    $result['error'] = $validator->get_errors_array();
    $result["result"] = false;
    die(json_encode($result));
}
コード例 #10
0
ファイル: tests.php プロジェクト: rcrowe/GUMP
#!/usr/bin/php -q
<?php 
require "gump.class.php";
$rules = array('missing' => 'required', 'email' => 'valid_email', 'max_len' => 'max_len,1', 'min_len' => 'min_len,4', 'exact_len' => 'exact_len,10', 'alpha' => 'alpha', 'alpha_numeric' => 'alpha_numeric', 'alpha_dash' => 'alpha_dash', 'numeric' => 'numeric', 'integer' => 'integer', 'boolean' => 'boolean', 'float' => 'float', 'valid_url' => 'valid_url', 'url_exists' => 'url_exists', 'valid_ip' => 'valid_ip');
$invalid_data = array('missing' => '', 'email' => "not a valid email\r\n", 'max_len' => "1234567890", 'min_len' => "1", 'exact_len' => "123456", 'alpha' => "*(^*^*&", 'alpha_numeric' => "abcdefg12345+\r\n\r\n\r\n", 'alpha_dash' => "ab<script>alert(1);</script>cdefg12345-_+", 'numeric' => "one, two\r\n", 'integer' => "1,003\r\n\r\n\r\n\r\n", 'boolean' => "this is not a boolean\r\n\r\n\r\n\r\n", 'float' => "not a float\r\n", 'valid_url' => "\r\n\r\nhttp://add", 'url_exists' => "http://asdasdasd354.gov", 'valid_ip' => "google.com");
$valid_data = array('missing' => 'This is not missing', 'email' => '*****@*****.**', 'max_len' => '1', 'min_len' => '1234', 'exact_len' => '1234567890', 'alpha' => 'abcdefg', 'alpha_numeric' => 'abcdefg12345', 'alpha_dash' => 'abcdefg12345-_', 'numeric' => 2.0, 'integer' => 3, 'boolean' => FALSE, 'float' => 10.1, 'valid_url' => 'http://wixel.net', 'url_exists' => 'http://wixel.net', 'valid_ip' => '69.163.138.62');
echo "\nBEFORE SANITIZE:\n\n";
print_r($invalid_data);
echo "\nAFTER SANITIZE:\n\n";
print_r(GUMP::sanitize($invalid_data));
echo "\nTHESE ALL FAIL:\n\n";
print_r(GUMP::validate($invalid_data, $rules));
if (GUMP::validate($valid_data, $rules)) {
    echo "\nTHESE ALL SUCCEED:\n\n";
    print_r($valid_data);
}
echo "\nDONE\n\n";
コード例 #11
0
/**
 * Insert User Account
 *
 * Controller for the User Account module.
 *
 * @author      Goran Halusa <*****@*****.**>
 * @since       0.1.0
 */
function insert_user_account()
{
    $app = \Slim\Slim::getInstance();
    $env = $app->environment();
    $final_global_template_vars = $app->config('final_global_template_vars');
    require_once $_SERVER["PATH_TO_VENDOR"] . "wixel/gump/gump.class.php";
    require_once $final_global_template_vars["absolute_path_to_this_module"] . "/models/user_account.class.php";
    require_once $final_global_template_vars["absolute_path_to_this_module"] . "/models/register_account.class.php";
    require_once $final_global_template_vars["default_module_list"]["authenticate"]["absolute_path_to_this_module"] . "/models/authenticate.class.php";
    require_once $_SERVER["PATH_TO_VENDOR"] . "phpmailer/phpmailer/PHPMailerAutoload.php";
    $db_conn = new \PHPSkeleton\models\db($final_global_template_vars["db_connection"]);
    $db_resource = $db_conn->get_resource();
    $useraccount = new \PHPSkeleton\UserAccount($db_resource, $final_global_template_vars["session_key"]);
    $register_account = new \PHPSkeleton\RegisterAccount($db_resource, $final_global_template_vars["session_key"]);
    $authenticate = new \PHPSkeleton\Authenticate($db_resource, $final_global_template_vars["session_key"]);
    $gump = new GUMP();
    $mail = new PHPMailer();
    $errors = false;
    $posted_data = $app->request()->post() ? $app->request()->post() : false;
    $account_email_exists = $register_account->account_email_exists($posted_data["user_account_email"]);
    if ($account_email_exists) {
        $app->flash('message', 'It looks like you already have an account. Email address is already in use.');
        $app->redirect($final_global_template_vars["path_to_this_module"] . "/register/");
    }
    // GUMP validation rules
    $rules = array("user_account_email" => "required|valid_email", "user_account_password" => "required|max_len,100|min_len,6", "first_name" => "required|alpha_numeric", "last_name" => "required|alpha_numeric");
    // Validation using GUMP
    if ($posted_data) {
        $validated = array();
        $errors = array();
        $validated = $gump->validate($posted_data, $rules);
        if ($validated !== true) {
            $errors = \phpskeleton\models\utility::gump_parse_errors($validated);
        }
        if ($errors) {
            $env = $app->environment();
            $env["default_validation_errors"] = $errors;
        }
    }
    $default_validation_errors = isset($env["default_validation_errors"]) ? $env["default_validation_errors"] : false;
    // If there are no errors, process posted data and email to user
    if (!$default_validation_errors && $posted_data) {
        $emailed_hash = md5(rand(0, 1000));
        // INSERT this user into the user_account table
        $statement = $db_resource->prepare("INSERT INTO user_account\n          (user_account_email, user_account_password, first_name, last_name, acceptable_use_policy, created_date, active, emailed_hash)\n          VALUES ( :user_account_email, :user_account_password, :first_name, :last_name, 1, NOW(), 0, :emailed_hash )");
        $statement->bindValue(":user_account_email", $posted_data['user_account_email'], PDO::PARAM_STR);
        $statement->bindValue(":user_account_password", $authenticate->generate_hashed_password($posted_data['user_account_password']), PDO::PARAM_STR);
        $statement->bindValue(":first_name", $posted_data['first_name'], PDO::PARAM_STR);
        $statement->bindValue(":last_name", $posted_data['last_name'], PDO::PARAM_STR);
        $statement->bindValue(":emailed_hash", $emailed_hash, PDO::PARAM_STR);
        $statement->execute();
        $error = $db_resource->errorInfo();
        if ($error[0] != "00000") {
            die('The INSERT INTO user_account failed.');
        }
        $last_inserted_user_account_id = $db_resource->lastInsertId();
        // INSERT this user into the user_account_groups table with "Author" privileges
        $statement = $db_resource->prepare("INSERT INTO user_account_groups\n          (role_id, user_account_id, group_id)\n          VALUES ( 2, :user_account_id, 1 )");
        $statement->bindValue(":user_account_id", $last_inserted_user_account_id, PDO::PARAM_INT);
        $statement->execute();
        $error = $db_resource->errorInfo();
        if ($error[0] != "00000") {
            die('The INSERT INTO user_account_groups failed.');
        }
        // Send emails
        // Email setup for user
        $to = $posted_data['user_account_email'];
        // Send email to our user
        $subject = 'Signup | Verification';
        // Give the email a subject
        $message = '<h2>Hello ' . $posted_data['first_name'] . '!</h2>
        <p>Your account has been created, you can login with the following credentials after you have 
        activated your account by accessing the url below.</p>
        <hr>
        <p>Username: '******'user_account_email'] . '</p>
        <p>Password: (The password you submitted during the registration process.)</p>
        <hr>
        <p>Please click this link to activate your account:<br />
        <a href="http://' . $_SERVER["SERVER_NAME"] . '/user_account/verify/?user_account_email=' . $posted_data['user_account_email'] . '&emailed_hash=' . $emailed_hash . '">http://' . $_SERVER["SERVER_NAME"] . '/user_account/verify/?user_account_email=' . $posted_data['user_account_email'] . '&emailed_hash=' . $emailed_hash . '</a></p>';
        // Our message above including the link
        // Email setup for Universal Administrators
        // First, get all of the "Universal Administrator" email addresses
        $admin_emails = array();
        $universal_administrator_emails = $useraccount->get_universal_administrator_emails();
        // Create a comma-delimited list of email addresses
        if (is_array($universal_administrator_emails) && !empty($universal_administrator_emails)) {
            foreach ($universal_administrator_emails as $email) {
                array_push($admin_emails, $email["user_account_email"]);
            }
        }
        $subject_admins = 'New User Registration';
        // Give the email a subject
        $message_admins = '<h2>New User</h2>
        <p>A new user has registered.</p>
        <h3>Details</h3>
        <p>Name: ' . $posted_data['first_name'] . ' ' . $posted_data['last_name'] . '</p>
        <p>Email: ' . $posted_data['user_account_email'] . '</p>
        <hr>
        <p><a href="http://' . $_SERVER["SERVER_NAME"] . '/authenticate/">Login to administer</a></p>';
        // Our message above including the link
        // For the ability to send emails from an AWS EC2 instance
        // If you need this functionality, you can configure the settings accordingly in /default_global_settings.php
        if ($final_global_template_vars["hosting_vendor"] && $final_global_template_vars["hosting_vendor"] == "aws_ec2") {
            $email = array();
            require_once $final_global_template_vars["path_to_smtp_settings"];
            // SMTP Settings
            $mail->IsSMTP();
            $mail->SMTPAuth = $email['settings']['smtpauth'];
            $mail->SMTPSecure = $email['settings']['smtpsecure'];
            $mail->Host = $email['settings']['host'];
            $mail->Username = $email['settings']['username'];
            $mail->Password = $email['settings']['password'];
        }
        // Send email to user
        $mail->SetFrom($final_global_template_vars["send_emails_from"], $final_global_template_vars["site_name"] . ' Accounts');
        // From (verified email address)
        $mail->Subject = $subject;
        // Subject
        $mail->MsgHTML($message);
        $mail->AddAddress($to);
        // Recipient
        $mail->Send();
        $mail->ClearAllRecipients();
        // Send email to Universal Administrators
        // Subject
        $mail->Subject = $subject_admins;
        $mail->MsgHTML($message_admins);
        // Universal Admin recipients
        if (is_array($universal_administrator_emails) && !empty($universal_administrator_emails)) {
            foreach ($universal_administrator_emails as $email) {
                $mail->AddAddress($email["user_account_email"]);
            }
            $mail->Send();
            $mail->ClearAllRecipients();
        }
    }
    if (!$errors) {
        $app->flash('message', 'Account creation was successful. You will receive an email shortly with further instructions.');
        $app->redirect($final_global_template_vars["path_to_this_module"] . "/register/");
    } else {
        $env = $app->environment();
        $env["default_validation_errors"] = $errors;
    }
}
コード例 #12
0
<?php

# Check user & validate data
switch (true) {
    # Not logged in
    case is_loggedin():
        JSON::parse(100, 'negative', '<i class="fa fa-exclamation-triangle"></i> You\'re already logged in!', null, true);
        break;
        # No post data
    # No post data
    case !is_form_data():
        JSON::parse(100, 'negative', '<i class="fa fa-exclamation-triangle"></i> There was a problem logging you in. (Error: No data received)', null, true);
        break;
}
# Create User Object
$_ce_user = new CMSEditor\User($_ce_config);
# New GUMP Object
$form = new GUMP();
# Get Input
$data = form_data();
# Validate Input
$form->validate($data, array('username' => 'required', 'password' => 'required'));
# Run GUMP
$response = $form->run($data);
# Get Response
if ($response === false) {
    JSON::parse(100, 'negative', $form->get_readable_errors(true));
} else {
    # Attempt login
    $_ce_user->login($data['username'], $data['password']);
}
コード例 #13
0
ファイル: url_exists.php プロジェクト: jsnshrmn/Suma
#!/usr/bin/php -q
<?php 
require "../gump.class.php";
$validator = new GUMP();
$_POST = array('url' => 'http://ahakjdhkahddfsdfsdfdkjad.com');
$rules = array('url' => 'url_exists');
print_r($validator->validate($_POST, $rules));
コード例 #14
0
ファイル: url_exists.php プロジェクト: hawkii/GUMP
#!/usr/bin/php -q
<?php 
require "../gump.class.php";
$_POST = array('url' => 'http://ahakjdhkahddfsdfsdfdkjad.com');
$rules = array('url' => 'url_exists');
print_r(GUMP::validate($_POST, $rules));
コード例 #15
0
ファイル: user.router.php プロジェクト: WebstudioNoord/notes
     //
     if ($app->request->post('password') !== $app->request->post('password_confirm')) {
         $validated_data = false;
     }
 }
 /*
 if (is_array($validated_data)) {
 	foreach($validated_data as $key => $val)
 	{
 	    $validated_data[$key] = htmlentities($val);
 	}
 }
 echo '<pre>';var_dump($validated_data);echo '</pre>';
 */
 if ($validated_data === false) {
     $errors = $gump->validate($app->request->post(), $validation_rules_2);
     if (!is_array($errors)) {
         $errors = [];
     }
     $validate_username = GUMP::is_valid(['username' => $app->request->post('username')], ['username' => 'istaken']);
     if ($validate_username !== true) {
         $errors[] = array('field' => 'username', 'value' => '', 'rule' => 'validate_istaken', 'param' => '');
     }
     $validate_email = GUMP::is_valid(['email' => $app->request->post('email')], ['email' => 'istaken']);
     if ($validate_email !== true) {
         $errors[] = array('field' => 'email', 'value' => '', 'rule' => 'validate_istaken', 'param' => '');
     }
     if ($app->request->post('password') !== $app->request->post('password_confirm')) {
         $errors[] = array('field' => 'password_confirm', 'value' => '', 'rule' => 'validate_password_confirm', 'param' => '');
     }
     if (is_array($errors)) {
コード例 #16
0
ファイル: Validator.php プロジェクト: vijinho/FFMVC
 /**
  * Perform data validation against the provided ruleset.
  *
  * @param mixed $input
  * @param array optinal $ruleset ot use class rulset
  * @return mixed
  */
 public function validate(array $input, array $ruleset = [])
 {
     return empty($rulseset) ? parent::validate($input, $this->validation_rules) : parent::validate($input, $rulset);
 }
コード例 #17
0
ファイル: form.php プロジェクト: ghalusa/php-skeleton-app
/**
 * Form
 *
 * Controller for the Web App Installer module.
 *
 * @author      Goran Halusa <*****@*****.**>
 * @since       0.1.0
 */
function form()
{
    $app = \Slim\Slim::getInstance();
    $env = $app->environment();
    $final_global_template_vars = $app->config('final_global_template_vars');
    // Redirect to the installer if database variables aren't present, and if we aren't already there.
    if (isset($final_global_template_vars["db_connection"]["name"]) && isset($final_global_template_vars["db_connection"]["host"]) && isset($final_global_template_vars["db_connection"]["user"]) && isset($final_global_template_vars["db_connection"]["password"]) && $_SERVER["REQUEST_URI"] == "/webapp_installer/") {
        header("Location: " . $final_global_template_vars["login_url"] . "/");
        exit;
    }
    require_once $_SERVER["PATH_TO_VENDOR"] . "wixel/gump/gump.class.php";
    $gump = new GUMP();
    $data = $posted_data = $app->request()->post() ? $app->request()->post() : false;
    // GUMP validation rules
    $rules = array("user_account_email" => "required", "user_account_password" => "required", "first_name" => "required", "last_name" => "required", "application_name" => "required", "session_key" => "required", "cname" => "required", "database_host" => "required", "database_name" => "required", "database_username" => "required", "database_password" => "required");
    // Validation using GUMP
    if ($posted_data) {
        $validated = array();
        $errors = array();
        $validated = $gump->validate($posted_data, $rules);
        if ($validated !== true) {
            $errors = \phpskeleton\models\utility::gump_parse_errors($validated);
        }
        if ($errors) {
            $env = $app->environment();
            $env["default_validation_errors"] = $errors;
        }
    }
    $default_validation_errors = isset($env["default_validation_errors"]) ? $env["default_validation_errors"] : false;
    // If there are no errors, begin the second round of checks
    if (!$default_validation_errors && $posted_data) {
        // Check to see if the database user exists
        $link = @mysqli_connect($posted_data['database_host'], $posted_data['database_username'], $posted_data['database_password']);
        if (!$link) {
            // die('Could not connect to the database. Please check your parameters.');
            $app->flash('message', 'Could not connect to the database. Please check your parameters.');
            $app->redirect($final_global_template_vars["path_to_this_module"]);
        }
        // Next, check to see if the database exists by making $posted_data['database_name'] the current db
        $db_selected = mysqli_select_db($link, $posted_data['database_name']);
        if (!$db_selected) {
            // die('Cannot use the "'.$posted_data['database_name'].'" database. Does it exist?');
            $app->flash('message', 'Cannot use the "' . $posted_data['database_name'] . '" database. Does it exist?');
            $app->redirect($final_global_template_vars["path_to_this_module"]);
        }
        // If there are no MYSQL errors, overwrite the default_global_settings.php file
        $file_name = "default_global_settings.php";
        $original_file = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/' . $file_name);
        $parsed = str_replace('#~site_name~#', '"site_name" => "' . $posted_data['application_name'] . '",', $original_file);
        $parsed = str_replace('#~session_key~#', ',"session_key" => "' . $posted_data['session_key'] . '"', $parsed);
        $parsed = str_replace('#~name~#', '"name" => ($_SERVER["IS_DEV"] == "true") ? "' . $posted_data['database_name'] . '" : "' . $posted_data['database_name'] . '"', $parsed);
        $parsed = str_replace('#~host~#', ',"host" => "' . $posted_data['database_host'] . '"', $parsed);
        $parsed = str_replace('#~user~#', ',"user" => "' . $posted_data['database_username'] . '"', $parsed);
        $parsed = str_replace('#~password~#', ',"password" => "' . $posted_data['database_password'] . '",', $parsed);
        $parsed = str_replace('#~admin_emails~#', ',"admin_emails" => "' . $posted_data['user_account_email'] . '",', $parsed);
        unlink($_SERVER['DOCUMENT_ROOT'] . '/' . $file_name);
        $file_handle = fopen($_SERVER['DOCUMENT_ROOT'] . '/' . $file_name, 'w') or die("can't open file");
        fwrite($file_handle, $parsed);
        fclose($file_handle);
        chmod($_SERVER['DOCUMENT_ROOT'] . '/' . $file_name, 0664);
        // Overwrite the .htaccess file
        $file_name = ".htaccess";
        $original_file = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/' . $file_name);
        $parsed = str_replace('"^([^\\.]*)\\.com$"', $posted_data['cname'], $original_file);
        unlink($_SERVER['DOCUMENT_ROOT'] . '/' . $file_name);
        $file_handle = fopen($_SERVER['DOCUMENT_ROOT'] . '/' . $file_name, 'w') or die("can't open file");
        fwrite($file_handle, $parsed);
        fclose($file_handle);
        chmod($_SERVER['DOCUMENT_ROOT'] . '/' . $file_name, 0664);
        // Build the database tables
        $db_vars = array("name" => $posted_data['database_name'], "host" => $posted_data['database_host'], "user" => $posted_data['database_username'], "password" => $posted_data['database_password']);
        $db_conn = new \PHPSkeleton\models\db($db_vars);
        $db = $db_conn->get_resource();
        require_once $final_global_template_vars["default_module_list"]["authenticate"]["absolute_path_to_this_module"] . "/models/authenticate.class.php";
        $authenticate = new \PHPSkeleton\Authenticate($db, $final_global_template_vars["session_key"]);
        $statement = $db->prepare("CREATE TABLE `user_account` (\n      `user_account_id` int(10) NOT NULL AUTO_INCREMENT,\n      `user_account_email` varchar(255) NOT NULL,\n      `user_account_password` varchar(255) NOT NULL,\n      `first_name` varchar(255) NOT NULL,\n      `last_name` varchar(255) NOT NULL,\n      `acceptable_use_policy` int(1) DEFAULT NULL,\n      `active` int(1) NOT NULL DEFAULT '0',\n      `emailed_hash` varchar(255) DEFAULT NULL,\n      `created_date` datetime DEFAULT NULL,\n      `modified_date` datetime DEFAULT NULL,\n      PRIMARY KEY (`user_account_id`)\n    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table stores user accounts'");
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('CREATE TABLE `user_account` failed.');
        }
        // INSERT this user into the user_account table
        $statement = $db->prepare("INSERT INTO user_account\n      (user_account_email, user_account_password, first_name, last_name, acceptable_use_policy, created_date, active)\n      VALUES ( :user_account_email, :user_account_password, :first_name, :last_name, 1, NOW(), 1 )");
        $statement->bindValue(":user_account_email", $posted_data['user_account_email'], PDO::PARAM_STR);
        $statement->bindValue(":user_account_password", $authenticate->generate_hashed_password($posted_data['user_account_password']), PDO::PARAM_STR);
        $statement->bindValue(":first_name", $posted_data['first_name'], PDO::PARAM_STR);
        $statement->bindValue(":last_name", $posted_data['last_name'], PDO::PARAM_STR);
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('The INSERT INTO user_account failed.');
        }
        $last_inserted_user_account_id = $db->lastInsertId();
        $statement = $db->prepare("CREATE TABLE `user_account_addresses` (\n      `user_account_addresses_id` int(11) NOT NULL AUTO_INCREMENT,\n      `user_account_id` int(11) NOT NULL,\n      `address_label` varchar(100) NOT NULL DEFAULT '',\n      `address_1` varchar(50) DEFAULT NULL,\n      `address_2` varchar(50) DEFAULT NULL,\n      `city` varchar(50) NOT NULL DEFAULT '',\n      `state` char(2) NOT NULL DEFAULT '',\n      `zip` varchar(10) NOT NULL,\n      `date_created` datetime NOT NULL,\n      `created_by_user_account_id` int(11) NOT NULL,\n      `last_modified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,\n      `last_modified_user_account_id` int(11) NOT NULL,\n      `primary` tinyint(1) NOT NULL DEFAULT '0',\n      `active` tinyint(1) NOT NULL DEFAULT '1',\n      PRIMARY KEY (`user_account_addresses_id`),\n      KEY `created_by_user_account_id` (`created_by_user_account_id`),\n      KEY `last_modified_user_account_id` (`last_modified_user_account_id`)\n    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table stores user account addresses'");
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('CREATE TABLE `user_account_addresses` failed.');
        }
        $statement = $db->prepare("CREATE TABLE `group` (\n      `group_id` int(11) NOT NULL AUTO_INCREMENT,\n      `name` varchar(100) NOT NULL DEFAULT '',\n      `abbreviation` varchar(10) NOT NULL DEFAULT '',\n      `description` mediumtext NOT NULL,\n      `address_1` varchar(50) DEFAULT NULL,\n      `address_2` varchar(50) DEFAULT NULL,\n      `city` varchar(50) NOT NULL DEFAULT '',\n      `state` char(2) NOT NULL DEFAULT '',\n      `zip` varchar(10) NOT NULL,\n      `date_created` datetime NOT NULL,\n      `created_by_user_account_id` int(11) NOT NULL,\n      `last_modified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,\n      `last_modified_user_account_id` int(11) NOT NULL,\n      `active` tinyint(1) NOT NULL DEFAULT '1',\n      PRIMARY KEY (`group_id`),\n      KEY `created_by_user_account_id` (`created_by_user_account_id`),\n      KEY `last_modified_user_account_id` (`last_modified_user_account_id`)\n    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table stores groups for user accounts'");
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('CREATE TABLE `group` failed.');
        }
        $statement = $db->prepare("INSERT INTO `group` (\n      `group_id`\n      ,`name`\n      ,`abbreviation`\n      ,`description`\n      ,`address_1`\n      ,`address_2`\n      ,`city`\n      ,`state`\n      ,`zip`\n      ,`date_created`\n      ,`created_by_user_account_id`\n      ,`last_modified`\n      ,`last_modified_user_account_id`\n      ,`active`\n    )\n    VALUES (1\n      ,'Global Group'\n      ,'GLOBAL'\n      ,'Global Web App Group'\n      ,'ADDRESS PLACEHOLDER'\n      ,''\n      ,'CITY PLACEHOLDER'\n      ,'STATE PLACEHOLDER'\n      ,'12345'\n      ,NOW()\n      ,:user_account_id\n      ,NOW()\n      ,:user_account_id\n      ,1)\n    ");
        $statement->bindValue(":user_account_id", $last_inserted_user_account_id, PDO::PARAM_INT);
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('The INSERT INTO `group` failed.');
        }
        $statement = $db->prepare("CREATE TABLE `group_closure_table` (\n      `ancestor` int(10) NOT NULL DEFAULT '0',\n      `descendant` int(10) NOT NULL DEFAULT '0',\n      `pathlength` int(10) NOT NULL DEFAULT '0',\n      PRIMARY KEY (`ancestor`,`descendant`)\n    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table was from the guidance of Mr. Bill Karwin'");
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('The CREATE TABLE `group_closure_table` failed.');
        }
        $statement = $db->prepare("INSERT INTO `group_closure_table` (\n      `ancestor`\n      ,`descendant`\n      ,`pathlength`\n    )\n    VALUES (1,1,0)\n    ");
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('The INSERT INTO `group_closure_table` failed.');
        }
        $statement = $db->prepare("CREATE TABLE `user_account_groups` (\n      `role_id` int(10) NOT NULL DEFAULT '0',\n      `user_account_id` int(10) NOT NULL DEFAULT '0',\n      `group_id` int(10) NOT NULL DEFAULT '0',\n      `user_account_groups_id` int(10) NOT NULL AUTO_INCREMENT,\n      PRIMARY KEY (`user_account_groups_id`),\n      KEY `role_id` (`role_id`),\n      KEY `user_account_id` (`user_account_id`),\n      KEY `group_id` (`group_id`)\n    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table stores user account groups'");
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('CREATE TABLE `user_account_groups` failed.');
        }
        $statement = $db->prepare("CREATE TABLE `user_account_proxy` (\n      `user_account_groups_id` int(10) NOT NULL DEFAULT '0',\n      `proxy_user_account_id` int(10) NOT NULL DEFAULT '0',\n      PRIMARY KEY (`user_account_groups_id`,`proxy_user_account_id`)\n    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table stores user account proxy users'");
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('CREATE TABLE `user_account_proxy` failed.');
        }
        $statement = $db->prepare("CREATE TABLE `user_account_roles` (\n      `role_id` int(10) NOT NULL AUTO_INCREMENT,\n      `label` varchar(50) DEFAULT NULL,\n      PRIMARY KEY (`role_id`)\n    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table stores user account roles'");
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('CREATE TABLE `user_account_roles` failed.');
        }
        $statement = $db->prepare("INSERT INTO `user_account_roles` (`role_id`,`label`)\n      VALUES\n      (1, 'Administrator'),\n      (2, 'Author'),\n      (3, 'Proxy'),\n      (4, 'Editor'),\n      (5, 'Manager'),\n      (6, 'Universal Administrator')\n    ");
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('The INSERT INTO `user_account_roles` failed.');
        }
        // INSERT this user into the user_account_groups table with "Universal Administrator" privileges
        $statement = $db->prepare("INSERT INTO user_account_groups\n      (role_id, user_account_id, group_id)\n      VALUES ( 6, :user_account_id, 1 ), ( 1, :user_account_id, 1 )");
        $statement->bindValue(":user_account_id", $last_inserted_user_account_id, PDO::PARAM_INT);
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('The INSERT INTO user_account_groups failed.');
        }
        $statement = $db->prepare("CREATE TABLE `login_attempt` (\n      `login_attempt_id` int(11) NOT NULL AUTO_INCREMENT,\n      `user_account_email` varchar(255) NOT NULL,\n      `ip_address` varchar(255) NOT NULL DEFAULT '0',\n      `result` varchar(255) DEFAULT NULL,\n      `page` varchar(255) DEFAULT NULL,\n      `created_date` datetime DEFAULT NULL,\n      PRIMARY KEY (`login_attempt_id`)\n    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='This table is used to log login attempts'");
        $statement->execute();
        $error = $db->errorInfo();
        if ($error[0] != "00000") {
            var_dump($db->errorInfo());
            die('The CREATE TABLE `login_attempt` failed.');
        }
        // Don't return the user account password and the CSRF key value.
        unset($data['user_account_password']);
        unset($data['csrf_key']);
        $data['success_message'] = 'installed';
    }
    if (!$posted_data) {
        $data['cname'] = $_SERVER['SERVER_NAME'];
        $data['database_host'] = 'localhost';
    }
    $app->render('form.php', array("page_title" => "Web Application Installer", "hide_page_header" => true, "path_to_this_module" => $final_global_template_vars["path_to_this_module"], "errors" => $default_validation_errors, "data" => $data));
}
コード例 #18
0
ファイル: full_example.php プロジェクト: hawkii/GUMP
#!/usr/bin/php -q
<?php 
require "../gump.class.php";
// Set the data
$_POST = array('username' => 'SeanNieuwoudt', 'password' => 'mypassword', 'email' => '*****@*****.**', 'gender' => 'm', 'credit_card' => '9872389-2424-234224-234', 'bio' => 'This is good! I think I will switch to another language');
$_POST = GUMP::sanitize($_POST);
// You don't have to sanitize, but it's safest to do so.
// Let's define the rules and filters
$rules = array('username' => 'required|alpha_numeric|max_len,100|min_len,6', 'password' => 'required|max_len,100|min_len,6', 'email' => 'required|valid_email', 'gender' => 'required|exact_len,1', 'credit_card' => 'required|valid_cc', 'bio' => 'required');
$filters = array('username' => 'trim|sanitize_string', 'password' => 'trim|base64_encode', 'email' => 'trim|sanitize_email', 'gender' => 'trim', 'bio' => 'translate,en,de');
$_POST = GUMP::filter($_POST, $filters);
// You can run filter() or validate() first
$validated = GUMP::validate($_POST, $rules);
// Check if validation was successful
if ($validated === TRUE) {
    echo "Successful Validation\n\n";
    print_r($_POST);
    // You can now use POST data safely
    exit;
} else {
    print_r($_POST);
    print_r($validated);
    // Shows all the rules that failed along with the data
}
コード例 #19
0
ファイル: url_exists.php プロジェクト: lanlin/GUMP
#!/usr/bin/php -q
<?php 
error_reporting(-1);
ini_set('display_errors', 1);
require "../gump.class.php";
$validator = new GUMP();
$_POST = array('url' => 'http://sudygausdjhasgdjasjhdasd987lkasjhdkasdkjs.com/');
$rules = array('url' => 'url_exists');
$is_valid = $validator->validate($_POST, $rules);
if ($is_valid === true) {
    echo "The URL provided is valid";
} else {
    print_r($validator->get_readable_errors());
}
コード例 #20
0
ファイル: contains.php プロジェクト: lanlin/GUMP
#!/usr/bin/php -q
<?php 
require "../gump.class.php";
$validator = new GUMP();
$rules = array('account_type' => "required|contains,pro free basic premium", 'priority' => "required|contains,'low' 'medium' 'very high'");
echo "\nVALID DATA TEST:\n\n";
// Valid Data
$_POST_VALID = array('account_type' => 'pro', 'priority' => 'very high');
$valid = $validator->validate($_POST_VALID, $rules);
if ($valid !== true) {
    echo $validator->get_readable_errors(true);
} else {
    echo "Validation passed! \n";
}
echo "\nINVALID DATA TEST:\n\n";
// Invalid
$_POST_INVALID = array('account_type' => 'bad', 'priority' => 'unknown');
$invalid = $validator->validate($_POST_INVALID, $rules);
if ($invalid !== true) {
    echo $validator->get_readable_errors(true);
    echo "\n\n";
} else {
    echo "Validation passed!\n\n";
}
コード例 #21
0
ファイル: Account.php プロジェクト: egnsh93/cst8257-Project
 /**
  * Handle account registrations and view rendering
  */
 public function register()
 {
     // If the user is already logged in, redirect
     if (\Helpers\Session::get('loggedin')) {
         \Helpers\Url::redirect('Courses');
     }
     // If the registration form is submitted
     if (isset($_POST['submit'])) {
         // Check if the student exists
         $studentExists = $this->account->studentExists($_POST['student_id']);
         // If user does not exists
         if (!$studentExists) {
             $validator = new GUMP();
             // Sanitize the submission
             $_POST = $validator->sanitize($_POST);
             // Set the data
             $input_data = array('student_id' => $_POST['student_id'], 'student_name' => $_POST['student_name'], 'student_phone' => $_POST['student_phone'], 'student_password' => $_POST['student_password'], 'student_password_confirmation' => $_POST['student_password_confirmation']);
             // Define custom validation rules
             $rules = array('student_id' => 'required|numeric|min_len,5', 'student_name' => 'required|alpha_space', 'student_phone' => 'required|phone_number', 'student_password' => 'required|regex,/^\\S*(?=\\S{6,})(?=\\S*[a-z])(?=\\S*[A-Z])(?=\\S*[\\d])\\S*$/', 'student_password_confirmation' => 'required|contains,' . $_POST['student_password']);
             // Define validation filters
             $filters = array('student_id' => 'trim|sanitize_string', 'student_name' => 'trim|sanitize_string', 'student_phone' => 'trim|sanitize_string', 'student_password' => 'trim', 'student_password_confirmation' => 'trim');
             // Validate the data
             $_POST = $validator->filter($_POST, $filters);
             $validated = $validator->validate($_POST, $rules);
             // If data is valid
             if ($validated === true) {
                 // Create password hash
                 $password = $_POST['student_password'];
                 $hash = \Helpers\Password::make($password);
                 // Insert student into DB
                 $student_data = array('StudentId' => $_POST['student_id'], 'Name' => $_POST['student_name'], 'Phone' => $_POST['student_phone'], 'Password' => $hash);
                 // Insert the student into the database
                 $this->account->insertStudent($student_data);
                 // Get the newly created user hash
                 $currentUser = $this->account->getStudentHash($_POST['student_id']);
                 // Create a session with user info
                 \Helpers\Session::set('StudentId', $currentUser[0]->StudentId);
                 \Helpers\Session::set('Name', $currentUser[0]->Name);
                 \Helpers\Session::set('loggedin', true);
                 // Redirect to course selection page
                 \Helpers\Url::redirect('Courses');
             } else {
                 // Set errors
                 $error = $validator->get_errors_array();
             }
         } else {
             // Set additional error
             $error['exists'] = 'ID already exists';
         }
     }
     $data['title'] = 'New User';
     View::renderTemplate('header', $data, 'account');
     View::render('account/register', $data, $error);
     View::renderTemplate('footer', $data, 'account');
 }
コード例 #22
0
/**
 * Insert/Update User Account
 *
 * Controller for the User Account module.
 *
 * @author      Goran Halusa <*****@*****.**>
 * @since       0.1.0
 * @param       array  $route  The route data array
 */
function insert_update_user_account(\Slim\Route $route)
{
    $app = \Slim\Slim::getInstance();
    $final_global_template_vars = $app->config('final_global_template_vars');
    require_once $final_global_template_vars["absolute_path_to_this_module"] . "/models/user_account.class.php";
    require_once $final_global_template_vars["default_module_list"]["group"]["absolute_path_to_this_module"] . "/models/group.class.php";
    require_once $final_global_template_vars["default_module_list"]["authenticate"]["absolute_path_to_this_module"] . "/models/authenticate.class.php";
    require_once $_SERVER["PATH_TO_VENDOR"] . "wixel/gump/gump.class.php";
    // URL parameters matched in the route.
    $params = $route->getParams();
    $user_account_id = isset($params["user_account_id"]) ? $params["user_account_id"] : false;
    $db_conn = new \PHPSkeleton\models\db($final_global_template_vars["db_connection"]);
    $db_resource = $db_conn->get_resource();
    $useraccount = new \PHPSkeleton\UserAccount($db_resource, $final_global_template_vars["session_key"]);
    $group = new \PHPSkeleton\Group($db_resource, $final_global_template_vars["session_key"]);
    $authenticate = new \PHPSkeleton\Authenticate($db_resource, $final_global_template_vars["session_key"]);
    $post = $app->request()->post();
    $errors = false;
    $gump = new GUMP();
    $rules_password = array();
    $rules = array("first_name" => "required|alpha_numeric", "last_name" => "required|alpha_numeric", "user_account_email" => "required|valid_email");
    if (isset($post["user_account_password"]) && !empty($post["user_account_password"])) {
        $rules_password = array("user_account_password" => "max_len,100|min_len,6", "password_check" => "required|max_len,100|min_len,6");
    }
    $rules = array_merge($rules, $rules_password);
    $validated = $gump->validate($post, $rules);
    if ($post["user_account_password"] != $post["password_check"]) {
        $validated_password_check = array("field" => "user_account_password_check", "value" => null, "rule" => "validate_required");
        if (is_array($validated)) {
            array_push($validated, $validated_password_check);
        } else {
            $validated = array($validated_password_check);
        }
    }
    $errors = array();
    if ($validated !== true) {
        $errors = \phpskeleton\models\utility::gump_parse_errors($validated);
    }
    if (isset($errors["user_account_password_check"])) {
        $errors["user_account_password_check"] = "Passwords did not match.";
    }
    $has_permission = array_intersect($_SESSION[$final_global_template_vars["session_key"]]["user_role_list"], $final_global_template_vars["role_perm_manage_all_accounts_access"]);
    $role_perm_manage_all_accounts_access = empty($has_permission) ? false : true;
    if (!empty($post) && $role_perm_manage_all_accounts_access) {
        $current_group_values = $useraccount->get_user_group_roles_map($user_account_id, $final_global_template_vars["proxy_id"]);
        $proposed_group_value = json_decode($post["group_data"], true);
        $changes = array();
        $current_group_role_array = array();
        $proposed_group_role_array = array();
        foreach ($proposed_group_value as $single_group_info) {
            foreach ($single_group_info["roles"] as $single_role_id) {
                $tmp_array = array("group_id" => $single_group_info["group_id"], "role_id" => $single_role_id);
                $proposed_group_role_array[] = json_encode($tmp_array);
            }
        }
        if (is_array($current_group_values) && !empty($current_group_values)) {
            foreach ($current_group_values as $single_group_info) {
                foreach ($single_group_info["roles"] as $single_role_id) {
                    $tmp_array = array("group_id" => $single_group_info["group_id"], "role_id" => $single_role_id);
                    $current_group_role_array[] = json_encode($tmp_array);
                }
            }
        }
        $changes = array_diff($proposed_group_role_array, $current_group_role_array);
        $changes = array_merge($changes, array_diff($current_group_role_array, $proposed_group_role_array));
        /**
         * Check to see if the user is trying to hack the system and add a role they are not able to.
         **/
        foreach ($changes as $single_change) {
            $single_change_array = json_decode($single_change, true);
            $show_all = array_intersect($_SESSION[$final_global_template_vars["session_key"]]["user_role_list"], $final_global_template_vars["role_perm_assign_user_account_to_any_group"]);
            if (!empty($show_all)) {
                // This user can add any group to any user.
            } else {
                $group_roles = $useraccount->has_role($_SESSION[$final_global_template_vars["session_key"]]["user_account_id"], $final_global_template_vars["administrator_id"], $single_change_array["group_id"]);
                if (empty($group_roles)) {
                    $failed_group = $group->get_group_record($single_change_array["group_id"]);
                    $errors[] = "You are not able to administor group: " . $failed_group["name"];
                }
            }
        }
        // Check to see if the user is trying to add a role to a group they are not able to.
        foreach ($changes as $single_change) {
            $single_change_array = json_decode($single_change, true);
            if (in_array($single_change_array["role_id"], $final_global_template_vars["exclude_ids_from_selector"])) {
                $errors[] = "You are not able to administer that role.";
            }
        }
    }
    if (!$errors) {
        // Hash the incoming password (with some salt).
        if (!empty($post["user_account_password"])) {
            $post["user_account_password"] = $authenticate->generate_hashed_password($post["user_account_password"]);
        }
        $useraccount->insert_update_user_account($post, $user_account_id, true, $final_global_template_vars["proxy_id"], $role_perm_manage_all_accounts_access);
        $useraccount->insert_addresses($post, $user_account_id, $_SESSION[$final_global_template_vars["session_key"]]["user_account_id"]);
        $app->flash('message', 'Account successfully updated.');
        if ($role_perm_manage_all_accounts_access) {
            $app->redirect($final_global_template_vars["path_to_this_module"]);
        } else {
            $app->redirect($final_global_template_vars["path_to_this_module"] . "/manage/" . $user_account_id);
        }
    } else {
        $env = $app->environment();
        $env["default_validation_errors"] = $errors;
    }
}