Process the validation errors and return human readable error messages.
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; }
function _parseParameters($parameters, $validationRules, $filterRules) { $gump = new \GUMP(); $parameters = $gump->sanitize($parameters); $parameters = $gump->run($parameters); if ($parameters === false) { global $debugLevel; if ($debugLevel >= DEBUG) { echo $gump->get_readable_errors(true); } $parameters = array(); } return $parameters; }
/** * * 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(); }
function diy_adddevice($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; $org = OAuth2\Request::createFromGlobals()->request["org"]; $device = OAuth2\Request::createFromGlobals()->request["device"]; $client_secret = OAuth2\Request::createFromGlobals()->request["passwd"]; $device_desc = OAuth2\Request::createFromGlobals()->request["device_desc"]; $diy_error["post"]["org"] = $org; $diy_error["post"]["device"] = $device; $diy_error["post"]["client_secret"] = $client_secret; $diy_error["post"]["device_desc"] = $device_desc; $post["org"] = $org; //organisation oauth_devices $post["device"] = $device; // to client_id tou device oauth_devices oauth_clients oauth_public_keys $post["client_secret"] = $client_secret; //mia perigrafi oti thelei o christis oauth_devices $post["device_desc"] = $device_desc; //mia perigrafi oti thelei o christis oauth_devices //$result["result"]["up"] = $up; $gump = new GUMP(); $gump->validation_rules(array('org' => 'required|alpha_numeric', 'device' => 'required|alpha_numeric', 'client_secret' => 'required|max_len,100|min_len,6', 'device_desc' => 'required|max_len,100')); $gump->filter_rules(array('org' => 'trim|sanitize_string', 'device' => 'trim|sanitize_string', 'client_secret' => 'trim', 'device_desc' => '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 { //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"; } if ($orgexists == "yes" && ($orgowner == "yes" || $orgadmin == "yes") && $orgdeviceexists == "no") { //}else{ try { $tempfile = tempnam('tmp/', ''); if (file_exists($tempfile)) { unlink($tempfile); } mkdir($tempfile); if (is_dir($tempfile)) { exec("openssl genrsa -out {$tempfile}/{$client_id}-privkey.pem 2048"); exec("openssl rsa -in {$tempfile}/{$client_id}-privkey.pem -pubout -out {$tempfile}/{$client_id}-pubkey.pem"); $publicKey = file_get_contents("{$tempfile}/{$client_id}-pubkey.pem"); $privateKey = file_get_contents("{$tempfile}/{$client_id}-privkey.pem"); // oauth_public_keys table $encryption_algorithm = "RS256"; $stmt5 = $storage->prepare('INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES (:client_id, :public_key, :private_key, :encryption_algorithm)'); $stmt5->execute(array('client_id' => $device, 'public_key' => $publicKey, 'private_key' => $privateKey, ':encryption_algorithm' => $encryption_algorithm)); unlink("{$tempfile}/{$client_id}-pubkey.pem"); unlink("{$tempfile}/{$client_id}-privkey.pem"); // na ftiaxo to key me tis portes na einai etoimo // tha to kano messo cron // o pinakas ta echei ola oauth_clients } // user_id for dev $lastkey = $storage->query('SELECT user_id FROM oauth_users ORDER BY user_id DESC LIMIT 1'); foreach ($lastkey as $curRow) { $lastkey = intval($curRow[0]); } $lastkey++; // oauth_users table $stmt = $storage->prepare('INSERT INTO oauth_users (user_id,email_verified) VALUES (:user_id,"1")'); $stmt->execute(array('user_id' => $lastkey)); $scope = $org . "_dev"; $scope .= ' ' . $org . "_dpri"; $apiport = $storage->query('SELECT apiport FROM oauth_clients ORDER BY apiport DESC LIMIT 1'); foreach ($apiport as $curRow) { $apiport = intval($curRow[0]); } $dataport = $apiport + 1; $apiport = $apiport + 2; $apihost = diyConfig::read('api.host'); $sshhost = diyConfig::read('ssh.host'); $sshport = diyConfig::read('ssh.port'); // oauth_ports table $stmt2 = $storage->prepare('INSERT INTO oauth_ports (port, client_id) VALUES (:port, :client_id)'); $stmt2->execute(array('client_id' => $device, 'port' => $dataport)); $stmt2 = $storage->prepare('INSERT INTO oauth_ports (port, client_id) VALUES (:port, :client_id)'); $stmt2->execute(array('client_id' => $device, 'port' => $apiport)); // oauth_clients table $tty = "/dev/ttyACM0"; $baud = "115200"; $stmt1 = $storage->prepare('INSERT INTO oauth_clients (client_id, client_secret, user_id, scope, dataport, apiport, apihost, sshhost, sshport, tty, baud) VALUES (:client_id, :client_secret, :user_id, :scope, :dataport, :apiport, :apihost, :sshhost, :sshport, :tty, :baud)'); $stmt1->execute(array('user_id' => $lastkey, 'client_id' => $device, 'client_secret' => $client_secret, 'scope' => $scope, 'dataport' => $dataport, 'apiport' => $apiport, 'apihost' => $apihost, 'sshhost' => $sshhost, 'sshport' => $sshport, 'tty' => $tty, 'baud' => $baud)); // oauth_devices table $public_key_active = "yes"; $status = "private"; $mode = "devel"; $stmt11 = $storage->prepare('INSERT INTO oauth_devices (device, device_desc, organisation, client_id, public_key_active, status, mode) VALUES (:device, :device_desc, :organisation, :client_id, :public_key_active, :status, :mode)'); $stmt11->execute(array('device' => $device, 'client_id' => $client_id, 'device_desc' => $device_desc, 'organisation' => $org, 'public_key_active' => $public_key_active, 'status' => $status, 'mode' => $mode)); $post["status"] = $status; $post["mode"] = $mode; //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; }
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; } }
function activity_form($activity_id = 0) { global $mysqli; global $backend; if ($activity_id) { $activity = new Activity($activity_id); $form_type = 'update'; } else { $activity = new Activity(); $form_type = 'insert'; } $html = ''; $fields = array('title' => array('var' => 'title', 'label' => 'Activity Title', 'desc' => 'Required. This is the public title of the activity. You may change this later.', 'type' => 'text', 'std' => $activity->title, 'validate' => 'required', 'filter' => 'trim|sanitize_string', 'param' => 's'), 'folder' => array('var' => 'folder', 'label' => 'Activity folder', 'desc' => 'Required. Name of the folder to create on the ASHP server. Just enter the name of the folder <strong>without any slashes</strong>.', 'type' => 'text', 'std' => $activity->folder, 'validate' => 'required|alpha_dash', 'filter' => 'trim|sanitize_string', 'param' => 's'), 'url' => array('var' => 'url', 'label' => 'Live Activity URL', 'desc' => 'The full URL of the activity, including <strong>http://</strong><br />You can leave blank to default to http://ashpadvantagemedia.com/ActivityFolder.<br /><span class="text-danger">Remember to use <strong>http://www.ashpadvantagemedia.com</strong> instead of <strong>http://www.ashpadvantage.com</strong>.</span>', 'type' => 'text', 'std' => $activity->url, 'validate' => 'valid_url', 'filter' => 'trim|sanitize_string', 'param' => 's'), 'sponsor' => array('var' => 'sponsor', 'label' => 'Activity Sponsor', 'desc' => 'The sponsor of the activity.', 'type' => 'text', 'std' => $activity->sponsor, 'validate' => '', 'filter' => 'trim|sanitize_string', 'param' => 's'), 'type_id' => array('var' => 'type_id', 'label' => 'Activity Type', 'desc' => 'Select the type of activity.', 'type' => 'select', 'options' => $backend->activity_types, 'std' => $activity->type_id, 'validate' => 'required', 'filter' => 'trim|sanitize_string', 'param' => 'i'), 'live_website' => array('var' => 'live_website', 'label' => 'Live Website Template', 'desc' => 'Choose which template to display on the live site..', 'type' => 'select', 'options' => $backend->website_types, 'std' => $activity->live_website, 'validate' => 'required', 'filter' => 'trim|sanitize_string', 'param' => 's'), 'has_live' => array('var' => 'has_live', 'label' => 'Has Live Component', 'desc' => 'Select the live component this activity has.', 'type' => 'radio', 'options' => array('none', 'webcast', 'webinar'), 'std' => $activity->has_live, 'validate' => 'required', 'filter' => 'trim|sanitize_string', 'param' => 's'), 'director_id' => array('var' => 'director_id', 'label' => 'Scientific Project Director', 'desc' => '', 'type' => 'select', 'options' => $backend->directors, 'std' => $activity->director_id, 'validate' => 'required', 'filter' => 'trim|sanitize_string', 'param' => 'i'), 'manager_id' => array('var' => 'manager_id', 'label' => 'Project Manager', 'desc' => '', 'type' => 'select', 'options' => $backend->managers, 'std' => $activity->manager_id, 'validate' => 'required', 'filter' => 'trim|sanitize_string', 'param' => 'i'), 'vendor_id' => array('var' => 'vendor_id', 'label' => 'Web Vendor', 'desc' => '', 'type' => 'select', 'options' => $backend->vendors, 'std' => $activity->vendor_id, 'validate' => 'required', 'filter' => 'trim|sanitize_string', 'param' => 'i')); if (isset($_POST['submit'])) { $gump = new GUMP(); foreach ($_POST['form'] as $k => $v) { //update the std value for form output below $fields[$k]['std'] = $v; if (!empty($fields[$k]['validate'])) { $validate[$k] = $fields[$k]['validate']; } if (!empty($fields[$k]['filter'])) { $filter[$k] = $fields[$k]['filter']; } } $error_text = ''; $gump->validation_rules($validate); $gump->filter_rules($filter); $validated_data = $gump->run($_POST['form']); if ($form_type == 'insert' && activity_folder_exists($validated_data['folder'])) { $validated_data = false; $error_text .= 'Folder already exists. Please choose another folder name.<br />'; } if ($validated_data === false) { $errors = $gump->get_readable_errors(false); foreach ($errors as $error) { $error_text .= $error . '<br />'; } echo edgimo_error($error_text); } else { if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit; } if ($validated_data['url'] == '') { $validated_data['url'] = 'http://ashpadvantagemedia.com/' . $validated_data['folder']; } if ($form_type == 'update') { $query = $mysqli->prepare("UPDATE ashp_activities SET title=?, url=?, folder=?, sponsor=?, type_id=?, director_id=?, manager_id=?, vendor_id=?, live_website=?, has_live=? WHERE activity_id=?"); $query->bind_param('ssssiiiiiss', $validated_data['title'], $validated_data['url'], $validated_data['folder'], $validated_data['sponsor'], $validated_data['type_id'], $validated_data['director_id'], $validated_data['manager_id'], $validated_data['vendor_id'], $validated_data['live_website'], $validated_data['has_live'], $activity_id); echo edgimo_success('Activity details have been updated.'); $query->execute(); $query->close(); echo '<script>edgimo_redirect("edit.php?table=ashp_activities&id=' . $activity_id . '");</script>'; } if ($form_type == 'insert') { $query = $mysqli->prepare("INSERT INTO ashp_activities (title, url, folder, sponsor, type_id, director_id, manager_id, vendor_id, live_website, has_live) VALUES (?,?,?,?,?,?,?,?,?,?)"); $query->bind_param('ssssiiiiss', $validated_data['title'], $validated_data['url'], $validated_data['folder'], $validated_data['sponsor'], $validated_data['type_id'], $validated_data['director_id'], $validated_data['manager_id'], $validated_data['vendor_id'], $validated_data['live_website'], $validated_data['has_live']); $query->execute(); $query->close(); $activity_id = $mysqli->query("SELECT activity_id FROM ashp_activities WHERE title = '{$validated_data['title']}'"); $vars = $activity_id->fetch_array(MYSQLI_ASSOC); $activity_id = $vars['activity_id']; $insert_fields = array_merge($backend->get_fields(0, $validated_data['has_live']), $backend->get_fields($validated_data['type_id'], $validated_data['has_live'])); foreach ($insert_fields as $field) { if (strstr($field['copy'], '{{LIVE_OPTIONS}}')) { $field['copy'] = live_options_replace($field['copy'], $validated_data['has_live']); } $query = $mysqli->prepare("INSERT INTO ashp_activity_content (activity_id, field_id, heading, copy, field_type, hook_name) VALUES (?,?,?,?,?,?)"); $query->bind_param('iissss', $activity_id, $field['field_id'], $field['heading'], $field['copy'], $field['field_type'], $field['hook_name']); $query->execute(); $query->close(); } create_site($validated_data['folder'], $activity_id); echo edgimo_success('New activity created.'); echo '<script>edgimo_redirect("edit.php?table=ashp_activities&id=' . $activity_id . '");</script>'; } } } $html .= '<form class="form-horizontal" role="form" method="post">'; foreach ($fields as $field) { isset($errors) && array_key_exists($field['var'], $errors) ? $error = 'has-error' : ($error = ''); $html .= '<div class="form-group ' . $error . '">'; switch ($field['type']) { case 'text': if (!isset($type)) { $type = 'text'; } $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <input class="form-control" type="' . $type . '" name="form[' . $field['var'] . ']" value="' . $field['std'] . '"> </div>'; break; case 'select': $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <select class="form-control" name="form[' . $field['var'] . ']">'; foreach ($field['options'] as $option) { $field['std'] == $option[0] ? $selected = 'selected' : ($selected = ''); $html .= '<option ' . $selected . ' value="' . $option[0] . '">' . $option[1] . '</option>'; } $html .= '</select> </div>'; break; case 'radio': $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> '; foreach ($field['options'] as $option) { $field['std'] == $option ? $checked = 'checked' : ($checked = ''); $html .= ' <div class="radio-inline"> <label> <input type="radio" name="form[' . $field['var'] . ']" value="' . $option . '" ' . $checked . '> ' . ucfirst($option) . ' </label> </div>'; } $html .= ' </div>'; break; } $html .= ' <div class="col-lg-4"> <p class="description">' . $field['desc'] . '</p> </div> </div>'; } $html .= ' <hr> <div class="form-group"> <div class="col-lg-6 col-lg-offset-2"> <button type="submit" class="btn btn-primary" name="submit">Submit</button> </div> </div> </form> '; return $html; }
function user_form($user_id = 0) { global $mysqli; global $user; if ($user_id) { $form_user = new User(get_user_email_by_id($user_id)); $form_type = 'update'; if ($form_user->email != $_SESSION['email'] && !$user->is_allowed('edit_ashp_users')) { echo edgimo_error('Your user role (' . $user->role . ') is not allowed to make edits on this page.'); return; } } else { if (!$user->is_allowed('add_user')) { echo edgimo_error('Your user role (' . $user->role . ') is not allowed to add users.'); return; } $form_user = new User(); $form_type = 'insert'; } $html = ''; $fields = array('first_name' => array('var' => 'first_name', 'label' => 'First Name', 'type' => 'text', 'std' => $form_user->first_name, 'validate' => 'required|valid_name', 'filter' => 'trim|sanitize_string', 'param' => 's', 'desc' => ''), 'last_name' => array('var' => 'last_name', 'label' => 'Last Name', 'type' => 'text', 'std' => $form_user->last_name, 'validate' => 'required|valid_name', 'filter' => 'trim|sanitize_string', 'param' => 's', 'desc' => ''), 'email' => array('var' => 'email', 'label' => 'Email', 'type' => 'text', 'std' => $form_user->email, 'validate' => 'required|valid_email', 'filter' => 'trim|sanitize_string', 'param' => 's', 'desc' => ''), 'password' => array('var' => 'password', 'label' => 'Password', 'type' => 'password', 'std' => '', 'validate' => 'required', 'filter' => '', 'param' => 's', 'desc' => '')); if ($user->is_allowed('change_roles')) { $fields['role'] = array('var' => 'role', 'label' => 'Role', 'type' => 'select', 'options' => unserialize(ROLES), 'std' => $form_user->role, 'validate' => 'required', 'filter' => 'trim|sanitize_string', 'param' => 's', 'desc' => ''); } //special instructions for updating password if ($form_type == 'update') { $fields['password']['desc'] = 'Only enter a new password here if you wish to update the existing password'; } if (isset($_POST['submit'])) { $gump = new GUMP(); //password can be left blank when updating account. If it is, just plug in the saved value if ($form_type == 'update') { if ($_POST['form']['password'] === '') { $_POST['form']['password'] = $form_user->password; } } //add values to the validate and filter gump arrays foreach ($_POST['form'] as $k => $v) { //update the std value for form output below $fields[$k]['std'] = $v; if (!empty($fields[$k]['validate'])) { $validate[$k] = $fields[$k]['validate']; } if (!empty($fields[$k]['filter'])) { $filter[$k] = $fields[$k]['filter']; } } //run gump $gump->validation_rules($validate); $gump->filter_rules($filter); //get validated data $validated_data = $gump->run($_POST['form']); if (empty($validated_data['role'])) { $validated_data['role'] = $form_user->role; } if ($validated_data === false) { $errors = $gump->get_readable_errors(false); $error_text = ''; foreach ($errors as $error) { $error_text .= $error . '<br />'; } echo edgimo_error($error_text); } else { if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit; } if ($form_type == 'update') { $query = $mysqli->prepare("UPDATE ashp_users SET first_name=?, last_name=?, email=?, role=?, password=? WHERE user_id=?"); $password = sha1($validated_data['password']); $query->bind_param('sssssi', $validated_data['first_name'], $validated_data['last_name'], $validated_data['email'], $validated_data['role'], $password, $form_user->user_id); echo edgimo_success('Account details have been updated.'); } if ($form_type == 'insert') { $query = $mysqli->prepare("INSERT INTO ashp_users (email, first_name, last_name, password, role, status) VALUES (?,?,?,?,?,?)"); $password = sha1($validated_data['password']); $status = 'active'; $query->bind_param('ssssss', $validated_data['email'], $validated_data['first_name'], $validated_data['last_name'], $password, $validated_data['role'], $status); echo edgimo_success('New user created.'); } $query->execute(); $query->close(); $new_user = new User($validated_data['email']); $user_vars = get_object_vars($new_user); echo '<script>table_insert(' . json_encode($user_vars) . ');</script>'; } } $html .= '<form class="form-horizontal" role="form" method="post">'; foreach ($fields as $field) { isset($errors) && array_key_exists($field['var'], $errors) ? $error = 'has-error' : ($error = ''); $html .= '<div class="form-group ' . $error . '">'; switch ($field['type']) { case 'password': $type = 'password'; $field['std'] = ''; case 'text': if (!isset($type)) { $type = 'text'; } $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <input class="form-control" type="' . $type . '" name="form[' . $field['var'] . ']" value="' . $field['std'] . '"> </div>'; break; case 'select': $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <select class="form-control" name="form[' . $field['var'] . ']">'; foreach ($field['options'] as $option) { $field['std'] == $option ? $selected = 'selected' : ($selected = ''); $html .= '<option ' . $selected . ' value="' . $option . '">' . $option . '</option>'; } $html .= '</select> </div>'; break; } $html .= ' <div class="col-lg-4"> <p class="description">' . $field['desc'] . '</p> </div> </div>'; } $html .= ' <div class="form-group"> <div class="col-lg-6 col-lg-offset-2"> <button type="submit" class="btn btn-primary" name="submit">Submit</button> </div> </div> </form> '; return $html; }
function diy_addorg($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; $org = OAuth2\Request::createFromGlobals()->request["org"]; $org_desc = OAuth2\Request::createFromGlobals()->request["org_desc"]; $diy_error["post"]["org"] = $org; $diy_error["post"]["org_desc"] = $org_desc; $post["org"] = $org; //organisation oauth_devices $post["org_desc"] = $org_desc; //mia perigrafi oti thelei o christis oauth_devices $gump = new GUMP(); $gump->validation_rules(array('org' => 'required|alpha_numeric', 'org_desc' => 'required|max_len,100')); $gump->filter_rules(array('org' => 'trim|sanitize_string', 'org_desc' => '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 { //check if device name exists $stmt = $storage->prepare('SELECT * FROM oauth_organisations WHERE organisation = :org'); $stmt->execute(array('org' => trim($org))); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ($row) { $result["result"]["error"] = ExceptionMessages::OrgExist . " , " . ExceptionCodes::OrgExist; } else { try { // oauth_organisation table $stmt2 = $storage->prepare('INSERT INTO oauth_organisations (organisation, client_id, desc) VALUES (:org, :client_id, :desc)'); $stmt2->execute(array('client_id' => $client_id, 'org' => $org, 'desc' => $org_desc)); // scopes gia devices $scope = $org; $is_default = 0; $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)'); $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default)); $scope = $org . "_dev"; $is_default = 0; $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)'); $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default)); $scope = $org . "_dpri"; $is_default = 0; $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)'); $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default)); $scope = $org . "_org"; $is_default = 0; $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)'); $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default)); $scope = $org . "_dpub"; $is_default = 0; $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)'); $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default)); // scopes gia users $scope = $org . "_view"; $is_default = 0; $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)'); $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default)); $scope = $org . "_devel"; $is_default = 0; $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)'); $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default)); $scope = $org . "_admin"; $is_default = 0; $stmt3 = $storage->prepare('INSERT INTO oauth_scopes (scope, is_default) VALUES (:scope, :is_default)'); $stmt3->execute(array('scope' => $scope, 'is_default' => $is_default)); $stmt6 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :client_id'); $stmt6->execute(array('client_id' => trim($client_id))); $row6 = $stmt6->fetch(PDO::FETCH_ASSOC); if ($row6) { $scope6 = $row6["scope"]; $scope6 .= " " . $org . "_admin"; $scope6 .= " " . $org . "_view"; $stmt5 = $storage->prepare('UPDATE oauth_clients set scope = :scope6 where client_id = :client_id'); $stmt5->execute(array('scope6' => $scope6, 'client_id' => $client_id)); } //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; }
function diy_register() { global $app, $diy_storage; $result["controller"] = __FUNCTION__; $result["function"] = substr($app->request()->getPathInfo(), 1); $result["method"] = $app->request()->getMethod(); $params = loadParameters(); $client_id = $params["client_id"]; $client_secret = $params["client_secret"]; $firstname = $params["first_name"]; $lastname = $params["last_name"]; $email = $params["email"]; $post["client_id"] = $client_id; $post["client_secret"] = $client_secret; $post["firstname"] = $firstname; $post["lastname"] = $lastname; $post["email"] = $email; foreach ($post as $curKey => $curValue) { $diy_error["post"][$curKey] = $curValue; } $gump = new GUMP(); $gump->validation_rules(array('client_id' => 'required|alpha_numeric', 'client_secret' => 'required|alpha_numeric', 'firstname' => 'required|alpha_numeric', 'lastname' => 'required|alpha_numeric', 'email' => 'required|valid_email')); $gump->filter_rules(array('client_id' => 'trim|sanitize_string', 'client_secret' => 'trim|sanitize_string', 'firstname' => 'trim|sanitize_string', 'lastname' => 'trim|sanitize_string', 'email' => '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); } try { if (count($result["parse_errors"]) <= 0) { $storage = $diy_storage(); $lastkey = $storage->query('SELECT user_id FROM oauth_users ORDER BY user_id DESC LIMIT 1'); foreach ($lastkey as $curRow) { $lastkey = intval($curRow[0]); } $code = md5($post["firstname"] . $post["lastname"] . $post["email"]); // Create user $storage->query('INSERT INTO oauth_users (user_id, first_name, last_name, email, email_verified, email_ver_code) VALUES (' . ($lastkey + 1) . ', "' . $post["firstname"] . '", "' . $post["lastname"] . '", "' . $post["email"] . '", 0, "' . $code . '")'); $user_id = $storage->lastInsertId(); // Create client $publicKey = file_get_contents('../../ssh/CLIENT_ID1_pubkey.pem'); $privateKey = file_get_contents('../../ssh/CLIENT_ID1_privkey.pem'); $storage->query('INSERT INTO oauth_clients (client_id, client_secret, scope, user_id) VALUES ("' . $post["client_id"] . '", "' . $post["client_secret"] . '", "main", ' . $user_id . ')'); $client_id = $storage->lastInsertId(); $storage->query('INSERT INTO oauth_public_keys (client_id, public_key, private_key, encryption_algorithm) VALUES ("' . $post["client_id"] . '", "' . $publicKey . '", "' . $privateKey . '", "RS256")'); // Send email $mailserver = diyConfig::read('mail.smtpserver'); $mailserverport = diyConfig::read('mail.smtpport'); $mailfrom = diyConfig::read('mail.fromuser'); $link = 'https://' . $_SERVER['HTTP_HOST'] . '/api/activate/' . $code; $transport = Swift_SmtpTransport::newInstance($mailserver, $mailserverport); $mailer = Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance('Wonderful Subject')->setFrom(array($mailfrom => 'Diyiot'))->setTo(array($post["email"]))->setSubject('Welcome to diyiot')->setBody('Hi ' . $post["firstname"] . ',<BR /><BR />To active your account please click the following link <a href="' . $link . '">' . $link . '</a>.', 'text/html', 'UTF-8'); $mailer->send($message); } //result_messages=============================================================== $result["result"]["user_id"] = $user_id; $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 (isset($user_id)) { $storage->query('DELETE FROM oauth_users WHERE user_id = ' . $user_id); } } if (diyConfig::read('debug') == 1) { $result["debug"] = $diy_error; } return $result; }
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 if (!file_exists($filename)) { $unsaved++; } # Attempt to save content if (file_exists($filename) && file_put_contents($filename, $field['content'])) { $saved++; }
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; }
#!/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); }
function login_form() { if (isset($_POST['login_submit'])) { //clear the message(s) unset($_GET['message']); $gump = new GUMP(); $gump->validation_rules(array('email' => 'required|valid_email', 'password' => 'required')); $gump->filter_rules(array('email' => 'trim|sanitize_email', 'password' => 'sanitize_string')); $validated_data = $gump->run($_POST); if ($validated_data === false) { $errors = $gump->get_readable_errors(false); $error_text = ''; foreach ($errors as $error) { $error_text .= $error . '<br />'; } echo edgimo_error($error_text); } else { $email = $validated_data['email']; $password = $validated_data['password']; if (login($email, $password)) { $user = new User($email); $_SESSION['email'] = $user->email; $_SESSION['timeout'] = time(); echo '<script>edgimo_redirect("index.php");</script>'; } else { echo edgimo_error('Invalid email or password. Please try again'); } } } //end submit if (isset($_GET['message'])) { $message = edgimo_success('You have been logged out.'); } else { $message = ''; } echo $message; ?> <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Log In</h3> </div> <div class="panel-body"> <form class="form-horizontal" role="form" method="post"> <?php isset($errors) && array_key_exists('email', $errors) ? $error = 'has-error' : ($error = ''); ?> <div class="form-group <?php echo $error; ?> "> <label for="email" class="col-lg-4 control-label">Email</label> <div class="col-lg-8"> <input type="text" class="form-control" name="email" placeholder="Email"> </div> </div> <?php isset($errors) && array_key_exists('password', $errors) ? $error = 'has-error' : ($error = ''); ?> <div class="form-group <?php echo $error; ?> "> <label for="password" class="col-lg-4 control-label">Password</label> <div class="col-lg-8"> <input type="password" class="form-control" name="password" placeholder="Password"> </div> </div> <div class="form-group"> <div class="col-lg-offset-4 col-lg-8"> <button type="submit" name="login_submit" class="btn btn-primary">Sign in</button> </div> </div> </form> </div> </div> </div> </div> <?php }
function stockfiles_form($stock_file_id = 0) { global $user; global $backend; global $mysqli; if ($stock_file_id) { $stock_file = new StockFile($stock_file_id); $form_type = 'update'; if (!$user->is_allowed('edit_ashp_stock_files')) { echo edgimo_error('Your user role (' . $user->role . ') is not allowed to make edits on this page.'); return; } } else { $stock_file = new StockFile(); $form_type = 'insert'; if (!$user->is_allowed('add_stock_file')) { echo edgimo_error('Your user role (' . $user->role . ') is not allowed to make edits on this page.'); return; } } $html = ''; $fields = array('display_name' => array('var' => 'display_name', 'label' => 'Display Name', 'desc' => 'This will be displayed publicly as the name of the file.', 'type' => 'text', 'std' => $stock_file->display_name, 'validate' => 'required', 'filter' => 'trim|sanitize_string', 'param' => 's'), 'file_name' => array('var' => 'file_name', 'label' => 'File', 'desc' => 'File will be renamed based on what you enter in Display Name.', 'type' => 'file', 'std' => $stock_file->file_name, 'validate' => 'required', 'filter' => 'trim|sanitize_string', 'param' => 's'), 'hook_name' => array('var' => 'hook_name', 'label' => 'Hook Name', 'desc' => 'Use all lowercase with no space. Make it short but easy to remember.', 'type' => 'text', 'std' => $stock_file->hook_name, 'validate' => 'required|alpha_dash', 'filter' => 'trim|sanitize_string', 'param' => 's')); if (isset($_POST['submit'])) { $gump = new GUMP(); foreach ($_POST['form'] as $k => $v) { $fields[$k]['std'] = $v; $stock_file->{$k} = $v; if (!empty($fields[$k]['validate'])) { $validate[$k] = $fields[$k]['validate']; } if (!empty($fields[$k]['filter'])) { $filter[$k] = $fields[$k]['filter']; } } $gump->validation_rules($validate); $gump->filter_rules($filter); $validated_data = $gump->run($_POST['form']); if ($validated_data === false) { $errors = $gump->get_readable_errors(false); $error_text = ''; foreach ($errors as $error) { $error_text .= $error . '<br />'; } echo edgimo_error($error_text); } else { $validated_data['hook_name'] = strtolower($validated_data['hook_name']); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit; } if (!isset($validated_data['file_name'])) { $validated_data['file_name'] = ''; } if ($_FILES['form']['name']['file_name'] !== '') { $uploaded_file = $_FILES['form']['name']['file_name']; $ext = pathinfo($uploaded_file, PATHINFO_EXTENSION); $validated_data['file_name'] = slugify($validated_data['display_name']) . '.' . $ext; if (move_uploaded_file($_FILES['form']['tmp_name']['file_name'], STOCK_FILES_DIR . $validated_data['file_name'])) { echo edgimo_success("File uploaded as " . $validated_data['file_name'] . "."); } else { echo edgimo_error("Sorry, there was a problem uploading your file."); } } else { if ($form_type == 'update') { $validated_data['file_name'] = $stock_file->file_name; } } if ($form_type == 'update') { $query = $mysqli->prepare("UPDATE ashp_stock_files SET display_name=?, file_name=?, hook_name=? WHERE stock_file_id=?"); $query->bind_param('sssi', $validated_data['display_name'], $validated_data['file_name'], $validated_data['hook_name'], $stock_file_id); $query->execute(); $query->close(); echo edgimo_success('Stock File details have been updated.'); header('refresh: 1; URL=stockfiles.php'); } if ($form_type == 'insert') { $query = $mysqli->prepare("INSERT INTO ashp_stock_files (display_name, file_name, hook_name) VALUES (?,?,?)"); $query->bind_param('sss', $validated_data['display_name'], $validated_data['file_name'], $validated_data['hook_name']); $query->execute(); $query->close(); echo edgimo_success('New stock file added.'); header('refresh: 1; URL=stockfiles.php'); } } } $html .= '<form enctype="multipart/form-data" class="form-horizontal" role="form" method="post">'; foreach ($fields as $field) { isset($errors) && array_key_exists($field['var'], $errors) ? $error = 'has-error' : ($error = ''); $html .= '<div class="form-group ' . $error . '">'; switch ($field['type']) { case 'text': if (!isset($type)) { $type = 'text'; } $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <input class="form-control" type="' . $type . '" name="form[' . $field['var'] . ']" value="' . $field['std'] . '"> </div>'; break; case 'select': $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <select class="form-control" name="form[' . $field['var'] . ']">'; foreach ($field['options'] as $k => $v) { $field['std'] == $k ? $selected = 'selected' : ($selected = ''); $html .= '<option ' . $selected . ' value="' . $k . '">' . $v . '</option>'; } $html .= '</select> </div>'; break; case 'textarea': $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <textarea class="wysiwyg" name="form[' . $field['var'] . ']">' . $field['std'] . '</textarea> </div> '; break; case 'file': $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <input class="form-control" type="file" name="form[' . $field['var'] . ']" value="' . $field['std'] . '"> <p class="form-control-static"><strong>Currently</strong>: <a href="' . STOCK_FILES_DIR . $field['std'] . '" target="_blank">' . $field['std'] . '</a></p> </div>'; break; } $html .= ' <div class="col-lg-4"> <p class="description">' . $field['desc'] . '</p> </div> </div>'; } $html .= ' <hr> <div class="form-group"> <div class="col-lg-6 col-lg-offset-2"> <button type="submit" class="btn btn-primary" name="submit">Submit</button> </div> </div> </form> '; return $html; }
function diy_movedevice($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"]; $orgto = OAuth2\Request::createFromGlobals()->query["orgto"]; $diy_error["post"]["device"] = $device; $diy_error["post"]["orgto"] = $orgto; $post["device"] = $device; // to client_id tou device oauth_devices oauth_clients oauth_public_keys $post["orgto"] = $orgto; // 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', 'orgto' => 'required|alpha_numeric')); $gump->filter_rules(array('device' => 'trim|sanitize_string', 'orgto' => '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 { $movedevice = "no"; $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; } function check($storage, $userscopes, $org, $client_id, $device) { //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") { $result["result"]["check"] = "ok"; return $result; } else { $result["result"]["check"] = "no"; return $result; } } $diy_error["error"]["check"] = check($storage, $userscopes, $org, $client_id, $device); // check if user owned the devices or have admin scope in orgfrom $checkr = check($storage, $userscopes, $org, $client_id, $device); if ($checkr["result"]["check"] == "ok") { $diy_error["error"]["orgfrom"] = "ok"; // check if user owned the devices or have admin scope in orgto $checkr1 = check($storage, $userscopes, $orgto, $client_id, $device); if ($checkr1["result"]["check"] == "ok") { $diy_error["error"]["orgto"] = "ok"; $movedevice = "yes"; } } //if( ($orgexists == "yes" && ($orgowner == "yes" || $orgadmin == "yes")) && $orgdeviceexists == "yes"){ if ($movedevice == "yes") { //}else{ try { $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) { $scopedevt = $row1["scope"]; $orgt = $org . "_"; $orgtot = $orgto . "_"; $scopedev = str_replace($orgt, $orgtot, $scopedevt); // oauth_clients table $stmt1 = $storage->prepare('UPDATE oauth_clients set scope = :scopedev where client_id = :client_id'); $stmt1->execute(array('client_id' => $device, 'scopedev' => $scopedev)); // oauth_devices table $stmt11 = $storage->prepare('UPDATE oauth_devices set organisation = :orgto where device = :device'); $stmt11->execute(array('device' => $device, 'orgto' => $orgto)); } //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; }
function diy_wssdeviceAccess($payload, $storage, $exceptions) { global $app; $post["session"] = OAuth2\Request::createFromGlobals()->query["session"]; $post["wss_user"] = OAuth2\Request::createFromGlobals()->query["wss_user"]; $post["device"] = OAuth2\Request::createFromGlobals()->query["device"]; $gump = new GUMP(); $gump->validation_rules(array('wss_user' => 'required|alpha_numeric', 'device' => 'required|alpha_numeric', 'session' => 'required|alpha_numeric')); $gump->filter_rules(array('wss_user' => 'trim|sanitize_string', 'device' => 'trim|sanitize_string', 'session' => 'trim|sanitize_string')); //$result["gump2"] = $validated; // validation successful $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; $result["result"]["view"] = 0; $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 { $stmt = $storage->prepare('SELECT * FROM oauth_devices WHERE device = :device'); $stmt->execute(array('device' => $post["device"])); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ($row["organisation"]) { $organisation = trim($row["organisation"]); //$organisation=$row["scope"]; // o user einai sto scope try { $stmt1 = $storage->prepare('SELECT * FROM oauth_https_wss WHERE wss_user = :wss_user and session = :session'); $stmt1->execute(array('wss_user' => trim($post["wss_user"]), 'session' => trim($post["session"]))); $row1 = $stmt1->fetch(PDO::FETCH_ASSOC); if ($row1["client_id"]) { $client_user = $row1["client_id"]; if ($row["status"] == "org") { try { $stmt2 = $storage->prepare('SELECT * FROM oauth_clients WHERE client_id = :client_user'); $stmt2->execute(array('client_user' => trim($client_user))); $row2 = $stmt2->fetch(PDO::FETCH_ASSOC); if ($row2["scope"]) { $devview = $organisation . "_view"; if (strpos(trim($row2["scope"]), $devview) !== false) { $result["result"]["view"] = 1; } else { $diy_error["errors"] = ExceptionMessages::ScopeNotFound . " , " . ExceptionCodes::ScopeNotFound; } } } catch (Exception $e) { echo "error " . $e->getCode(); $diy_error["db"] = $e->getCode(); } } elseif ($row["status"] == "public") { $result["result"]["view"] = 1; } elseif ($row["status"] == "private" && $row["client_id"] == $client_user) { $result["result"]["view"] = 1; } elseif ($row["status"] == "private" && $row["client_id"] != $client_user) { $result["result"]["view"] = 0; } } else { $diy_error["errors"] = ExceptionMessages::UserNotFound . " , " . ExceptionCodes::UserNotFound; //$result["errors"]["select"] = exceptions::MethodNotFound; } } catch (Exception $e) { echo "error " . $e->getCode(); $diy_error["db"] = $e->getCode(); } } //result_messages=============================================================== $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(); echo "error " . $e->getCode(); $diy_error["db"] = $e->getCode(); } } if (diyConfig::read('debug') == 1) { $result["debug"] = $diy_error; } return $result; }
$app->render('user/blank.php'); $app->stop(); } } $app->post('/login', function () use($app) { $username = $app->request->post('username'); $password = $app->request->post('password'); $_SESSION[Username] = $username; $gump = new GUMP(); $_POST = $gump->sanitize($app->request->post()); // You don't have to sanitize, but it's safest to do so. $gump->validation_rules(array('username' => 'required', 'password' => 'required')); $gump->filter_rules(array('username' => 'trim|sanitize_string', 'password' => 'trim')); $validated_data = $gump->run($app->request->post()); if ($validated_data === false) { foreach ($gump->get_readable_errors(false) as $k => $v) { $app->flash('danger validate_' . $k, print_r($v, true)); } } else { //$app->flash('success validate', print_r($validated_data,true)); #http://stackoverflow.com/questions/4364686/how-do-i-sanitize-input-with-pdo #https://youtu.be/sRfYgco3xo4?t=1758 $sql = 'SELECT * FROM users WHERE name=:name OR email=:name'; $user = $app->db->prepare($sql); /*** bind the paramaters ***/ $user->bindParam(':name', $username, PDO::PARAM_STR); /*** execute the prepared statement ***/ $user->execute(); $user = $user->fetch(); // store $hash in db at signup //$hash = password_hash($password, PASSWORD_DEFAULT);
<?php require 'gump.class.php'; require 'PHPMailerAutoload.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('mail' => 'required|valid_email', 'objet' => 'required|max_len,100', 'msg' => 'required|max_len,1666|min_len,6')); $gump->filter_rules(array('mail' => 'trim|sanitize_email', 'objet' => 'trim|sanitize_string', 'msg' => 'trim|sanitize_string')); $validated_data = $gump->run($_POST); if ($validated_data === false) { echo $gump->get_readable_errors(true); } else { // Form is valid we send the mail ! // https://github.com/PHPMailer/PHPMailer#a-simple-example $mail = new PHPMailer(); $mail->isMail(); $mail->From = $_POST['mail']; $mail->addAddress('*****@*****.**', 'Skullmasher Heartless'); $mail->addCC('*****@*****.**', 'Neko'); $mail->addCC('*****@*****.**', 'Mathilde Couvreur'); $mail->isHTML(true); // Set email format to HTML $mail->Subject = '[TEST]' . $_POST['objet']; $mail->Body = $_POST['msg']; $mail->AltBody = $_POST['msg']; if (!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent';
if (!$user->isSuperUser()) { $app->flash('error', 'Your are not administrator.'); $app->redirect('/managers/login'); } $gump = new GUMP(); $_POST = $gump->sanitize($_POST); // You don't have to sanitize, but it's safest to do so. $gump->validation_rules(array('winning_price' => 'required|numeric', 'draw_date' => 'required|max_len,10|min_len,6')); $gump->filter_rules(array('winning_price' => 'trim', 'draw_date' => 'trim')); if (!preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $_POST['draw_date'])) { $app->flash('error', "Invalid Date"); $app->redirect('/managers/draws'); } $validator = $gump->run($_POST); if ($validator === false) { $app->flash('error', $gump->get_readable_errors(true)); $app->redirect('/managers/draws'); } else { if (!Draw::isExists($_POST['draw_date']) && Draw::validDate($_POST['draw_date'])) { $draw = new Draw(); $draw->winning_price = $_POST['winning_price']; $draw->date = date("Y-m-d H:i:s", strtotime($_POST['draw_date'])); $draw->status = "open"; $draw->save(); $app->flash('info', "Draw has been successfully created."); $app->redirect('/managers/draws'); } else { $app->flash('error', "There is already a draw scheduled for this day or the date is invalid."); $app->redirect('/managers/draws'); } }
function faculty_form($faculty_id = 0) { global $mysqli; global $backend; global $user; if ($faculty_id) { $faculty = new Faculty($faculty_id); $form_type = 'update'; if (!$user->is_allowed('edit_ashp_faculty')) { echo edgimo_error('Your user role (' . $user->role . ') is not allowed to make edits on this page.'); return; } } else { $faculty = new Faculty(); $form_type = 'insert'; if (!$user->is_allowed('add_faculty')) { echo edgimo_error('Your user role (' . $user->role . ') is not allowed to make edits on this page.'); return; } } $html = ''; $fields = array('first_name' => array('var' => 'first_name', 'label' => 'First Name', 'desc' => '', 'type' => 'text', 'std' => $faculty->first_name, 'validate' => 'required|valid_name', 'filter' => 'trim|sanitize_string', 'param' => 's'), 'middle_name' => array('var' => 'middle_name', 'label' => 'Middle Name', 'desc' => '', 'type' => 'text', 'std' => $faculty->middle_name, 'validate' => '', 'filter' => 'trim|sanitize_string', 'param' => 's'), 'last_name' => array('var' => 'last_name', 'label' => 'Last Name', 'desc' => '', 'type' => 'text', 'std' => $faculty->last_name, 'validate' => 'required|valid_name', 'filter' => 'trim|sanitize_string', 'param' => 's'), 'credentials' => array('var' => 'credentials', 'label' => 'Credentials', 'desc' => '', 'type' => 'text', 'std' => $faculty->credentials, 'validate' => '', 'filter' => 'trim|sanitize_string', 'param' => 's'), 'title' => array('var' => 'title', 'label' => 'Title', 'desc' => '', 'type' => 'textarea_basic', 'std' => $faculty->title, 'validate' => '', 'filter' => 'trim|basic_tags', 'param' => 's'), 'bio' => array('var' => 'bio', 'label' => 'Bio', 'desc' => '', 'type' => 'textarea', 'std' => $faculty->bio, 'validate' => '', 'filter' => 'trim', 'param' => 's'), 'image' => array('var' => 'image', 'label' => 'Image', 'desc' => 'Upload the faculty photo and alert your web vendor so that it can be resized and processed. To replace an existing photo, just upload a new file.', 'type' => 'file', 'std' => $faculty->image, 'validate' => '', 'filter' => 'trim|sanitize_string', 'param' => 's')); if (isset($_POST['submit'])) { $gump = new GUMP(); foreach ($_POST['form'] as $k => $v) { //update the std value for form output below $fields[$k]['std'] = $v; $faculty->{$k} = $v; if ($fields[$k]['type'] == 'textarea_basic') { $_POST['form'][$k] = nl2br($_POST['form'][$k]); } if (!empty($fields[$k]['validate'])) { $validate[$k] = $fields[$k]['validate']; } if (!empty($fields[$k]['filter'])) { $filter[$k] = $fields[$k]['filter']; } } $gump->validation_rules($validate); $gump->filter_rules($filter); $validated_data = $gump->run($_POST['form']); $duplicate = false; if ($form_type == 'insert' && is_duplicate_faculty($validated_data['first_name'], $validated_data['last_name'])) { $validated_data = false; $duplicate = true; } $redirect = true; if (!$duplicate && $form_type == 'insert' && is_similar_faculty($validated_data['last_name'])) { echo edgimo_error('Warning: Similar faculty name found in database.'); $redirect = false; } if ($validated_data === false) { $errors = $gump->get_readable_errors(false); $error_text = ''; foreach ($errors as $error) { $error_text .= $error . '<br />'; } } if ($duplicate) { $errors['first_name'] = true; $errors['last_name'] = true; $error_text .= 'Duplicate faculty member found.<br />'; } if (isset($error_text)) { echo edgimo_error($error_text); } if ($validated_data !== false) { if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit; } if (!isset($validated_data['image'])) { $validated_data['image'] = ''; } if ($_FILES['form']['name']['image'] !== '') { $image = $_FILES['form']['name']['image']; $ext = pathinfo($image, PATHINFO_EXTENSION); $validated_data['image'] = slugify($validated_data['last_name']) . '-' . slugify($validated_data['first_name']) . '.' . $ext; if (move_uploaded_file($_FILES['form']['tmp_name']['image'], FACULTY_IMAGES_DIR . $validated_data['image'])) { } else { echo edgimo_error("Sorry, there was a problem uploading your file."); } } else { if ($form_type == 'update') { $validated_data['image'] = $faculty->image; } } if ($form_type == 'update') { $query = $mysqli->prepare("UPDATE ashp_faculty SET first_name=?, middle_name=?, last_name=?, credentials=?, title=?, image=?, bio=? WHERE faculty_id=?"); $query->bind_param('sssssssi', $validated_data['first_name'], $validated_data['middle_name'], $validated_data['last_name'], $validated_data['credentials'], $validated_data['title'], $validated_data['image'], $validated_data['bio'], $faculty_id); echo edgimo_success('Faculty details have been updated.'); echo '<script>edgimo_redirect("faculty.php");</script>'; } if ($form_type == 'insert') { $query = $mysqli->prepare("INSERT INTO ashp_faculty (first_name, middle_name, last_name, credentials, title, image, bio) VALUES (?,?,?,?,?,?,?)"); $query->bind_param('sssssss', $validated_data['first_name'], $validated_data['middle_name'], $validated_data['last_name'], $validated_data['credentials'], $validated_data['title'], $validated_data['image'], $validated_data['bio']); echo edgimo_success('New faculty member added.'); if ($redirect) { echo '<script>edgimo_redirect("faculty.php");</script>'; } } $query->execute(); $query->close(); } } $html .= '<div class="row"><div class="col-lg-10 col-lg-offset-2"><p class="description">Last updated: ' . date('F j, Y', strtotime($faculty->updated)) . '</p></div></div>'; $html .= '<form enctype="multipart/form-data" class="form-horizontal" role="form" method="post">'; foreach ($fields as $field) { isset($errors) && array_key_exists($field['var'], $errors) ? $error = 'has-error' : ($error = ''); $html .= '<div class="form-group ' . $error . '">'; switch ($field['type']) { case 'text': if (!isset($type)) { $type = 'text'; } $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <input class="form-control" type="' . $type . '" name="form[' . $field['var'] . ']" value="' . $field['std'] . '"> </div>'; break; case 'select': $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <select class="form-control" name="form[' . $field['var'] . ']">'; foreach ($field['options'] as $k => $v) { $field['std'] == $k ? $selected = 'selected' : ($selected = ''); $html .= '<option ' . $selected . ' value="' . $k . '">' . $v . '</option>'; } $html .= '</select> </div>'; break; case 'textarea': $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <textarea class="wysiwyg" name="form[' . $field['var'] . ']">' . $field['std'] . '</textarea> </div> '; break; case 'textarea_basic': $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <textarea class="basic" name="form[' . $field['var'] . ']">' . str_replace('<br />', "", $field['std']) . '</textarea> </div> '; break; case 'file': $html .= ' <label class="col-lg-2 control-label" for="form[' . $field['var'] . ']">' . $field['label'] . '</label> <div class="col-lg-6"> <input class="form-control" type="file" name="form[' . $field['var'] . ']" value="' . $field['std'] . '"> <img class="preview" src="' . FACULTY_IMAGES_DIR . $field['std'] . '"> </div>'; break; } $html .= ' <div class="col-lg-4"> <p class="description">' . $field['desc'] . '</p> </div> </div>'; } $html .= ' <hr> <div class="form-group"> <div class="col-lg-6 col-lg-offset-2"> <button type="submit" class="btn btn-primary" name="submit">Submit</button> </div> </div> </form> '; return $html; }
<?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";
if (!empty($fields[$k]['filter'])) { $filter[$k] = $fields[$k]['filter']; } } $gump->validation_rules($validate); $gump->filter_rules($filter); $validated_data = $gump->run($_POST['form']); $error_text = ''; $privatekey = "6Lepf-gSAAAAAEE3oZNbZJE0FvuD4gtkQ04gZkAL"; $resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { $validated_data = false; $error_text .= $resp->error . '<br />'; } if ($validated_data === false) { $errors = $gump->get_readable_errors(false); foreach ($errors as $error) { $error_text .= $error . '<br />'; } $html .= '<div class="alert alert-danger"><p>' . $error_text . '</p></div>'; } else { $query = $mysqli->prepare("INSERT INTO ashp_email_list (first_name, last_name, email, city, state, activity_id) VALUES (?,?,?,?,?,?)"); $query->bind_param('sssssi', $validated_data['first_name'], $validated_data['last_name'], $validated_data['email'], $validated_data['city'], $validated_data['state'], $activity_id); $html .= '<div class="alert alert-success"><p>Thank you! Your information has been saved.</p></div>'; $form_saved = true; $query->execute(); $query->close(); } } $form_html .= '<form class="form" role="form" method="post">'; foreach ($fields as $field) {
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; }
/** * * @param array $d * @return boolean */ protected function validateUserInfo(array $data) { require_once ROOT . DS . 'vendor' . DS . 'autoload.php'; $gump = new \GUMP(); $gump->validation_rules(array('firstName' => 'required|alpha|max_len,' . $this->config['max_firstname_len'] . '|min_len,' . $this->config['min_firstname_len'], 'lastName' => 'required|alpha|max_len,' . $this->config['max_lastname_len'] . '|min_len,' . $this->config['min_lastname_len'], 'email' => 'required|valid_email|max_len,' . $this->config['max_email_len'] . '|min_len,' . $this->config['min_email_len'], 'password' => 'required|max_len,' . $this->config['max_password_len'] . '|min_len,' . $this->config['min_password_len'])); # Might remove these $gump->filter_rules(array('firstName' => 'trim|sanitize_string', 'lastName' => 'trim|sanitize_string', 'email' => 'trim|sanitize_email', 'password' => 'trim')); $validate = $gump->run($data); if ($validate === false) { echo $gump->get_readable_errors(false); return false; } return true; }