/** * @dataProvider providerIDNEmail * * @param string $email * @param boolean $validateIDN * @param string $assertion */ public function testIDNUrl($email, $validateIDN, $assertion) { $emailValidator = new CEmailValidator(); $emailValidator->validateIDN = $validateIDN; $result = $emailValidator->validateValue($email); $this->assertEquals($assertion, $result); }
/** * Send reminder emails to those who haven't paid for their next week's box */ public function actionSendReminderEmails() { $Customers = Customer::model()->findAllWithNoOrders(); foreach ($Customers as $Cust) { $validator = new CEmailValidator(); if ($validator->validateValue(trim($Cust->User->email))) { $User = $Cust->User; $User->auto_login_key = $User->generatePassword(50, 4); $User->update_time = new CDbExpression('NOW()'); $User->update(); $adminEmail = SnapUtil::config('boxomatic/adminEmail'); $adminEmailFromName = SnapUtil::config('boxomatic/adminEmailFromName'); $message = new YiiMailMessage('Running out of orders'); $message->view = 'customer_running_out_of_orders'; $message->setBody(array('Customer' => $Cust, 'User' => $User), 'text/html'); $message->addTo($Cust->User->email); $message->addBcc($adminEmail); //$message->addTo('*****@*****.**'); $message->setFrom(array($adminEmail => $adminEmailFromName)); if (!@Yii::app()->mail->send($message)) { echo '<p style="color:red"><strong>Email failed sending to: ' . $Cust->User->email . '</strong></p>'; } else { echo '<p>Running out of orders message sent to: ' . $Cust->User->email . '</p>'; } } else { echo '<p style="color:red"><strong>Email not valid: "' . $Cust->User->email . '"</strong></p>'; } } echo '<p><strong>Finished.</strong></p>'; //Yii::app()->end(); }
/** * Authenticates a user. * @return boolean whether authentication succeeds. */ public function authenticate() { $validator = new CEmailValidator(); //判断是否是邮箱,是邮箱则以邮箱登录 if ($validator->validateValue($this->email)) { $user = Users::model()->find('email=:email', array(':email' => $this->email)); } else { //不是邮箱则认为是电话号码 $user = Users::model()->find('phone=:phone', array(':phone' => $this->email)); } if ($user === null) { $this->errorCode = self::ERROR_USERNAME_INVALID; } else { if ($user['status'] != Common::STATUS_PASSED) { if ($user['classify'] == Users::CLASSIFY_COMMON_USER) { $this->errorCode = self::ERROR_USERNAME_INVALID; } } else { if (!$this->validatePassword($user->password, $user->hash)) { $this->errorCode = self::ERROR_PASSWORD_INVALID; } else { $this->_id = $user->id; $this->username = $user->username; $this->errorCode = self::ERROR_NONE; } } } return $this->errorCode == self::ERROR_NONE; }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionMakePayment() { $model = new UserPayment(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['UserPayment'])) { $model->attributes = $_POST['UserPayment']; $model->user_id = Yii::app()->user->user_id; $model->payment_date = new CDbExpression('NOW()'); if ($model->save()) { $Customer = $model; $validator = new CEmailValidator(); if ($validator->validateValue($Customer->email)) { //email payment receipt $adminEmail = SnapUtil::config('boxomatic/adminEmail'); $adminEmailFromName = SnapUtil::config('boxomatic/adminEmailFromName'); $message = new YiiMailMessage('Payment receipt'); $message->view = 'customer_payment_receipt'; $message->setBody(array('Customer' => $Customer, 'UserPayment' => $model), 'text/html'); $message->addTo($Customer->email); $message->addTo($adminEmail); $message->setFrom(array($adminEmail => $adminEmailFromName)); if (!@Yii::app()->mail->send($message)) { $mailError = true; } } $this->redirect(array('view', 'id' => $model->payment_id)); } } $User = BoxomaticUser::model()->findByPk(Yii::app()->user->id); $this->render('make_payment', array('model' => $model, 'User' => $User, 'Customer' => $User)); }
/** * validate comma-separated email string * @param object data model * @param string data model attributes * */ protected function validateAttribute($object, $attribute) { $values = $object->{$attribute}; if ($this->allowEmpty && $this->isEmpty($values)) { return; } $values = explode($this->delimiter, $values); $count = count($values); if ($count > $this->max && $this->max != 0) { $message = $this->message !== null ? $this->message : Yii::t('yii', 'A maximum of {value} email(s) allowed.'); $this->addError($object, $attribute, $message, array('{value}' => $this->max)); return; } if ($count < $this->min && $this->min != 0) { $message = $this->message !== null ? $this->message : Yii::t('yii', 'At least {value} email(s) required.'); $this->addError($object, $attribute, $message, array('{value}' => $this->min)); return; } foreach ($values as $value) { $value = trim($value); if (!parent::validateValue($value)) { if (!empty($value)) { $message = $this->message !== null ? $this->message : Yii::t('yii', '{value} is not a valid email address.'); $this->addError($object, $attribute, $message, array('{value}' => $value)); } } } }
public function registrar_usuario_cruge($correo, $gen_key = true, $contrasena = null) { $usuario_cruge = Yii::app()->user->um->createBlankUser(); $usuario_cruge->email = $correo; if (Yii::app()->user->um->loadUser($usuario_cruge->email) != null) { if ($usuario_cruge->password != NULL && $usuario_cruge->state != 0) { return $usuario_cruge; } } else { $mail_validator = new CEmailValidator(); if (!$mail_validator->validateValue($correo)) { return false; } if ($gen_key) { $usuario_cruge->authkey = md5(uniqid(time() . rand(), true)); } $usuario_cruge->username = Yii::app()->user->um->generateNewUsername($correo); if ($contrasena != null) { Yii::app()->user->um->changePassword($usuario_cruge, $contrasena); } if (Yii::app()->user->um->save($usuario_cruge)) { return $usuario_cruge; } else { Yii::log(PHP_EOL . '<--->' . PHP_EOL . $e->getMessage() . PHP_EOL, 'warning'); return false; } } }
/** * Authenticates a user. * @return boolean whether authentication succeeds. */ public function authenticate() { $validator = new CEmailValidator(); if ($validator->validateValue($this->email)) { $user = Users::model()->find('email=:email', array(':email' => $this->email)); } else { $user = Users::model()->find('truename=:truename', array(':truename' => $this->email)); } if ($user === null) { $this->errorCode = self::ERROR_USERNAME_INVALID; } else { if ($user['status'] != Posts::STATUS_PASSED) { $this->errorCode = self::ERROR_USERNAME_INVALID; } else { if (!$this->validatePassword($user->password)) { $this->errorCode = self::ERROR_PASSWORD_INVALID; } else { $this->_id = $user->id; $this->username = $user->truename; $this->errorCode = self::ERROR_NONE; } } } return $this->errorCode == self::ERROR_NONE; }
public function setEmails($emails) { $this->_emails = array_values(array_unique((array) $emails)); $emailValidator = new CEmailValidator(); foreach ($this->_emails as $email) { if (!$emailValidator->validateValue($email)) { throw new CException('Некорректный e-mail ' . $email); } } }
public function validateProvidedEmail($attribute, $params) { if ($this->selectContactOrEmailRadioButton == 0) { return true; } $emailValidator = new CEmailValidator(); if (!$emailValidator->validateValue($this->inputEmailAddressBox)) { $this->addError($attribute, Zurmo::t('MarketingModule', 'Please provide an email address.')); return false; } return true; }
public function actionSendMail() { $model = new MailForm(); if (isset($_POST['MailForm'])) { $model->attributes = $_POST['MailForm']; } $validator = new CEmailValidator(); if ($validator->validateValue($model->to) && $validator->validateValue($model->from)) { $m = new Mail(); // create the mail $m->From($model->from); $m->To($model->to); $m->Subject(Yii::app()->params['appName']); $m->Body($model->body, "utf-8"); //$m->Attach ($_SERVER['DOCUMENT_ROOT'] . "/fb/hannah/soutez-o-stan/images/2011_223_0444_POUKAZKA_NA_FB_stan_spacak_triko_03.jpg", "image/jpg", "attachment", "2011_223_0444_POUKAZKA_NA_FB_stan_spacak_triko_03.jpg"); // attach toto.gif file as fun.gif $m->Send(); echo "1"; } else { echo "0"; } }
public function validateEmail($attribute, $params) { $validator = new CEmailValidator(); $emails = explode(",", $this->{$attribute}); $error = 'Emails has error in'; foreach ($emails as $email) { $email = trim($email); if (!$validator->validateValue($email)) { $error .= " '" . $email . "' "; } } if ($error != 'Emails has error in') { $this->addError($attribute, $error); } }
/** * @see BatchAttributeValueDataAnalyzer::analyzeByValue() */ protected function analyzeByValue($value) { if ($value == null) { return; } $validator = new CEmailValidator(); $validatedEmail = $validator->validateValue($value); if ($validatedEmail === false) { $this->messageCountData[static::INVALID]++; return; } if (strlen($validatedEmail) > $this->maxLength) { $this->messageCountData[static::EMAIL_TOO_LONG]++; } }
/** * Phương thức checkUserExists($attribute, $params) dùng để kiểm tra xem username có tồn tại không * * @param type $attribute * @param type $params */ public function checkUserExists($attribute, $params) { $validator = new CEmailValidator(); if (strpos($this->username, '@') !== false) { if ($validator->validateValue($this->username)) { $user = User::model()->notsafe()->findByAttributes(array('email' => $this->username)); } else { $this->addError('username', UserModule::t("{attribute} is not a valid email address.", array('{attribute}' => $this->username))); } } else { $user = User::model()->notsafe()->findByUserName($this->username); } if (isset($user)) { $this->__user = $user; } else { $this->addError('username', UserModule::t('User "{path}" does not exist.', array('{path}' => $this->username))); } }
/** * Given a value, resolve that the value is a correctly formatted email address. If not, an * InvalidValueToSanitizeException is thrown. * @param string $modelClassName * @param string $attributeName * @param mixed $value * @param array $mappingRuleData */ public static function sanitizeValue($modelClassName, $attributeName, $value, $mappingRuleData) { assert('is_string($modelClassName)'); assert('is_string($attributeName)'); assert('$mappingRuleData == null'); if ($value == null) { return $value; } $maxLength = DatabaseCompatibilityUtil::getMaxVarCharLength(); $validator = new CEmailValidator(); $validatedEmail = $validator->validateValue($value); if ($validatedEmail === false) { throw new InvalidValueToSanitizeException(Zurmo::t('ImportModule', 'Invalid email format.')); } if (strlen($validatedEmail) > $maxLength) { throw new InvalidValueToSanitizeException(Zurmo::t('ImportModule', 'Email was too long.')); } return $value; }
public function actionCambiarcorreo() { $mail_validator = new CEmailValidator(); if (isset($_POST['RegistroForm']['correo']) && isset($_POST['RegistroForm']['repetir_correo']) && $_POST['RegistroForm']['correo'] == $_POST['RegistroForm']['repetir_correo'] && $mail_validator->validateValue($_POST['RegistroForm']['correo']) && !Yii::app()->user->um->loadUser($_POST['RegistroForm']['correo'])) { $correo = $_POST['RegistroForm']['correo']; $usuario_cruge = Yii::app()->user->um->loadUserById(Yii::app()->user->id); $usuario_cruge->authkey = md5(uniqid(time() . rand(), true)); $usuario_cruge->util = $correo; if (Yii::app()->user->um->save($usuario_cruge)) { $this->getModule()->crugemailer->verificar_correo($usuario_cruge); $msg = json_encode(array('email' => $usuario_cruge->email)); } else { $msg = json_encode(array('error' => "No se pudo guardar el correo")); } } else { $msg = json_encode(array('error' => "Ocurrió un error")); } echo header('Content-type: application/json; charset=UTF-8'); echo $msg; }
/** * Verify our email address is valid using built in Validator. * * @param CActiveRecord $obj Configuration key. * * @return boolean */ public function validateEmail($obj) { $objV = new CEmailValidator(); if (empty($obj->key_value) === false) { return $objV->validateValue($obj->key_value); } return true; }
/** * */ public function actionProcessCustBox($custBox) { $CustBox = UserBox::model()->findByPk($custBox); $User = $CustBox->User; if ($User->balance >= $CustBox->Box->box_price + $CustBox->delivery_cost) { $Payment = new UserPayment(); $Payment->payment_value = -1 * ($CustBox->Box->box_price + $CustBox->delivery_cost); //make price a negative value for payment table $Payment->payment_type = 'DEBIT'; $Payment->payment_date = new CDbExpression('NOW()'); $Payment->user_id = $CustBox->user_id; $Payment->staff_id = Yii::app()->user->id; $note = '1 x ' . $CustBox->Box->BoxSize->box_size_name . ' Box @ ' . SnapFormat::currency($CustBox->Box->box_price); $tmpDel = (double) $CustBox->delivery_cost; if (!empty($tmpDel)) { $note .= ' + ' . SnapFormat::currency($tmpDel) . ' delivery'; } $Payment->payment_note = $note; $Payment->save(); $CustBox->status = UserBox::STATUS_APPROVED; $CustBox->save(); //Box approved email $validator = new CEmailValidator(); if ($validator->validateValue($User->email)) { $adminEmail = SnapUtil::config('boxomatic/adminEmail'); $adminEmailFromName = SnapUtil::config('boxomatic/adminEmailFromName'); $date = $CustBox->Box->DeliveryDate->date; $message = new YiiMailMessage('Your order for ' . $date . ' has been approved'); $message->view = 'customer_box_approved'; $message->setBody(array('Customer' => $User, 'UserBox' => $CustBox), 'text/html'); $message->addTo($User->email); $message->addTo($adminEmail); $message->setFrom(array($adminEmail => $adminEmailFromName)); if (!@Yii::app()->mail->send($message)) { $mailError = true; } } Yii::app()->user->setFlash('success', "User included in this date's delivery."); } else { Yii::app()->user->setFlash('error', "Insufficient funds!"); } $this->redirect(array('userBoxes', 'date' => $CustBox->Box->delivery_date_id)); }
/** * register user * Enter description here ... */ function actionUpdateProfile() { header('Content-type: application/json'); // if(!Yii::app()->request->isPostRequest){ // IjoyPlusServiceUtils::exportServiceError(Constants::METHOD_NOT_SUPPORT); // return ; // } if (!IjoyPlusServiceUtils::validateAPPKey()) { IjoyPlusServiceUtils::exportServiceError(Constants::APP_KEY_INVALID); return; } $nickname = Yii::app()->request->getParam("nickname"); $pwd = Yii::app()->request->getParam("password"); $username = Yii::app()->request->getParam("username"); $sourceid = Yii::app()->request->getParam("source_id"); $source_type = Yii::app()->request->getParam("source_type"); if (!IjoyPlusServiceUtils::validateThirdPartSource($source_type)) { IjoyPlusServiceUtils::exportServiceError(Constants::THIRD_PART_SOURCE_TYPE_INVALID); return; } if (!(isset($nickname) && !is_null($nickname) && strlen($nickname) > 0)) { IjoyPlusServiceUtils::exportServiceError(Constants::NICKNAME_IS_NULL); return; } if (!(isset($pwd) && !is_null($pwd) && strlen($pwd) > 0)) { IjoyPlusServiceUtils::exportServiceError(Constants::PWD_IS_NULL); return; } if (isset($username) && !is_null($username) && strlen($username) > 0) { $emailValidator = new CEmailValidator(); if (!$emailValidator->validateValue($username)) { IjoyPlusServiceUtils::exportServiceError(Constants::EMAIL_INVALID); return; } else { $record = User::model()->find('LOWER(username)=?', array(strtolower($username))); if ($record !== null) { IjoyPlusServiceUtils::exportServiceError(Constants::USERNAME_EXIST); return; } } } try { $record = User::model()->find('LOWER(nickname)=?', array(strtolower($nickname))); if ($record !== null) { IjoyPlusServiceUtils::exportServiceError(Constants::NICKNAME_IS_EXSTING); return; } else { $model = new User(); $model->nickname = $nickname; $model->password = md5($pwd); $model->username = $username; $model->status = Constants::USER_APPROVAL; $model->create_date = new CDbExpression('NOW()'); switch ($source_type) { case Constants::THIRD_PART_ACCOUNT_DOUBAN: $model->douban_user_id = $sourceid; break; case Constants::THIRD_PART_ACCOUNT_QQ: $model->qq_wb_user_id = $sourceid; break; case Constants::THIRD_PART_ACCOUNT_REN_REN: $model->ren_user_id = $sourceid; break; case Constants::THIRD_PART_ACCOUNT_SINA: $model->sina_wb_user_id = $sourceid; break; } if ($model->save()) { $identity = new IjoyPlusUserIdentity($username, $pwd); $identity->setId($model->id); $identity->setState('nickname', $model->nickname); Yii::app()->user->login($identity); UserManager::followPrestiges($model->id); IjoyPlusServiceUtils::exportServiceError(Constants::SUCC); // } else { Yii::log(CJSON::encode($model->getErrors()), "warning"); // var_dump(); IjoyPlusServiceUtils::exportServiceError(Constants::SYSTEM_ERROR); } } } catch (Exception $e) { Yii::log(CJSON::encode($e), "error"); IjoyPlusServiceUtils::exportServiceError(Constants::SYSTEM_ERROR); } }
/** * Given a partial name or e-mail address, search for all Users, Leads or Contacts * JSON encode the resulting array of contacts. */ public function actionAutoCompleteForMultiSelectAutoComplete($term, $autoCompleteOptions = null) { $pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType('autoCompleteListPageSize', get_class($this->getModule())); $usersByFullName = UserSearch::getUsersByPartialFullName($term, $pageSize, $autoCompleteOptions); $usersByEmailAddress = UserSearch::getUsersByEmailAddress($term, 'contains', true, $autoCompleteOptions, $pageSize); $contacts = ContactSearch::getContactsByPartialFullNameOrAnyEmailAddress($term, $pageSize, null, 'contains', $autoCompleteOptions); $autoCompleteResults = array(); foreach ($usersByEmailAddress as $user) { if (isset($user->primaryEmail->emailAddress)) { $autoCompleteResults[] = array('id' => strval($user->primaryEmail), 'name' => strval($user) . ' (' . $user->primaryEmail . ')'); } } foreach ($usersByFullName as $user) { if (isset($user->primaryEmail->emailAddress)) { $autoCompleteResults[] = array('id' => strval($user->primaryEmail), 'name' => strval($user) . ' (' . $user->primaryEmail . ')'); } } foreach ($contacts as $contact) { if (isset($contact->primaryEmail->emailAddress)) { $autoCompleteResults[] = array('id' => strval($contact->primaryEmail), 'name' => strval($contact) . ' (' . $contact->primaryEmail . ')'); } } $emailValidator = new CEmailValidator(); if (count($autoCompleteResults) == 0 && $emailValidator->validateValue($term)) { $autoCompleteResults[] = array('id' => $term, 'name' => $term); } echo CJSON::encode($autoCompleteResults); }
/** * Parses a To, CC, or BCC header into an array compatible with PHPMailer. * * Each element of the array corresponds to an email addressee; the first * element is the name, the second, the value. * * The special case of "LastName, FirstName" is covered (splitting on commas * will break in this case) is covered by using a bit of RegExp from an idea * shared here: * * http://stackoverflow.com/a/2202489/1325798 * * @param type $header */ public static function addressHeaderToArray($header, $ignoreInvalidAddresses = false) { // First, tokenize all pieces of the header to avoid splitting inside of // recipient names: preg_match_all('/"(?:\\\\.|[^\\\\"])*"|[^,\\s]+/', $header, $matches); $tokenCount = 0; $values = array(); foreach ($matches[0] as $matchedPiece) { $piece = trim($matchedPiece, ','); $token = "\\{token_{$tokenCount}\\}"; $values[$token] = $piece; $tokenCount++; } $tokens = array_flip($values); $delimiter = '-&@&-'; // Something highly unlikely to ever appear in an email header $tokenizedHeader = str_replace(',', $delimiter, strtr($header, $tokens)); $headerPieces = explode($delimiter, strtr($tokenizedHeader, $values)); $headerArray = array(); foreach ($headerPieces as $recipient) { $recipient = trim($recipient); if (empty($recipient)) { continue; } $matches = array(); $emailValidator = new CEmailValidator(); // if it's just a simple email, we're done! if ($emailValidator->validateValue($recipient)) { $headerArray[] = array('', $recipient); } elseif (strlen($recipient) < 255 && preg_match('/^"?((?:\\\\"|[^"])*)"?\\s*<(.+)>$/i', $recipient, $matches)) { // otherwise, it must be of the variety <*****@*****.**> "Bob Slydel" // (with or without quotes) if (count($matches) == 3 && $emailValidator->validateValue($matches[2])) { $headerArray[] = array($matches[1], $matches[2]); } else { if (!$ignoreInvalidAddresses) { throw new CException(Yii::t('app', 'Invalid email address list.')); } } } else { if (!$ignoreInvalidAddresses) { throw new CException(Yii::t('app', 'Invalid email address list:' . $recipient)); } } } return $headerArray; }
/** * Checks a comma separated list of e-mails which should invited to space. * E-Mails needs to be valid and not already registered. * * @param type $attribute * @param type $params */ public function checkInviteExternal($attribute, $params) { // Check if email field is not empty if ($this->{$attribute} != "") { $emails = explode(",", $this->{$attribute}); // Loop over each given e-mail foreach ($emails as $email) { $email = trim($email); $validator = new CEmailValidator(); if (!$validator->validateValue($email)) { $this->addError($attribute, Yii::t('SpaceModule.forms_SpaceInviteForm', "{email} is not valid!", array("{email}" => $email))); continue; } $user = User::model()->findByAttributes(array('email' => $email)); if ($user != null) { $this->addError($attribute, Yii::t('SpaceModule.forms_SpaceInviteForm', "{email} is already registered!", array("{email}" => $email))); continue; } $this->invitesExternal[] = $email; } } }
private function sendemail($address, $text) { Yii::import('ext.yii-mail.YiiMailMessage'); $validator = new CEmailValidator(); if ($validator->validateValue($address)) { $message = new YiiMailMessage(); $message->setBody($text, 'text/html'); $message->subject = 'NASTROYKI'; $message->addTo($address); $message->from = Yii::app()->params['adminEmail']; return Yii::app()->mail->send($message); } return false; }
public function actionEdit() { $msgEmail = ""; $request = Yii::app()->getRequest(); $id = trim($request->getParam("id")); if (!empty($_POST)) { $name = trim($request->getPost("name")); $admin = trim($request->getPost("admin")); $username = trim($request->getPost("username")); $password = trim($request->getPost("password")); $provider = trim($request->getPost("provider")); $status = trim($request->getPost("status")); $validate = new CEmailValidator(); if ($name == "") { $msgEmail = "邮箱名称选项不能留空"; } else { if (strlen($name) > 64) { $msgEmail = "输入不能大于64个字符"; } else { if (!$validate->validateValue($name)) { $msgEmail = "请输入合法的电子邮箱"; } } } if ($msgEmail == "") { $email = array('name' => $name, 'admin' => $admin, 'username' => $username, 'password' => $password, 'provider' => $provider, 'status' => $status); try { $res = new Email(); $res->_pk = $id; $res->_attributes = $email; $res->setIsNewRecord(false); $res->update(); $this->redirect(array('list')); } catch (CDbException $e) { throw CDbException($e); } } } try { $Rs = new Email(); $rsInfo = $Rs->findByPk($id); } catch (CDbException $e) { throw CDbException($e); } $this->render('edit', array('r' => Yii::app()->request->baseUrl . '/', 'rsInfo' => $rsInfo, 'msgEmail' => $msgEmail)); }
public function actionAddComment() { $keyid = zmf::val('k', 2); $to = zmf::val('to', 2); $type = zmf::val('t', 1); $content = zmf::val('c', 1); $email = zmf::val('email', 1); $username = zmf::val('username', 1); if (!isset($type) or !in_array($type, array('posts'))) { $this->jsonOutPut(0, Yii::t('default', 'forbiddenaction')); } if (!isset($keyid) or !is_numeric($keyid)) { $this->jsonOutPut(0, Yii::t('default', 'pagenotexists')); } if (!$content) { $this->jsonOutPut(0, '评论不能为空哦~'); } if ($this->uid) { $status = Posts::STATUS_PASSED; $uid = $this->uid; } else { if (!$username) { $this->jsonOutPut(0, '请填写称呼'); } zmf::setCookie('noLoginUsername', $username, 2592000); if ($email != '') { $validator = new CEmailValidator(); if (!$validator->validateValue($email)) { $this->jsonOutPut(0, '请填写正确的邮箱地址'); } zmf::setCookie('noLoginEmail', $email, 2592000); } $status = Posts::STATUS_STAYCHECK; $uid = 0; if (zmf::actionLimit($type, $keyid, 5, 86400, true)) { $this->jsonOutPut(0, '操作太频繁,请稍后再试'); } } $postInfo = Posts::model()->findByPk($keyid); if (!$postInfo || $postInfo['status'] != Posts::STATUS_PASSED) { $this->jsonOutPut(0, '您所评论的内容不存在'); } //处理文本 $filter = Posts::handleContent($content); $content = $filter['content']; $model = new Comments(); $toNotice = true; $touid = $postInfo['uid']; if ($to) { $comInfo = Comments::model()->findByPk($to); if (!$comInfo || $comInfo['status'] != Posts::STATUS_PASSED) { $to = ''; } elseif ($comInfo['uid'] == $uid) { $toNotice = false; } else { $touid = $comInfo['uid'] > 0 ? $comInfo['uid'] : ''; $toNotice = true; } } $intoData = array('logid' => $keyid, 'uid' => $uid, 'content' => $content, 'cTime' => zmf::now(), 'classify' => $type, 'platform' => '', 'tocommentid' => $to, 'status' => $status, 'username' => $username, 'email' => $email); unset(Yii::app()->session['checkHasBadword']); $model->attributes = $intoData; if ($model->validate()) { if ($model->save()) { if ($type == 'posts') { $_url = CHtml::link('查看详情', array('posts/view', 'id' => $keyid, '#' => 'pid-' . $model->id)); if ($status == Posts::STATUS_PASSED) { Posts::updateCommentsNum($keyid); } $_content = '您的文章有了新的评论,' . $_url; } if ($to && $_url) { $_content = '您的评论有了新的回复,' . $_url; } if ($toNotice) { $_noticedata = array('uid' => $touid, 'authorid' => $uid, 'content' => $_content, 'new' => 1, 'type' => 'comment', 'cTime' => zmf::now(), 'from_id' => $model->id, 'from_num' => 1); Notification::add($_noticedata); } if ($uid) { $intoData['loginUsername'] = $this->userInfo['truename']; } $html = $this->renderPartial('/posts/_comment', array('data' => $intoData, 'postInfo' => $postInfo), true); $this->jsonOutPut(1, $html); } else { $this->jsonOutPut(0, '新增评论失败'); } } else { $this->jsonOutPut(0, '新增评论失败'); } }
/** * Activa una cuenta */ public function actionAccountActivation() { //Initi $template = 'error'; $data = array('message' => '', 'code' => 'en la activación.'); //Validation input /* $user = new Users(); $user->attributes = array( 'email'=>$_GET['email'] ); */ //Check email $validator = new CEmailValidator(); if ($validator->validateValue($_GET['email'])) { //Check if user exist $user = Users::model()->find('email=:email', array(':email' => $_GET['email'])); if ($user) { //User found if ($user->status == Users::STATUS_PENDING_ACTIVATION) { //Load his knight $knight = Knights::model()->find('users_id=:users_id', array('users_id' => $user->id)); //Check if code is the same $codigo_activacion = md5($user->email . $knight->name . $user->password_md5 . $user->suscribe_date); if ($_GET['code'] === $codigo_activacion) { //ACTIVATED ACCOUNT //1.- change status $user->status = Users::STATUS_ENABLE; $user->save(); $knight->status = Knights::STATUS_WITHOUT_EQUIPMENT; $knight->save(); //2.- create card $knight_card = new KnightsCard(); $knight_card->attributes = array('knights_id' => $knight->id); $knight_card->save(); //3.- Create general stats $knight_stats = new KnightsStats(); $knight_stats->attributes = array('knights_id' => $knight->id); if (!$knight_stats->save()) { Yii::trace('[Site][actionAccountActivation] No se puede salvar las stats del caballero', 'error'); } //4.- set stats attack location //load all location /* $locations = Constants::model()->findAll( 'type=:type', array( ':type'=> Constants::KNIGHTS_LOCATION) ); if( count($locations) > 0 ){ //Foreach location set a value for attack location. Defense is depending of shield foreach( $locations as $location ){ $knights_stats_attack_location = new KnightsStatsAttackLocation(); $knights_stats_attack_location->attributes = array( 'knights_id'=>$knight->id, 'location'=>$location['id'] ); $knights_stats_attack_location->save(); } }else{ $data['message'] .= 'No hay datos de localizaciones'; } */ //Change for points of location. 48 is the maximun position number in the attack and defense points for ($i = 1; $i <= 48; $i++) { $knights_stats_attack_location = new KnightsStatsAttackLocation(); $knights_stats_attack_location->attributes = array('knights_id' => $knight->id, 'location' => $i); $knights_stats_attack_location->save(); } //6.- Set default equipment //Set armours foreach (Armours::getDefaultEquipment() as $key => $id) { //Find armour $armour = Armours::model()->findByPk($id); if ($armour) { //creamos nuevo objeto de la armadura $armour_object = new ArmoursObjects(); $armour_object->attributes = array('armours_id' => $id, 'knights_id' => $knight->id, 'current_pde' => $armour->pde); if (!$armour_object->save()) { //$data['message'] .= '<p>Armadura '.$id.' ('.$armour_object->attributes['armours_id'].') generada ('.var_dump( $armour_object->getErrors()).') '; Yii::trace('[SITE][actionAccountActivation] Error al salvar la armadura ' . $armour->name, 'error'); } //Lo inventariamos. Como son los primeros objetos la posición que ocupa será empezando desde 1 $inventory = new Inventory(); //Sabemos que no hay objetos por lo que ocupamos las primeras posiciones, que concuerdan con el id $inventory->attributes = array('knights_id' => $knight->id, 'type' => Inventory::EQUIPMENT_TYPE_ARMOUR, 'identificator' => $armour_object->id, 'position' => $key + 11); $data['message'] .= 'e inventariada (' . $inventory->save() . ')</p>'; } else { $data['message'] .= '<p>KAKUNA MATATA!!'; } } //Set spears $position = 27; $spear = Spears::model()->findByPk(1); //Lanza de entrenamiento foreach (Spears::getDefaultEquipment() as $key => $id) { //Creamos el bojeto lanza $spear_object = new SpearsObjects(); $spear_object->attributes = array('spears_id' => $spear->id, 'knights_id' => $knight->id, 'current_pde' => $spear->pde); $spear_object->save(); $data['message'] .= '<p>Lanza ' . $id . ' generada</p>'; //La inventariamos $inventory = new Inventory(); $inventory->attributes = array('knights_id' => $knight->id, 'type' => Inventory::EQUIPMENT_TYPE_SPEAR, 'identificator' => $spear_object->id, 'position' => $position++); $data['message'] .= 'e inventariada (' . $inventory->save() . ')</p>'; } //Creamos las eventos de knights_events_last $sql = ''; for ($i = 0; $i < Yii::app()->params['events']['event_last']['maximum']; $i++) { $sql .= 'INSERT INTO knights_events_last (knights_id, type, identificator, date) VALUES (' . $knight->id . ', ' . KnightsEvents::TYPE_VOID . ', 0, \'2012-01-01 00:00:' . ($i < 10 ? '0' . $i : $i) . '\' );'; /* $event = new KnightsEventsLast(); $event->attributes = array( 'knights_id'=>$knight->id, 'type'=> KnightsEvents::TYPE_VOID, 'identificator'=>0, 'date'=>'2012-01-01 00:00:'.(($i<10)?'0'.$i:$i)//for update ); $event->save(); */ } $command = Yii::app()->db->createCommand($sql); $command->execute(); Yii::app()->db->setActive(false); //Create healing row $healing = new Healings(); $healing->attributes = array('knights_id' => $knight->id, 'next_healing_date' => null); if (!$healing->save()) { Yii::trace('[SITE][actionAccountActivation] I can not insert healing row.', 'error'); } //Create settings $knights_settings = new KnightsSettings(); $knights_settings->attributes = array('knights_id' => $knight->id); if (!$knights_settings->save()) { Yii::trace('[SITE][actionAccountActivation] I can not insert setting row.', 'error'); } unset($knights_settings); //UPDATE YELLOW PAGES $initial_character = substr($knight->name, 0, 1); if (is_numeric($initial_character)) { $initial_character = '[0-9]'; } else { $initial_character = strtoupper($initial_character); } $yellow_pages_total = YellowPagesTotal::model()->with('letter0')->find('letter0.name = :letter', array(':letter' => $initial_character)); $yellow_pages_total->total += 1; if (!$yellow_pages_total->save()) { Yii::trace('[SITE][actionAccountActivation] No se ha podido actualizar yellow pages total', 'error'); } $yellow_pages_total_by_letter = new YellowPagesTotalByLetter(); $yellow_pages_total_by_letter->attributes = array('letter' => $yellow_pages_total->letter, 'knights_id' => $knight->id); if (!$yellow_pages_total_by_letter->save()) { Yii::trace('[SITE][actionAccountActivation] No se ha podido crear yellow pages total by letter', 'error'); } //Hacemos el login de alta $model = new LoginForm(); $model->attributes = array('username' => $user->email, 'password' => 'nolosabemos'); //Check if all is ok if ($model->loginFromValidation()) { $template = 'accountActivation'; } else { $data['message'] = 'Se ha producido un error al validar la cuenta. Escribenos un correo a ' . Yii::app()->params['adminEmail']; } } else { $data['message'] = 'El usuario y el código de activación no son correctos.'; } } else { //Message Error: user is not pending of activation $data['message'] = 'El usuario no está pendiente de activación'; } } else { //User not found $data['message'] = 'El usuario o código de activación no están relacionados.'; } } else { //Input not valid $data['message'] = 'Los datos de entrada no son correctos.'; } //Show Output $this->render($template, $data); }
/** * Invites a not registered member to this space * * @param type $email * @param type $originatorUserId */ public function inviteMemberByEMail($email, $originatorUserId) { // Invalid E-Mail $validator = new CEmailValidator(); if (!$validator->validateValue($email)) { return false; } // User already registered $user = User::model()->findByAttributes(array('email' => $email)); if ($user != null) { return false; } $userInvite = UserInvite::model()->findByAttributes(array('email' => $email)); // No invite yet if ($userInvite == null) { // Invite EXTERNAL user $userInvite = new UserInvite(); $userInvite->email = $email; $userInvite->source = UserInvite::SOURCE_INVITE; $userInvite->user_originator_id = $originatorUserId; $userInvite->room_invite_id = $this->getOwner()->id; $userInvite->save(); $this->sendInviteMail($userInvite); // There is a pending registration // Steal it und send mail again // Unfortunately there a no multiple workspace invites supported // so we take the last one } else { $userInvite->user_originator_id = $originatorUserId; $userInvite->room_invite_id = $this->getOwner()->id; $userInvite->save(); //$userInvite->sendInviteMail(); $this->sendInviteMail($userInvite); } return true; }
public function testShortEmailIsValidEmail() { $validator = new CEmailValidator(); $validatedEmail = $validator->validateValue('*****@*****.**'); $this->assertTrue($validatedEmail); }
protected function resolveValidatedEmail($email) { $validator = new CEmailValidator(); return $validator->validateValue($email); }
public function actionEstimate() { $country = Yii::app()->request->getPost("country", null); $province = Yii::app()->request->getPost("province", null); $postcode = Yii::app()->request->getPost("postalcode", null); $email = Yii::app()->request->getPost("email", null); if ($country === null) { throw new CHttpException(400, 'Your request is invalid.'); } if (Yii::app()->user->isGuest) { if ($email === null) { // Cart is not registred to any user AND no email was provided. throw new CHttpException(400, 'Your request is invalid.'); } $validator = new CEmailValidator(); if (!$validator->validateValue($email)) { throw new CHttpException(400, 'Your request is invalid.'); } $user = Yii::app()->user->createGuestUser($email); } $cart = $this->getCart(); Yii::app()->session['cart_country'] = $country; Yii::app()->session['cart_province'] = $province; if ($postcode) { // Save the updated postcode Yii::app()->user->user->postcode = $postcode; Yii::app()->user->user->save(); } $dataProvider = new CActiveDataProvider('OrderHasProduct', array('criteria' => array('condition' => 'order_id=' . $cart->id, 'with' => array('product')), 'pagination' => false)); $total_weight = 0.0; $total_value = 0.0; $total_item_qty = 0; foreach ($dataProvider->getData() as $relationship) { $total_weight += $relationship->quantity * $relationship->product->weight; $total_value += $relationship->quantity * $relationship->price_paid; $total_item_qty += $relationship->quantity; } if ($total_item_qty == 0) { throw new CHttpException(400, 'The cart is empty.'); } // Build the json request data we'll send to our server $weight = $total_weight; $handling = 0; $postal_code = $postcode; $country_code = $country; $value = $total_value; $qty = $total_item_qty; $orderData = array("weight" => $weight, "handling" => $handling, "postal_code" => $postal_code, "country_code" => $country_code, "value" => $value, "qty" => $qty, "locale" => Yii::app()->language); $jsonpayload = json_encode($orderData); // Ping our main store cloud services bridge so the change is repercuted on all the client stores $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://kle-en-main.com/CloudServices/index.php/BoukemAPI/canadaPostEstimate/listServices?storeid=" . Yii::app()->params['outbound_api_user'] . "&storekey=" . Yii::app()->params['outbound_api_secret']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonpayload); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); $result = curl_exec($ch); curl_close($ch); $arr = json_decode($result); if (!isset($arr->services)) { throw new CHttpException(400, Yii::t('app', "Postes Canada ne peut fournir d'estimation en ce moment.")); } $rates = $arr->services; if ($rates === null) { throw new CHttpException(400, Yii::t('app', 'Une erreur est survenue.')); } $methods = $this->renderPartial('_estimate', array('methods' => $rates), true); $outputdict = array("shipping_block" => $methods); $outputdict['taxes'] = $this->taxesForProvinceCountryValue($province, $country, $total_value); $this->renderJSON($outputdict); }
public function parseMailingList($attribute, $params) { // $to = trim($this->$attribute); // if(empty($to)) // return false; $splitString = explode(',', $this->{$attribute}); // require_once('protected/components/phpMailer/class.phpmailer.php'); $invalid = false; foreach ($splitString as &$token) { $token = trim($token); if (empty($token)) { continue; } $matches = array(); $emailValidator = new CEmailValidator(); // if(PHPMailer::ValidateAddress($token)) { // if it's just a simple email, we're done! if ($emailValidator->validateValue($token)) { // if it's just a simple email, we're done! $this->mailingList[$attribute][] = array('', $token); } elseif (strlen($token) < 255 && preg_match('/^"?([^"]*)"?\\s*<(.+)>$/i', $token, $matches)) { // otherwise, it must be of the variety <*****@*****.**> "Bob Slydel" if (count($matches) == 3 && $emailValidator->validateValue($matches[2])) { // (with or without quotes) $this->mailingList[$attribute][] = array($matches[1], $matches[2]); } else { $invalid = true; break; } } else { $invalid = true; break; } } if ($invalid) { $this->addError($attribute, Yii::t('app', 'Invalid email address list.')); } }