/**
  * Returns the message text. {{-transformation is done.
  *
  * @return string Unescaped message text.
  */
 public function getWikitext()
 {
     return $this->mMessage->text();
 }
 /**
  * Make a new user account using the loaded data.
  * @private
  * @throws PermissionsError|ReadOnlyError
  * @return Status
  */
 public function addNewAccountInternal()
 {
     global $wgAuth, $wgMemc, $wgAccountCreationThrottle, $wgEmailConfirmToEdit;
     // If the user passes an invalid domain, something is fishy
     if (!$wgAuth->validDomain($this->mDomain)) {
         return Status::newFatal('wrongpassword');
     }
     // If we are not allowing users to login locally, we should be checking
     // to see if the user is actually able to authenticate to the authenti-
     // cation server before they create an account (otherwise, they can
     // create a local account and login as any domain user). We only need
     // to check this for domains that aren't local.
     if ('local' != $this->mDomain && $this->mDomain != '') {
         if (!$wgAuth->canCreateAccounts() && (!$wgAuth->userExists($this->mUsername) || !$wgAuth->authenticate($this->mUsername, $this->mPassword))) {
             return Status::newFatal('wrongpassword');
         }
     }
     if (wfReadOnly()) {
         throw new ReadOnlyError();
     }
     # Request forgery checks.
     if (!self::getCreateaccountToken()) {
         self::setCreateaccountToken();
         return Status::newFatal('nocookiesfornew');
     }
     # The user didn't pass a createaccount token
     if (!$this->mToken) {
         return Status::newFatal('sessionfailure');
     }
     # Validate the createaccount token
     if ($this->mToken !== self::getCreateaccountToken()) {
         return Status::newFatal('sessionfailure');
     }
     # Check permissions
     $currentUser = $this->getUser();
     $creationBlock = $currentUser->isBlockedFromCreateAccount();
     if (!$currentUser->isAllowed('createaccount')) {
         throw new PermissionsError('createaccount');
     } elseif ($creationBlock instanceof Block) {
         // Throws an ErrorPageError.
         $this->userBlockedMessage($creationBlock);
         // This should never be reached.
         return false;
     }
     # Include checks that will include GlobalBlocking (Bug 38333)
     $permErrors = $this->getPageTitle()->getUserPermissionsErrors('createaccount', $currentUser, true);
     if (count($permErrors)) {
         throw new PermissionsError('createaccount', $permErrors);
     }
     $ip = $this->getRequest()->getIP();
     if ($currentUser->isDnsBlacklisted($ip, true)) {
         return Status::newFatal('sorbs_create_account_reason');
     }
     # Now create a dummy user ($u) and check if it is valid
     $u = User::newFromName($this->mUsername, 'creatable');
     if (!$u) {
         return Status::newFatal('noname');
     }
     # Make sure the user does not exist already
     $lock = $wgMemc->getScopedLock(wfGlobalCacheKey('account', md5($this->mUsername)));
     if (!$lock) {
         return Status::newFatal('usernameinprogress');
     } elseif ($u->idForName(User::READ_LOCKING)) {
         return Status::newFatal('userexists');
     }
     if ($this->mCreateaccountMail) {
         # do not force a password for account creation by email
         # set invalid password, it will be replaced later by a random generated password
         $this->mPassword = null;
     } else {
         if ($this->mPassword !== $this->mRetype) {
             return Status::newFatal('badretype');
         }
         # check for password validity, return a fatal Status if invalid
         $validity = $u->checkPasswordValidity($this->mPassword, 'create');
         if (!$validity->isGood()) {
             $validity->ok = false;
             // make sure this Status is fatal
             return $validity;
         }
     }
     # if you need a confirmed email address to edit, then obviously you
     # need an email address.
     if ($wgEmailConfirmToEdit && strval($this->mEmail) === '') {
         return Status::newFatal('noemailtitle');
     }
     if (strval($this->mEmail) !== '' && !Sanitizer::validateEmail($this->mEmail)) {
         return Status::newFatal('invalidemailaddress');
     }
     # Set some additional data so the AbortNewAccount hook can be used for
     # more than just username validation
     $u->setEmail($this->mEmail);
     $u->setRealName($this->mRealName);
     $abortError = '';
     $abortStatus = null;
     if (!Hooks::run('AbortNewAccount', array($u, &$abortError, &$abortStatus))) {
         // Hook point to add extra creation throttles and blocks
         wfDebug("LoginForm::addNewAccountInternal: a hook blocked creation\n");
         if ($abortStatus === null) {
             // Report back the old string as a raw message status.
             // This will report the error back as 'createaccount-hook-aborted'
             // with the given string as the message.
             // To return a different error code, return a Status object.
             $abortError = new Message('createaccount-hook-aborted', array($abortError));
             $abortError->text();
             return Status::newFatal($abortError);
         } else {
             // For MediaWiki 1.23+ and updated hooks, return the Status object
             // returned from the hook.
             return $abortStatus;
         }
     }
     // Hook point to check for exempt from account creation throttle
     if (!Hooks::run('ExemptFromAccountCreationThrottle', array($ip))) {
         wfDebug("LoginForm::exemptFromAccountCreationThrottle: a hook " . "allowed account creation w/o throttle\n");
     } else {
         if ($wgAccountCreationThrottle && $currentUser->isPingLimitable()) {
             $key = wfMemcKey('acctcreate', 'ip', $ip);
             $value = $wgMemc->get($key);
             if (!$value) {
                 $wgMemc->set($key, 0, 86400);
             }
             if ($value >= $wgAccountCreationThrottle) {
                 return Status::newFatal('acct_creation_throttle_hit', $wgAccountCreationThrottle);
             }
             $wgMemc->incr($key);
         }
     }
     if (!$wgAuth->addUser($u, $this->mPassword, $this->mEmail, $this->mRealName)) {
         return Status::newFatal('externaldberror');
     }
     self::clearCreateaccountToken();
     return $this->initUser($u, false);
 }
Пример #3
0
function iterate($offset)
{
    $file = Api::getUpdates((string) $offset);
    for ($i = 0; $i < count($file); $i++) {
        $current = new Message($file[$i]);
        $offset = max($current->updateId, $offset) + 1;
        $cityLevel = [['Алматы'], ['Астана'], ['Шымкент'], ['Тараз'], ['Кызылорда'], ['Атырау'], ['Актау'], ['Караганда'], ['Павлодар'], ['Семипалатинск'], ['Костанай'], ['Петропавловск'], ['Талдыкорган'], ['Кокшетау']];
        $firstLevel = [['Услуги'], ['Акции'], ['Проверить Баланс'], ['Адреса, контакты'], ['Отправить запрос о неполадках'], ['Приложения АЛМА-ТВ']];
        $secondLevel = [['Телевидение'], ['Интернет'], ['Интернет + ТВ'], ['TV BOX']];
        // $current->reply("Ima got your text with {$current->text()}");
        if ($current->text() == '/start') {
            $current->replyCode('Добро пожаловать! Вас приветствует официальный бот АЛМА-ТВ' . '%0A' . 'Чтобы продолжить выберите ваш город:', $cityLevel);
        }
        if ($current->text() == 'Павлодар') {
            $current->replyDropDown("Выберите:", $firstLevel);
        }
        if ($current->text() == 'Алматы') {
            $current->replyDropDown("Выберите:", $firstLevel);
        }
        if ($current->text() == 'Шымкент') {
            $current->replyDropDown("Выберите:", $firstLevel);
        }
        if ($current->text() == 'Услуги') {
            $current->replyDropDown("Выберите:", $secondLevel);
        }
        if ($current->text() == 'Акции') {
            $current->reply('Уважаемые дамы и господа!' . '%0A' . 'АЛМА-ТВ запускает новогоднюю акцию, которая позволяет сэкономить до 10 000 тенге.' . '%0A' . 'При внесении предоплаты за 12 и более месяцев, предоставляются скидки:' . '%0A' . '-     на пакеты «TV100+» и «Антенна80+» - скидка 18%' . '%0A' . '-      на пакеты «TVMAX» и «AntennaMAX» -скидка в 24%.' . '%0A' . 'Специальное предложение, действует до 31 января 2016 года.');
        }
        if ($current->text() == 'Адреса, контакты') {
            $current->replyDropDown("Выберите:", $secondLevel);
        }
        if ($current->text() == 'Отправить запрос о неполадках') {
            $current->replyDropDown("Выберите:", $secondLevel);
        }
        if ($current->text() == 'Приложения АЛМА-ТВ') {
            $current->reply('Приложение “Alma TV” позволяет получить мгновенный доступ к балансу Вашего счёта, телепрограмме и многому другому. Дополнительно, у пользователя есть возможность отправки заявок на подключение или ремонт в несколько простых шагов.
        Для проверки баланса требуется быть абонентом компании «АЛМА-ТВ», остальные функции доступны всем пользователям. Возможность управления Вашим счётом и множество иных функций появятся в следующих версиях приложения.' . '%0A' . 'Для скачивания приложения ALMA-TV на Android перейдите по ссылке: ' . '%0A' . 'Приложение "TV BOX". Смотрите любимые передачи, как на телевизоре, так и на мобильных устройствах.
        Сортируйте каналы по жанрам, ставьте видео на паузу и перематывайте, выбирайте звуковую дорожку и качество изображения. Подробнее об этих и других функциях TV Box на сайте tv-box.kz' . '%0A' . 'Для скачивания приложения TV BOX на Ваше мобильное устройство, пройдите по ссылкам:', $secondLevel);
        }
        echo "==> Message text {$current->text()} \n\r";
    }
    echo "==> Setup new offset {$offset}\n\r";
    return $offset;
}
 /**
  * Process the form.  At this point we know that the user passes all the criteria in
  * userCanExecute(), and if the data array contains 'Username', etc, then Username
  * resets are allowed.
  * @param $data array
  * @throws MWException
  * @throws ThrottledError|PermissionsError
  * @return Bool|Array
  */
 public function onSubmit(array $data)
 {
     global $wgAuth;
     if (isset($data['Domain'])) {
         if ($wgAuth->validDomain($data['Domain'])) {
             $wgAuth->setDomain($data['Domain']);
         } else {
             $wgAuth->setDomain('invaliddomain');
         }
     }
     if (isset($data['Capture']) && !$this->getUser()->isAllowed('passwordreset')) {
         // The user knows they don't have the passwordreset permission,
         // but they tried to spoof the form. That's naughty
         throw new PermissionsError('passwordreset');
     }
     /**
      * @var $firstUser User
      * @var $users User[]
      */
     if (isset($data['Username']) && $data['Username'] !== '') {
         $method = 'username';
         $users = array(User::newFromName($data['Username']));
     } elseif (isset($data['Email']) && $data['Email'] !== '' && Sanitizer::validateEmail($data['Email'])) {
         $method = 'email';
         $res = wfGetDB(DB_SLAVE)->select('user', User::selectFields(), array('user_email' => $data['Email']), __METHOD__);
         if ($res) {
             $users = array();
             foreach ($res as $row) {
                 $users[] = User::newFromRow($row);
             }
         } else {
             // Some sort of database error, probably unreachable
             throw new MWException('Unknown database error in ' . __METHOD__);
         }
     } else {
         // The user didn't supply any data
         return false;
     }
     // Check for hooks (captcha etc), and allow them to modify the users list
     $error = array();
     if (!wfRunHooks('SpecialPasswordResetOnSubmit', array(&$users, $data, &$error))) {
         return array($error);
     }
     if (count($users) == 0) {
         if ($method == 'email') {
             // Don't reveal whether or not an email address is in use
             return true;
         } else {
             return array('noname');
         }
     }
     $firstUser = $users[0];
     if (!$firstUser instanceof User || !$firstUser->getID()) {
         // Don't parse username as wikitext (bug 65501)
         return array(array('nosuchuser', wfEscapeWikiText($data['Username'])));
     }
     // Check against the rate limiter
     if ($this->getUser()->pingLimiter('mailpassword')) {
         throw new ThrottledError();
     }
     // Check against password throttle
     foreach ($users as $user) {
         if ($user->isPasswordReminderThrottled()) {
             global $wgPasswordReminderResendTime;
             # Round the time in hours to 3 d.p., in case someone is specifying
             # minutes or seconds.
             return array(array('throttled-mailpassword', round($wgPasswordReminderResendTime, 3)));
         }
     }
     global $wgNewPasswordExpiry;
     // All the users will have the same email address
     if ($firstUser->getEmail() == '') {
         // This won't be reachable from the email route, so safe to expose the username
         return array(array('noemail', wfEscapeWikiText($firstUser->getName())));
     }
     // We need to have a valid IP address for the hook, but per bug 18347, we should
     // send the user's name if they're logged in.
     $ip = $this->getRequest()->getIP();
     if (!$ip) {
         return array('badipaddress');
     }
     $caller = $this->getUser();
     wfRunHooks('User::mailPasswordInternal', array(&$caller, &$ip, &$firstUser));
     $username = $caller->getName();
     $msg = IP::isValid($username) ? 'passwordreset-emailtext-ip' : 'passwordreset-emailtext-user';
     // Send in the user's language; which should hopefully be the same
     $userLanguage = $firstUser->getOption('language');
     $passwords = array();
     foreach ($users as $user) {
         $password = $user->randomPassword();
         $user->setNewpassword($password);
         $user->saveSettings();
         $passwords[] = $this->msg('passwordreset-emailelement', $user->getName(), $password)->inLanguage($userLanguage)->text();
         // We'll escape the whole thing later
     }
     $passwordBlock = implode("\n\n", $passwords);
     $this->email = $this->msg($msg)->inLanguage($userLanguage);
     $this->email->params($username, $passwordBlock, count($passwords), '<' . Title::newMainPage()->getCanonicalURL() . '>', round($wgNewPasswordExpiry / 86400));
     $title = $this->msg('passwordreset-emailtitle');
     $this->result = $firstUser->sendMail($title->text(), $this->email->text());
     if (isset($data['Capture']) && $data['Capture']) {
         // Save the user, will be used if an error occurs when sending the email
         $this->firstUser = $firstUser;
     } else {
         // Blank the email if the user is not supposed to see it
         $this->email = null;
     }
     if ($this->result->isGood()) {
         return true;
     } elseif (isset($data['Capture']) && $data['Capture']) {
         // The email didn't send, but maybe they knew that and that's why they captured it
         return true;
     } else {
         // @todo FIXME: The email wasn't sent, but we have already set
         // the password throttle timestamp, so they won't be able to try
         // again until it expires...  :(
         return array(array('mailerror', $this->result->getMessage()));
     }
 }
 /**
  * Adds a user based greeting to the text mail
  * @param Message $message
  * @param User $oUser
  * @return String
  */
 public function userBasedDecorateIntro($message, $oUser)
 {
     $sRealname = BsCore::getUserDisplayName($oUser);
     $sReturn = wfMessage('bs-email-greeting-receiver')->params($oUser->getName(), $sRealname)->inLanguage($oUser->getOption('language'))->text();
     return $sReturn . "\n\n" . $message->text();
 }
Пример #6
0
	/**
	 * Makes a row with aggregate numbers.
	 * @param $message Message
	 * @param $numbers array ( total, translate, fuzzy )
	 * @return string Html
	 */
	public function makeTotalRow( Message $message, $numbers ) {
		list( $total, $translated, $fuzzy ) = $numbers;
		$out  = "\t" . Html::openElement( 'tr' );
		$out .= "\n\t\t" . Html::element( 'td', array(), $message->text() );
		$out .= $this->makeNumberColumns( $fuzzy, $translated, $total );
		$out .= "\n\t" . Xml::closeElement( 'tr' ) . "\n";
		return $out;
	}
Пример #7
0
 /**
  * Generates an exception about a misuse of a widget (bad parameter syntax, value > max, ...)
  * 
  * @param Message $message
  * @throws UserError
  */
 public static function ThrowUserError($message)
 {
     throw new UserError($message->text());
 }
 /**
  * Makes a row with aggregate numbers.
  * @param Message $message
  * @param array $stats ( total, translate, fuzzy )
  * @return string Html
  */
 public function makeTotalRow(Message $message, $stats)
 {
     $out = "\t" . Html::openElement('tr');
     $out .= "\n\t\t" . Html::element('td', array(), $message->text());
     $out .= $this->makeNumberColumns($stats);
     $out .= "\n\t" . Xml::closeElement('tr') . "\n";
     return $out;
 }