/** * Install hstore * /usr/share/postgresql/contrib # cat hstore.sql | psql -U pgsql -d onphp **/ public function testHstore() { foreach (DBTestPool::me()->getPool() as $connector => $db) { DBPool::me()->setDefault($db); $properties = array('age' => '23', 'weight' => 80, 'comment' => null); $user = TestUser::create()->setCity($moscow = TestCity::create()->setName('Moscow'))->setCredentials(Credentials::create()->setNickname('fake')->setPassword(sha1('passwd')))->setLastLogin(Timestamp::create(time()))->setRegistered(Timestamp::create(time())->modify('-1 day'))->setProperties(Hstore::make($properties)); $moscow = TestCity::dao()->add($moscow); $user = TestUser::dao()->add($user); Cache::me()->clean(); TestUser::dao()->dropIdentityMap(); $user = TestUser::dao()->getById('1'); $this->assertInstanceOf('Hstore', $user->getProperties()); $this->assertEquals($properties, $user->getProperties()->getList()); $form = TestUser::proto()->makeForm(); $form->get('properties')->setFormMapping(array(Primitive::string('age'), Primitive::integer('weight'), Primitive::string('comment'))); $form->import(array('id' => $user->getId())); $this->assertNotNull($form->getValue('id')); $object = $user; FormUtils::object2form($object, $form); $this->assertInstanceOf('Hstore', $form->getValue('properties')); $this->assertEquals(array_filter($properties), $form->getValue('properties')->getList()); $subform = $form->get('properties')->getInnerForm(); $this->assertEquals($subform->getValue('age'), '23'); $this->assertEquals($subform->getValue('weight'), 80); $this->assertNull($subform->getValue('comment')); $user = new TestUser(); FormUtils::form2object($form, $user, false); $this->assertEquals($user->getProperties()->getList(), array_filter($properties)); } }
/** * @return ModelAndView **/ public function run(Prototyped $subject, Form $form, HttpRequest $request) { if ($object = $form->getValue('id')) { FormUtils::object2form($object, $form); } return ModelAndView::create(); }
public function preamble($form) { if ($form->attr['action'] === false) { return; } $attr = FormUtils::serializeAttr($form->attr); echo "<form {$attr}>\n"; }
public function init() { $this->addWidget('first_name', new sfWidgetFormInputText(), new sfValidatorString(array("required" => true), array("required" => "Please enter your first name."))); $this->addWidget('last_name', new sfWidgetFormInputText(), new sfValidatorString(array("required" => true), array("required" => "Please enter your last name."))); $this->addWidget('phone', new sfWidgetFormInputText(), FormUtils::getPhoneValidator()); $this->addWidget('email', new sfWidgetFormInputText(), FormUtils::getEmailValidator()); $passwordValidator = new sfValidatorString(array("required" => true, 'min_length' => 6), array('min_length' => "Your password must be at least 6 characters.", "required" => "Please enter a password.")); $this->addWidget('password', new sfWidgetFormInputPassword(), $passwordValidator); }
/** * @return ModelAndView **/ public function run(Prototyped $subject, Form $form, HttpRequest $request) { $form->markGood('id'); if (!$form->getErrors()) { FormUtils::form2object($form, $subject); return parent::run($subject, $form, $request); } return new ModelAndView(); }
public function getContent(array $extra_attr = array(), array $label = array()) { $attr = array_merge_recursive($extra_attr, $this->attr); if ($this->getContainer() instanceof FormGroup) { return "<label class=\"form-checkbox\" " . FormUtils::serializeAttr($label) . "><input " . $this->serializeAttr($attr) . " /> {$this->text}</label>"; } else { return "<input " . $this->serializeAttr($attr) . " />"; } }
/** * @return ModelAndView **/ public function run(Prototyped $subject, Form $form, HttpRequest $request) { if (!$form->getErrors()) { ClassUtils::copyProperties($form->getValue('id'), $subject); FormUtils::form2object($form, $subject, false); return parent::run($subject, $form, $request); } return new ModelAndView(); }
public function preamble($form) { if ($this->preambleWritten || $form->attr['action'] === false) { return; } $sattr = FormUtils::serializeAttr($form->attr); echo "<form {$sattr}>\n"; $this->preambleWritten = true; }
public function init() { /* * BASIC INFO */ $this->addWidget('first_name', new sfWidgetFormInputText(), new sfValidatorString(array("required" => true), array("required" => "Please enter your first name."))); $this->addWidget('last_name', new sfWidgetFormInputText(), new sfValidatorString(array("required" => true), array("required" => "Please enter your last name."))); $this->addWidget('email', new sfWidgetFormInputText(), new sfValidatorEmail(array("required" => true), array("required" => "Please enter a valid email address."))); $this->addWidget('phone', new sfWidgetFormInputText(), FormUtils::getPhoneValidator(true)); }
public function configure() { unset($this['id']); unset($this['identifier']); unset($this['country']); $this->setWidget('address1', new sfWidgetFormInputText()); $this->setWidget('address2', new sfWidgetFormInputText()); $this->setWidget('city', new sfWidgetFormInputText()); $this->setWidget('state', FormUtils::getStateWidget(true)); $this->setValidators(array('name' => new sfValidatorString(array('required' => true, 'max_length' => 100), array('required' => "Please enter a minyan name")), 'address1' => new sfValidatorString(array('required' => true)), 'address2' => new sfValidatorString(array('required' => false)), 'city' => new sfValidatorString(array('required' => true)), 'state' => FormUtils::getStateValidator(true), 'zip' => FormUtils::getZipValidator(true))); }
public function serializeOptions($selected) { return implode("\n", array_map(function ($cur) use($selected) { $attr = ['value' => $cur->value]; if ($cur->value == $selected) { $attr['selected'] = true; } $sattr = FormUtils::serializeAttr($attr); $label = htmlspecialchars($cur->label); return "<option {$sattr}>{$label}</option>"; }, $this->options)); }
public function Validate($id, $item) { $result = $this->validate_required($item, "email"); if ($result) { if ($this->model->is_exists($item['email'], $id)) { $this->ferr('email', 'EXISTS'); } if (!FormUtils::is_email($item['email'])) { $this->ferr('email', 'WRONG'); } } $this->validate_check_result(); }
public function Validate($id, $item) { $result = $this->validate_required($item, $this->required_fields); //result here used only to disable further validation if required fields validation failed if ($result) { if ($this->model->is_exists($item['email'], $id)) { $this->ferr('email', 'EXISTS'); } if (!FormUtils::is_email($item['email'])) { $this->ferr('email', 'WRONG'); } } $this->validate_check_result(); }
public function SaveAction($form_id) { $id = $form_id + 0; $item = req('item'); try { $this->Validate($id, $item); #load old record if necessary #$item_old = $this->model->one($id); $itemdb = FormUtils::form2dbhash($item, $this->save_fields); $id = $this->model_add_or_update($id, $itemdb); fw::redirect($this->base_url . '/' . $id . '/edit'); } catch (ApplicationException $ex) { $this->set_form_error($ex->getMessage()); $this->route_redirect("ShowForm"); } }
public function renderField($field, $error) { $label = $field->getLabel(); $content = $field->getContent(); $hint = $field->getHint(); $required = $field->attribute('required'); $class = ['form-row']; if ($required) { $class[] = 'required'; } $row_attr = FormUtils::serializeAttr(['class' => $class]); if ($field instanceof FormInput) { list($prefix, $suffix) = $field->getAddons(); $have_addon = (bool) ($prefix || $suffix); if ($prefix) { $prefix = "<span class=\"form-prefix\">{$prefix}</span>"; } if ($suffix) { $suffix = "<span class=\"form-suffix\">{$suffix}</span>"; } } else { $have_addon = false; } echo "<div {$row_attr}>\n"; if ($label !== false) { echo "<span class=\"form-label\">{$label}</span>\n"; } if ($have_addon) { echo "<span class=\"form-field\"><span class=\"form-addon\">{$prefix}{$content}{$suffix}</span></span>\n"; } else { if ($content !== false) { echo "<span class=\"form-field\">{$content}</span>\n"; } } if ($error !== false) { echo "<span class=\"form-error\">{$error}</span>\n"; } if ($hint !== false) { echo "<span class=\"form-hint\">{$hint}</span>\n"; } echo '</div>'; }
public function Validate($id, $item) { $result = $this->validate_required($item, "email old_pwd pwd pwd2"); if ($result) { $itemdb = $this->model->one($id); if ($item['old_pwd'] != $itemdb['pwd']) { $this->ferr('old_pwd', 'WRONG'); } if ($this->model->is_exists($item['email'], $id)) { $this->ferr('email', 'EXISTS'); } if (!FormUtils::is_email($item['email'])) { $this->ferr('email', 'WRONG'); } if ($item['pwd'] != $item['pwd2']) { $this->ferr('pwd2', 'NOTEQUAL'); } } $this->validate_check_result(); }
public function SaveAction($form_id) { $id = $form_id + 0; $item = req('item'); try { $this->Validate($id, $item); #load old record if necessary #$item_old = $this->model->one($id); $itemdb = FormUtils::form2dbhash($item, $this->save_fields); #TODO - checkboxes support #FormUtils::form2dbhash_checkboxes($itemdb, $item, 'is_checkbox'); $id = $this->model->update($id, $itemdb); #TODO cleanup any caches that depends on settings #FwCache::remove("XXX"); fw::redirect($this->base_url . '/' . $id . '/edit'); } catch (ApplicationException $ex) { $this->set_form_error($ex->getMessage()); $this->route_redirect("ShowForm"); } }
public function SaveAction($form_id) { $id = $form_id + 0; $item = req('item'); if (!is_array($item)) { $item = array(); } $files = UploadUtils::get_posted_files('file1'); try { $this->Validate($id, $item, $files); #load old record if necessary #$item_old = $this->model->one($id); $itemdb = FormUtils::form2dbhash($item, $this->save_fields); if (!strlen($itemdb["iname"])) { $itemdb["iname"] = 'new file upload'; } $is_add = $id == 0; $id = $this->model_add_or_update($id, $itemdb); #Proceed upload if (count($files)) { $this->model->upload($id, $files[0], $is_add); } logger($this->fw->get_response_expected_format()); if ($this->fw->get_response_expected_format() == 'json') { $item = $this->model->one($id); return array('success' => true, 'id' => $id, 'item' => $item, 'url' => $this->model->get_url_direct($item)); } else { fw::redirect($this->base_url . '/' . $id . '/edit'); } } catch (ApplicationException $ex) { logger($this->fw->get_response_expected_format()); logger($ex->getMessage()); if ($this->fw->get_response_expected_format() == 'json') { return array('success' => false, 'err_msg' => $ex->getMessage(), 'id' => $id); } else { $this->set_form_error($ex->getMessage()); $this->route_redirect("ShowForm"); } } }
*/ require_once '../include/load_config.php'; require_once '../classes/formutils.class.php'; require_once '../include/auth.inc'; require_once '../classes/lang.class.php'; require_once '../classes/dbutils.class.php'; require_once '../classes/usernotices.class.php'; require_once '../classes/userutils.class.php'; $notice = UserNotices::get_instance(); $mysqli = DBUtils::get_mysqli_link($configObject->get('cfg_db_host'), $configObject->get('cfg_db_username'), $configObject->get('cfg_db_passwd'), $configObject->get('cfg_db_database'), $configObject->get('cfg_db_charset'), $notice, $configObject->get('dbclass')); $password = $password_confirm = $email = ''; $message = ''; $critical_errors = array(); $errors = array(); $token = ''; $form_util = new FormUtils(); // Check if we've been passed a token $token = (isset($_GET['token']) and $_GET['token'] != '') ? $_GET['token'] : (!empty($_POST['token']) ? $_POST['token'] : ''); if ($token == '') { $critical_errors[] = $string['notokensupplied']; } else { // Check if the token exists and has not expired $stmt = $mysqli->prepare("SELECT id, user_id FROM password_tokens WHERE token = ? AND time > DATE_ADD(NOW(), INTERVAL -1 DAY) ORDER BY id DESC LIMIT 1"); $stmt->bind_param('s', $token); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($id, $user_id); $stmt->fetch(); if ($stmt->num_rows == 0) { $critical_errors[] = 'Invalid token'; }
/** * @return MetaConfiguration **/ public function checkIntegrity() { $out = $this->getOutput()->newLine()->infoLine('Checking sanity of generated files: ')->newLine(); set_include_path(get_include_path() . PATH_SEPARATOR . ONPHP_META_BUSINESS_DIR . PATH_SEPARATOR . ONPHP_META_DAO_DIR . PATH_SEPARATOR . ONPHP_META_PROTO_DIR . PATH_SEPARATOR . ONPHP_META_AUTO_BUSINESS_DIR . PATH_SEPARATOR . ONPHP_META_AUTO_DAO_DIR . PATH_SEPARATOR . ONPHP_META_AUTO_PROTO_DIR . PATH_SEPARATOR); $out->info("\t"); $formErrors = array(); foreach ($this->classes as $name => $class) { if (!($class->getPattern() instanceof SpookedClassPattern || $class->getPattern() instanceof SpookedEnumerationPattern || $class->getPattern() instanceof InternalClassPattern) && class_exists($class->getName(), true)) { $out->info($name, true); $info = new ReflectionClass($name); $this->checkClassSanity($class, $info); if ($info->implementsInterface('Prototyped')) { $this->checkClassSanity($class, new ReflectionClass('Proto' . $name)); } if ($info->implementsInterface('DAOConnected')) { $this->checkClassSanity($class, new ReflectionClass($name . 'DAO')); } foreach ($class->getInterfaces() as $interface) { Assert::isTrue($info->implementsInterface($interface), 'class ' . $class->getName() . ' expected to implement interface ' . $interface); } // special handling for Enumeration instances if ($class->getPattern() instanceof EnumerationClassPattern) { $object = new $name(call_user_func(array($name, 'getAnyId'))); Assert::isTrue(unserialize(serialize($object)) == $object); $out->info(', '); if ($this->checkEnumerationRefIntegrity) { $this->checkEnumerationReferentialIntegrity($object, $class->getTableName()); } continue; } if ($class->getPattern() instanceof AbstractClassPattern) { $out->info(', '); continue; } $object = new $name(); $proto = $object->proto(); $form = $proto->makeForm(); foreach ($class->getProperties() as $name => $property) { Assert::isTrue($property->toLightProperty($class) == $proto->getPropertyByName($name), 'defined property does not match autogenerated one - ' . $class->getName() . '::' . $property->getName()); } if (!$object instanceof DAOConnected) { $out->info(', '); continue; } $dao = $object->dao(); Assert::isEqual($dao->getIdName(), $class->getIdentifier()->getColumnName(), 'identifier name mismatch in ' . $class->getName() . ' class'); try { DBPool::getByDao($dao); } catch (MissingElementException $e) { // skipping $out->info(', '); continue; } $query = Criteria::create($dao)->setLimit(1)->add(Expression::notNull($class->getIdentifier()->getName()))->addOrder($class->getIdentifier()->getName())->toSelectQuery(); $out->warning(' (' . $query->getFieldsCount() . '/' . $query->getTablesCount() . '/'); $clone = clone $object; if (serialize($clone) == serialize($object)) { $out->info('C', true); } else { $out->error('C', true); } $out->warning('/'); try { $object = $dao->getByQuery($query); $form = $object->proto()->makeForm(); FormUtils::object2form($object, $form); if ($errors = $form->getErrors()) { $formErrors[$class->getName()] = $errors; $out->error('F', true); } else { $out->info('F', true); } } catch (ObjectNotFoundException $e) { $out->warning('F'); } $out->warning('/'); if (Criteria::create($dao)->setFetchStrategy(FetchStrategy::cascade())->toSelectQuery() == $dao->makeSelectHead()) { $out->info('H', true); } else { $out->error('H', true); } $out->warning('/'); // cloning once again $clone = clone $object; FormUtils::object2form($object, $form); FormUtils::form2object($form, $object); if ($object != $clone) { $out->error('T', true); } else { $out->info('T', true); } $out->warning(')')->info(', '); } } $out->infoLine('done.'); if ($formErrors) { $out->newLine()->errorLine('Errors found:')->newLine(); foreach ($formErrors as $class => $errors) { $out->errorLine("\t" . $class . ':', true); foreach ($errors as $name => $error) { $out->errorLine("\t\t" . $name . ' - ' . ($error == Form::WRONG ? ' wrong' : ' missing')); } $out->newLine(); } } return $this; }
public function SaveFacebook() { $item = FormUtils::form2dbhash($_REQUEST, 'access_token id email first_name last_name name username gender link locale timezone verified'); #TODO better validate if (!$item['access_token'] || !$item['id']) { throw new ApplicationException("Wrong facebook data", 1); } /* $fb = new Facebook(array( 'appId' => $GLOBALS['FACEBOOK_APP_ID'], 'secret' => $GLOBALS['FACEBOOK_APP_SECRET'], )); $fb_user_id = $facebook->getUser(); $user_profile = $facebook->api('/me'); */ #check if such user exists $users_id = 0; #first - check by email $hU = $this->model->one_by_email($item['email']); if ($hU['id']) { $users_id = $hU['id']; } if (!$users_id) { #now check by facebook email $hU = db_row("select * from users where fb_email=" . dbq($item['email'])); if ($hU['id']) { $users_id = $hU['id']; } } if (!$users_id) { #now check by facebook id $hU = db_row("select * from users where fb_id=" . dbq($item['id'])); if ($hU['id']) { $users_id = $hU['id']; } } if ($users_id) { #update user's missing data from facebook $vars = array('fb_access_token' => $item['access_token']); if ($hU['sex'] != ($item['gender'] == 'male' ? 1 : 0)) { $vars['sex'] = $item['gender'] == 'male' ? 1 : 0; } if (!$hU['fname']) { $vars['fname'] = $item['first_name']; } if (!$hU['lname']) { $vars['lname'] = $item['last_name']; } if ($hU['fb_email'] != $item['email'] && $item['email']) { $vars['fb_email'] = $item['email']; } if (!$hU['fb_id']) { $vars['fb_id'] = $item['id']; } if (!$hU['fb_link']) { $vars['fb_link'] = $item['link']; } if (!$hU['fb_locale']) { $vars['fb_locale'] = $item['locale']; } if (!$hU['fb_name']) { $vars['fb_name'] = $item['name']; } if (!$hU['fb_timezone']) { $vars['fb_timezone'] = $item['timezone']; } if (!$hU['fb_username']) { $vars['fb_username'] = $item['username']; } if (!$hU['fb_verified']) { $vars['fb_verified'] = $item['verified'] == 'true' ? 1 : 0; } if (!$hU['fb_picture_url']) { $vars['fb_picture_url'] = 'http://graph.facebook.com/' . $item['username'] . '/picture'; } db_update('users', $vars, $users_id); } else { #register user first if new $users_id = $this->model->add(array('email' => $item['email'], 'nick' => $item['name'], 'sex' => $item['gender'] == 'male' ? 1 : 0, 'fname' => $item['first_name'], 'lname' => $item['last_name'], 'fb_id' => $item['id'], 'fb_link' => $item['link'], 'fb_locale' => $item['locale'], 'fb_name' => $item['name'], 'fb_timezone' => $item['timezone'], 'fb_username' => $item['username'], 'fb_verified' => $item['verified'] == 'true' ? 1 : 0, 'fb_picture_url' => 'http://graph.facebook.com/' . $item['username'] . '/picture', 'fb_access_token' => $item['access_token'])); } #automatically login the user $_SESSION['is_just_registered'] = 1; $this->model->do_login($users_id); $ps = array('status' => 0, 'err_msg' => ''); parse_json($ps); }
echo $form['event_time']->renderError(); ?> </div> <div class="field <? if ($form['extra_reason']->hasError()) echo 'error';?>"> <?php echo $form['extra_reason']->render(); ?> <label>Extra Reason to Come<span style="color: #CCCCCC"> - e.g. Yankel Zissel's father's Yartzheit</span></label> <?php echo $form['extra_reason']->renderError(); ?> </div> </div> </div> <div style="clear: both; "></div> <? FormUtils::writeCSRFToken($form);?> <div class="fieldset"> <div class="fields"> <div class="field"> <button type="submit" class="action">Send blast!</button> </div> </div> </div> <div style="clear: both; "></div> </form>
public function get_select_options($sel_id) { return FormUtils::select_options_db($this->ilist(), $sel_id); }
public function get_select_options($sel_id, $parent_id = NULL) { return FormUtils::select_options_db($this->ilist($parent_id), $sel_id); }
* @author Rob Ingram * @version 1.0 * @copyright Copyright (c) 2014 The University of Nottingham * @package */ require_once '../include/load_config.php'; require_once '../classes/formutils.class.php'; require_once '../classes/lang.class.php'; require_once '../classes/dbutils.class.php'; require_once '../classes/usernotices.class.php'; $notice = UserNotices::get_instance(); $mysqli = DBUtils::get_mysqli_link($configObject->get('cfg_db_host'), $configObject->get('cfg_db_username'), $configObject->get('cfg_db_passwd'), $configObject->get('cfg_db_database'), $configObject->get('cfg_db_charset'), $notice, $configObject->get('dbclass')); $email = isset($_GET['email']) ? $_GET['email'] : ''; $message = ''; $errors = array(); $form_util = new FormUtils(); if (isset($_POST['submit']) and $_POST['submit'] == $string['send']) { $email = $_POST['email']; // Process the form submission $errors = $form_util->check_required(array('email' => $string['emailaddress'])); if (count($errors) == 0) { // Check if the supplied value is an email address (avoid an unnecessary DB call) if (!$form_util->is_email($email)) { $errors[] = $string['emailaddressinvalid']; } else { if ($form_util->is_email_in_cfg_institutional_domains($email)) { $errors[] = $string['emailaddressininstitutionaldomains']; } else { // If it is, look for the user in the database $stmt = $mysqli->prepare("SELECT id, title, surname FROM users WHERE email = ? ORDER BY id DESC LIMIT 1"); $stmt->bind_param('s', $email);
protected function serializeAttr($data = null) { return FormUtils::serializeAttr($data ?: $this->attr, ['type', 'name', 'id']); }
</tr> <? endforeach; ?> </table> <? endif; ?> </div> <div class="contact_method"> <h2>Contact methods for this minyan: </h2> <form action="<?php echo url_for('subscriptions/updateContactMethod?minyanId=' . $minyan->getId()); ?> " method="post"> <input name="contact_method[phone]" type="checkbox" <?php echo FormUtils::writeChecked($minyanUser->getUsePhone()); ?> /> Phone <br/> <input name="contact_method[text]" type="checkbox" <?php echo FormUtils::writeChecked($minyanUser->getUseSms()); ?> /> Text <br/> <input name="contact_method[email]" type="checkbox" <?php echo FormUtils::writeChecked($minyanUser->getUseEmail()); ?> /> Email <br/><br/> <button type="submit" class="fancy">Update</button> </form> </div> <? Utils::clearDiv(); ?>
private function lazyTest() { $city = TestCity::dao()->getById(1); $object = TestLazy::dao()->add(TestLazy::create()->setCity($city)->setCityOptional($city)->setEnum(new ImageType(ImageType::getAnyId()))); Cache::me()->clean(); $form = TestLazy::proto()->makeForm(); $form->import(array('id' => $object->getId())); $this->assertNotNull($form->getValue('id')); FormUtils::object2form($object, $form); foreach ($object->proto()->getPropertyList() as $name => $property) { if ($property->getRelationId() == MetaRelation::ONE_TO_ONE && $property->getFetchStrategyId() == FetchStrategy::LAZY) { $this->assertEquals($object->{$property->getGetter()}(), $form->getValue($name)); } } }
/** * perform 2 queries to get list of rows * @return int $this->list_count count of rows obtained from db * @return array of arrays $this->list_rows list of rows * @return string $this->list_pager pager from FormUtils::get_pager */ public function get_list_rows() { $this->list_count = db_value("select count(*) from {$this->table_name} where " . $this->list_where); if ($this->list_count) { $offset = $this->list_filter['pagenum'] * $this->list_filter['pagesize']; $limit = $this->list_filter['pagesize']; $sql = "SELECT * FROM {$this->table_name} WHERE {$this->list_where} ORDER BY {$this->list_orderby} LIMIT {$offset}, {$limit}"; $this->list_rows = db_array($sql); $this->list_pager = FormUtils::get_pager($this->list_count, $this->list_filter['pagenum'], $this->list_filter['pagesize']); } else { $this->list_rows = array(); $this->list_pager = array(); } }
protected function addObject(HttpRequest $request, Form $form, Identifiable $object) { FormUtils::form2object($form, $object); return $object->dao()->add($object); }