public function validate($checkMode = 'all', $requireMode = 'null') { //You do not need this if you extend DooModel or DooSmartModel //MODE: all, all_one, skip Doo::loadHelper('DooValidator'); $v = new DooValidator(); $v->checkMode = $checkMode; $v->requiredMode = $requireMode; return $v->validate(get_object_vars($this), $this->getVRules()); }
/** * Validate form * * @var array Values for form, for example $_POST * * @return boolean True or false if form is not valid */ public function isValid($values) { $valid = true; $errors = array(); try { Doo::loadHelper('DooValidator'); $v = new DooValidator(); } catch (DooFormException $e) { echo 'Validator class coulndt be loaded ' . $e->getMessage() . '\\n'; } $formElements = $this->_formElements; $elementValues = array(); foreach ($this->_elements as $element => $e) { // handle values if (isset($values[$element])) { $elementValues[$element] = $values[$element]; } // handle validators if (isset($e[1]['validators'])) { if (!isset($e[1]['required']) || $e[1]['required'] != false) { $elementRules = array($element => $e[1]['validators']); $errors[$element] = $v->validate($values, $elementRules); if ($errors[$element]) { unset($elementValues[$element]); } } else { if (isset($elementValues[$element]) && $elementValues[$element] != "") { $elementRules = array($element => $e[1]['validators']); $errors[$element] = $v->validate($values, $elementRules); } } } // handle captcha if (isset($e[0]) && $e[0] == 'captcha') { $sessionData = isset($_SESSION['doo_captcha_' . $element]) ? md5($_SESSION['doo_captcha_' . $element]) : ''; $msg = isset($e[1]['message']) ? $e[1]['message'] : null; $elementRules = array($element => array('equal', $sessionData, $msg)); $values[$element] = md5($values[$element]); $errors[$element] = $v->validate($values, $elementRules); if ($errors[$element]) { unset($elementValues[$element]); } // delete captcha if captcha is good if (isset($e[1]['url']) && file_exists($e[1]['directory'] . '/' . $sessionData . ".jpg")) { unlink($e[1]['directory'] . '/' . $sessionData . ".jpg"); } } // handle file if (isset($e[0]) && $e[0] == 'file') { // if there is file check if file exists if (isset($_FILES[$element])) { // check file extension if (isset($e[1]['extension'])) { $extensions = array(); $extension = substr($_FILES[$element]['name'], strrpos($_FILES[$element]['name'], '.') + 1); $extensions = explode(',', $e[1]['extension']); if (!in_array($extension, $extensions)) { $errors[$element] = array('File must have ' . $e[1]['extension'] . ' extension.'); } } // check file size if (isset($e[1]['size'])) { if ($e[1]['size'] < $_FILES[$element]['size']) { $errors[$element] = array('File is too big!'); } } } else { if (isset($e[1]['required']) && $e[1]['required'] == 1) { $errors[$element][] = array('File for upload is required.'); } } } } // set values $this->_elementValues = $elementValues; if (count($errors) > 0) { $this->_errors = $errors; foreach ($errors as $error => $e) { if (!empty($e)) { $valid = false; } } } return $valid; }
/** * Validate the Model with the rules defined in getVRules() * * @param object $model Model object to be validated. * @param string $checkMode Validation mode. all, all_one, skip * @param string $requireMode Require Check Mode. null, nullempty * @return array Return array of errors if exists. Return null if data passes the validation rules. */ public static function _validate($model, $checkMode = 'all', $requireMode = 'null') { //all, all_one, skip Doo::loadHelper('DooValidator'); $v = new DooValidator(); $v->checkMode = $checkMode; $v->requiredMode = $requireMode; return $v->validate(get_object_vars($model), $model->getVRules()); }
/** * Generates Model class files from a MySQL database * @param bool $comments Generate comments along with the Model class * @param bool $vrules Generate validation rules along with the Model class * @param string $extends make Model class to extend DooModel or DooSmartModel * @param bool $createBase Generate base model class, will not rewrite/replace model classes if True. * @param string $baseSuffix Suffix string for the base model. * @param int $chmod Chmod for file manager * @param string $path Path to write the model class files */ public static function genMySQL($comments = true, $vrules = true, $extends = 'DooModel', $createBase = true, $baseSuffix = 'Base', $chmod = null, $path = null) { if ($path === null) { $path = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER . 'model/'; } Doo::loadHelper('DooFile'); if ($chmod === null) { $fileManager = new DooFile(); } else { $fileManager = new DooFile($chmod); } $dbconf = Doo::db()->getDefaultDbConfig(); if (!isset($dbconf) || empty($dbconf)) { echo "<html><head><title>DooPHP Model Generator - DB: Error</title></head><body bgcolor=\"#2e3436\"><span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;\"><span style=\"color:#fff;\">Please setup the DB first in index.php and db.conf.php</span></span>"; exit; } $dbname = $dbconf[1]; echo "<html><head><title>DooPHP Model Generator - DB: {$dbname}</title></head><body bgcolor=\"#2e3436\">"; $smt = Doo::db()->query("SHOW TABLES"); $tables = $smt->fetchAll(); $clsExtendedNum = 0; foreach ($tables as $tbl) { if (stristr($_SERVER['SERVER_SOFTWARE'], 'Win32')) { $tblname = $tbl['Tables_in_' . strtolower($dbname)]; } else { $tblname = $tbl['Tables_in_' . $dbname]; } $smt2 = null; unset($smt2); $smt2 = Doo::db()->query("DESC `{$tblname}`"); $fields = $smt2->fetchAll(); //print_r($fields); $classname = ''; $temptbl = $tblname; for ($i = 0; $i < strlen($temptbl); $i++) { if ($i == 0) { $classname .= strtoupper($temptbl[0]); } else { if ($temptbl[$i] == '_' || $temptbl[$i] == '-' || $temptbl[$i] == '.') { $classname .= strtoupper($temptbl[$i + 1]); $arr = str_split($temptbl); array_splice($arr, $i, 1); $temptbl = implode('', $arr); } else { $classname .= $temptbl[$i]; } } } if (!empty($extends)) { if ($createBase != True) { if ($extends == DooModelGen::EXTEND_MODEL || $extends == DooModelGen::EXTEND_SMARTMODEL) { $filestr = "<?php\nDoo::loadCore('db/{$extends}');\n\nclass {$classname} extends {$extends}{\n"; } else { $filestr = "<?php\nDoo::loadClass('{$extends}');\n\nclass {$classname} extends {$extends}{\n"; } } else { if ($extends == DooModelGen::EXTEND_MODEL || $extends == DooModelGen::EXTEND_SMARTMODEL) { $filestr = "<?php\nDoo::loadCore('db/{$extends}');\n\nclass {$classname}{$baseSuffix} extends {$extends}{\n"; } else { $filestr = "<?php\nDoo::loadClass('{$extends}');\n\nclass {$classname}{$baseSuffix} extends {$extends}{\n"; } } } else { if ($createBase != True) { $filestr = "<?php\nclass {$classname}{\n"; } else { $filestr = "<?php\nclass {$classname}{$baseSuffix}{\n"; } } $pkey = ''; $ftype = ''; $fieldnames = array(); if ($vrules) { Doo::loadHelper('DooValidator'); } $rules = array(); foreach ($fields as $f) { $fstring = ''; if ($comments && isset($f['Type']) && !empty($f['Type'])) { preg_match('/([^\\(]+)[\\(]?([\\d]*)?[\\)]?(.+)?/', $f['Type'], $ftype); $length = ''; $more = ''; if (isset($ftype[2]) && !empty($ftype[2])) { $length = " Max length is {$ftype['2']}."; } if (isset($ftype[3]) && !empty($ftype[3])) { $more = " {$ftype['3']}."; $ftype[3] = trim($ftype[3]); } $fstring = "\n /**\n * @var {$ftype[1]}{$length}{$more}\n */\n"; //-------- generate rules for the setupValidation() in Model ------ if ($vrules) { $rule = array(); if ($rulename = DooValidator::dbDataTypeToRules(strtolower($ftype[1]))) { $rule = array(array($rulename)); } if (isset($ftype[3]) && $ftype[3] == 'unsigned') { $rule[] = array('min', 0); } if (ctype_digit($ftype[2])) { if ($ftype[1] == 'varchar' || $ftype[1] == 'char') { $rule[] = array('maxlength', intval($ftype[2])); } else { if ($rulename == 'integer') { $rule[] = array('maxlength', intval($ftype[2])); } } } if (strtolower($f['Null']) == 'no' && strpos(strtolower($f['Extra']), 'auto_increment') === false) { $rule[] = array('notnull'); } else { $rule[] = array('optional'); } if (isset($rule[0])) { $rules[$f['Field']] = $rule; } } } $filestr .= "{$fstring} public \${$f['Field']};\n"; $fieldnames[] = $f['Field']; if ($f['Key'] == 'PRI') { $pkey = $f['Field']; } } $fieldnames = implode($fieldnames, "','"); $filestr .= "\n public \$_table = '{$tblname}';\n"; $filestr .= " public \$_primarykey = '{$pkey}';\n"; $filestr .= " public \$_fields = array('{$fieldnames}');\n"; if ($vrules && !empty($rules)) { $filestr .= "\n public function getVRules() {\n return " . self::exportRules($rules) . "\n }\n\n"; if (empty($extends)) { $filestr .= " public function validate(\$checkMode='all'){\n\t\t//You do not need this if you extend DooModel or DooSmartModel\n\t\t//MODE: all, all_one, skip\n\t\tDoo::loadHelper('DooValidator');\n\t\t\$v = new DooValidator;\n\t\t\$v->checkMode = \$checkMode;\n\t\treturn \$v->validate(get_object_vars(\$this), \$this->getVRules());\n\t}\n\n"; } } $filestr .= "}"; if ($createBase != True) { if ($fileManager->create($path . "{$classname}.php", $filestr, 'w+')) { echo "<span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;\"><span style=\"color:#fff;\">Model for table </span><strong><span style=\"color:#e7c118;\">{$tblname}</span></strong><span style=\"color:#fff;\"> generated. File - </span><strong><span style=\"color:#729fbe;\">{$classname}</span></strong><span style=\"color:#fff;\">.php</span></span><br/><br/>"; } else { echo "<span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;\"><span style=\"color:#f00;\">Model for table </span><strong><span style=\"color:#e7c118;\">{$tblname}</span></strong><span style=\"color:#f00;\"> could not be generated. File - </span><strong><span style=\"color:#729fbe;\">{$classname}</span></strong><span style=\"color:#f00;\">.php</span></span><br/><br/>"; } } else { if ($fileManager->create($path . "base/{$classname}{$baseSuffix}.php", $filestr, 'w+')) { echo "<span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;\"><span style=\"color:#fff;\">Base model for table </span><strong><span style=\"color:#e7c118;\">{$tblname}</span></strong><span style=\"color:#fff;\"> generated. File - </span><strong><span style=\"color:#729fbe;\">{$classname}{$baseSuffix}</span></strong><span style=\"color:#fff;\">.php</span></span><br/><br/>"; $clsfile = $path . "{$classname}.php"; if (!file_exists($clsfile)) { $filestr = "<?php\nDoo::loadModel('base/{$classname}{$baseSuffix}');\n\nclass {$classname} extends {$classname}{$baseSuffix}{\n}"; if ($fileManager->create($clsfile, $filestr, 'w+')) { echo "<span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;\"><span style=\"color:#fff;\">Model for table </span><strong><span style=\"color:#e7c118;\">{$tblname}</span></strong><span style=\"color:#fff;\"> generated. File - </span><strong><span style=\"color:#729fbe;\">{$classname}</span></strong><span style=\"color:#fff;\">.php</span></span><br/><br/>"; $clsExtendedNum++; } else { echo "<span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;\"><span style=\"color:#f00;\">Model for table </span><strong><span style=\"color:#e7c118;\">{$tblname}</span></strong><span style=\"color:#f00;\"> could not be generated. File - </span><strong><span style=\"color:#729fbe;\">{$classname}</span></strong><span style=\"color:#f00;\">.php</span></span><br/><br/>"; } } } else { echo "<span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;\"><span style=\"color:#f00;\">Base model for table </span><strong><span style=\"color:#e7c118;\">{$tblname}</span></strong><span style=\"color:#f00;\"> could not be generated. File - </span><strong><span style=\"color:#729fbe;\">{$classname}{$baseSuffix}</span></strong><span style=\"color:#f00;\">.php</span></span><br/><br/>"; } } } $total = sizeof($tables) + $clsExtendedNum; echo "<span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;color:#fff;\">Total {$total} file(s) generated.</span></body></html>"; }
/** * Generates Model class files from a MySQL database * @param bool $comments Generate comments along with the Model class */ public static function gen_mysql($comments = true, $vrules = true) { $dbconf = Doo::db()->getDefaultDbConfig(); if (!isset($dbconf) || empty($dbconf)) { echo "<html><head><title>DooPHP Model Generator - DB: Error</title></head><body bgcolor=\"#2e3436\"><span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;\"><span style=\"color:#fff;\">Please setup the DB first in index.php and db.conf.php</span></span>"; exit; } $dbname = $dbconf[1]; echo "<html><head><title>DooPHP Model Generator - DB: {$dbname}</title></head><body bgcolor=\"#2e3436\">"; $smt = Doo::db()->query("SHOW TABLES"); $tables = $smt->fetchAll(); foreach ($tables as $tbl) { if (stristr($_SERVER['SERVER_SOFTWARE'], 'Win32')) { $tblname = $tbl['Tables_in_' . strtolower($dbname)]; } else { $tblname = $tbl['Tables_in_' . $dbname]; } $smt2 = Doo::db()->query("DESC `{$tblname}`"); $fields = $smt2->fetchAll(); //print_r($fields); $classname = ''; $temptbl = $tblname; for ($i = 0; $i < strlen($temptbl); $i++) { if ($i == 0) { $classname .= strtoupper($temptbl[0]); } else { if ($temptbl[$i] == '_' || $temptbl[$i] == '-' || $temptbl[$i] == '.') { $classname .= strtoupper($temptbl[$i + 1]); $arr = str_split($temptbl); array_splice($arr, $i, 1); $temptbl = implode('', $arr); } else { $classname .= $temptbl[$i]; } } } $filestr = "<?php\nclass {$classname}{\n"; $pkey = ''; $ftype = ''; $fieldnames = array(); if ($vrules) { Doo::loadHelper('DooValidator'); } $rules = array(); foreach ($fields as $f) { $fstring = ''; if ($comments && isset($f['Type']) && !empty($f['Type'])) { preg_match('/([^\\(]+)[\\(]?([\\d]*)?[\\)]?(.+)?/', $f['Type'], $ftype); $length = ''; $more = ''; if (isset($ftype[2]) && !empty($ftype[2])) { $length = " Max length is {$ftype['2']}."; } if (isset($ftype[3]) && !empty($ftype[3])) { $more = " {$ftype['3']}."; $ftype[3] = trim($ftype[3]); } $fstring = "\n /**\n * @var {$ftype[1]}{$length}{$more}\n */\n"; //-------- generate rules for the setupValidation() in Model ------ if ($vrules) { $rule = array(); if ($rulename = DooValidator::dbDataTypeToRules(strtolower($ftype[1]))) { $rule = array(array($rulename)); } if (isset($ftype[3]) && $ftype[3] == 'unsigned') { $rule[] = array('min', 0); } if (ctype_digit($ftype[2])) { if ($ftype[1] == 'varchar' || $ftype[1] == 'char') { $rule[] = array('maxlength', intval($ftype[2])); } else { if ($rulename == 'integer') { $rule[] = array('maxlength', intval($ftype[2])); } } } if (strtolower($f['Null']) == 'no') { $rule[] = array('notnull'); } else { $rule[] = array('optional'); } if (isset($rule[0])) { $rules[$f['Field']] = $rule; } } } $filestr .= "{$fstring} public \${$f['Field']};\n"; $fieldnames[] = $f['Field']; if ($f['Key'] == 'PRI') { $pkey = $f['Field']; } } $fieldnames = implode($fieldnames, "','"); $filestr .= "\n public \$_table = '{$tblname}';\n"; $filestr .= " public \$_primarykey = '{$pkey}';\n"; $filestr .= " public \$_fields = array('{$fieldnames}');\n"; if ($vrules && isset($rules) && !empty($rules)) { $filestr .= "\n public function getVRules() {\n return " . self::exportRules($rules) . "\n }\n\n"; $filestr .= " public function validate(\$checkMode='all'){\r\n //You do not need this if you extend DooModel or DooSmartModel\r\n //MODE: all, all_one, skip\r\n Doo::loadHelper('DooValidator');\r\n \$v = new DooValidator;\r\n \$v->checkMode = \$checkMode;\r\n return \$v->validate(get_object_vars(\$this), \$this->getVRules());\r\n }\n\n"; } $filestr .= "}\n?>"; $handle = fopen(Doo::conf()->SITE_PATH . "/protected/model/{$classname}.php", 'w+'); fwrite($handle, $filestr); fclose($handle); echo "<span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;\"><span style=\"color:#fff;\">Model for table </span><strong><span style=\"color:#e7c118;\">{$tblname}</span></strong><span style=\"color:#fff;\"> generated. File - </span><strong><span style=\"color:#729fbe;\">{$classname}</span></strong><span style=\"color:#fff;\">.php</span></span><br/><br/>"; //print_r($rules); } $total = sizeof($tables); echo "<span style=\"font-size:190%;font-family: 'Courier New', Courier, monospace;color:#fff;\">Total {$total} file(s) generated.</span></body></html>"; }
/** * 用户登录 * @param string $account * @param string $passwd * @param string $safecode * @return int */ public function login($account, $passwd, $safecode = '', $lang = 'zh', $remember = 0) { Doo::loadHelper('DooValidator'); $v = new DooValidator(); $success = TRUE; $userinfo = $errors = array(); $postData = array('username' => $account, 'password' => $passwd, 'captcha' => $safecode, 'lang' => $lang); //D($postData); $rules = array('username' => array(array('maxlength', 20), array('notnull')), 'password' => array(array('maxlength', 20), array('notnull')), 'captcha' => array(array('notnull'), array('custom', 'User::vSafecode')), 'lang' => array(array('notnull'), array('inList', array_keys(Doo::conf()->langList)))); if ($this->_checkSafecode == FALSE) { unset($rules['captcha']); } if ($errors = $v->validate($postData, $rules)) { $success = FALSE; } // 无论登录是否正确都删除验证码 unset($_SESSION['safe_code']); if ($success) { //根据用户账号查数据库获取用户 $param = array('username' => $account); $result = DBproxy::getProcedure('Manage')->setDimension(2)->spSysUserSSign($param); if (!empty($result)) { $userinfo = $result; $userinfo['uname'] = $userinfo['username'] = $account; } else { $success = FALSE; $errors['username'] = '******'; } } if ($success) { if ($userinfo['passwd'] != $this->password($passwd)) { $success = FALSE; $errors['password'] = '******'; } } //用户锁定 if ($success) { if ($userinfo['is_locked'] == 1) { $success = FALSE; $errors['username'] = '******'; } } //用户验证 if ($success) { if ($userinfo['is_check'] == 0) { $success = FALSE; $errors['username'] = '******'; } } if ($success) { //取所属角色(s) $userinfo['roleids'] = $this->get_user_roles($userinfo['uid']); $this->userinfo = $userinfo; //最后做是否验证的检查 if ($userinfo['is_check'] == 1) { $_SESSION['userinfo'] = $this->userinfo; //写权限到$_SESSION['authory'] $this->authorityInSession(); $this->insert_login_log($userinfo['uid']); } else { $_SESSION['userinfo_tmp'] = $this->userinfo; } } if ($success && $remember) { @setcookie($this->_rememberKey, encrypt(getIp() . '|' . $account . '|' . $passwd . '|' . $lang, Doo::conf()->KEY_PASSWORD), time() + 30 * 86400, '/'); } return array('success' => $success, 'errors' => $errors); }
function saveNewPost() { Doo::loadHelper('DooValidator'); $_POST['content'] = trim($_POST['content']); //get defined rules and add show some error messages $validator = new DooValidator(); $validator->checkMode = DooValidator::CHECK_SKIP; if ($error = $validator->validate($_POST, 'post_create.rules')) { $data['rootUrl'] = Doo::conf()->APP_URL; $data['title'] = 'Error Occured!'; $data['content'] = '<p style="color:#ff0000;">' . $error . '</p>'; $data['content'] .= '<p>Go <a href="javascript:history.back();">back</a> to edit.</p>'; $this->render('admin_msg', $data); } else { Doo::loadModel('Post'); Doo::loadModel('Tag'); Doo::autoload('DooDbExpression'); $p = new Post($_POST); $p->createtime = new DooDbExpression('NOW()'); //insert the post along with the tags if (self::$tags != Null) { $tags = array(); foreach (self::$tags as $t) { $tg = new Tag(); $tg->name = $t; $tags[] = $tg; } $id = $p->relatedInsert($tags); } else { $id = $p->insert(); } //clear the sidebar cache Doo::cache('front')->flushAllParts(); $data['rootUrl'] = Doo::conf()->APP_URL; $data['title'] = 'Post Created!'; $data['content'] = '<p>Your post is created successfully!</p>'; if ($p->status == 1) { $data['content'] .= '<p>Click <a href="' . $data['rootUrl'] . 'article/' . $id . '">here</a> to view the published post.</p>'; } $this->render('admin_msg', $data); } }