示例#1
8
 /**
  * Decrypts given string with crypt, blowfish and base64 with private key
  * 
  * @param   String $stringToDesalt    String to encode  
  * @return  String $decodedString     encoded String
  */
 public function getDecodedString($stringToDesalt)
 {
     $cipherKey = crypt(base64_decode($stringToDesalt), $this->getPrivateKey());
     $bf = new Blowfish($cipherKey.$this->getPrivateKey());
     $decodedString = $bf->decrypt(base64_decode($stringToDesalt));    
     return $decodedString;
 }
示例#2
0
 /**
  * Decrypts the ciphertext using Blowfish with the given key.
  *
  * @param string $ciphertext the encrypted string
  * @param string $key the encryption key
  * @param int $mode one of BLOWFISH_MODE_CBC, BLOWFISH_MODE_EBC. BLOWFISH_MODE_CBC is recommened
  * @param int $padding one of BLOWFISH_PADDING_NONE, BLOWFISH_PADDING_RFC, BLOWFISH_PADDING_ZERO. BLOWFISH_PADDING_RFC is recommened
  * @param int $iv the initialisation vector. Required when using CBC mode.
  * @return string Returns the plaintext string.
  * @author Matt Harris
  **/
 public function decrypt($ciphertext, $key, $mode = Blowfish::BLOWFISH_MODE_CBC, $padding = Blowfish::BLOWFISH_PADDING_RFC, $iv = NULL)
 {
     if ($mode == Blowfish::BLOWFISH_MODE_CBC and empty($iv)) {
         throw new Exception('CBC Mode requires an IV key');
         return;
     }
     $plaintext = '';
     $fish = new Blowfish($key, $mode, $padding, $iv);
     $block =& $fish->blockSize;
     $len = strlen($ciphertext);
     # encrypt in 1 byte intervals
     for ($i = 0; $i < $len; $i += $block) {
         list(, $xL, $xR) = unpack('N2', substr($ciphertext, $i, $block));
         $fish->_decipher($xL, $xR);
         if ($mode == Blowfish::BLOWFISH_MODE_CBC) {
             $chain = $i == 0 ? $fish->IV : substr($ciphertext, $i - $block, $block);
             $plaintext .= pack('N2', $xL, $xR) ^ $chain;
         } else {
             $plaintext .= pack('N2', $xL, $xR);
         }
     }
     $plaintext = $fish->_unpad($plaintext);
     unset($fish);
     return $plaintext;
 }
示例#3
0
function SSO_EndpointOutput($result)
{
    global $sso_encrypted, $sso_apikey_info, $sso_data, $sso_skipsleep;
    if (!$sso_skipsleep) {
        SSO_RandomSleep();
    }
    $result = @json_encode($result);
    if ($sso_encrypted) {
        if ($sso_apikey_info["keyinfo"]["mode"] === "aes256") {
            $result = ExtendedAES::CreateDataPacket($result, $sso_apikey_info["keyinfo"]["key"], $sso_apikey_info["keyinfo"]["opts"]);
        } else {
            $result = Blowfish::CreateDataPacket($result, $sso_apikey_info["keyinfo"]["key"], $sso_apikey_info["keyinfo"]["opts"]);
        }
        $result = base64_encode($result);
    }
    echo $result;
    exit;
}
示例#4
0
 static function Hash($data, $rounds, $mintime)
 {
     $data = (string) $data;
     if ($data == "") {
         return array("success" => false, "error" => "No data.");
     }
     // Expand data.
     $origdata = $data;
     while (strlen($data) < 56) {
         $data .= $origdata;
     }
     $maxpos = strlen($data);
     $data .= $data;
     // Run through Blowfish.
     $result = "";
     for ($x = 0; $x < 32; $x++) {
         $result .= chr($x);
     }
     $x = 0;
     $ts = microtime(true) + $mintime / 1000;
     $totalrounds = 0;
     if (self::IsMcryptAvailable()) {
         $mp = mcrypt_module_open(MCRYPT_BLOWFISH, "", MCRYPT_MODE_ECB, "");
         $iv = str_repeat("", mcrypt_enc_get_iv_size($mp));
         if (mcrypt_enc_get_key_size($mp) != 56) {
             return array("success" => false, "error" => "Unexpected response from PHP function.");
         }
         while ($rounds > 0) {
             $key = substr($data, $x, 56);
             $x = ($x + 56) % $maxpos;
             mcrypt_generic_init($mp, $key, $iv);
             $result = mcrypt_generic($mp, $result);
             mcrypt_generic_deinit($mp);
             $result = substr($result, -1) . substr($result, 0, -1);
             $rounds--;
             $totalrounds++;
             if (!$rounds && $mintime > 0 && microtime(true) < $ts) {
                 $rounds++;
             }
         }
         mcrypt_module_close($mp);
     } else {
         $numbits = 56 * 8;
         $bf = new Blowfish();
         while ($rounds > 0) {
             $key = substr($data, $x, 56);
             $x = ($x + 56) % $maxpos;
             $bf->SetKey($key, $numbits);
             $bf->AddData($result);
             $bf->Finalize();
             $result = $bf->Encrypt();
             $result = substr($result, -1) . substr($result, 0, -1);
             $rounds--;
             $totalrounds++;
             if (!$rounds && $mintime > 0 && microtime(true) < $ts) {
                 $rounds++;
             }
         }
     }
     return array("success" => true, "hash" => $result, "rounds" => $totalrounds);
 }
            $error = 'email exists';
        }
    }
}
// Mailing revive
$revive_sent = false;
$nbRevive = 0;
if (Tools::isSubmit('revive')) {
    $activeTab = 'pending';
    if (Tools::getValue('friendChecked') and sizeof($friendsChecked = Tools::getValue('friendChecked')) >= 1) {
        foreach ($friendsChecked as $key => $friendChecked) {
            if (ReferralProgramModule::isSponsorFriend((int) $cookie->id_customer, (int) $friendChecked)) {
                if (Configuration::get('PS_CIPHER_ALGORITHM')) {
                    $cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
                } else {
                    $cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
                }
                $referralprogram = new ReferralProgramModule((int) $key);
                $vars = array('{email}' => $cookie->email, '{lastname}' => $cookie->customer_lastname, '{firstname}' => $cookie->customer_firstname, '{email_friend}' => $referralprogram->email, '{lastname_friend}' => $referralprogram->lastname, '{firstname_friend}' => $referralprogram->firstname, '{link}' => 'authentication.php?create_account=1&sponsor=' . base64_encode($cipherTool->encrypt($referralprogram->id . '|' . $referralprogram->email . '|')), '{discount}' => $discount);
                $referralprogram->save();
                Mail::Send((int) $cookie->id_lang, 'referralprogram-invitation', Mail::l('Referral Program'), $vars, $referralprogram->email, $referralprogram->firstname . ' ' . $referralprogram->lastname, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/mails/');
                $revive_sent = true;
                $nbRevive++;
            }
        }
    } else {
        $error = 'no revive checked';
    }
}
$customer = new Customer((int) $cookie->id_customer);
$stats = $customer->getStats();
示例#6
0
 /**
  * Hook display on form create account
  * Add an additional input on bottom for fill the sponsor's e-mail address
  */
 public function hookCreateAccountForm($params)
 {
     global $smarty;
     $blowfish = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
     $explodeResult = explode('|', $blowfish->decrypt(urldecode(Tools::getValue('sponsor'))));
     if ($explodeResult and count($explodeResult) > 1 and list($id_referralprogram, $email) = $explodeResult and intval($id_referralprogram) and Validate::isEmail($email) and $id_referralprogram == ReferralProgramModule::isEmailExists($email)) {
         $referralprogram = new ReferralProgramModule($id_referralprogram);
         if (Validate::isLoadedObject($referralprogram)) {
             /* hack for display referralprogram information in form */
             $_POST['customer_firstname'] = $referralprogram->firstname;
             $_POST['firstname'] = $referralprogram->firstname;
             $_POST['customer_lastname'] = $referralprogram->lastname;
             $_POST['lastname'] = $referralprogram->lastname;
             $_POST['email'] = $referralprogram->email;
             $_POST['email_create'] = $referralprogram->email;
             $sponsor = new Customer($referralprogram->id_sponsor);
             $_POST['referralprogram'] = $sponsor->email;
         }
     }
     return $this->display(__FILE__, 'authentication.tpl');
 }
示例#7
0
    function hookFooter($params)
    {
        global $protocol_content, $server_host;
        // Identification information are encrypted to prevent hacking attempts
        $blowfish = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
        if (!isset($params['cookie']->id_guest)) {
            Guest::setNewGuest($params['cookie']);
            // Ajax request sending browser information
            $token = $blowfish->encrypt($params['cookie']->id_guest);
            $this->_html = '
			<script type="text/javascript" src="' . $protocol_content . $server_host . __PS_BASE_URI__ . 'js/pluginDetect.js"></script>
			<script type="text/javascript">
				plugins = new Object;
				
				plugins.adobe_director = (PluginDetect.getVersion("Shockwave") != null) ? 1 : 0;
				plugins.adobe_flash = (PluginDetect.getVersion("Flash") != null) ? 1 : 0;
				plugins.apple_quicktime = (PluginDetect.getVersion("QuickTime") != null) ? 1 : 0;
				plugins.windows_media = (PluginDetect.getVersion("WindowsMediaPlayer") != null) ? 1 : 0;
				plugins.sun_java = (PluginDetect.getVersion("java") != null) ? 1 : 0;
				plugins.real_player = (PluginDetect.getVersion("RealPlayer") != null) ? 1 : 0;
				
				$(document).ready(
					function() {
						navinfo = new Object;
						navinfo = { screen_resolution_x: screen.width, screen_resolution_y: screen.height, screen_color:screen.colorDepth};
						for (var i in plugins)
							navinfo[i] = plugins[i];
						navinfo.type = "navinfo";
						navinfo.token = "' . $token . '";
						$.post("' . $protocol_content . $server_host . __PS_BASE_URI__ . 'statistics.php", navinfo);
					}
				);
			</script>';
        }
        // Record the guest path then increment the visit counter of the page
        $tokenArray = Connection::setPageConnection($params['cookie']);
        ConnectionsSource::logHttpReferer();
        Page::setPageViewed($tokenArray['id_page']);
        // Ajax request sending the time spend on the page
        $token = $blowfish->encrypt($tokenArray['id_connections'] . '|' . $tokenArray['id_page'] . '|' . $tokenArray['time_start']);
        $this->_html .= '
		<script type="text/javascript">
			var time_start;
			$(window).load(
				function() {
					time_start = new Date();
				}
			);
			$(window).unload(
				function() {
					var time_end = new Date();
					var pagetime = new Object;
					pagetime.type = "pagetime";
					pagetime.token = "' . $token . '";
					pagetime.time = time_end-time_start;
					$.post("' . $protocol_content . $server_host . __PS_BASE_URI__ . 'statistics.php", pagetime);
				}
			);
		</script>';
        return $this->_html;
    }
示例#8
0
文件: index.php 项目: marks2016/sso
 public static function VerifyPasswordInfo($data, $hash, $numrounds)
 {
     global $sso_settings;
     if ($sso_settings["sso_login"]["password_mode"] == "password_hash_bcrypt" && function_exists("password_verify")) {
         $result = @password_verify($data, pack("H*", $hash));
         if ($result === false) {
             return false;
         }
     } else {
         $result = Blowfish::Hash($data, $numrounds, 0);
         if (!$result["success"] || $hash !== bin2hex($result["hash"])) {
             return false;
         }
     }
     return true;
 }
示例#9
0
<?php

require_once '../blowfish.php';
$examples = array(array('d)U>tQwbUWIozi2R"fOvK0Wuxyl79P%Uxr>;7iiy,b0hByATUB', 'x03nMwK34x&ciSUH0I1got', 'password'), array('RiV3wc615X6J2lzK', 'QndancjtdZ&b_J5aeId62x7Kxu`[dFFt{t7yGcS+O!w7JbAlQe', 'p'), array('d)U>tQwbUWIozi2R"fOvK0Wuxyl79P%Uxr>;7iiy,b0hByATUB', 'x03nMwK34x&ciSUH0I1got', 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'), array('This is my secret key and it can be plain text', 'What about this initialisation vector?', 'I hope you know this invalidates my warranty'), array('This is my secret key and it can be plain test', 'What about this initialisation vector?', ''));
foreach ($examples as $ex) {
    $ciphertext = Blowfish::encrypt($ex[2], $ex[0], Blowfish::BLOWFISH_MODE_CBC, Blowfish::BLOWFISH_PADDING_RFC, $ex[1]);
    $deciphered = Blowfish::decrypt($ciphertext, $ex[0], Blowfish::BLOWFISH_MODE_CBC, Blowfish::BLOWFISH_PADDING_RFC, $ex[1]);
    echo '<pre>';
    printf('Plaintext: %s (length %d)%s', $ex[2], strlen($ex[2]), PHP_EOL);
    printf('Ciphertext: %s (length %d)%s', $ciphertext, strlen($ciphertext), PHP_EOL);
    printf('Deciphered text: %s (length %d)%s', $deciphered, strlen($deciphered), PHP_EOL);
}
示例#10
0
 function check_implementation()
 {
     $blowfish = new Blowfish("");
     $vectors = array(array(array(0x0, 0x0), array(0x0, 0x0), array(0x4ef99745, 0x6198dd78)), array(array(0xffffffff, 0xffffffff), array(0xffffffff, 0xffffffff), array(0x51866fd5, 0xb85ecb8a)), array(array(0x1234567, 0x89abcdef), array(0x11111111, 0x11111111), array(0x61f9c380, 0x2281b096)));
     //Correct implementation?
     $correct = true;
     //Test vectors, see http://www.schneier.com/code/vectors.txt
     foreach ($vectors as $vector) {
         $key = $vector[0];
         $plain = $vector[1];
         $cipher = $vector[2];
         $blowfish->key_setup($key);
         $return = $blowfish->block_encrypt($vector[1][0], $vector[1][1]);
         if ($return[0] != $cipher[0] || $return[1] != $cipher[1]) {
             $correct = false;
         }
     }
     return $correct;
 }
示例#11
0
 /**
  * This method decrypts $content using the password $key.<br />
  * If the mcrypt extension is installed, it will use $cipher as cipher and 
  * $mode as mode.<br />
  * If not, no matter what is given in $cipher and $mode, this method will use
  * blowfish in CBC mode, with RFC padding style. In this case, it uses Matt Harris'
  * blowfish class instead of the mcrypt extension.
  * @param str $content The encrypted text to decrypt.
  * @param str $key The secret key. Defaults to an empty string.
  * @param str $cipher One of the MCRYPT_ciphername PHP constants. Defaults to MCRYPT_RIJNDAEL_256.
  * @param str $mode One of the MCRYPT_MODE_modename PHP constants. Defaults to MCRYPT_MODE_CBC.
  * @return str The decrypted text.
  */
 public function uncrypt($content, $key = '', $cipher = MCRYPT_RIJNDAEL_256, $mode = MCRYPT_MODE_CBC)
 {
     $this->debug(__FUNCTION__, 2, __LINE__);
     $this->debug('Uncrypting with key ' . $key, 3, __LINE__);
     if (!empty($content)) {
         if ($this->mcrypt_active) {
             $iv_size = mcrypt_get_iv_size($cipher, $mode);
             $iv = substr(md5('hskjdh kjqsdnqndqs; sqnd;qskjdhkjha knd;n;za jkah'), 0, $iv_size);
             $content = substr($content, $iv_size);
             if ($key == '') {
                 $key = MD5(__CLASS__ . 'defaultpass');
                 $this->debug('No key given. We will use ' . $key, 3, __LINE__);
             } else {
                 $key = MD5(__CLASS__ . $key);
                 $this->debug('A key was given. We will use ' . $key, 3, __LINE__);
             }
             $uncrypted = mcrypt_decrypt($cipher, $key, $content, $mode, $iv);
             $ret = rtrim($uncrypted, "");
         } else {
             $iv = md5('jdqlkj ,ql dqd45dq454 ù;:sqmqdqsdd1216qq2s sqqsd!');
             // We will use the blowfish class instead of mcrypt
             $ret = Blowfish::decrypt($content, $key, Blowfish::BLOWFISH_MODE_CBC, Blowfish::BLOWFISH_PADDING_RFC, $iv);
         }
         return $ret;
     }
     return 'Nothing to uncrypt...';
 }
示例#12
0
<?php

/**
 * Statistics
 * @category stats
 *
 * @author Damien Metzger / Epitech
 * @copyright Epitech / PrestaShop
 * @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
 * @version 1.1
 */
if (!isset($_POST['token']) or !isset($_POST['type'])) {
    die;
}
include dirname(__FILE__) . '/config/config.inc.php';
$blowfish = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
$token = $blowfish->decrypt($_POST['token']);
if ($_POST['type'] == 'navinfo') {
    if (!Validate::isUnsignedId(intval($token))) {
        exit;
    }
    $guest = new Guest($token);
    $guest->javascript = true;
    $guest->screen_resolution_x = intval($_POST['screen_resolution_x']);
    $guest->screen_resolution_y = intval($_POST['screen_resolution_y']);
    $guest->screen_color = intval($_POST['screen_color']);
    $guest->sun_java = intval($_POST['sun_java']);
    $guest->adobe_flash = intval($_POST['adobe_flash']);
    $guest->adobe_director = intval($_POST['adobe_director']);
    $guest->apple_quicktime = intval($_POST['apple_quicktime']);
    $guest->real_player = intval($_POST['real_player']);
示例#13
0
function SSO_ValidateUser()
{
    global $sso_rng, $sso_db, $sso_db_user_sessions, $sso_db_temp_sessions, $sso_session_info, $sso_apirow, $sso_sessionrow, $sso_sessionrow2, $sso_ipaddr, $sso_settings;
    try {
        // Browser gets a token representing the new session in the temporary session.
        $sso_session_info["new_id2"] = $sso_rng->GenerateString();
        $sso_db->Query("UPDATE", array($sso_db_temp_sessions, array("info" => serialize($sso_session_info)), "WHERE" => "id = ?"), $sso_sessionrow->id);
        // Validate the session.
        $sso_db->Query("UPDATE", array($sso_db_user_sessions, array("updated" => CSDB::ConvertToDBTime(time()), "info" => serialize(array("validated" => true, "ipaddr" => $sso_ipaddr["ipv6"]))), "WHERE" => "id = ?"), $sso_sessionrow2->id);
        // Build the redirect.
        $redirect = str_replace(array("\r", "\n"), "", base64_decode($sso_session_info["url"]));
        $redirect .= (strpos($redirect, "?") === false ? "?" : "&") . "from_sso_server=1&sso_id=" . urlencode($sso_session_info["new_id2"]) . "&sso_id2=" . urlencode($_REQUEST["sso_id"]);
        // Set the namespace cookie.
        if (isset($sso_settings[""]["namespacekey2"])) {
            $namespaces = SSO_LoadNamespaces(true);
            $namespaces[$sso_apirow->namespace] = $_COOKIE["sso_server_id2"];
            $data = serialize($namespaces);
            $data = base64_encode(Blowfish::CreateDataPacket($data, pack("H*", $sso_settings[""]["namespacekey"]), array("prefix" => $sso_rng->GenerateString(), "mode" => "CBC", "iv" => pack("H*", $sso_settings[""]["namespaceiv"]), "key2" => pack("H*", $sso_settings[""]["namespacekey2"]), "iv2" => pack("H*", $sso_settings[""]["namespaceiv2"]), "lightweight" => true)));
            SetCookieFixDomain("sso_server_ns", $data, 0, "", "", SSO_IsSSLRequest(), true);
        }
        // Set the exposed namespace cookie if the option is enabled.
        if (isset($sso_settings[""]["expose_namespaces"]) && $sso_settings[""]["expose_namespaces"] && isset($sso_settings[""]["namespacekey4"])) {
            $namespaces = SSO_LoadNamespaces(false);
            $namespaces[$sso_apirow->namespace] = $sso_sessionrow2->id;
            $data = serialize($namespaces);
            $data = base64_encode(Blowfish::CreateDataPacket($data, pack("H*", $sso_settings[""]["namespacekey3"]), array("prefix" => $sso_rng->GenerateString(), "mode" => "CBC", "iv" => pack("H*", $sso_settings[""]["namespaceiv3"]), "key2" => pack("H*", $sso_settings[""]["namespacekey4"]), "iv2" => pack("H*", $sso_settings[""]["namespaceiv4"]), "lightweight" => true)));
            $host = str_replace(array("http://", "https://"), "", BB_GetRequestHost());
            SetCookieFixDomain("sso_server_ns2", $data, 0, "/", $host, false, true);
        }
        // Redirect back to the client.
        SSO_ExternalRedirect($redirect, true);
    } catch (Exception $e) {
        // Don't do anything here.  Just catch the database exception and let the code fall through.
        // It should be nearly impossible to get here in the first place.
    }
    return false;
}
示例#14
0
文件: crud.php 项目: cmskit/core
$referenceFields = $referenceName ? $_SESSION[$projectName]['settings']['labels'][$referenceName] : array('id' => 1);
$objectFields = $_SESSION[$projectName]['settings']['labels'][$objectName];
foreach ($_POST as $k => $v) {
    switch (substr($k, 0, 2)) {
        // base64-encode Content
        case 'e_':
            $_POST[$k] = base64_encode($v);
            break;
            // encrypt Content (Blowfish) OR prevent replacing encrypted Content
        // encrypt Content (Blowfish) OR prevent replacing encrypted Content
        case 'c_':
            if (isset($_SESSION[$projectName]['config']['crypt'][$objectName][$k])) {
                require_once 'inc/php/crypt.php';
                // the Key is buid  MD5( projectname + objectname + fieldname + entry_id + password )
                $key = md5($projectName . $objectName . $k . $objectId . $_SESSION[$projectName]['config']['crypt'][$objectName][$k]);
                $_POST[$k] = Blowfish::encrypt($v, $key, md5($_CONF::$DB_PASSWORD[$objectDB]));
            } else {
                unset($_POST[$k]);
            }
            break;
    }
}
$objectHooks = $objects[$objectName]['hooks'];
$c->lang = $lang;
$c->LL = $LL;
$c->projectName = $projectName;
$c->ppath = $projectPath;
$c->objects = $objects;
$c->objectName = $objectName;
$c->objectId = $objectId;
$c->objectFields = $objectFields;
示例#15
0
        } else {
            list($key, $plaintext, $expected_ciphertext) = preg_split('/\\s+/', $v);
            $iv = NULL;
        }
        $key = trim($key);
        $key = pack('H' . strlen($key), $key);
        if ($mode == Blowfish::BLOWFISH_MODE_CBC) {
            $iv = trim($iv);
            $iv = pack('H' . strlen($iv), $iv);
        }
        $plaintext = trim($plaintext);
        $plaintext = pack('H' . strlen($plaintext), $plaintext);
        $expected_ciphertext = trim($expected_ciphertext);
        $expected_ciphertext = pack('H' . strlen($expected_ciphertext), $expected_ciphertext);
        # test vectors were created with different padding types
        if ($mode == Blowfish::BLOWFISH_MODE_CBC) {
            $padding = Blowfish::BLOWFISH_PADDING_ZERO;
        } else {
            $padding = Blowfish::BLOWFISH_PADDING_NONE;
        }
        $actual_ciphertext = Blowfish::encrypt($plaintext, $key, $mode, $padding, $iv);
        $actual_deciphered = Blowfish::decrypt($expected_ciphertext, $key, $mode, $padding, $iv);
        $cipher_result = $actual_ciphertext == $expected_ciphertext ? 'PASS' : 'FAIL';
        $plain_result = $actual_deciphered == $plaintext ? 'PASS' : 'FAIL';
        if ($mode != Blowfish::BLOWFISH_MODE_CBC) {
            echo sprintf('%-50s%-20s%-20s%-10s%-20s%-20s%-10s%s', base64_encode($key), base64_encode($plaintext), base64_encode($actual_deciphered), $plain_result, base64_encode($expected_ciphertext), base64_encode($actual_ciphertext), $cipher_result, PHP_EOL);
        } else {
            echo sprintf('%-21s%-50s%-50s%-10s%s%-21s%-50s%-50s%-10s%s', $key, base64_encode($plaintext), base64_encode($actual_deciphered), $plain_result, PHP_EOL, $iv, base64_encode($expected_ciphertext), base64_encode($actual_ciphertext), $cipher_result, PHP_EOL);
        }
    }
}
示例#16
0
 /**
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     // get discount value (ready to display)
     $discount_type = (int) Configuration::get('REFERRAL_DISCOUNT_TYPE');
     if ($discount_type == 1) {
         $discount = Discount::display((double) Configuration::get('REFERRAL_PERCENTAGE'), $discount_type, new Currency($this->context->currency->id));
     } else {
         $discount = Discount::display((double) Configuration::get('REFERRAL_DISCOUNT_VALUE_' . (int) $this->context->currency->id), $discount_type, new Currency($this->context->currency->id));
     }
     $activeTab = 'sponsor';
     $error = false;
     // Mailing invitation to friend sponsor
     $invitation_sent = false;
     $nbInvitation = 0;
     if (Tools::isSubmit('submitSponsorFriends') and Tools::getValue('friendsEmail') and sizeof($friendsEmail = Tools::getValue('friendsEmail')) >= 1) {
         $activeTab = 'sponsor';
         if (!Tools::getValue('conditionsValided')) {
             $error = 'conditions not valided';
         } else {
             $friendsLastName = Tools::getValue('friendsLastName');
             $friendsFirstName = Tools::getValue('friendsFirstName');
             $mails_exists = array();
             foreach ($friendsEmail as $key => $friendEmail) {
                 $friendEmail = strval($friendEmail);
                 $friendLastName = strval($friendsLastName[$key]);
                 $friendFirstName = strval($friendsFirstName[$key]);
                 if (empty($friendEmail) and empty($friendLastName) and empty($friendFirstName)) {
                     continue;
                 } elseif (empty($friendEmail) or !Validate::isEmail($friendEmail)) {
                     $error = 'email invalid';
                 } elseif (empty($friendFirstName) or empty($friendLastName) or !Validate::isName($friendLastName) or !Validate::isName($friendFirstName)) {
                     $error = 'name invalid';
                 } elseif (ReferralProgramModule::isEmailExists($friendEmail) or Customer::customerExists($friendEmail)) {
                     $mails_exists[] = $friendEmail;
                 } else {
                     $referralprogram = new ReferralProgramModule();
                     $referralprogram->id_sponsor = (int) $this->context->customer->id;
                     $referralprogram->firstname = $friendFirstName;
                     $referralprogram->lastname = $friendLastName;
                     $referralprogram->email = $friendEmail;
                     if (!$referralprogram->validateFields(false)) {
                         $error = 'name invalid';
                     } else {
                         if ($referralprogram->save()) {
                             if (Configuration::get('PS_CIPHER_ALGORITHM')) {
                                 $cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
                             } else {
                                 $cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
                             }
                             $vars = array('{email}' => strval($this->context->customer->email), '{lastname}' => strval($this->context->customer->lastname), '{firstname}' => strval($this->context->customer->firstname), '{email_friend}' => $friendEmail, '{lastname_friend}' => $friendLastName, '{firstname_friend}' => $friendFirstName, '{link}' => Context::getContext()->link->getPageLink('authentication', true, Context::getContext()->language->id, 'create_account=1&sponsor=' . urlencode($cipherTool->encrypt($referralprogram->id . '|' . $referralprogram->email . '|')), false), '{discount}' => $discount);
                             Mail::Send((int) $this->context->language->id, 'referralprogram-invitation', Mail::l('Referral Program', (int) $this->context->language->id), $vars, $friendEmail, $friendFirstName . ' ' . $friendLastName, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/../../mails/');
                             $invitation_sent = true;
                             $nbInvitation++;
                             $activeTab = 'pending';
                         } else {
                             $error = 'cannot add friends';
                         }
                     }
                 }
                 if ($error) {
                     break;
                 }
             }
             if ($nbInvitation > 0) {
                 unset($_POST);
             }
             //Not to stop the sending of e-mails in case of doubloon
             if (sizeof($mails_exists)) {
                 $error = 'email exists';
             }
         }
     }
     // Mailing revive
     $revive_sent = false;
     $nbRevive = 0;
     if (Tools::isSubmit('revive')) {
         $activeTab = 'pending';
         if (Tools::getValue('friendChecked') and sizeof($friendsChecked = Tools::getValue('friendChecked')) >= 1) {
             foreach ($friendsChecked as $key => $friendChecked) {
                 if (ReferralProgramModule::isSponsorFriend((int) $this->context->customer->id, (int) $friendChecked)) {
                     if (Configuration::get('PS_CIPHER_ALGORITHM')) {
                         $cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
                     } else {
                         $cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
                     }
                     $referralprogram = new ReferralProgramModule((int) $key);
                     $vars = array('{email}' => $this->context->customer->email, '{lastname}' => $this->context->customer->lastname, '{firstname}' => $this->context->customer->firstname, '{email_friend}' => $referralprogram->email, '{lastname_friend}' => $referralprogram->lastname, '{firstname_friend}' => $referralprogram->firstname, '{link}' => Context::getContext()->link->getPageLink('authentication', true, Context::getContext()->language->id, 'create_account=1&sponsor=' . urlencode($cipherTool->encrypt($referralprogram->id . '|' . $referralprogram->email . '|')), false), '{discount}' => $discount);
                     $referralprogram->save();
                     Mail::Send((int) $this->context->language->id, 'referralprogram-invitation', Mail::l('Referral Program', (int) $this->context->language->id), $vars, $referralprogram->email, $referralprogram->firstname . ' ' . $referralprogram->lastname, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/../../mails/');
                     $revive_sent = true;
                     $nbRevive++;
                 }
             }
         } else {
             $error = 'no revive checked';
         }
     }
     $customer = new Customer((int) $this->context->customer->id);
     $stats = $customer->getStats();
     $orderQuantity = (int) Configuration::get('REFERRAL_ORDER_QUANTITY');
     $canSendInvitations = false;
     if ((int) $stats['nb_orders'] >= $orderQuantity) {
         $canSendInvitations = true;
     }
     // Smarty display
     $this->context->smarty->assign(array('activeTab' => $activeTab, 'discount' => $discount, 'orderQuantity' => $orderQuantity, 'canSendInvitations' => $canSendInvitations, 'nbFriends' => (int) Configuration::get('REFERRAL_NB_FRIENDS'), 'error' => $error, 'invitation_sent' => $invitation_sent, 'nbInvitation' => $nbInvitation, 'pendingFriends' => ReferralProgramModule::getSponsorFriend((int) $this->context->customer->id, 'pending'), 'revive_sent' => $revive_sent, 'nbRevive' => $nbRevive, 'subscribeFriends' => ReferralProgramModule::getSponsorFriend((int) $this->context->customer->id, 'subscribed'), 'mails_exists' => isset($mails_exists) ? $mails_exists : array()));
     $this->setTemplate('program.tpl');
 }
function updateTracking($static = false, $idShop = 0, $idGroupShop = 0)
{
    $api = new ShipwireTracking();
    $api->retrieveFull();
    $d = $api->sendData();
    if ($d['Status']) {
        if ($static) {
            return false;
        } else {
            die('KO');
        }
    }
    if ($d['TotalOrders'] > 0) {
        foreach ($d['Order'] as $order) {
            $o = array();
            if (isset($order['@attributes'])) {
                $o = $order['@attributes'];
            }
            if (!isset($o['id'])) {
                Logger::addLog('Shipwire: Order ID not defined. >>>>' . print_r($d, true) . '<<<<', 4);
                continue;
            }
            $orderExists = Db::getInstance()->ExecuteS('SELECT `id_order`
				FROM `' . _DB_PREFIX_ . 'shipwire_order`
				WHERE `id_order` = ' . (int) $o['id'] . ' LIMIT 1');
            if (isset($orderExists[0]['id_order']) && !empty($orderExists[0]['id_order'])) {
                Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'shipwire_order` SET ' . (isset($order['TrackingNumber']) ? '`tracking_number` = \'' . pSQL($order['TrackingNumber']) . '\',' : '') . (isset($o['shipped']) ? '`shipped` = \'' . pSQL($o['shipped']) . '\'' : '') . (isset($o['shipper']) ? ',`shipper` = \'' . pSQL($o['shipper']) . '\'' : '') . (isset($o['shipDate']) ? ',`shipDate` = \'' . pSQL($o['shipDate']) . '\'' : '') . (isset($o['expectedDeliveryDate']) ? ',`expectedDeliveryDate` = \'' . pSQL($o['expectedDeliveryDate']) . '\'' : '') . (isset($o['href']) ? ',`href` = \'' . pSQL($o['href']) . '\'' : '') . (isset($o['shipperFullName']) ? ',`shipperFullName` = \'' . pSQL($o['shipperFullName']) . '\'' : '') . ' WHERE `id_order` = ' . (int) $o['id']);
            } else {
                Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'shipwire_order`
				(`id_order`, `id_shop`, `id_group_shop`, `tracking_number`, `shipped`, `shipper`, `shipDate`, `expectedDeliveryDate`, `href`, `shipperFullName`)
				VALUES (
				\'' . pSQL($o['id']) . '\'' . ',' . (int) $idShop . ',' . (int) $idGroupShop . (isset($order['TrackingNumber']) ? ',\'' . pSQL($order['TrackingNumber']) . '\'' : ',\'\'') . (isset($o['shipped']) ? ',\'' . pSQL($o['shipped']) . '\'' : ',\'\'') . (isset($o['shipper']) ? ',\'' . pSQL($o['shipper']) . '\'' : ',\'\'') . (isset($o['shipDate']) ? ',\'' . pSQL($o['shipDate']) . '\'' : ',\'\'') . (isset($o['expectedDeliveryDate']) ? ',\'' . pSQL($o['expectedDeliveryDate']) . '\'' : ',\'\'') . (isset($o['href']) ? ',\'' . pSQL($o['href']) . '\'' : ',\'\'') . (isset($o['shipperFullName']) ? ',\'' . pSQL($o['shipperFullName']) . '\'' : ',\'\'') . ')');
            }
            $result = Db::getInstance()->getValue('SELECT `transaction_ref`
				FROM `' . _DB_PREFIX_ . 'shipwire_order`
				WHERE `id_order` = ' . (int) $o['id']);
            if (empty($result)) {
                $module = new Shipwire();
                $module->updateOrderStatus((int) $o['id'], true);
            }
            if (isset($order['TrackingNumber'])) {
                Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'orders`
										SET `shipping_number` = \'' . pSQL($order['TrackingNumber']) . '\'
										WHERE `id_order` = ' . (int) $o['id']);
                if ($o['id']) {
                    $psOrder = new Order($o['id']);
                    if ($psOrder->id) {
                        $history = new OrderHistory();
                        $history->id_order = $o['id'];
                        if (isset($o['shipped']) && $o['shipped'] == 'YES') {
                            $history->changeIdOrderState(Configuration::get('SHIPWIRE_SENT_ID'), $o['id']);
                        }
                        $history->addWithemail();
                    }
                }
            }
        }
    }
    if (Configuration::get('PS_CIPHER_ALGORITHM')) {
        $cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
    } else {
        $cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
    }
    $shipWireInventoryUpdate = new ShipwireInventoryUpdate(Configuration::get('SHIPWIRE_API_USER'), $cipherTool->decrypt(Configuration::get('SHIPWIRE_API_PASSWD')));
    $shipWireInventoryUpdate->getInventory();
    if ($static) {
        return true;
    } else {
        die('OK');
    }
}
示例#18
0
 public function LoginAddMap(&$mapinfo, $userrow, &$userinfo, $admin)
 {
     global $sso_rng;
     $info = $this->GetInfo();
     if ($info["cookiekey"] != "" && $info["cookieiv"] != "" && $info["cookiekey2"] != "" && $info["cookieiv2"] != "" && isset($userinfo["sso_antiphish"])) {
         // Set the anti-phishing cookie here.
         $data = base64_encode(Blowfish::CreateDataPacket($userinfo["sso_antiphish"], pack("H*", $info["cookiekey"]), array("prefix" => $sso_rng->GenerateString(), "mode" => "CBC", "iv" => pack("H*", $info["cookieiv"]), "key2" => pack("H*", $info["cookiekey2"]), "iv2" => pack("H*", $info["cookieiv2"]), "lightweight" => true)));
         SetCookieFixDomain("sso_l_ap", $data, time() + 365 * 24 * 60 * 60, "", "", BB_IsSSLRequest(), true);
     }
 }
示例#19
0
 /**
  * Hook display on form create account
  * Add an additional input on bottom for fill the sponsor's e-mail address
  */
 public function hookCreateAccountForm($params)
 {
     include_once dirname(__FILE__) . '/ReferralProgramModule.php';
     if (Configuration::get('PS_CIPHER_ALGORITHM')) {
         $cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
     } else {
         $cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
     }
     $explodeResult = explode('|', $cipherTool->decrypt(urldecode(Tools::getValue('sponsor'))));
     if ($explodeResult and count($explodeResult) > 1 and list($id_referralprogram, $email) = $explodeResult and (int) $id_referralprogram and !empty($email) and Validate::isEmail($email) and $id_referralprogram == ReferralProgramModule::isEmailExists($email)) {
         $referralprogram = new ReferralProgramModule($id_referralprogram);
         if (Validate::isLoadedObject($referralprogram)) {
             /* hack for display referralprogram information in form */
             $_POST['customer_firstname'] = $referralprogram->firstname;
             $_POST['firstname'] = $referralprogram->firstname;
             $_POST['customer_lastname'] = $referralprogram->lastname;
             $_POST['lastname'] = $referralprogram->lastname;
             $_POST['email'] = $referralprogram->email;
             $_POST['email_create'] = $referralprogram->email;
             $sponsor = new Customer((int) $referralprogram->id_sponsor);
             $_POST['referralprogram'] = $sponsor->email;
         }
     }
     return $this->display(__FILE__, 'authentication.tpl');
 }
示例#20
0
    public function CustomFrontend()
    {
        global $g_sso_login_modules, $sso_settings, $sso_header, $sso_footer, $sso_target_url, $sso_db, $sso_session_info, $sso_rng;
        $messages = array("errors" => array(), "warnings" => array(), "success" => "");
        $info = $this->GetInfo();
        if ($info["cookiekey"] != "" && $info["cookieiv"] != "" && $info["cookiekey2"] != "" && $info["cookieiv2"] != "") {
            // Initialize active modules.
            $this->activemodules = array();
            foreach ($g_sso_login_modules as $key => $info2) {
                if ($sso_settings["sso_login"]["modules"][$key]["_a"]) {
                    $module = "sso_login_module_" . $key;
                    $this->activemodules[$key] = new $module();
                }
            }
            $sso_db_sso_login_users = SSO_DB_PREFIX . "p_sso_login_users";
            if (isset($_REQUEST["id"]) && isset($_COOKIE["sso_l_rme"])) {
                // Decrypt data.
                $info2 = @base64_decode($_COOKIE["sso_l_rme"]);
                if ($info2 !== false) {
                    $info2 = Blowfish::ExtractDataPacket($info2, pack("H*", $info["cookiekey"]), array("mode" => "CBC", "iv" => pack("H*", $info["cookieiv"]), "key2" => pack("H*", $info["cookiekey2"]), "iv2" => pack("H*", $info["cookieiv2"]), "lightweight" => true));
                }
                if ($info2 !== false) {
                    $info2 = @unserialize($info2);
                }
                if ($info2 !== false) {
                    $id = (int) $_REQUEST["id"];
                    if (isset($info2[$id]) && is_array($info2[$id]) && count($info2[$id]) == 2) {
                        // Load database information and verify the sign in.
                        $userrow = $sso_db->GetRow("SELECT", array("*", "FROM" => "?", "WHERE" => "id = ?"), $sso_db_sso_login_users, $id);
                        if ($userrow && (!isset($userrow->verified) || $userrow->verified)) {
                            $userinfo = SSO_DecryptDBData($userrow->info);
                            if ($userinfo !== false && isset($userinfo["sso_remember_me"]) && isset($userinfo["sso_remember_me"][$info2[$userrow->id][0]])) {
                                $info3 = $userinfo["sso_remember_me"][$info2[$userrow->id][0]];
                                $ts = CSDB::ConvertFromDBTime($info3["expires"]);
                                if ($ts > time()) {
                                    $data = $info3["salt"] . ":" . $info2[$userrow->id][1];
                                    if (sso_login::VerifyPasswordInfo($data, $info3["hash"], $info3["rounds"])) {
                                        // Sign in is now verified to be valid.
                                        if (!$info3["bypass"] && ($sso_settings["sso_login"]["require_two_factor"] || isset($userinfo["two_factor_method"]) && $userinfo["two_factor_method"] != "")) {
                                            // Go to two-factor authentication page.
                                            $methods = array();
                                            foreach ($this->activemodules as $key => &$instance) {
                                                $name = $instance->GetTwoFactorName(false);
                                                if ($name !== false) {
                                                    $methods[$key] = true;
                                                }
                                            }
                                            if ($sso_settings["sso_login"]["require_two_factor"] && (!isset($userinfo["two_factor_method"]) || !isset($methods[$userinfo["two_factor_method"]]))) {
                                                $messages["errors"][] = BB_Translate("A valid two-factor authentication method for this account is not available.  Use account recovery to restore access to the account.");
                                            } else {
                                                $sso_session_info["sso_login_two_factor"] = array("id" => $userrow->id, "v" => $sso_rng->GenerateString(), "expires" => CSDB::ConvertToDBTime(time() + 5 * 60));
                                                if (!SSO_SaveSessionInfo()) {
                                                    $messages["errors"][] = BB_Translate("Login exists but a fatal error occurred.  Fatal error:  Unable to save session information.");
                                                } else {
                                                    $this->activemodules[$userinfo["two_factor_method"]]->SendTwoFactorCode($messages, $userrow, $userinfo);
                                                    if (!count($messages["errors"])) {
                                                        header("Location: " . BB_GetRequestHost() . $sso_target_url . "&sso_login_action=two_factor&sso_v=" . urlencode($sso_session_info["sso_login_two_factor"]["v"]));
                                                        exit;
                                                    }
                                                }
                                            }
                                        } else {
                                            // Login succeeded.  Activate the user.
                                            $mapinfo = array();
                                            if ($sso_settings["sso_login"]["install_type"] == "email_username" || $sso_settings["sso_login"]["install_type"] == "email") {
                                                $mapinfo[$sso_settings["sso_login"]["map_email"]] = $userrow->email;
                                            }
                                            if ($sso_settings["sso_login"]["install_type"] == "email_username" || $sso_settings["sso_login"]["install_type"] == "username") {
                                                $mapinfo[$sso_settings["sso_login"]["map_username"]] = $userrow->username;
                                            }
                                            $origuserinfo = $userinfo;
                                            foreach ($this->activemodules as &$instance) {
                                                $instance->LoginAddMap($mapinfo, $userrow, $userinfo, false);
                                            }
                                            // If a module updated $userinfo, then update the database.
                                            if (serialize($userinfo) !== serialize($origuserinfo)) {
                                                $userinfo2 = SSO_EncryptDBData($userinfo);
                                                try {
                                                    $sso_db->Query("UPDATE", array($sso_db_sso_login_users, array("info" => $userinfo2), "WHERE" => "id = ?"), $userrow->id);
                                                } catch (Exception $e) {
                                                    $messages["errors"][] = BB_Translate("Database query error.");
                                                }
                                            }
                                            if (!count($messages["errors"])) {
                                                SSO_ActivateUser($userrow->id, $userinfo["extra"], $mapinfo, CSDB::ConvertFromDBTime($userrow->created));
                                                // Only falls through on account lockout or a fatal error.
                                                $messages["errors"][] = BB_Translate("User activation failed.");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            echo $sso_header;
            SSO_OutputHeartbeat();
            ?>
<div class="sso_main_wrap sso_login">
<div class="sso_main_wrap_inner">
	<div class="sso_main_messages_wrap">
		<div class="sso_main_messages">
<?php 
            if (count($messages["errors"])) {
                ?>
			<div class="sso_main_messageerror"><?php 
                echo htmlspecialchars($messages["errors"][0]);
                ?>
</div>
<?php 
            }
            ?>
			<div class="sso_main_messageerror"><?php 
            echo htmlspecialchars(BB_Translate("An error occurred while processing the remembered sign in.  You will have to sign in normally."));
            ?>
</div>
		</div>
	</div>
	<div class="sso_login_signin"><a href="<?php 
            echo htmlspecialchars($sso_target_url);
            ?>
"><?php 
            echo htmlspecialchars(BB_Translate("Sign in"));
            ?>
</a></div>
</div>
</div>
<?php 
            echo $sso_footer;
        }
    }