public function testFileUploadField2() { $this->setExpectedException('fValidationException'); $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['CONTENT_TYPE'] = 'multipart/form-data'; $_FILES = array(); $_FILES['file'] = array('name' => 'test.txt', 'type' => '', 'tmp_name' => './resources/text/example', 'error' => '', 'size' => 17); $uploader = new fUpload(); $uploader->setMIMETypes(array('text/csv'), 'Please upload a CSV file'); try { $v = new fValidation(); $v->addFileUploadRule('file', $uploader); $v->validate(); } catch (fValidationException $e) { $this->assertContains('File: Please upload a CSV file', $e->getMessage()); throw $e; } }
$types = Tag::get_by_type('consumable_type'); } include 'views/consumables/addedit.php'; } /** * Edit a consumable */ if ($action == 'edit') { // Get ID $id = fRequest::get('id', 'integer'); try { // Get consumable via ID $c = new Consumable($id); if (fRequest::isPost()) { // Try to validate options $validator = new fValidation(); $validator->addOneOrMoreRule('col_c', 'col_y', 'col_m', 'col_k'); $validator->overrideFieldName(array('col_c' => 'Colour (Cyan)', 'col_y' => 'Colour (Yellow)', 'col_m' => 'Colour (Magenta)', 'col_k' => 'Colour (Black)')); $validator->validate(); // Update consumable object from POST data and save $c->populate(); $c->linkModels(); $c->linkTags(); $c->store(); // Messaging fMessaging::create('affected', fURL::get(), $c->getId()); fMessaging::create('success', fURL::get(), 'The consumable ' . $c->getName() . ' was successfully updated.'); fURL::redirect(fURL::get()); } } catch (fNotFoundException $e) { fMessaging::create('error', fURL::get(), 'The consumable requested, ID ' . $id . ', could not be found.');
<?php $title = 'Hack Me Sticker'; require './header.php'; $cards = fRecordSet::build('Card', array('uid=' => $_GET['cardid'])); if ($cards->count() == 0) { fURL::redirect("/kiosk/addcard.php?cardid=" . $_GET['cardid']); } $card = $cards->getRecord(0); $user = new User($card->getUserId()); $user->load(); # echo json_encode($_POST); if (isset($_POST['print']) && $user->isMember()) { try { fRequest::validateCSRFToken($_POST['token']); $validator = new fValidation(); $validator->addRequiredFields('more_info'); $validator->validate(); $data = array('donor_id' => $user->getId(), 'donor_name' => $user->getFull_Name(), 'donor_email' => $user->getEmail(), 'dispose_date' => date('Y-m-d', strtotime("+2 weeks")), 'more_info' => $_POST['more_info']); $data_string = json_encode($data); $ch = curl_init('http://kiosk.london.hackspace.org.uk:12345/print/hackme'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string))); $result = curl_exec($ch); curl_close($ch); echo "<p>Your sticker is being printed now.</p>"; } catch (fValidationException $e) { $e->printMessage(); }
<?php $page = 'edit'; $title = "Edit your details"; $desc = ''; require '../header.php'; if (!isset($user)) { fURL::redirect('/login.php?forward=/members/edit.php'); } ?> <h2>Edit Your Membership Account</h2> <?php if (isset($_POST['submit'])) { try { fRequest::validateCSRFToken($_POST['token']); $validator = new fValidation(); $validator->addRequiredFields('fullname', 'email', 'address', 'length'); $validator->addEmailFields('email'); $validator->validate(); if ($_POST['newpassword'] != '') { if ($_POST['newpassword'] != $_POST['newpasswordconfirm']) { throw new fValidationException('Passwords do not match'); } $user->setPassword(fCryptography::hashPassword($_POST['newpassword'])); } $user->setEmail(strtolower(trim($_POST['email']))); $user->setFullName(trim($_POST['fullname'])); $user->setAddress(trim($_POST['address'])); $user->setSubscriptionPeriod($_POST['length']); $user->setEmergencyName(trim($_POST['emergency_name'])); $user->setEmergencyPhone(trim($_POST['emergency_phone']));
<?php $page = 'login'; require 'header.php'; if ($user) { fURL::redirect('/members'); } if (isset($_POST['submit'])) { try { fRequest::validateCSRFToken($_POST['token']); $validator = new fValidation(); $validator->addRequiredFields('password', 'email'); $validator->addEmailFields('email'); $validator->validate(); $users = fRecordSet::build('User', array('email=' => strtolower($_POST['email']))); if ($users->count() == 0) { throw new fValidationException('Invalid username or password.'); } $rec = $users->getRecords(); $user = $rec[0]; if (!fCryptography::checkPasswordHash($_POST['password'], $user->getPassword())) { throw new fValidationException('Invalid username or password.'); } fSession::set('user', $user->getId()); if (fRequest::get('persistent_login', 'boolean')) { fSession::enablePersistence(); } if (isset($_POST['forward'])) { fURL::redirect('http://' . $_SERVER['SERVER_NAME'] . $_POST['forward']); } else { fURL::redirect('/members');
<?php $page = 'membership'; require 'header.php'; if ($user) { fURL::redirect('/members'); } if (isset($_POST['submit'])) { try { fRequest::validateCSRFToken($_POST['token']); $validator = new fValidation(); $validator->addRequiredFields('fullname', 'password', 'email', 'address'); $validator->addEmailFields('email'); $validator->validate(); if ($_POST['password'] != $_POST['passwordconfirm']) { throw new fValidationException('Passwords do not match'); } $user = new User(); $user->setEmail(strtolower($_POST['email'])); $user->setFullName($_POST['fullname']); $user->setAddress($_POST['address']); $user->setPassword(fCryptography::hashPassword($_POST['password'])); if (isset($_POST['hackney'])) { $user->setHackney(true); } $user->store(); fSession::set('user', $user->getId()); fURL::redirect('/members'); exit; } catch (fValidationException $e) { echo "<p>" . $e->printMessage() . "</p>";
<?php $page = 'cards'; $title = 'Add card'; $desc = ''; require '../header.php'; if (!isset($user)) { fURL::redirect('/login.php?forward=/members/cards.php'); } if (isset($_POST['submit'])) { try { fRequest::validateCSRFToken($_POST['token']); $validator = new fValidation(); $validator->addRequiredFields('uid'); $validator->addRegexRule('uid', '#^[0-9a-fA-F]+$#', 'Not in hex format'); $validator->validate(); $uid = strtoupper($_POST['uid']); if ($uid == '21222324') { /* New Visa cards return this, presumably for privacy */ throw new fValidationException('Non-unique UID. This card cannot be added to the system.'); } $card = new Card(); $card->setUserId($user->getId()); $card->setAddedDate(time()); $card->setUid($uid); $card->store(); fURL::redirect('/members/cards.php'); exit; } catch (fValidationException $e) { echo "<p>" . $e->printMessage() . "</p>"; } catch (fSQLException $e) {
function build_json_response() { if (!isset($_POST['json'])) { return array('error' => array('message' => "No JSON found")); } $data = json_decode($_POST['json'], true); if (!$data) { return array('error' => array('message' => "JSON could not be decoded")); } $_POST = $data; // fValidation inspects $_POST for field data $validator = new fValidation(); $validator->addRequiredFields('title', 'details', 'venue', 'address', 'organizer', 'email', 'read_comic'); $validator->addEmailFields('email'); $validator->addRegexReplacement('#^(.*?): (.*)$#', '\\2 for <span class="field-name">\\1</span>'); // If id is specified require secret $validator->addConditionalRule(array('id'), NULL, array('secret')); $messages = $validator->validate(TRUE, TRUE); if (!$data['read_comic']) { $messages['read_comic'] = 'You must have read the Ride Leading Comic'; } if ($messages) { return array('error' => array('message' => 'There were errors in your fields', 'fields' => $messages)); } $inputDateStrings = get($data['dates'], array()); $validDates = array(); $invalidDates = array(); foreach ($inputDateStrings as $dateString) { $date = DateTime::createFromFormat('Y-m-d', $dateString); if ($date) { $validDates[] = $date; } else { $invalidDates[] = $dateString; } } if ($invalidDates) { $messages['dates'] = "Invalid dates: " . implode(', ', $invalidDates); } if (count($validDates) === 1) { $data['datestype'] = 'O'; $data['datestring'] = date_format($validDates[0], 'l, F j'); } else { // not dealing with 'consecutive' $data['datestype'] = 'S'; $data['datestring'] = 'Scattered days'; } // Converts data to an event, loading the existing one if id is included in data $event = Event::fromArray($data); // Else if ($event->exists() && !$event->secretValid($data['secret'])) { return array('error' => array('message' => 'Invalid secret, use link from email')); } $messages = $event->validate($return_messages = TRUE, $remove_column_names = TRUE); if (isset($_FILES['file'])) { $uploader = new fUpload(); $uploader->setMIMETypes(array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png'), 'The file uploaded is not an image'); $uploader->setMaxSize('2MB'); $uploader->setOptional(); $file_message = $uploader->validate('file', TRUE); if ($file_message != null) { $messages['file'] = $file_message; } global $IMAGEDIR; $file = $uploader->move($IMAGEDIR, 'file'); $event->setImage($file->getName()); } if ($messages) { return array('error' => array('message' => 'There were errors in your fields', 'fields' => $messages)); } // if needs secret generate and email if (!$event->exists()) { $includeSecret = true; } else { $includeSecret = false; } // If there are validation errors this starts spewing html, so we validate before $event->store(); // Create/delete EventTimes to match the list of dates included EventTime::matchEventTimesToDates($event, $validDates); // Returns the created object $details = $event->toDetailArray(true); if ($includeSecret) { $details['secret'] = $event->getPassword(); // Wait until after it is stored to ensure it has an id $event->emailSecret(); } return $details; }
<?php $shells = array('/bin/bash', '/bin/sh', '/bin/zsh'); if ($user->isMember()) { $user_profile = $user->createUsersProfile(); if ($user_profile->getAllowEmail() && $user->getLdapemail() == '') { $email = $user->getEmail(); } else { $email = $user->getLdapemail(); } // Link or unlink a user. if (array_key_exists('create', $_POST) && array_key_exists('token', $_POST)) { $ok = false; try { fRequest::validateCSRFToken($_POST['token']); $validator = new fValidation(); $validator->addRequiredFields('ldapuser', 'ldapnthash', 'ldapsshahash', 'ldapshell', 'ldapemail'); $validator->addEmailFields('ldapemail'); $validator->validate(); // Attempt account creation and promotion. if (!preg_match('/^[a-z][a-z0-9_-]{0,31}$/', $_POST['ldapuser'])) { throw new fValidationException('<p>The username must only contain a-z, 0-9 _ and -.</p>'); } $not_allowed_names = array("root" => 1, "daemon" => 1, "bin" => 1, "sys" => 1, "sync" => 1, "games" => 1, "man" => 1, "lp" => 1, "mail" => 1, "news" => 1, "uucp" => 1, "proxy" => 1, "www-data" => 1, "backup" => 1, "list" => 1, "irc" => 1, "gnats" => 1, "nobody" => 1, "libuuid" => 1, "sshd" => 1, "ntp" => 1, "messagebus" => 1, "colord" => 1, "saned" => 1, "openldap" => 1, "avahi" => 1, "mpd" => 1, "radvd" => 1, "quasselcore" => 1, "statd" => 1, "ntop" => 1, "postgres" => 1, "bitlbee" => 1, "smokeping" => 1, "debian-exim" => 1, "snmp" => 1, "asterisk" => 1, "debian-tor" => 1, "privoxy" => 1, "bind" => 1, "dhcpd" => 1, "ircensus" => 1, "cacti" => 1, "mysql" => 1, "hplip" => 1, "haldaemon" => 1, "mosquitto" => 1, "postfix" => 1, "glados" => 1, "boarded" => 1, "board" => 1, "bmeter" => 1, "netometer" => 1, "robonaut" => 1, "postmaster" => 1, "hostmaster" => 1, "webmaster" => 1, "abuse" => 1, "spam" => 1, "billing" => 1, "accounts" => 1, "support" => 1, "techsupport" => 1, "trustees" => 1, "noc" => 1, "security" => 1, "directors" => 1, "contact" => 1, "info" => 1, "property" => 1, "ebay" => 1, "elections" => 1, "accounts" => 1, "membership" => 1, "sysadmin" => 1, "anonymous" => 1, "anon" => 1, "administrator" => 1, "admin" => 1); if (array_key_exists(strtolower($_POST['ldapuser']), $not_allowed_names)) { throw new fValidationException('<p>You are not allowed to use ' . htmlspecialchars($_POST['ldapuser']) . ' as a username.</p>'); } if (!in_array($_POST['ldapshell'], $shells)) { throw new fValidationException('<p>' . htmlspecialchars($_POST['ldapshell']) . ' is not a valid shell.</p>'); } if (!preg_match('/^[A-F0-9]{32}$/', $_POST['ldapnthash'])) {
<?php $page = 'addcard'; require 'header.php'; if ($user) { fSession::destroy(); fURL::redirect(); } if (isset($_POST['submit'])) { try { fRequest::validateCSRFToken($_POST['token']); // Strip colons from uid (easier to copy paste from some NFC // reader apps). fRequest::set('uid', str_replace(':', '', fRequest::get('uid'))); $validator = new fValidation(); $validator->addRequiredFields('password', 'email', 'uid'); $validator->addEmailFields('email'); $validator->addRegexRule('uid', '#^[0-9a-fA-F]+$#', 'Not in hex format'); $validator->validate(); $uid = strtoupper($_POST['uid']); if ($uid == '21222324') { /* New Visa cards return this, presumably for privacy */ throw new fValidationException('Non-unique UID. This card cannot be added to the system.'); } // Random IDs are 4 bytes long and start with 0x08 // http://www.nxp.com/documents/application_note/AN10927.pdf if (strlen($uid) === 8 && substr($uid, 0, 2) === "08") { throw new fValidationException('ID is randomly generated and will change every time the card is used!'); } if (strlen($uid) === 8 && substr($uid, 0, 2) === "88") { throw new fValidationException('Card UID\'s can\'t start with 88');
throw new fValidationException('Invalid token, please make sure you followed the correct link'); } $user->setPassword(fCryptography::hashPassword($_POST['password'])); $user->store(); fURL::redirect('/login.php'); exit; } catch (fValidationException $e) { echo "<p>" . $e->printMessage() . "</p>"; } catch (fSQLException $e) { echo "<p>An unexpected error occurred, please try again later</p>"; trigger_error($e); } } elseif (isset($_POST['sendtoken'])) { try { fRequest::validateCSRFToken($_POST['token']); $validator = new fValidation(); $validator->addRequiredFields('email'); $validator->validate(); $user = new User(array('email' => $_POST['email'])); $token = $user->getResetPasswordToken(); $email = new fEmail(); $email->addRecipient($user->getEmail()); $email->setFromEmail('*****@*****.**', 'London Hackspace'); $email->setSubject('London Hackspace Password Reset'); $name = $user->getFullName(); $email->setBody("Hi {$name},\n\nYou (or someone pretending to be you) requested a password reset for your\nLondon Hackspace account. To reset your password, go to this address:\n\nhttp://{$_SERVER['SERVER_NAME']}/passwordreset.php?token={$token}\n\nIf you don't want to reset your password, just ignore this email.\n\nCheers,\n\nThe London Hackspace email monkey\n"); $email->send(); echo "<p>An email has been sent to you with further instructions.</p>"; } catch (fNotFoundException $e) { ?> <p>No user exists with that email address. <a href="signup.php">Sign up</a>?
public function testAddURL6() { $this->setExpectedException('fValidationException'); $_POST['foo'] = "http://flourishlib.com/foo bar/"; $_GET['bar'] = "http://flourishlib.com/foo bar/"; try { $v = new fValidation(); $v->addURLFields('foo', 'bar'); $v->validate(); } catch (fValidationException $e) { $this->assertContains('Foo: Please enter a URL in the form http://www.example.com/page', $e->getMessage()); $this->assertContains('Bar: Please enter a URL in the form http://www.example.com/page', $e->getMessage()); throw $e; } }
$db->translatedQuery('SELECT ug_user FROM user_groups WHERE ug_user=%i AND ug_group=\'sysop\'', $user)->fetchRow(); } catch (fNoRowsException $e) { // Add the MediaWiki user to the 'sysop' group. $db->translatedQuery('INSERT INTO user_groups VALUES (%i,\'sysop\')', $user); } } elseif (array_key_exists('unlink', $_POST)) { // Delete the MediaWiki user from the 'sysop' group. $db->translatedQuery('DELETE FROM user_groups WHERE ug_user=%i AND ug_group=\'sysop\'', $user); } } catch (fNoRowsException $e) { echo '<p>That wiki account does not have a confirmed e-mail that matches the e-mail of your Hackspace account.</p>'; } } elseif (array_key_exists('create', $_POST)) { fRequest::validateCSRFToken($_POST['token']); try { $validator = new fValidation(); $validator->addRequiredFields('username', 'password'); $validator->validate(); if ($_POST['password'] !== $_POST['passwordconfirm']) { throw new fValidationException('<p>Passwords do not match.</p>'); } // Attempt account creation and promotion. $username = escapeshellarg($_POST['username']); $password = escapeshellarg($_POST['password']); $success = trim(shell_exec("unset REQUEST_METHOD;php {$path}maintenance/createAndPromote.php --globals {$username} {$password} 2>&1 1> /dev/null")); if ($success === 'account exists.') { throw new fValidationException('<p>An account on the wiki with that username already exists.</p>'); } elseif ($success !== '') { throw new fValidationException('<p>An unknown error ocurred while creating that wiki account, please contact IRC.</p>'); } else { // Update e-mail address for created user.
$maxStorageMonths = 6; if (isset($_POST['token'])) { try { fRequest::validateCSRFToken($_POST['token']); $identicalNames = fRecordSet::build('Project', array('user_id=' => $user->getId(), 'name=' => array(filter_var($_POST['name'], FILTER_SANITIZE_STRING))), array('name' => 'asc')); if (!isset($_POST['name']) || $_POST['name'] == '') { throw new fValidationException('Name field is required.'); } if (count($identicalNames) > 0 && !$project->getId()) { throw new fValidationException('You\'ve already made a request with that name. How is this request different to the last time? Our members like to know a project with multiple storage requests is being actively worked on and progress is being made.'); } if (!isset($_POST['description']) || $_POST['description'] == '') { throw new fValidationException('Description field is required.'); } if ($_POST['contact'] && $_POST['contact'] != '') { $validator = new fValidation(); $validator->addEmailFields('contact'); $validator->validate(); } if (!isset($_POST['location_id']) || $_POST['location_id'] == '') { throw new fValidationException('Location select is required.'); } if (!isset($_POST['location']) || $_POST['location'] == '') { throw new fValidationException('Location field is required.'); } if (!isset($_POST['from_date']) || $_POST['from_date'] == '') { throw new fValidationException('Arrival field is required.'); } if (!isset($_POST['to_date']) || $_POST['to_date'] == '') { throw new fValidationException('Removal field is required.'); }