Author: Sean Nieuwoudt (http://twitter.com/SeanNieuwoudt)
function diy_compile($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $srcfile = OAuth2\Request::createFromGlobals()->request["srcfile"];
    $srclib = OAuth2\Request::createFromGlobals()->request["srclib"];
    $device = OAuth2\Request::createFromGlobals()->request["device"];
    $comp = OAuth2\Request::createFromGlobals()->request["comp"];
    $filename = OAuth2\Request::createFromGlobals()->request["filename"];
    $writedevice = OAuth2\Request::createFromGlobals()->request["writedevice"];
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $diy_error["post"]["device"] = $device;
    $post["srcfile"] = $srcfile;
    //organisation                                  oauth_devices
    $post["device"] = $device;
    //organisation                                  oauth_devices
    $post["comp"] = $comp;
    //organisation                                  oauth_devices
    $post["filename"] = $filename;
    //organisation                                  oauth_devices
    $post["writedevice"] = $writedevice;
    //organisation                                  oauth_devices
    $gump = new GUMP();
    $gump->validation_rules(array('device' => 'required|alpha_numeric', 'filename' => 'required|alpha_numeric', 'comp' => 'required|alpha_numeric', 'writedevice' => 'required|alpha_numeric'));
    $gump->filter_rules(array('device' => 'trim|sanitize_string', 'filename' => 'trim|sanitize_string', 'comp' => 'trim|sanitize_string', 'writedevice' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        try {
            $sourceWriteDir = __DIR__ . '/../../../data/sketches/' . $client_id . '/' . $device . '/' . $filename;
            if (file_exists($sourceWriteDir)) {
                throw new \Exception('Filename ' . $filename . ' for user ' . $client_id . ' and device ' . $device . ' already exists');
            }
            $stmt2 = $storage->prepare('SELECT * FROM oauth_devices WHERE device = :device');
            $stmt2->execute(array('device' => trim($device)));
            $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
            if ($row2["organisation"]) {
                $org = trim($row2["organisation"]);
            }
            if ($row2["mode"]) {
                $mode = trim($row2["mode"]);
            }
            if ($row2["status"]) {
                $status = trim($row2["status"]);
            }
            if ($row2["client_id"]) {
                $devclient_id = trim($row2["client_id"]);
            }
            $orgscopeadmin = "no";
            $orgscopedevel = "no";
            if ($mode == "devel" && $status == "org") {
                $userscopes = explode(' ', trim($userscope));
                $adminscope = $org . "_admin";
                $develscope = $org . "_admin";
                // o user aniki sto scope
                for ($i = 0; $i <= count($userscopes); $i++) {
                    if (trim($userscopes[$i]) == $adminscope) {
                        $orgscopeadmin = "yes";
                    }
                    if (trim($userscopes[$i]) == $develscope) {
                        $orgscopedevel = "yes";
                    }
                }
                // einai o owner
                if ($devclient_id == $client_id) {
                    $orgscopeadmin = "yes";
                }
            }
            // einmai o owner
            if ($mode == "devel" && $status == "private" && $devclient_id == $client_id) {
                $orgscopeadmin = "yes";
            }
            $result["result"]["sketch1"] = $orgscopeadmin;
            if ($orgscopeadmin == "yes" || $orgscopedevel == "yes") {
                try {
                    $stmt2 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :device');
                    $stmt2->execute(array('device' => trim($device)));
                    $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
                    if ($row2["apiport"]) {
                        // *************************************** compiler *********************************
                        // srcfile echeis se base64 ton kodika
                        // compiler echeis ton compiler pou thelei o user   mechri stigmis echoume   gcc, ino
                        // filename to filename pou edosse o user
                        // o poros compilesketch
                        // afou kanei compile
                        // epistrefei
                        // error   ta lathi  h noerrors
                        // binfile    to hex file
                        $compilerserver = diyConfig::read("compiler.host");
                        $compilerserver .= ":" . diyConfig::read("compiler.port");
                        $data1 = 'filename=' . $filename;
                        $data1 .= '&compiler=' . $comp;
                        $data1 .= '&srcfile=' . $srcfile;
                        $fixedFiles = array();
                        foreach ($srclib as $curName => $curFile) {
                            $fixedFiles[] = 'srclib[' . $curName . ']=' . $curFile;
                        }
                        $data1 .= '&' . implode('&', $fixedFiles);
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, "{$compilerserver}/api/compilesketch");
                        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
                        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
                        curl_setopt($ch, CURLOPT_POST, 1);
                        $or = curl_exec($ch);
                        if (!$or) {
                            $or = curl_error($ch);
                        }
                        $result["compiler"] = $or;
                        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
                        $result["status"] = "200";
                        $r = json_decode($or, true);
                        if (!$r) {
                            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: CompilationError";
                            $result["compiler"] = $or;
                            $result["status"] = "500";
                            return $result;
                        }
                        if ($r['status'] != 200) {
                            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: CompilationError";
                            $result["status"] = "500";
                            return $result;
                        }
                        unset($result["compiler"]);
                        // No need to transfer this to the user
                        //$srcfilebase64encode = base64_encode($srcfile);
                        $apiport = trim($row2["apiport"]);
                        // *************************************** compiler *********************************
                        if ($r['status'] == 200 && $writedevice == "yes") {
                            $apiport = trim($row2["apiport"]);
                            $binfile = $r['hex'];
                            $data1 = 'file=base64';
                            $data1 .= '&binfile=' . $binfile;
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:{$apiport}/api/writesketch");
                            curl_setopt($ch, CURLOPT_TIMEOUT, 90);
                            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
                            curl_setopt($ch, CURLOPT_POST, 1);
                            $r = curl_exec($ch);
                            $result["sketch"] = $r;
                            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
                            $result["status"] = "200";
                            //$result["result"]=  $r;
                        }
                        // If we are here with no exceptions then everything went well. Lets save the sketch.
                        $ziptmp = tempnam(sys_get_temp_dir(), 'diytmpzip') . '.tgz';
                        file_put_contents($ziptmp, base64_decode($r['zip']));
                        $p = new PharData($ziptmp);
                        $p->decompress();
                        // creates /path/to/my.tar
                        $ziptmpextracted = str_replace('.tgz', '.tar', $ziptmp);
                        $phar = new PharData($ziptmpextracted);
                        $writeDir = __DIR__ . '/../../../data/sketches/' . $client_id . '/' . $filename;
                        $phar->extractTo($sourceWriteDir);
                    }
                } catch (Exception $e) {
                    $diy_error["db"] = $e->getCode();
                    $result["status"] = $e->getCode();
                    $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
                }
            }
        } catch (Exception $e) {
            $diy_error["db"] = $e->getCode();
            $result["status"] = $e->getCode();
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
/**
 * 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;
    }
}
/**
 * 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;
    }
}
Example #4
0
 /**
  * Checks, sanitizes and Escapes the Userinput
  *
  * Dies if User submitted incorrect data
  */
 protected function gradeInputPreprocess()
 {
     require_once PATH_INCLUDE . '/gump.php';
     $gump = new GUMP();
     $rules = array('gradelabel' => array('required|min_len,1|max_len,255', 'sql_escape', _g('Gradelabel')), 'gradelevel' => array('required|numeric|min_len,1|max_len,3', 'sql_escape', _g('Gradelevel')), 'schooltype' => array('numeric|min_len,1|max_len,11', 'sql_escape', _g('Schooltype')));
     $gump->rules($rules);
     if (!$gump->run($_POST)) {
         $this->_interface->dieError($gump->get_readable_string_errors(true));
     }
 }
Example #5
0
 protected function gump()
 {
     require_once PATH_INCLUDE . '/gump.php';
     try {
         $gump = new GUMP($_POST);
         $gump->rules(array('userInput' => array($_POST['regex'], '', $_POST['elementName'])));
         if (!$gump->run($_POST)) {
             die('wrongInput');
         } else {
             die('correctInput');
         }
     } catch (Exception $e) {
         die('somethingWentWrong' . $e->getMessage());
     }
 }
 /**
  * Function to create and return previously created instance
  *
  * @return GUMP
  */
 public static function get_instance()
 {
     if (self::$instance === null) {
         self::$instance = new self();
     }
     return self::$instance;
 }
 public function delete()
 {
     $options = WebApp::post('options') === NULL ? array() : strgetcsv(WebApp::post('options'));
     if (count($options) == 0) {
         return new ActionResult($this, '/admin/core/option_view', 0, 'No option(s) were selected!', B_T_FAIL);
     }
     foreach ($options as $option) {
         $validated = GUMP::is_valid(array('opt' => $option), array('opt' => 'integer'));
         if ($validated !== true) {
             return new ActionResult($this, '/admin/core/option_view', 0, 'No option(s) were selected!', B_T_FAIL);
         }
     }
     $delete = $this->mySQL_w->prepare("DELETE FROM `core_options` WHERE `id`=?");
     $affected_rows = 0;
     foreach ($options as $id) {
         $delete->bind_param('i', $id);
         $delete->execute();
         $delete->store_result();
         $affected_rows += $delete->affected_rows;
     }
     if ($affected_rows == count($options)) {
         $this->parent->parent->logEvent($this::name_space, 'Deleted options: ' . csvgetstr($options));
         return new ActionResult($this, '/admin/core/option_view', 1, 'Successfully deleted selected option(s)!', B_T_SUCCESS);
     } else {
         $this->parent->parent->logEvent($this::name_space, 'Deleted some options: ' . csvgetstr($options));
         return new ActionResult($this, '/admin/core/option_view', 1, 'Successfully deleted ' . $affected_rows . '/' . count($options) . ' selected option(s)!<br /><small>Possible cause: <code>Unknown</code></small>', B_T_WARNING);
     }
 }
 public function save()
 {
     GUMP::add_validator("unique", function ($field, $input, $param = NULL) {
         $checkExistingUser = R::findOne('user', 'user=?', array($input));
         if ($checkExistingUser == NULL) {
             return FALSE;
         } else {
             return TRUE;
         }
     });
     GUMP::add_validator("strong", function ($field, $input, $param = NULL) {
         return checkPasswordStrength($input);
     });
     $rules = array('reseller_username' => 'required|alpha_numeric|max_len,10|min_len,6|unique', 'reseller_password' => 'required|max_len,10|min_len,7|strong');
     $filters = array('reseller_username' => 'trim|sanitize_string', 'reseller_password' => 'trim|sanitize_string|md5');
     $app = Slim::getInstance();
     $post = $app->request()->post();
     // $app - Slim main app instance
     $postValues = $gump->filter($post, $filters);
     $validated = $gump->validate($gump->filter($postValues, $filters), $rules);
     if ($validated === TRUE) {
         $createUser = R::dispense('user');
         $createUser->user = $postValues['reseller_username'];
         $createUser->user = $postValues['reseller_password'];
     } else {
         $this->setError($gump->get_readable_errors(true));
     }
     if ($this->getError() == "") {
         $this->fails = FALSE;
     } else {
         $this->fails = TRUE;
     }
 }
Example #9
0
 public function register_post()
 {
     $gump = new GUMP();
     $form = $gump->sanitize($_POST);
     $gump->validation_rules(array("firstname" => "required|valid_name", "lastname" => "required|valid_name", "street" => "required|street_address", "zip" => "required|numeric,min_len=4", "city" => "required", "country" => "required", "email" => "required|valid_email", "password" => "required", "password_verify" => "required"));
     $validation = $gump->run($form);
     if ($validation === false) {
         $errors = $gump->errors();
         for ($i = 0; $i < count($errors); $i++) {
             $this->form[$errors[$i]["field"]]["error"] = true;
         }
     } else {
         if ($user = (new Login())->createLogin($form["email"], $form["password"], $form["company"], $form["firstname"], $form["lastname"], $form["street"], $form["zip"], $form["city"], $form["country"])) {
             $session = new \Base\Session();
             $session->set("user_id", $user->getId());
             (new Request())->redirect("dashboard");
         }
     }
     $this->assign("error_message", "E-Mail oder Passwort falsch.");
     $this->register();
 }
/**
 * 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;
    }
}
Example #11
0
 /**
  * Validates the input of the admin
  */
 protected function inputCheck()
 {
     require_once PATH_INCLUDE . '/gump.php';
     $gump = new \GUMP();
     try {
         $gump->rules($this->_changeRules);
         //Set none-filled-out formelements to be at least a void string,
         //for easier processing
         // $_POST = $gump->voidVarsToStringByRuleset(
         // 	$_POST, self::$registerRules);
         //validate the elements
         if (!$gump->run($_POST)) {
             die(json_encode(array('value' => 'error', 'message' => $gump->get_readable_string_errors(false))));
         }
     } catch (\Exception $e) {
         $this->_logger->log('error checking input', 'error', Null, json_encode(array('message' => $e->getMessage())));
         die(json_encode(array('value' => 'error', 'message' => array('Konnte die Eingaben nicht überprüfen!'))));
     }
     if (!empty($_POST['cardnumber'])) {
         $this->cardnumberDuplicatedCheck($_POST['cardnumber']);
     }
 }
 function get_menu_level()
 {
     // Do we need to check the wp_nonce??
     require_once CPT_PLUGIN_DIR . 'assets/php/gump/gump.class.php';
     // Let clean the data
     $gump = new GUMP();
     $sanitized_data = $gump->sanitize($_REQUEST);
     // printme($_GET);
     // Get the post_type
     $menu_slug = $sanitized_data['menu'];
     $menu_item_id = $sanitized_data['menu_item_id'];
     $menu_level = $sanitized_data['menu_level'];
     $taxonomy = 'hi_' . str_replace("-", "_", $menu_slug) . '_tax';
     // Because cpts cannot be more than 20 characters we need to filter for
     // these custom post types that have truncated names
     if ($menu_slug == "health-and-safety") {
         $cpt = new stdClass();
         $cpt->label = 'Health and Safety';
         $taxonomy = 'hi_health_safety_tax';
     } else {
         if ($menu_slug == "committee-services") {
             $cpt = new stdClass();
             $cpt->label = 'Committee Services';
             $taxonomy = 'hi_committee_service_tax';
         } else {
             $cpt = get_post_type_object('hi_' . str_replace("-", "_", $menu_slug));
         }
     }
     // depending on the value
     if ($menu_level == 'level_two') {
         wp_nav_menu(array('theme_location' => $menu_slug, 'depth' => 1, 'walker' => new Content_menu_walker(2, $menu_slug), 'container' => false, 'items_wrap' => '<h3>' . $cpt->label . '</h3><ul>%3$s</ul>'));
     } elseif ($menu_level == 'level_three') {
         $tax_slug = $sanitized_data['tax'];
         $term = get_term_by('slug', $tax_slug, $taxonomy);
         wp_nav_menu(array('theme_location' => $menu_slug, 'depth' => 1, 'level' => 2, 'child_of' => (int) $menu_item_id, 'walker' => new Content_menu_walker(3, $menu_slug), 'container' => false, 'items_wrap' => '<h3>' . $term->name . '</h3><ul>%3$s</ul>'));
     }
     die;
 }
Example #13
0
 public function addSub()
 {
     $gump = new GUMP();
     $gump->validation_rules(array('module' => 'required|integer|min_len,1', 'PID' => 'required|integer', 'parent' => 'required|integer'));
     $gump->filter_rules(array('module' => 'trim|whole_number', 'PID' => 'trim|whole_number', 'parent' => 'trim|whole_number'));
     $valid_data = $gump->run($_POST);
     if ($valid_data === false) {
         return new ActionResult($this, '/admin/core/menu_add', 0, 'Failed to add menu sub menu item.<br />Error: <code>Please check you have completed all fields as instructed.</code>', B_T_FAIL);
     }
     $max_query = $this->mySQL_r->query("SELECT MAX(`position`) FROM `core_menu`");
     $parent_query = $this->mySQL_r->prepare("SELECT `MID` FROM `core_menu` WHERE `MID`=?");
     if (!$parent_query) {
         return new ActionResult($this, '/admin/core/menu_add', 0, 'Failed to add sub menu item.<br/>Error: <code>Query to check parent item exists failed</code>', B_T_FAIL);
     }
     if (!$max_query) {
         return new ActionResult($this, '/admin/core/menu_add', 0, 'Failed to add sub menu item.<br/>Error: <code>Failed to get next free position</code>', B_T_FAIL);
     }
     $parent_query->bind_param('i', $valid_data['parent']);
     $parent_query->execute();
     $parent_query->store_result();
     if ($parent_query->num_rows != 1) {
         return new ActionResult($this, '/admin/core/menu_add', 0, 'Failed to add sub menu item.<br/>Error: <code>Failed to check parent exists</code>', B_T_FAIL);
     }
     $max = $max_query->fetch_row();
     $max = $max[0] + 1;
     $add_query = $this->mySQL_w->prepare("INSERT INTO `core_menu` (`position`, `parent`, `PID`, `dropdown`, `divider` ) VALUES (?, ?, ?, 0, 0)");
     if (!$add_query) {
         return new ActionResult($this, '/admin/core/menu_add', 0, 'Failed to add menu.<br/>Error: <code>Insert query failed</code>', B_T_FAIL);
     }
     $add_query->bind_param('iii', $max, $valid_data['parent'], $valid_data['PID']);
     $add_query->execute();
     if ($add_query->affected_rows == 1) {
         return new ActionResult($this, '/admin/core/menu_edit/' . $valid_data['parent'] . '/?tp=dropdown', 1, 'Succeesfully add sub menu item!', B_T_SUCCESS);
     } else {
         return new ActionResult($this, '/admin/core/menu_addsub/' . $valid_data['parent'], 0, 'Tried to add sub menu item, but failed!', B_T_FAIL);
     }
 }
Example #14
0
 public function save()
 {
     if (WebApp::post('mysql_r_pass') === '') {
         WebApp::post('mysql_r_pass', $this->parent->parent->config->config['mysql']['r']['pass']);
     }
     if (WebApp::post('mysql_w_pass') === '') {
         WebApp::post('mysql_r_pass', $this->parent->parent->config->config['mysql']['w']['pass']);
     }
     $gump = new GUMP();
     $gump->validation_rules(array('core_errors' => 'required|boolean', 'core_maintenance' => 'required|boolean', 'core_debug' => 'required|boolean', 'core_https_a' => 'required|boolean', 'core_https_f' => 'required|boolean', 'core_cdn' => 'required', 'mysql_db' => 'required', 'mysql_r_user' => 'required', 'mysql_r_host' => 'required', 'mysql_r_port' => 'required|integer', 'mysql_w_user' => 'required', 'mysql_w_host' => 'required', 'mysql_w_port' => 'required|integer', 'reCAPTCHA_pub' => 'required|alpha_dash', 'reCAPTCHA_priv' => 'required|alpha_dash'));
     $gump->filter_rules(array('core_cdn' => 'trim|urlencode'));
     $valid_data = $gump->run($_POST);
     if ($valid_data === false) {
         return new ActionResult($this, '/admin/core/config_edit', 0, 'Failed to save config!<br />Error: <code>Please check you have completed all fields as instructed.</code>', B_T_FAIL);
     }
     $configFile = fopen(__LIBDIR__ . '/config.inc.php', 'w');
     if (fwrite($configFile, $this->getFile($valid_data))) {
         fclose($configFile);
         return new ActionResult($this, '/admin/core/config_view', 1, 'Succeesfully saved config!', B_T_SUCCESS);
     } else {
         fclose($configFile);
         return new ActionResult($this, '/admin/core/config_edit', 0, 'Failed to save config!', B_T_SFAIL);
     }
 }
Example #15
0
 public static function validate($validation, $value, $type)
 {
     $rules = array('required');
     if (array_key_exists('email', $validation)) {
         array_push($rules, 'valid_email');
     }
     if (array_key_exists('starts', $validation)) {
         array_push($rules, 'starts,' . $validation['starts']);
     }
     if (array_key_exists('regex', $validation)) {
         $regex = is_array($validation['regex']) ? implode(',', $validation['regex']) : $validation['regex'];
         error_log($regex);
         error_log($value);
         if (!preg_match($regex, $value)) {
             return false;
         }
     }
     if ($type == 'string') {
         if (array_key_exists('maxLength', $validation)) {
             array_push($rules, 'max_len,' . $validation['maxLength']);
         }
         if (array_key_exists('minLength', $validation)) {
             if ($validation['minLength'] === 0 && strlen($value) == 0) {
                 return true;
             }
             array_push($rules, 'min_len,' . $validation['minLength']);
         }
     } else {
         if ($type == 'integer' || $type == 'timestamp') {
             if ($type == 'integer') {
                 array_push($rules, 'integer');
             }
             if (array_key_exists('min', $validation)) {
                 array_push($rules, 'min_numeric,' . $validation['min']);
             }
             if (array_key_exists('max', $validation)) {
                 array_push($rules, 'max_numeric,' . $validation['max']);
             }
         }
     }
     if (count($rules) == 1) {
         return true;
     }
     $valid = \GUMP::is_valid(array('temp' => $value), array('temp' => implode('|', $rules)));
     return $valid === true;
 }
 /**
  * @param array $params
  * @param array $files
  * @return array
  */
 public function run($params = array(), $files = array())
 {
     // Siga esse modelo para retornar erros
     $error = array("error" => false, "errorInfo" => "", "errorDesc" => "", "errorFields" => array());
     // Roda validação de campos simples
     foreach ($this->postRules as $field => $rule) {
         $data = array();
         $data[$field] = $rule;
         $validated = \GUMP::is_valid($params, $data);
         if ($validated !== true) {
             $error['errorFields'][] = $field;
         }
     }
     foreach ($this->fileRules as $field => $rule) {
         if (isset($files[$field]['name']) && !empty($files[$field]['name'])) {
             $storage = new FileSystem('public/uploads', BASEPATH);
             $file = new File($field, $storage);
             $file->setName(uniqid());
             $file->addValidations(array(new \Upload\Validation\Extension($rule['extension']), new \Upload\Validation\Size($rule['size'])));
             $name = $file->getNameWithExtension();
             try {
                 $file->upload();
                 $params[$field] = $name;
             } catch (\Exception $e) {
                 $error['errorFields'][] = $field;
             }
         } else {
             if (!isset($params[$field]) || empty($params[$field])) {
                 $error['errorFields'][] = $field;
             }
         }
     }
     if (!empty($error['errorFields'])) {
         $error['error'] = true;
         $error['errorInfo'] = "Erro ao salvar registro.";
         $error['errorDesc'] = "Preencha todos os campos corretamente";
         return array_merge_recursive($error, $params);
     } else {
         // Roda os tratamentos
         return $this->treatment($params, $files);
     }
 }
 public static function validate(\RedBeanPHP\OODBBean $bean)
 {
     $data = $bean->export();
     $model = $bean->box() !== null ? $bean->box() : null;
     if (!$model) {
         throw new ModelValidation_Exception('This bean does not have a model!');
     }
     $rules = isset($model::$rules) ? $model::$rules : null;
     if (!$rules) {
         throw new ModelValidation_Exception('This bean does not have any established rules!');
     }
     $validations = [];
     $filters = [];
     $labels = [];
     $messages = [];
     foreach ($rules as $field => $rule) {
         if (isset($rule['filter'])) {
             $filters[$field] = $rule['filter'];
         }
         if (isset($rule['label'])) {
             $labels[$field] = $rule['label'];
         }
         if (isset($rule['validation'])) {
             $validations[$field] = $rule['validation'];
         }
         if (isset($rule['message'])) {
             $field = isset($rule['label']) ? $rule['label'] : ucwords(str_replace(array('_', '-'), chr(32), $field));
             $messages[$field] = $rule['message'];
         }
     }
     $gump = new \GUMP();
     if (!empty($filters)) {
         $gump->filter_rules($filters);
     }
     if (!empty($validations)) {
         $gump->validation_rules($validations);
     }
     if (!empty($labels)) {
         $gump->set_field_names($labels);
     }
     $validated_data = $gump->run($data);
     if ($validated_data === false) {
         return self::default2custom_errors($gump->get_errors_array(), $messages);
     } else {
         $bean->import($validated_data);
         return true;
     }
 }
	/**
	 *
	 *	Processes the request from the user
	 *	The main engine of the class
	 *
	 * 	@param object $post WP_Post Object
	 * 	returns nothing
	 *
	 */

	function process_article()
	{
		require_once CPT_PLUGIN_DIR . 'assets/php/gump/gump.class.php';

		$gump = new GUMP();

		$_POST = $gump->sanitize($_POST); // You don't have to sanitize, but it's safest to do so.

		$gump->validation_rules(array(
		    'email'       => 'required|valid_email',
		));

		$gump->filter_rules(array(
		    'email'    => 'trim|sanitize_email',
		));

		$validated_data = $gump->run($_POST);

		if($validated_data === false) {
			$this->message_type = 'error';
		    $this->message = $gump->get_readable_errors(true);
		} else {

			// Get the article data
			$this->post = get_post($validated_data['post_id'], OBJECT, 'edit');

			//build the html
			$email_html = $this->build_html();

			// If article is sent
			if($this->send_email($validated_data['email']))
			{
				$this->message_type = 'success';
			    $this->message = 'The article link has been emailed';
			}
			else
			{
				$this->message_type = 'error';
			    $this->message = 'The article has not been sent. Please try again';
			}
		}

		// Finally send the response to user
		$this->response_message();

	}
Example #19
0
function sendMailchimp($formData, $config)
{
    $validated = GUMP::is_valid($formData, array('newsletter-name' => 'required', 'newsletter-email' => 'required|valid_email'));
    if ($validated === true) {
        $Mailchimp = new Mailchimp($config['mailchimp_api_key']);
        $Mailchimp_Lists = new Mailchimp_Lists($Mailchimp);
        $email = $formData['newsletter-email'];
        //replace with a test email
        $name = $formData['newsletter-name'];
        //replace with a test email
        try {
            $subscriber = $Mailchimp_Lists->subscribe($config['mailchimp_list_id'], array('email' => $email, 'name' => $name));
            //pass the list id and email to mailchimp
        } catch (Exception $e) {
            $result = array('result' => 'error', 'msg' => $e->getMessage());
            return json_encode($result);
        }
        // check that we've succeded
        if (!empty($subscriber['leid'])) {
            $result = array('result' => 'success', 'msg' => array('Success! Thank you for signing up to our newsletter.'));
            return json_encode($result);
        }
    } else {
        $result = array('result' => 'error', 'msg' => $validated);
        return json_encode($result);
    }
}
Example #20
0
 /**
  * Checks the Inputdata of the registerform for correct Format and stuff
  */
 protected function registerCheck()
 {
     require_once PATH_INCLUDE . '/gump.php';
     $gump = new GUMP();
     $_POST['isSoli'] = isset($_POST['isSoli']) && $_POST['isSoli'] == 'true';
     try {
         $gump->rules(self::$registerRules);
         // $_POST = $gump->input_preprocess_by_ruleset($_POST,
         // self::$registerRules);
         //Set none-filled-out formelements to be at least a void string,
         //for easier processing
         $gump->voidVarsToStringByRuleset($_POST, self::$registerRules);
         //validate and MySQL-Escape the elements
         if ($gump->run($_POST)) {
         } else {
             die(json_encode(array('value' => 'inputError', 'message' => $gump->get_readable_string_errors(false))));
         }
     } catch (Exception $e) {
         die(json_encode(array('value' => 'inputError', 'message' => array('Konnte die Eingaben nicht überprüfen!'))));
     }
     if (!empty($_POST['cardnumber'])) {
         $this->cardnumberDuplicatedCheck($_POST['cardnumber']);
     }
 }
Example #21
0
<?php

include_once 'inc/class.simple_mail.php';
include_once 'inc/gump.class.php';
include_once 'mail-config.php';
// Check Data
$isValid = GUMP::is_valid($_POST, array('first-name' => 'required', 'phone-number' => 'required', 'guest-email' => 'required', 'message' => 'required', 'point-where' => 'required'));
if ($isValid === true) {
    // Submit Mail
    $mail = new SimpleMail();
    $mail->setTo(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)->setSubject('Новий клієнт')->setFrom(htmlspecialchars("*****@*****.**"), htmlspecialchars("company-mail"))->addGenericHeader('X-Mailer', 'PHP/' . phpversion())->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')->setMessage(createMessage($_POST))->setWrap(300);
    $mail->send();
    $result = array('result' => 'success', 'msg' => array('Success! Your contact request has been send.'));
    echo json_encode($result);
    return json_encode($result);
} else {
    $result = array('result' => 'error', 'msg' => $isValid);
    echo json_encode($result);
    return json_encode($result);
}
function createMessage($formData)
{
    $body = "У вас новий клієнт : <br><br>";
    $body .= "Ім'я:  " . htmlspecialchars($formData['first-name']) . " <br><br>";
    $body .= "Телефон:  " . htmlspecialchars($formData['phone-number']) . " <br><br>";
    $body .= "Пошта:  " . htmlspecialchars($formData['guest-email']) . " <br><br>";
    $body .= "Повідомлення:  " . htmlspecialchars($formData['message']) . " <br><br>";
    $body .= "Звідки прийшов:  " . htmlspecialchars($formData['point-where']) . " <br><br>";
    return $body;
}
Example #22
0
<?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";
Example #23
0
    # Not logged in
    case !is_loggedin():
        JSON::parse(100, 'negative', '<i class="fa fa-exclamation-triangle"></i> Access denied: you\'re not 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 saving your changes. (Error: No data received)', null, true);
        break;
}
# Saved Posts
$saved = 0;
# Unsaved
$unsaved = 0;
# New GUMP Object
$form = new GUMP();
# Get Input
$data = form_data();
# Run GUMP
$response = $form->run($data);
# Get Response
if ($response === false) {
    JSON::parse(100, 'negative', $form->get_readable_errors(true));
} else {
    # Loop through each of the submitted fields and
    # if a an html file exists, then we will update
    # the file with the newly uploaded content.
    foreach ($data['data'] as $field) {
        # Set Filename
        $filename = ROOT_DIR . '/' . PUBLIC_ROOT . '/content/field-' . $field['ID'] . '.html';
        # Check for file
Example #24
0
function diy_diyexec($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    $params = loadParameters();
    $device = OAuth2\Request::createFromGlobals()->request["device"];
    $exec = OAuth2\Request::createFromGlobals()->request["exec"];
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $diy_error["post"]["device"] = $device;
    $post["device"] = $device;
    //organisation                                  oauth_devices
    $post["exec"] = $exec;
    //organisation                                  oauth_devices
    $gump = new GUMP();
    $gump->validation_rules(array('device' => 'required|alpha_numeric', 'exec' => 'required|alpha_numeric'));
    $gump->filter_rules(array('device' => 'trim|sanitize_string', 'exec' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        try {
            $stmt2 = $storage->prepare('SELECT * FROM oauth_devices WHERE device = :device');
            $stmt2->execute(array('device' => trim($device)));
            $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
            if ($row2["organisation"]) {
                $org = trim($row2["organisation"]);
            }
            if ($row2["mode"]) {
                $mode = trim($row2["mode"]);
            }
            if ($row2["status"]) {
                $status = trim($row2["status"]);
            }
            if ($row2["client_id"]) {
                $devclient_id = trim($row2["client_id"]);
            }
            $orgscopeadmin = "no";
            $orgscopedevel = "no";
            if ($status == "org") {
                $userscopes = explode(' ', trim($userscope));
                $adminscope = $org . "_admin";
                $develscope = $org . "_admin";
                // o user aniki sto scope
                for ($i = 0; $i <= count($userscopes); $i++) {
                    if (trim($userscopes[$i]) == $adminscope) {
                        $orgscopeadmin = "yes";
                    }
                    if (trim($userscopes[$i]) == $develscope) {
                        $orgscopedevel = "yes";
                    }
                }
                // einai o owner
                if ($devclient_id == $client_id) {
                    $orgscopeadmin = "yes";
                }
            }
            // einmai o owner
            if ($status == "private" && $devclient_id == $client_id) {
                $orgscopeadmin = "yes";
            }
            if ($orgscopeadmin == "yes" || $orgscopedevel == "yes") {
                try {
                    $stmt2 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :device');
                    $stmt2->execute(array('device' => trim($device)));
                    $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
                    if ($row2["apiport"]) {
                        $stmt3 = $storage->prepare('SELECT * FROM oauth_diyexec WHERE exec = :exec');
                        $stmt3->execute(array('exec' => trim($exec)));
                        $row3 = $stmt3->fetch(PDO::FETCH_ASSOC);
                        if ($row3["exec"]) {
                            $apiport = trim($row2["apiport"]);
                            $diyexec = trim($row3["diyexec"]);
                            $diyexecurl = base64_encode($diyexec);
                            $data1 = 'exec=' . $diyexecurl;
                            //$result["result1"]=  $diyexec;
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:{$apiport}/api/diyexec");
                            curl_setopt($ch, CURLOPT_TIMEOUT, 20);
                            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $data1);
                            curl_setopt($ch, CURLOPT_POST, 1);
                            $r = curl_exec($ch);
                            var_dump($r);
                            $result["DEV"] = $r;
                        }
                    }
                } catch (Exception $e) {
                    $diy_error["db"] = $e->getCode();
                    $result["status"] = $e->getCode();
                    $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
                }
            }
        } catch (Exception $e) {
            $diy_error["db"] = $e->getCode();
            $result["status"] = $e->getCode();
            $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Example #25
0
 public function validate($data = null)
 {
     $gump = new \GUMP();
     $gump->validation_rules(['page' => 'required', 'email' => 'required', 'name' => 'required', 'phone' => 'required', 'city_id' => 'required', 'state_id' => 'required', 'message' => 'required', 'destination' => 'required']);
     return $gump->run($data);
 }
Example #26
0
#!/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());
}
Example #27
0
<?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');
$validated = $validator->validate($_POST, $rules);
if ($validated === TRUE) {
    die("true");
} else {
    die("false");
}
Example #28
0
function diy_removedevice($payload, $storage)
{
    global $app;
    $result["controller"] = __FUNCTION__;
    $result["function"] = substr($app->request()->getPathInfo(), 1);
    $result["method"] = $app->request()->getMethod();
    $params = loadParameters();
    $result->function = substr($app->request()->getPathInfo(), 1);
    $result->method = $app->request()->getMethod();
    //$params = loadParameters();
    $up = json_decode(base64_decode($payload));
    $client_id = $up->client_id;
    $userscope = $up->scope;
    $device = OAuth2\Request::createFromGlobals()->query["device"];
    $diy_error["post"]["device"] = $device;
    $post["device"] = $device;
    // to client_id tou device			oauth_devices	oauth_clients	oauth_public_keys
    //$result["result"]["up"] =  $up;
    $gump = new GUMP();
    $gump->validation_rules(array('device' => 'required|alpha_numeric'));
    $gump->filter_rules(array('device' => 'trim|sanitize_string'));
    $validated = $gump->run($post);
    if ($validated === false) {
        $result["parse_errors"] = $gump->get_readable_errors(true);
        $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $gump->get_readable_errors(true);
    } else {
        $dev = $storage->prepare('SELECT * FROM oauth_devices WHERE device  = :device');
        $dev->execute(array('device' => trim($device)));
        $rowdev = $dev->fetch(PDO::FETCH_ASSOC);
        if ($rowdev) {
            $org = $rowdev["organisation"];
        } else {
            $result["result"]["error"] = ExceptionMessages::DeviceNotExist . " , " . ExceptionCodes::DeviceNotExist;
        }
        //check if org name exists
        $orgexists = "no";
        $stmtorg = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org');
        $stmtorg->execute(array('org' => trim($org)));
        $roworg = $stmtorg->fetch(PDO::FETCH_ASSOC);
        if ($roworg) {
            $orgexists = "yes";
            //$result["result"]["error"] =  ExceptionMessages::OrgExist." , ". ExceptionCodes::OrgExist;
            $orgadmin = "no";
            $orgowner = "no";
            $userscopes = explode(' ', trim($userscope));
            $orgscope = $org . "_admin";
            for ($i = 0; $i <= count($userscopes); $i++) {
                if (trim($userscopes[$i]) == $orgscope) {
                    $orgadmin = "yes";
                }
            }
            if ($orgadmin == "no") {
                //check if org name exists and client_id
                $stmtorg1 = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org and client_id = :client_id');
                $stmtorg1->execute(array('org' => trim($org), 'client_id' => $client_id));
                $roworg1 = $stmtorg1->fetch(PDO::FETCH_ASSOC);
                if (!$roworg1) {
                    $result["result"]["error"] = ExceptionMessages::OrgOwner . " , " . ExceptionCodes::OrgOwner;
                } else {
                    $orgowner = "yes";
                }
            }
        } else {
            $result["result"]["error"] = ExceptionMessages::OrgNotExist . " , " . ExceptionCodes::OrgNotExist;
        }
        //check if device name exists
        $orgdeviceexists = "no";
        $stmt = $storage->prepare('SELECT client_id  FROM oauth_clients WHERE client_id = :device');
        $stmt->execute(array('device' => trim($device)));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            //$result["result"]["error"] =  ExceptionMessages::DeviceExist." , ". ExceptionCodes::DeviceExist;
            $orgdeviceexists = "yes";
        } else {
            $result["result"]["error"] = ExceptionMessages::DeviceNotExist . " , " . ExceptionCodes::DeviceNotExist;
            $orgdeviceexists = "no";
        }
        if ($orgexists == "yes" && ($orgowner == "yes" || $orgadmin == "yes") && $orgdeviceexists == "yes") {
            //}else{
            try {
                // oauth_public_keys table
                $encryption_algorithm = "RS256";
                $stmt5 = $storage->prepare('DELETE from oauth_public_keys where client_id = :client_id');
                $stmt5->execute(array('client_id' => $device));
                $stmt1 = $storage->prepare('SELECT * from oauth_clients where client_id = :client_id');
                $stmt1->execute(array('client_id' => $device));
                $row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
                if ($row1) {
                    $dataport = $row1["dataport"];
                    $apiport = $row1["apiport"];
                    // oauth_users table
                    $user_id = $row1["user_id"];
                    $stmt = $storage->prepare('DELETE from oauth_users where user_id = :user_id');
                    $stmt->execute(array('user_id' => $user_id));
                    // oauth_ports table
                    $stmt2 = $storage->prepare('DELETE from oauth_ports where port = :port');
                    $stmt2->execute(array('port' => $dataport));
                    $stmt2 = $storage->prepare('DELETE from oauth_ports where port = :port');
                    $stmt2->execute(array('port' => $apiport));
                    // oauth_clients table
                    $stmt1 = $storage->prepare('DELETE from oauth_clients where client_id = :client_id');
                    $stmt1->execute(array('client_id' => $device));
                    // oauth_devices table
                    $stmt11 = $storage->prepare('DELETE from oauth_devices where device = :device');
                    $stmt11->execute(array('device' => $device));
                }
                //result_messages===============================================================
                $result["result"]["result"] = $post;
                $result["result"]["session"] = $session;
                $result["error"] = $error;
                $result["status"] = "200";
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]: NoErrors";
            } catch (Exception $e) {
                $result["status"] = $e->getCode();
                $result["message"] = "[" . $result["method"] . "][" . $result["function"] . "]:" . $e->getMessage();
            }
        }
    }
    if (diyConfig::read('debug') == 1) {
        $result["debug"] = $diy_error;
    }
    return $result;
}
Example #29
0
<?php

include_once 'inc/class.simple_mail.php';
include_once 'inc/gump.class.php';
include_once 'mail-config.php';
// Check Data
$isValid = GUMP::is_valid($_POST, array('first-name' => 'required', 'last-name' => 'required', 'phone-number' => 'required', 'email-address' => 'required|valid_email', 'address' => 'required', 'city' => 'required', 'zip-code' => 'required'));
if ($isValid === true) {
    // Submit Mail
    $mail = new SimpleMail();
    $mail->setTo(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)->setSubject('New car rental request')->setFrom(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'] . ' ' . $_POST['last-name']))->addGenericHeader('X-Mailer', 'PHP/' . phpversion())->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')->setMessage(createMessage($_POST))->setWrap(100);
    $mail->send();
    // Submit Client Mail
    $mailClient = new SimpleMail();
    $mailClient->setTo(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'] . ' ' . $_POST['last-name']))->setSubject('Youre car rental request at ' . YOUR_COMPANY_NAME)->setFrom(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)->addGenericHeader('X-Mailer', 'PHP/' . phpversion())->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')->setMessage(createClientMessage($_POST))->setWrap(100);
    $mailClient->send();
    $result = array('result' => 'success', 'msg' => array('Success! Your contact request has been send.'));
    echo json_encode($result);
} else {
    $result = array('result' => 'error', 'msg' => $isValid);
    echo json_encode($result);
}
function createMessage($formData)
{
    $body = "You have got a new car rental request from your website : <br><br>";
    $body .= "--------------------------------------------------------------------------------- <br><br>";
    $body .= "<strong>Selected Car:</strong>  " . htmlspecialchars($formData['selected-car']) . " <br><br>";
    $body .= "--------------------------------------------------------------------------------- <br><br>";
    $body .= "<strong>Pick-Up Date/Time:</strong><br>";
    $body .= htmlspecialchars($formData['pick-up']) . " <br>";
    $body .= htmlspecialchars($formData['pickup-location']) . " <br><br>";
<?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');
$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));
}