Example #1
0
 public function testSetHashMethod()
 {
     $hasher = new Hasher();
     $this->assertEquals(new HashMethod(HashMethod::SHA1), $hasher->getHashMethod());
     $hashMethod = new HashMethod(HashMethod::SHA1);
     $hasher->setHashMethod($hashMethod);
     $this->assertSame($hashMethod, $hasher->getHashMethod());
 }
Example #2
0
 /**
  */
 public function testHash()
 {
     $username = '******';
     $password = '******';
     $hashedPassword = $this->hasher->hash($username, $password);
     self::assertSame($hashedPassword, '2df63690f4e665f3584bed37e314945a4acf59dbebe99e75b3ae1e1fd24e1142873ba98d2bc6a104ef0a1f9629782b6a52914a2d7b3f657b963a1b22489541b1');
     $otherHasher = new Hasher('43321');
     $hashedPasswordWithOtherSalt = $otherHasher->hash($username, $password);
     self::assertNotEquals($hashedPassword, $hashedPasswordWithOtherSalt, 'The same passwords with different salts should have different hashes.');
 }
Example #3
0
 /**
  * @inheritdoc
  */
 public function needsRehash($hashedValue, array $options = [])
 {
     if (!isset($options["cost"])) {
         $options["cost"] = self::DEFAULT_COST;
     }
     return parent::needsRehash($hashedValue, $options);
 }
Example #4
0
 private function newCookie()
 {
     $randomStringGenerator = new generateRandomString(30, true, 50, 300);
     $randomString = $randomStringGenerator->run();
     $this->key = Hasher::generateHmacHash($randomString) . " # " . $randomString;
     $aSingleDay = 24 * 60 * 60;
     $cookieExpireTime = time() + $aSingleDay;
     setcookie("educaskS", $this->key, $cookieExpireTime, null, null, null, true);
 }
Example #5
0
 public function testGenerateUnique()
 {
     \Kisma::set('debug.kisma.core.utility.hasher::generate_unique', true);
     $_hash1 = Hasher::generateUnique();
     $_hash2 = Hasher::generateUnique('*****@*****.**');
     $_hash3 = Hasher::generateUnique();
     $_hash4 = Hasher::generateUnique('*****@*****.**');
     $this->assertTrue($_hash1 != $_hash3 && $_hash2 != $_hash4);
 }
Example #6
0
 /**
  * Get a shortened URL
  * 
  * @param string $url URL
  * @return string
  */
 public static function getShortURL($url)
 {
     $hash = Hasher::getHashFromURL($url);
     if (!$hash && $this->shorten) {
         $hash = Hasher::hash($url);
     }
     if ($hash) {
         return elgg_normalize_url(implode('/', array(PAGEHANDLER, $hash)));
     }
     return $url;
 }
Example #7
0
 public function export($appId)
 {
     # ToDo; check that collections not empty
     $prefixTmpFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . strval(new \MongoDB\BSON\ObjectId()) . DIRECTORY_SEPARATOR;
     $collections = ['tables' => "'{applications: \"{$appId}\"}'", 'decisions' => "'{applications: \"{$appId}\"}'", 'changelogs' => "'{\"model.attributes.applications\": \"{$appId}\"}'"];
     foreach ($collections as $collection => $query) {
         exec(sprintf("mongoexport -h %s --port %s -d %s -q %s -c %s --out %s", env('DB_HOST'), env('DB_PORT'), env('DB_DATABASE'), $query, $collection, $prefixTmpFile . $collection . '.json'));
     }
     # create archive
     $archiveName = gmdate('Y-m-d_H:i:s') . '-' . Hasher::getToken(50) . "Z.tar.gz";
     exec(sprintf("cd %s && tar -cvzf '%s' *.json", $prefixTmpFile, __DIR__ . "/../../public/dump/{$archiveName}"));
     return config('services.link.dump_project') . '/' . $archiveName;
 }
Example #8
0
 public function attempt($username, $password)
 {
     $result = \Core\Storage::container()->get_storage($this->_table)->fetch(array('filter' => new \Core\Filter($this->_user_field, $username)))->{0};
     if (!$result) {
         throw new InvalidUserError();
     }
     try {
         $hasher = Hasher::create()->check($password, $result[$this->_password_field]);
         $this->_set_session($result['id'], $result);
     } catch (HashMismatch $e) {
         throw new IncorrectPasswordError();
     }
 }
Example #9
0
 public function validate_user($userdata)
 {
     $email = \Arr::get($userdata, 'email');
     if (!$this->has_user($email)) {
         Logger::instance()->log_log_in_attempt(Model_Log_In_Attempt::$ATTEMPT_NO_SUCH_USER, $email);
         throw new LogInFailed(\Lang::get('ethanol.errors.loginInvalid'));
     }
     $user = Model_User::find('first', array('related' => array('security', 'meta', 'groups'), 'where' => array(array('email', $email))));
     $password = \Arr::get($userdata, 'password');
     //Hash the given password and check that against the user
     $hashedPassword = Hasher::instance()->hash($password, $user->security->salt);
     if ($hashedPassword == $user->security->password) {
         $user->clean_security();
         return $user;
     }
     return false;
 }
Example #10
0
 function registrationAction()
 {
     $v_params['logined'] = LoginChecker::isLogined();
     $v_params['sys_name'] = SysPropertiesUtil::getPropertyValue("sys_name");
     $v_params['sys_slog'] = SysPropertiesUtil::getPropertyValue("sys_slog");
     $v_params['reg']['main'] = TRUE;
     if (0 < count($_POST)) {
         // Передача формы
         $containErrors = FALSE;
         if (isset($_POST['email'])) {
             $email = $_POST['email'];
             if (0 == strcmp("", $email)) {
                 $v_params['errors'][] = "Email не может быть пустым";
                 $containErrors = TRUE;
             } else {
                 if (!preg_match("/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}\$/", $email)) {
                     $v_params['errors'][] = "Скорее всего вы ввели email не правильно";
                     $containErrors = TRUE;
                 } else {
                     $imgAccount = ImgAccountUtil::getImgAccountByEmail($email);
                     if ($imgAccount) {
                         $v_params['errors'][] = "Такой Email уже зарегистрирован";
                         $containErrors = TRUE;
                     }
                 }
             }
         }
         if (isset($_POST['password1'])) {
             $password1 = $_POST['password1'];
             if ("" == $password1) {
                 $v_params['errors'][] = "Пароль не может быть пустым <br/>";
                 $containErrors = TRUE;
             } else {
                 if (9 > strlen($password1)) {
                     $v_params['errors'][] = "Длина пароля должна быть от 9 символов";
                     $containErrors = TRUE;
                 }
             }
         }
         if (0 != strcmp($_POST['password1'], $_POST['password2'])) {
             $v_params['errors'][] = "Пароль и его подтверждение не совпадают";
             $containErrors = TRUE;
         }
         if (isset($_POST['name'])) {
             $name = $_POST['name'];
             if ("" == $name) {
                 $v_params['errors'][] = "Введите название торгового стенда (позднее вы сможете его изменить)";
                 $containErrors = TRUE;
             }
         }
         $resp = recaptcha_check_answer(RECAPCHA_PRIVATE_KEY, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
         if (!$resp->is_valid) {
             $v_params['errors'][] = "Защита от роботов введена не верно";
             $containErrors = TRUE;
         }
         // Обработка
         if ($containErrors) {
             // Есть ошибки
             $v_params['addr_regions'] = AddrRegionUtil::getRegions();
             Application::fastView('main/sys_registration', $v_params);
         } else {
             // Нет ошибок, создаем аккаунт
             $imgAccount['email'] = $_POST['email'];
             $imgAccount['hashpass'] = Hasher::getHash($_POST['password1']);
             $imgAccount['show_email'] = 0;
             $imgAccount['active'] = 0;
             $imgAccount['img_name'] = $_POST['name'];
             $imgAccount['img_slog'] = $_POST['slog'];
             if (isset($_POST['region']) && "" != $_POST['region']) {
                 $addrRegion = AddrRegionUtil::getRegionByCode($_POST['region']);
                 $imgAddress['region_id'] = $addrRegion['id'];
             }
             $imgAddressId = ImgAddressUtil::insertImgAddress($imgAddress);
             $imgAccount['img_address_id'] = $imgAddressId;
             $imgAccount['show_address'] = 1;
             $activation_code = UUIDGenerator::generate();
             $imgAccount['check_code'] = $activation_code;
             $imgAccountId = ImgAccountUtil::createImgAccount($imgAccount);
             $mail_values['__root_url__'] = "http://" . $_SERVER["HTTP_HOST"];
             $mail_values['__act_url__'] = "http://" . $_SERVER["HTTP_HOST"] . "/activation?imgID=" . $imgAccountId . "&acode=" . $activation_code;
             MailWork::sendMailByTemplate($imgAccount['email'], "Завершение регистрации на сайте " . $_SERVER["HTTP_HOST"], "end_reg.html", $mail_values);
             $v_params['message'] = "На указаный email выслано письмо с подтверждением регистрации";
             $v_params['message_descr'] = "Проверьте свой почтовый ящик, там будет письмо с сылкой для активации созданного аккаунта, после чего вы сможете работать со своим торговым стендом";
             Application::fastView('main/sys_message', $v_params);
         }
     } else {
         $v_params['addr_regions'] = AddrRegionUtil::getRegions();
         Application::fastView('main/sys_registration', $v_params);
     }
 }
Example #11
0
function doConfigureContent()
{
    if (!isset($_SESSION['configureComplete'])) {
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['siteName'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['siteEmail'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['nonSecureURL'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['secureURL'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['webDirectory'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['timeZone'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['username'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['firstName'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['lastName'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['email'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['password1'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['password2'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if ($_POST['password1'] != $_POST['password2']) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'The inputted passwords for the first account don\'t match.';
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['smtpServer'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['smtpPort'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!is_numeric($_POST['smtpPort'])) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'Please enter a valid port for the SMTP Server.';
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['smtpUserName'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['smtpPassword1'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if (!isset($_POST['smtpPassword2'])) {
        unset($_SESSION['configureComplete']);
        header('Location: install.php?action=configure');
        return;
    }
    if ($_POST['smtpPassword1'] != $_POST['smtpPassword2']) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'The inputted passwords for the SMTP account don\'t match.';
        header('Location: install.php?action=configure');
        return;
    }
    $siteName = strip_tags(trim($_POST['siteName']));
    $siteEmail = strip_tags(trim($_POST['siteEmail']));
    $nonSecureURL = strip_tags(trim($_POST['nonSecureURL']));
    $secureURL = strip_tags(trim($_POST['secureURL']));
    $webDirectory = strip_tags(trim($_POST['webDirectory']));
    $timeZone = strip_tags(trim($_POST['timeZone']));
    $username = strip_tags(trim($_POST['username']));
    $firstName = strip_tags(trim($_POST['firstName']));
    $lastName = strip_tags(trim($_POST['lastName']));
    $email = strip_tags(trim($_POST['email']));
    $password = $_POST['password1'];
    $smtpServers = strip_tags(trim($_POST['smtpServer']));
    $smtpPort = intval($_POST['smtpPort']);
    $smtpUserName = strip_tags(trim($_POST['smtpUserName']));
    $enc = new Encrypter();
    $smtpPassword = $enc->encrypt(trim($_POST['smtpPassword1']));
    $smtpUseEncryption = isset($_POST['smtpUseEncryption']);
    $emailValidator = new emailValidator();
    if (!$emailValidator->validate($siteEmail)) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'The site email isn\'t a valid email address.';
        header('Location: install.php?action=configure');
        return;
    }
    if (!$emailValidator->validate($email)) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'The email address for the first user isn\'t valid.';
        header('Location: install.php?action=configure');
        return;
    }
    unset($emailValidator);
    $urlValidator = new urlValidator();
    $options = array('noDirectories', 'mightBeIP');
    $nonSecureOptions = array_merge($options, array('httpOnly'));
    $secureOptions = array_merge($options, array('httpsOnly'));
    if (!$urlValidator->validate($nonSecureURL, $nonSecureOptions)) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'The non-secure URL isn\'t valid. Please try again.';
        header('Location: install.php?action=configure');
        return;
    }
    if (!$urlValidator->validate($secureURL, $secureOptions)) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'The secure URL isn\'t valid. Please try again.';
        header('Location: install.php?action=configure');
        return;
    }
    unset($urlValidator);
    if ($webDirectory[0] != '/') {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'I couldn\'t validate the web directory. Please try again.';
        header('Location: install.php?action=configure');
        return;
    }
    $timeZoneValidator = new phpTimeZoneValidator();
    if (!$timeZoneValidator->validate($timeZone)) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'I couldn\'t validate the selected time zone. Please try again.';
        header('Location: install.php?action=configure');
        return;
    }
    unset($timeZoneValidator);
    $password = Hasher::generateHash($password);
    if ($password == false) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'I couldn\'t properly hash your password. Please try again.';
        header('Location: install.php?action=configure');
        return;
    }
    $database = Database::getInstance();
    $database->connect();
    if (!$database->isConnected()) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'I couldn\'t establish a connection to the database. Please try again. If you keep receiving this error, please delete the site/config.xml and start the installer again.';
        header('Location: install.php?action=configure');
        return;
    }
    if ($smtpUseEncryption == 'tls') {
        $smtpEncryption = 'true';
    } else {
        $smtpEncryption = 'false';
    }
    if ($webDirectory !== "/") {
        $webDirectory .= '/';
    }
    $variables = array('cleanURLsEnabled' => 'false', 'educaskVersion' => EDUCASK_VERSION, 'guestRoleID' => '1', 'maintenanceMode' => 'false', 'siteEmail' => $siteEmail, 'siteTheme' => 'default', 'siteTimeZone' => $timeZone, 'siteTitle' => $siteName, 'siteWebAddress' => $nonSecureURL, 'siteWebAddressSecure' => $secureURL, 'siteWebDirectory' => $webDirectory, 'smtpServer' => $smtpServers, 'smtpPort' => $smtpPort, 'smtpUserName' => $smtpUserName, 'smtpPassword' => $smtpPassword, 'smtpUseEncryption' => $smtpEncryption, 'lastCronRun' => '2015-01-01 21:15:53', 'cronRunning' => 'false', 'cronFrequency' => '10 minutes', 'minimumPasswordLength' => '5', 'lockoutPeriod' => '10', 'numberOfAttemptsBeforeLockout' => '3', 'maxSessionIdAge' => '600');
    foreach ($variables as $name => $value) {
        $name = $database->escapeString($name);
        $value = $database->escapeString($value);
        if (!$database->insertData('variable', 'variableName, variableValue', "'{$name}', '{$value}'")) {
            $_SESSION['errors'][] = "I wasn't able to insert the variable {$name} with a value of {$value} into the variable table. You may want to manually add this row to the variable table in the database. For help on this, please see <a href=\"https://www.educask.com\" target=\"_blank\">this page</a>.";
            //@ToDo: make the link point to actual help
            continue;
        }
    }
    $database->updateTable('variable', 'readOnly=1', "variableName='educaskVersion'");
    $sqlScript = EDUCASK_ROOT . '/core/sql/defaultRolesInstallSafe.sql';
    if (!is_file($sqlScript)) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'I couldn\'t find the SQL script to create the needed roles. Please make sure that ' . $sqlScript . ' exists and is readable by PHP.';
        header('Location: install.php?action=configure');
        return;
    }
    $sql = file_get_contents($sqlScript);
    if (!$sql) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'I couldn\'t read the SQL script in order to create the needed roles. Please make sure PHP can read the file ' . $sqlScript;
        header('Location: install.php?action=configure');
        return;
    }
    $sqlStatements = explode(';', $sql);
    foreach ($sqlStatements as $sqlStatement) {
        $sqlStatement = trim($sqlStatement);
        if ($sqlStatement == '') {
            continue;
        }
        $database->makeCustomQuery($sqlStatement);
    }
    $username = $database->escapeString($username);
    $firstName = $database->escapeString($firstName);
    $lastName = $database->escapeString($lastName);
    $email = $database->escapeString($email);
    $password = $database->escapeString($password);
    $success = $database->insertData('user', 'userID, userName, firstName, lastName, email, password, roleID', "0, 'anonGuest', 'Anonymous', 'Guest', '*****@*****.**', '', 1");
    $success = $success && $database->updateTable("user", "userID=0", "userID=1");
    $success = $success && $database->insertData('user', 'userID, userName, firstName, lastName, email, password, roleID', "1, '{$username}', '{$firstName}', '{$lastName}', '{$email}', '{$password}', 4");
    if (!$success) {
        unset($_SESSION['configureComplete']);
        $_SESSION['errors'][] = 'I couldn\'t create the new user account. Please try again. For help on this, please see <a href="https://www.educask.com" target="_blank">this page</a>.';
        //@ToDo: make the link point to actual help
        header('Location: install.php?action=configure');
        return;
    }
    $database->makeCustomQuery("ALTER TABLE user AUTO_INCREMENT=2");
    header('Location: install.php?action=install');
}
Example #12
0
 /**
  * @return string
  */
 public function algorithm()
 {
     return "ecdsa+" . $this->hasher->getAlgo();
 }
 public static function get(Clazz $clazz)
 {
     $hash = Hasher::hashObject($clazz);
     if (isset(self::$ACCESSORS[$hash])) {
         return self::$ACCESSORS[$hash];
     } else {
         return self::$ACCESSORS[Hasher::hashObject(Object::clazz())];
     }
 }
Example #14
0
 public function logIn($userName, $password)
 {
     if (!is_string($userName)) {
         return false;
     }
     if (!is_string($password)) {
         return false;
     }
     if ($this->isLoggedIn) {
         return true;
     }
     if (LockoutEngine::getInstance()->isLockedOut($_SERVER['REMOTE_ADDR'])) {
         return false;
     }
     //repeated twice just in case a plugin logs the user in
     if ($this->isLoggedIn) {
         return true;
     }
     $database = Database::getInstance();
     $database->connect();
     if (!$database->isConnected()) {
         return false;
     }
     $userName = $database->escapeString(trim($userName));
     $column = 'userID, roleID, userName, givenIdentifier, password, firstName, lastName, email, profilePictureLocation, birthday';
     $table = 'user';
     $where = '((email = \'' . $userName . '\') OR (userName = \'' . $userName . '\') OR (givenIdentifier = \'' . $userName . '\'))';
     if ($database->isConnected()) {
         $results = $database->getData($column, $table, $where);
     } else {
         $results = null;
     }
     //If there weren't any accounts found or too many accounts found
     if ($results === null) {
         return false;
     }
     if (count($results) > 1) {
         return false;
     }
     $dbPassword = $results[0]['password'];
     if (!Hasher::verifyHash($password, $dbPassword)) {
         return false;
     }
     self::setUserSession(new CurrentUser($results[0]['userID'], $results[0]['roleID'], $results[0]['givenIdentifier'], $results[0]['userName'], $results[0]['firstName'], $results[0]['lastName'], $results[0]['email'], new Link($results[0]['profilePictureLocation'], true), new DateTime($results[0]['birthday']), true));
     $this->isLoggedIn = true;
     $userID = $database->escapeString($this->getUserID());
     $database->updateTable('user', 'lastAccess = CURRENT_TIMESTAMP', "userID={$userID}");
     return true;
 }
 public function calc_rich()
 {
     Hasher::checkHash();
     $hash = Hasher::getHash();
     $tgl = addslashes($_POST['tgl']);
     $bln = addslashes($_POST['bln']);
     $thn = addslashes($_POST['th']);
     $gen = addslashes($_POST['gen']);
     $jam = addslashes($_POST['jam']);
     $tgl2 = addslashes($_POST['tgl2']);
     $bln2 = addslashes($_POST['bln2']);
     $thn2 = addslashes($_POST['th2']);
     $gen2 = addslashes($_POST['gen2']);
     $jam2 = addslashes($_POST['jam2']);
     //$tgl2 = 17; $bln2 = 6; $thn2 = 1982; $gen2 = 1;
     /*
     $tgl = 11;
     $bln = 3;
     $thn = 1981;
     $gen = 0;
     */
     $arr = MyBaziCalc::calc($jam, $tgl, $bln, $thn, $gen);
     $arr2 = MyBaziCalc::calc($jam2, $tgl2, $bln2, $thn2, $gen2);
     //pr($arr);
     //pr($arr2);
     $unsur = MyBaziCalc::getArrUnsur();
     /*****************************************
      *  KERJAKAN ARR 1
      *****************************************/
     //kerjakan arr 1
     $pillars = $arr['pillars'];
     //remove jam pillars
     unset($pillars['jam']);
     $kombi = BaziCombination::cek($pillars, $arr, $unsur);
     //pr($kombi);
     $tengod = Tengod::calc($kombi['newpillars'], $arr, $unsur);
     $hasil_type = BaziPembacaan::bacaTipe($kombi['newpillars'], $arr, $unsur, $tengod);
     $unsur_dibutuhkan = BaziPembacaan::unsurDibutuhkan($kombi['newpillars'], $arr, $unsur, $tengod, $hasil_type);
     $gudang = BaziBacaTengod::gudangUang($kombi, $arr, $unsur, $tengod);
     //pr($gudang);
     $posisi_gudang = $gudang['posisi'];
     $adaGudang = $gudang['ada'];
     $exp = explode("_", $posisi_gudang);
     $unsur_wealth = $exp[0];
     $gudang_tanah = $exp[1];
     /******************************************
      *  KERJAKAN ARR 2
      *****************************************/
     //kerjakan arr 2
     $pillars2 = $arr2['pillars'];
     //remove jam pillars
     unset($pillars2['jam']);
     $kombi2 = BaziCombination::cek($pillars2, $arr2, $unsur);
     //pr($kombi2);
     $tengod2 = Tengod::calc($kombi2['newpillars'], $arr2, $unsur);
     $hasil_type2 = BaziPembacaan::bacaTipe($kombi2['newpillars'], $arr2, $unsur, $tengod2);
     $unsur_dibutuhkan2 = BaziPembacaan::unsurDibutuhkan($kombi2['newpillars'], $arr2, $unsur, $tengod2, $hasil_type2);
     $gudang2 = BaziBacaTengod::gudangUang($kombi2, $arr2, $unsur, $tengod2);
     //pr($gudang2);
     $posisi_gudang2 = $gudang2['posisi'];
     $adaGudang2 = $gudang2['ada'];
     $exp2 = explode("_", $posisi_gudang2);
     $unsur_wealth2 = $exp2[0];
     $gudang_tanah2 = $exp2[1];
     /****************************************************8
      *    BERSAMA - SAMA
      ******************************************************/
     // cari apakah yang element gudang uang 1 ada di satunya
     $adaGudang3 = BaziBacaTengod::findElement($gudang_tanah, $pillars2);
     $adaGudang4 = BaziBacaTengod::findElement($gudang_tanah2, $pillars);
     $adaGudangGabungan = 0;
     if ($adaGudang3 > 0 || $adaGudang4 > 0) {
         $adaGudangGabungan = 1;
     }
     $bitcode = $adaGudang . $adaGudang2 . $adaGudangGabungan;
     $title = BaziQuiz::genericText('rich', "title_" . $bitcode);
     $return['picked'] = $title;
     //title nya
     //kerjakan descr nya
     $self = BaziQuiz::genericText('rich', "self_" . $adaGudang);
     $spouse = BaziQuiz::genericText('rich', "spouse_" . $adaGudang2);
     $both = BaziQuiz::genericText('rich', "both_" . $adaGudangGabungan);
     $return['more'] = "<p>" . $self . "</p><p>" . $spouse . "</p><p>" . $both . "</p>";
     // descr
     $return['text'] = $return['more'];
     //descr nya juga
     $return['base'] = base64_encode($bitcode);
     //base nya untuk macam2 titlenya
     /* **************
      * DEBUGERRR
      *************8*/
     /*
     echo "ada1 :".$adaGudang."<br>";
     echo "ada2 :".$adaGudang2."<br>";
     echo "ada3 :".$adaGudangGabungan."<br>";
     echo "bitcode".$bitcode;
     */
     //pr($json);
     echo json_encode($return);
     die;
     //echo "30";
     //exit();
 }
Example #16
0
 public function updateUserPassword(User $inUser, $newPassword, $oldPassword)
 {
     if (!PermissionEngine::getInstance()->currentUserCanDo('userCanUpdatePassword')) {
         return false;
     }
     if (strlen($newPassword) < $this->getMinimumPasswordLength()) {
         return false;
     }
     $userID = $inUser->getUserID();
     if (!is_numeric($userID)) {
         return false;
     }
     $db = Database::getInstance();
     if (!$db->isConnected()) {
         return false;
     }
     $userID = $db->escapeString($userID);
     $results = $db->getData('password', 'user', "userID = {$userID}");
     if ($results === false) {
         return false;
     }
     if ($results === null) {
         return false;
     }
     if (count($results) > 1) {
         return false;
     }
     $storedPassword = $results[0]['password'];
     if (!Hasher::verifyHash($oldPassword, $storedPassword)) {
         return false;
     }
     $newHashed = Hasher::generateHash($newPassword);
     $newHashed = $db->escapeString($newHashed);
     $results = $db->updateTable('user', "password = '******'", "userID = {$userID}");
     if (!$results) {
         return false;
     }
     return true;
 }
Example #17
0
 function settingsAction()
 {
     $img_id = $_SESSION['imag_id'];
     $imgAccount = ImgAccountUtil::getImgAccountById($img_id, TRUE);
     $v_params['sys_name'] = SysPropertiesUtil::getPropertyValue("sys_name");
     $v_params['sys_slog'] = SysPropertiesUtil::getPropertyValue("sys_slog");
     if (NULL != $imgAccount) {
         $v_params['logined'] = LoginChecker::isLogined();
         if ($v_params['logined'] == $img_id) {
             $v_params['mysc']['main'] = TRUE;
             $imgAddress = ImgAddressUtil::getImgAddressById($imgAccount['img_address_id']);
             // Данные аккаунта
             if (isset($_REQUEST['name_form'])) {
                 if (isset($_REQUEST['img_name'])) {
                     $imgAccount['img_name'] = trim($_REQUEST['img_name']);
                 }
                 if (isset($_REQUEST['img_slog'])) {
                     $imgAccount['img_slog'] = trim($_REQUEST['img_slog']);
                 }
                 // Сохраняем изменения
                 ImgAccountUtil::updateImgAccount($imgAccount);
                 $imgAccount = ImgAccountUtil::getImgAccountById($img_id, TRUE);
                 $v_params['result_text'] = "Название и слоган торгового стенда успешно изменены";
             }
             // Контактная информация
             if (isset($_REQUEST['contacts_form'])) {
                 // Данные адреса
                 if (isset($_REQUEST['addr_region'])) {
                     $addr_region_code = intval($_REQUEST['addr_region']);
                     $addr_region = AddrRegionUtil::getRegionByCode($addr_region_code);
                     $imgAddress['region_id'] = $addr_region['id'];
                 }
                 if (isset($_REQUEST['addr_city'])) {
                     $imgAddress['sity'] = $_REQUEST['addr_city'];
                 }
                 if (isset($_REQUEST['addr_street'])) {
                     $imgAddress['street'] = $_REQUEST['addr_street'];
                 }
                 if (isset($_REQUEST['addr_house'])) {
                     $imgAddress['house'] = $_REQUEST['addr_house'];
                 }
                 if (isset($_REQUEST['contacts_form'])) {
                     if (0 == strcmp("on", $_REQUEST['addr_show'])) {
                         $imgAccount['show_address'] = 1;
                     } else {
                         $imgAccount['show_address'] = 0;
                     }
                 }
                 // Данные телефона
                 if (isset($_REQUEST['phone_phone'])) {
                     $imgAccount['img_phone'] = $_REQUEST['phone_phone'];
                 }
                 if (isset($_REQUEST['contacts_form'])) {
                     if (0 == strcmp("on", $_REQUEST['phone_show'])) {
                         $imgAccount['show_phone'] = 1;
                     } else {
                         $imgAccount['show_phone'] = 0;
                     }
                 }
                 // Данные скайпа
                 if (isset($_REQUEST['skype_skype'])) {
                     $imgAccount['img_skype'] = $_REQUEST['skype_skype'];
                 }
                 if (isset($_REQUEST['contacts_form'])) {
                     if (0 == strcmp("on", $_REQUEST['skype_show'])) {
                         $imgAccount['show_skype'] = 1;
                     } else {
                         $imgAccount['show_skype'] = 0;
                     }
                 }
                 // Данные ICQ
                 if (isset($_REQUEST['icq_icq'])) {
                     $imgAccount['img_icq'] = $_REQUEST['icq_icq'];
                 }
                 if (isset($_REQUEST['contacts_form'])) {
                     if (0 == strcmp("on", $_REQUEST['icq_show'])) {
                         $imgAccount['show_icq'] = 1;
                     } else {
                         $imgAccount['show_icq'] = 0;
                     }
                 }
                 // Сохраняем изменения
                 ImgAddressUtil::updateImgAddress($imgAddress);
                 ImgAccountUtil::updateImgAccount($imgAccount);
                 $imgAccount = ImgAccountUtil::getImgAccountById($img_id, TRUE);
                 $imgAddress = ImgAddressUtil::getImgAddressById($imgAccount['img_address_id']);
                 $v_params['result_text'] = "Контактная информация успешно изменена";
             }
             // Форма смены пароля
             if (isset($_REQUEST['pass_form'])) {
                 $old_pass = $_REQUEST['pass_old'];
                 $new_pass = $_REQUEST['pass_new'];
                 $new_pass2 = $_REQUEST['pass_new2'];
                 if (0 == strcmp("", $old_pass)) {
                     $v_params['errors'][] = "Текущий пароль обязателен для ввода";
                 } else {
                     if (0 != strcmp($imgAccount['hashpass'], Hasher::getHash($old_pass))) {
                         $v_params['errors'][] = "Текущий пароль введен не верно";
                     }
                 }
                 if (0 == strcmp("", $new_pass)) {
                     $v_params['errors'][] = "Новый пароль обязателен для ввода";
                 } else {
                     if (9 > strlen($new_pass)) {
                         $v_params['errors'][] = "Новый пароль должен быть длиной от 9 символов";
                     }
                 }
                 if (0 == strcmp("", $new_pass2)) {
                     $v_params['errors'][] = "Повторите новый пароль";
                 } else {
                     if (0 != strcmp($new_pass, $new_pass2)) {
                         $v_params['errors'][] = "Новый пароль и его повторение не совпадают";
                     }
                 }
                 if (!count($v_params['errors'])) {
                     $imgAccount['hashpass'] = Hasher::getHash($new_pass);
                     // Сохраняем изменения
                     ImgAccountUtil::updateImgAccount($imgAccount);
                     $imgAccount = ImgAccountUtil::getImgAccountById($img_id, TRUE);
                     $v_params['result_text'] = "Пароль успешно изменен";
                 }
             }
             // Данные аккаунта
             $v_params['img_name'] = $imgAccount['img_name'];
             $v_params['img_slog'] = $imgAccount['img_slog'];
             // Данные адреса
             $v_params['img_region_code'] = $imgAddress['rcode'];
             $v_params['img_sity'] = $imgAddress['sity'];
             $v_params['img_street'] = $imgAddress['street'];
             $v_params['img_house'] = $imgAddress['house'];
             $v_params['img_address_show'] = $imgAccount['show_address'];
             if (77 == $v_params['img_region_code'] || 78 == $v_params['img_region_code']) {
                 $v_params['img_sity_disabled'] = TRUE;
             }
             // Данные телефона
             $v_params['img_phone'] = $imgAccount['img_phone'];
             $v_params['img_phone_show'] = $imgAccount['show_phone'];
             // Данные скайпа
             $v_params['img_skype'] = $imgAccount['img_skype'];
             $v_params['img_skype_show'] = $imgAccount['show_skype'];
             // Данные ICQ
             $v_params['img_icq'] = $imgAccount['img_icq'];
             $v_params['img_icq_show'] = $imgAccount['show_icq'];
             $v_params['img_gds_cats_HTML'] = ImgGdsCatUtil::createTreeHTML($imgAccount['id'], "/" . IMAG_PREFIX . $img_id . "/" . IMAG_DIR . "?" . PROD_CAT_PARAM_NAME . "=");
             $v_params['img_blog_cats_HTML'] = ImgBlogCatUtil::createTreeHTML($imgAccount['id'], "/" . IMAG_PREFIX . $img_id . "/" . BLOG_DIR . "?" . ART_CAT_PARAM_NAME . "=");
             $v_params['addr_regions'] = AddrRegionUtil::getRegions();
             Application::fastView('imag-admin/img_admin_settings', $v_params);
             return;
         } else {
         }
     }
     Application::fastView('main/sys_error', $v_params);
 }
Example #18
0
 public function __call($method, $arguments)
 {
     switch ($method) {
         case in_array($method, static::$retrieve):
             $params = array_merge(static::$options, $this->params);
             $this->params = array();
             switch ($method) {
                 case 'all':
                 case 'pick':
                     $limit = array_shift($arguments) ?: ($method === 'all' ? 0 : 1);
                     if ($limit > 1) {
                         $params['limit'] = $limit;
                     }
                     $result = $this->select($params['select'] ?: '*', $params['where'], $params);
                     return $limit != 1 ? $result->fetch_all() : $result->fetch();
                 case 'each':
                     @(list($lambda) = $arguments);
                     if ($lambda instanceof \Closure) {
                         $result = $this->select($params['select'] ?: '*', $params['where'], $params);
                         while ($row = $result->fetch()) {
                             $lambda($row);
                         }
                         return;
                     }
                 case 'count':
                     return (int) $this->select('COUNT(*)', $params['where'], $params)->result();
                 default:
                     throw new \Exception("Invalid parameters on '{$method}()'");
             }
         case in_array($method, static::$chained):
             if (sizeof($arguments) === 0) {
                 throw new \Exception("Missing arguments for '{$method}()'");
             } elseif (isset($this->params[$method])) {
                 array_unshift($arguments, $this->params[$method]);
             }
             @(list($first) = $arguments);
             $method = str_replace('get', 'select', $method);
             $this->params[$method] = $first;
             return $this;
         case 'index':
             @(list($name, $unique) = $arguments);
             return $this->add_index("{$this}_{$this->offset}_{$name}_idx", array($this->offset), !!$unique);
         case 'unindex':
             @(list($name) = $arguments);
             return $this->remove_index("{$this}_{$this->offset}_{$name}_idx", (string) $this);
         default:
             return parent::__call($method, $arguments);
     }
 }
 public function resetUsersPassword($token, $userID, $chosenPassword, $chosenPasswordConfirmation)
 {
     if (!is_string($token)) {
         return false;
     }
     if (!is_numeric($userID)) {
         return false;
     }
     if ($chosenPassword !== $chosenPasswordConfirmation) {
         return false;
     }
     if (strlen($chosenPassword) < $this->getMinimumPasswordLength()) {
         return false;
     }
     $database = Database::getInstance();
     if (!$database->isConnected()) {
         return false;
     }
     $forgotPassword1 = $this->getForgotPasswordByToken($token);
     if ($forgotPassword1 === false) {
         return false;
     }
     $forgotPassword2 = $this->getForgotPasswordByUserID($userID);
     if ($forgotPassword2 === false) {
         return false;
     }
     if (!$forgotPassword1->verify($forgotPassword2->getToken(), $forgotPassword2->getUserID())) {
         return false;
     }
     if (!$forgotPassword2->verify($forgotPassword1->getToken(), $forgotPassword1->getUserID())) {
         return false;
     }
     $newHash = Hasher::generateHash($chosenPassword);
     $newHash = $database->escapeString($newHash);
     $userID = $database->escapeString($forgotPassword1->getUserID());
     $result = $database->updateTable('user', "password = '******'", "userID = {$userID}");
     if (!$result) {
         return false;
     }
     return true;
 }
 public function hashCode()
 {
     $hashCode = '';
     foreach ($this as $key => $value) {
         $hashCode .= self::$HASH_SIGNATURE . Hasher::hash($key) . '=>' . Hasher::hash($value);
     }
     return md5($hashCode);
 }
Example #21
0
 /**
  * @param User $user
  * @param $password
  * @return bool
  */
 public function changeUserPassword(User $user, $password)
 {
     $user->hash = $this->hasher->hashPassword($password);
     return $user->save();
 }
Example #22
0
 /**
  * Test the Hasher throws an exception when a file isn't found
  * @expectedException \Heyday\HashPath\Exception
  */
 public function testGetFileHashThrows()
 {
     $hasher = new Hasher();
     $hasher->getFileHash(__DIR__ . '/non-existent-file');
 }