hash() public static method

Uses PHP's hashing functions to create a hash of the string provided, using the options specified. The default hash algorithm is SHA-512.
public static hash ( string $string, array $options = [] ) : string
$string string The string to hash.
$options array Supported options: - `'type'` _string_: Any valid hashing algorithm. See the `hash_algos()` function to determine which are available on your system. - `'salt'` _string_: A _salt_ value which, if specified, will be prepended to the string. - `'key'` _string_: If specified `hash_hmac()` will be used to hash the string, instead of `hash()`, with `'key'` being used as the message key. - `'raw'` _boolean_: If `true`, outputs the raw binary result of the hash operation. Defaults to `false`.
return string Returns a hashed string.
示例#1
0
 /**
  * Generate hashed and salted token from `'prefix'` and `md5` hashed `$email` value
  * @param $email string User email that will be used as base for secret token
  * @param array $options Supported options:
  *        - `'prefix'` _string|int_ If not passed this method will generate random int from
  *          `100000` to `999999`. Hashed email will be prefixed with value of this option.
  *          Example: `'prefix_value' . md5($email)`
  *        - All other options are same as `lithium\util\String::hash()`
  * @return string Hashed prefixed email salted and hashed again
  * @see lithium\util\String::hash()
  */
 public static function generate($email, array $options = array())
 {
     $options += array('prefix' => null, 'salt' => LI3_UM_TokenSalt, 'type' => 'sha256');
     $prefix = $options['prefix'] ? $options['prefix'] : mt_rand(100000, 999999);
     unset($options['prefix']);
     return String::hash($prefix . md5($email), $options);
 }
示例#2
0
 public function RemoveFriend($hashuser_id, $user_id, $username)
 {
     if (String::hash($user_id) == $hashuser_id) {
         $user = Session::read('default');
         $id = $user['_id'];
         $details = Details::find('first', array('conditions' => array('user_id' => $id)));
         $friends = $details['Friend'];
         $addfriend = array();
         if (count($friends) != 0) {
             foreach ($friends as $ra) {
                 if ($ra != $username) {
                     array_push($addfriend, $ra);
                 }
             }
         }
         $data = array('Friend' => $addfriend);
         //			print_r($data);
         $details = Details::find('first', array('conditions' => array('user_id' => $id)))->save($data);
     }
     $this->redirect(array('controller' => 'ex', 'action' => "dashboard/", 'locale' => $locale));
 }
示例#3
0
文件: Users.php 项目: nilamdoc/OxOPDF
        return false;
    }
});
Validator::add('uniqueUsername', function ($value, $rule, $options) {
    $conflicts = Users::count(array('username' => $value));
    if ($conflicts) {
        return false;
    }
    return true;
});
Validator::add('uniqueEmail', function ($value, $rule, $options) {
    $conflicts = Users::count(array('email' => $value));
    if ($conflicts) {
        return false;
    }
    return true;
});
Users::applyFilter('save', function ($self, $params, $chain) {
    if ($params['data']) {
        $params['entity']->set($params['data']);
        $params['data'] = array();
    }
    if (!$params['entity']->exists()) {
        $params['entity']->password = String::hash($params['entity']->password);
        $params['entity']->password2 = String::hash($params['entity']->password2);
        $params['entity']->created = new \MongoDate();
        $params['entity']->updated = new \MongoDate();
        $params['entity']->ip = $_SERVER['REMOTE_ADDR'];
    }
    return $chain->next($self, $params, $chain);
});
示例#4
0
								<tr>
									<td style="height:305px ">
									You have already made a withdrawal request for <strong><?php 
    echo number_format($transactions['Amount'], 8);
    ?>
 <?php 
    echo $transactions['Currency'];
    ?>
</strong> . Please check your email and complete the request. If you want to cancel the request, please send an email to <a href="mailto:support@SiiCrypto.com" >support@SiiCrypto.com</a>
									If your want to delete this request yourself, you can click on the link below:
									</td>
								</tr>
								<tr>
									<td>
										<strong><a href="/Users/removetransaction/<?php 
    echo String::hash($transactions['_id']);
    ?>
/<?php 
    echo $transactions['_id'];
    ?>
/funding/<?php 
    echo $transactions['Currency'];
    ?>
">REMOVE <i class="fa fa-remove"></i> <?php 
    echo number_format($transactions['Amount'], 8);
    ?>
 <?php 
    echo $transactions['Currency'];
    ?>
</a></strong>
									</td>
示例#5
0
 public function removetransaction($TransactionID, $ID, $url, $currency)
 {
     $Transaction = Transactions::find('first', array('conditions' => array('_id' => new MongoID($ID))));
     if (String::hash($Transaction['_id']) == $TransactionID) {
         $Remove = Transactions::remove(array('_id' => new MongoID($ID)));
     }
     return $this->redirect('/Users/' . $url . '/' . $currency);
 }
示例#6
0
			<table class="table table-condensed table-bordered table-hover" style="font-size:14px">
				<thead>
					<tr>
						<th style="text-align:center ">Exchange</th>
						<th style="text-align:center ">Price</th>
						<th style="text-align:center ">Amount</th>
					</tr>
				</thead>
				<tbody>
				<?php 
foreach ($YourOrders as $YO) {
    ?>
					<tr>
							<td style="text-align:left ">
							<a href="/ex/RemoveOrder/<?php 
    echo String::hash($YO['_id']);
    ?>
/<?php 
    echo $YO['_id'];
    ?>
/<?php 
    echo $sel_curr;
    ?>
" title="Remove this order"><i class="fa fa-times"></i></a> &nbsp; 
							<?php 
    echo $YO['Action'];
    ?>
 <?php 
    echo $YO['FirstCurrency'];
    ?>
/<?php 
示例#7
0
 /**
  * Method used to determine if an asset needs to be cached or timestamped.
  * Makes appropriate calls based on this.
  * @param  array  $files   [description]
  * @param  array  $options [description]
  * @return [type]          [description]
  */
 private function _runAssets(array $files = array(), array $options = array())
 {
     $this->styles = new AssetCollection();
     $this->scripts = new AssetCollection();
     if ($this->_config['compress'] or $this->_production) {
         $this->styles->ensureFilter(new Yui\CssCompressorFilter(YUI_COMPRESSOR));
         $this->scripts->ensureFilter(new Yui\JsCompressorFilter(YUI_COMPRESSOR));
     }
     $filename = "";
     // will store concatenated filename
     $stats = array('modified' => 0, 'size' => 0);
     // stores merged file stats
     // request type
     $type = $options['type'] == 'css' ? 'styles' : 'scripts';
     // loop over the sheets that were passed and run them thru Assetic
     foreach ($files as $file) {
         $_filename = $file;
         $path = $options['path'];
         // build filename if not a less file
         if ($isSpecial = $this->specialExt($file) or preg_match("/(.css|.js)\$/is", $file)) {
             $path .= $file;
         } else {
             $path .= "{$file}.{$options['type']}";
             $_filename = "{$file}.{$options['type']}";
         }
         // ensure file exists, if so set stats
         if (file_exists($path)) {
             $_stat = stat($path);
             $stats['modified'] += $_stat['mtime'];
             $stats['size'] += $_stat['size'];
             $stats[$path]['modified'] = $_stat['mtime'];
             $stats[$path]['size'] = $_stat['size'];
         } else {
             throw new RuntimeException("The {$options['type']} file '{$path}' does not exist");
         }
         $filters = array();
         // its a less or coffee file
         if ($isSpecial) {
             $path = $options['path'] . $file;
             $filters += $options['filters'];
         } else {
             // If we're not in production and we're not compressingthen we
             // dont need to cache static css assets
             if (!$this->_production and !$this->_config['compress']) {
                 $method = substr($type, 0, -1);
                 echo $this->_context->helper('html')->{$method}("{$_filename}?{$stats[$path]['modified']}") . "\n\t";
                 continue;
             }
         }
         $filename .= $path;
         // add asset to assetic collection
         $this->{$type}->add(new FileAsset($path, $filters));
     }
     // If in production merge files and server up a single stylesheet
     if ($this->_production) {
         // Hashed filename without stats appended.
         $_rawFilename = String::hash($filename, array('type' => 'sha1'));
         echo $this->buildHelper($_rawFilename, $this->{$type}, array('type' => $options['type'], 'stats' => $stats));
     } else {
         // not production so lets serve up individual files (better debugging)
         foreach ($this->{$type} as $leaf) {
             $filename = "{$leaf->getSourceRoot()}/{$leaf->getSourcePath()}";
             $_rawFilename = String::hash($filename, array('type' => 'sha1'));
             $stat = isset($stats[$filename]) ? $stats[$filename] : false;
             if ($stat) {
                 echo $this->buildHelper($_rawFilename, $leaf, array('type' => $options['type'], 'stats' => $stat));
             }
         }
     }
 }
示例#8
0
 /**
  * Tests hash generation using `String::hash()`.
  * @return string
  */
 public function testHash()
 {
     $salt = 'Salt and pepper';
     $value = 'Lithium rocks!';
     $expected = sha1($value);
     $result = String::hash($value, array('type' => 'sha1'));
     $this->assertEqual($expected, $result);
     $result = String::hash($value, array('type' => 'sha1') + compact('salt'));
     $this->assertEqual(sha1($salt . $value), $result);
     $this->assertEqual(md5($value), String::hash($value, array('type' => 'md5')));
     $result = String::hash($value, array('type' => 'md5') + compact('salt'));
     $this->assertEqual(md5($salt . $value), $result);
     $sha256 = function ($value) {
         if (function_exists('mhash')) {
             return bin2hex(mhash(MHASH_SHA256, $value));
         } elseif (function_exists('hash')) {
             return hash('sha256', $value);
         }
         throw new Exception();
     };
     try {
         $result = String::hash($value, array('type' => 'sha256'));
         $this->assertEqual($sha256($value), $result);
         $result = String::hash($value, array('type' => 'sha256') + compact('salt'));
         $this->assertEqual($sha256($salt . $value), $result);
     } catch (Exception $e) {
     }
     $string = 'Hash Me';
     $key = 'a very valid key';
     $salt = 'not too much';
     $type = 'sha256';
     $expected = '24f8664f7a7e56f85bd5c983634aaa0b0d3b0e470d7f63494475729cb8b3c6a4ef28398d7cf3';
     $expected .= '780c0caec26c85b56a409920e4af7eef38597861d49fbe31b9a0';
     $result = String::hash($string, compact('key'));
     $this->assertEqual($expected, $result);
     $expected = '35bc1d9a3332e524962909b7ccff6b34ae143f64c48ffa32b5be9312719a96369fbd7ebf6f49';
     $expected .= '09b375135b34e28b063a07b5bd62af165483c6b80dd48a252ddd';
     $result = String::hash($string, compact('salt'));
     $this->assertEqual($expected, $result);
     $expected = 'fa4cfa5c16d7f94e221e1d3a0cb01eadfd6823d68497a5fdcae023d24f557e4a';
     $result = String::hash($string, compact('type', 'key'));
     $this->assertEqual($expected, $result);
     $expected = 'a9050b4f44797bf60262de984ca12967711389cd6c4c4aeee2a739c159f1f667';
     $result = String::hash($string, compact('type'));
     $this->assertEqual($expected, $result);
 }
示例#9
0
}
Validator::add('passwordVerification', function ($value, $rule, $options) {
    if (!isset($options['values']['password2']) || $value == $options['values']['password2']) {
        return true;
    }
    return false;
});
Validator::add('uniqueUsername', function ($value, $rule, $options) {
    $conflicts = Users::count(array('username' => $value));
    if ($conflicts) {
        return false;
    }
    return true;
});
Users::applyFilter('save', function ($self, $params, $chain) {
    $entity = $params['entity'];
    $data = $params['data'];
    if ($data) {
        $entity->set($data);
        if (isset($data['password']) && $data['password'] && isset($data['password2']) && $data['password2']) {
            $entity->password = \lithium\util\String::hash($data['password']);
            $entity->password2 = \lithium\util\String::hash($data['password2']);
        }
    }
    if (!$entity->id) {
        $entity->created = new \MongoDate();
    }
    $entity->updated = new \MongoDate();
    $params['entity'] = $entity;
    return $chain->next($self, $params, $chain);
});
示例#10
0
<?php

namespace app\models;

class Authors extends \lithium\data\Model
{
    public $hasMany = array('Books');
    public $validates = array('email' => array(array('notEmpty', 'message' => 'You must type a valid email address')), 'password' => array(array('notEmpty', 'message' => 'You must type a password')));
}
Authors::applyFilter('save', function ($self, $params, $chain) {
    if (!$params['entity']->id && !empty($params['entity']->password)) {
        $params['entity']->password = \lithium\util\String::hash($params['entity']->password);
    }
    return $chain->next($self, $params, $chain);
});
    /**
     * Generic update() action.
     * The trick here is that $this->calling_class and $this->calling_method will hold a string
     * reference for which extended class called this update() method. We need that in order to
     * get the proper records and access.
    */
    public function update() {
        // get the "_type" ... page_type, user_type, or block_type
        $model = Inflector::classify(Inflector::singularize($this->request->params['controller']));
        $modelClass = 'minerva\models\\'.$model;
        $x_type = strtolower($model) . '_type';
        
        // Use the pretty URL if provided
		if(isset($this->request->params['url'])) {
			$conditions = array('url' => $this->request->params['url']);
		}
		
        // ...But if the id was provided, use that (for example; UsersController will be using the id)
		if(isset($this->request->params['id'])) {
			$conditions = array('_id' => $this->request->params['id']);
		}
        
        // or set it to "all" if there is no *_type in the record (this part differs from create() because the type won't come from the route)
        $type = $modelClass::find('first', array('conditions' => $conditions, 'fields' => array($x_type)))->$x_type;
        $type = (!empty($type)) ? $type:'all';
        
        // Get the model class we should be using for this (it could be an extended class from a library)
        
        $modelClass = $modelClass::getMinervaModel($model, $type);
        
		// Get the name for the page, so if another type library uses the "admin" (core) templates for this action, it will be shown
		$display_name = $modelClass::display_name();
		
		// Get the fields so the view template can build the form
		$fields = $modelClass::schema();
		// Don't need to have these fields in the form
		unset($fields['_id']);
        if($this->request->params['controller'] == 'users') {
            unset($fields['password']);
            // unset password and add a "new_password" field for UsersController
            $fields['new_password'] = null;
        }
		// If a *_type was passed in the params (and wasn't "all") we'll need it to save to the page document.
		$fields[$x_type]['form']['value'] = ($type != 'all') ? $type:null;
		
		// Get the document
		$document = $this->getDocument(array('action' => $this->calling_method, 'request' => $this->request, 'find_type' => 'first', 'conditions' => $conditions));
        
        // Update the record
		if ($this->request->data) {
			// Set some data
            $this->request->data['modified'] = date('Y-m-d h:i:s');
            
            // (note: the password stuff is only useful for UsersController)
            if($this->request->params['controller'] == 'users') {
                if(isset($this->request->data['password'])) {
                    unset($this->request->data['password']);
                }
                if((isset($this->request->data['new_password'])) && (!empty($this->request->data['new_password']))) {
                    $this->request->data['password'] = String::hash($this->request->data['new_password']);
                    unset($this->request->data['new_password']);
                }
            }
			
            // Save it
			if($document->save($this->request->data)) {
                FlashMessage::set('The content has been updated successfully.', array('options' => array('type' => 'success', 'pnotify_title' => 'Success', 'pnotify_opacity' => .8)));
                $this->redirect(array('controller' => $this->request->params['controller'], 'action' => 'index'));
			} else {
                FlashMessage::set('The content could not be updated, please try again.', array('options' => array('type' => 'error', 'pnotify_title' => 'Error', 'pnotify_opacity' => .8)));
            }
		}
	    
	    $this->set(compact('document', 'fields', 'display_name'));
    }
示例#12
0
 public function password()
 {
     if ($this->request->data) {
         if (stristr($_SERVER['HTTP_REFERER'], COMPANY_URL) === FALSE) {
             return $this->redirect('/login');
             exit;
         }
         $details = Details::find('first', array('conditions' => array('key' => $this->request->data['key']), 'fields' => array('user_id')));
         $msg = "Password Not Changed!";
         //			print_r($details['user_id']);
         if ($details['user_id'] != "") {
             if ($this->request->data['password'] == $this->request->data['password2']) {
                 //					print_r($this->request->data['password']);
                 $user = Users::find('first', array('conditions' => array('_id' => $details['user_id'])));
                 //					print_r($user['password']);
                 if ($user['password'] != String::hash($this->request->data['password'])) {
                     print_r($details['user_id']);
                     $data = array('password' => String::hash($this->request->data['password']));
                     //							print_r($data);
                     $user = Users::find('all', array('conditions' => array('_id' => $details['user_id'])))->save($data, array('validate' => false));
                     //		print_r($user);
                     if ($user) {
                         $msg = "Password changed!";
                     }
                 } else {
                     $msg = "Password same as old password!";
                 }
             } else {
                 $msg = "New password does not match!";
             }
         }
     }
     return compact('msg');
 }
示例#13
0
		
		// Set created, modified, and pretty url (slug)
		if (!$params['entity']->exists()) {
			if(Validator::rule('moreThanFive', $params['data']['password']) === true) {
				$params['data']['password'] = String::hash($params['data']['password']); // will be sha512
			}
			// Unique E-mail validation ONLY upon new record creation
			if(Validator::rule('uniqueEmail', $params['data']['email']) === false) {
				$params['data']['email'] = ''; 
			}
			
		} else {
			// If the fields password and password_confirm both exist, then validate the password field too
			if((isset($params['data']['password'])) && (isset($params['data']['password_confirm']))) {
				if(Validator::rule('moreThanFive', $params['data']['password']) === true) {
					$params['data']['password'] = String::hash($params['data']['password']); // will be sha512
				}
			}
			
			// If the new_email field was passed, the user is requesting to update their e-mail, we will set it and send an email to allow them to confirm, once confirmed it will be changed
			if(isset($params['data']['new_email'])) {
				// Unique E-mail validation
				if((Validator::rule('uniqueEmail', $params['data']['new_email']) === false) || (Validator::isEmail($params['data']['new_email']) === false)) {
					// Invalidate
					$params['data']['new_email'] = '';
				} else {
					$params['data']['approval_code'] = Util::unique_string(array('hash' => 'md5'));
					Email::changeUserEmail(array('first_name' => $params['data']['first_name'], 'last_name' => $params['data']['last_name'], 'to' => $params['data']['new_email'], 'approval_code' => $params['data']['approval_code']));
				}
			}
		}
示例#14
0
    public function YourOrders($FirstCurrency = "BTC", $SecondCurrency = "USD", $user_id = null)
    {
        $YourOrders = Orders::find('all', array('conditions' => array('user_id' => $user_id, 'Completed' => 'N', 'FirstCurrency' => $FirstCurrency, 'SecondCurrency' => $SecondCurrency), 'order' => array('DateTime' => -1)));
        $YourCompleteOrders = Orders::find('all', array('conditions' => array('user_id' => $user_id, 'Completed' => 'Y', 'FirstCurrency' => $FirstCurrency, 'SecondCurrency' => $SecondCurrency), 'order' => array('DateTime' => -1)));
        $YourOrdersHTML = '<table class="table table-condensed table-bordered table-hover" style="font-size:11px">
				<thead>
					<tr>
						<th style="text-align:center ">Exchange</th>
						<th style="text-align:center ">Price</th>
						<th style="text-align:center ">Amount</th>
					</tr>
				</thead>
				<tbody>';
        foreach ($YourOrders as $YO) {
            $YourOrdersHTML = $YourOrdersHTML . '<tr>
							<td style="text-align:left ">
							<a href="/ex/RemoveOrder/' . String::hash($YO['_id']) . '/' . $YO['_id'] . '/' . strtolower($FirstCurrency) . '_' . strtolower($SecondCurrency) . '" title="Remove this order">
								<i class="fa fa-times"></i></a> &nbsp; 
							' . $YO['Action'] . ' ' . $YO['FirstCurrency'] . '/' . $YO['SecondCurrency'] . '</td>
						<td style="text-align:right ">' . number_format($YO['PerPrice'], 3) . '...</td>
						<td style="text-align:right ">' . number_format($YO['Amount'], 3) . '...</td>
					</tr>';
        }
        $YourOrdersHTML = $YourOrdersHTML . '				</tbody>
			</table>';
        $YourCompleteOrdersHTML = '<table class="table table-condensed table-bordered table-hover" style="font-size:11px">
				<thead>
					<tr>
						<th style="text-align:center ">Exchange</th>
						<th style="text-align:center ">Price</th>
						<th style="text-align:center ">Amount</th>
					</tr>
				</thead>
				<tbody>';
        foreach ($YourCompleteOrders as $YO) {
            $YourCompleteOrdersHTML = $YourCompleteOrdersHTML . '<tr style="cursor:pointer" class=" tooltip-x" rel="tooltip-x" data-placement="top" title="' . $YO['Action'] . ' ' . number_format($YO['Amount'], 3) . ' at ' . number_format($YO['PerPrice'], 8) . ' on ' . gmdate('Y-m-d H:i:s', $YO['DateTime']->sec) . '">
						<td style="text-align:left ">
						' . $YO['Action'] . ' ' . $YO['FirstCurrency'] . '/' . $YO['SecondCurrency'] . '</td>
						<td style="text-align:right ">' . number_format($YO['PerPrice'], 3) . '...</td>
						<td style="text-align:right ">' . number_format($YO['Amount'], 3) . '...</td>
					</tr>';
        }
        $YourCompleteOrdersHTML = $YourCompleteOrdersHTML . '				</tbody>
			</table>';
        return $this->render(array('json' => array('YourCompleteOrdersHTML' => $YourCompleteOrdersHTML, 'YourOrdersHTML' => $YourOrdersHTML)));
    }
示例#15
0
 /**
  * testHash method - Tests hash generation using `util\String::hash()`
  *
  * @return void
  */
 public function testHash()
 {
     $salt = 'Salt and pepper';
     $value = 'Lithium rocks!';
     $expected = sha1($value);
     $result = String::hash($value, 'sha1');
     $this->assertEqual($expected, $result);
     $result = String::hash($value);
     $this->assertEqual($expected, $result);
     $expected = sha1($salt . $value);
     $result = String::hash($value, 'sha1', $salt);
     $this->assertEqual($expected, $result);
     $expected = md5($value);
     $result = String::hash($value, 'md5');
     $this->assertEqual($expected, $result);
     $expected = md5($salt . $value);
     $result = String::hash($value, 'md5', $salt);
     $this->assertEqual($expected, $result);
     $sha256 = function ($value) {
         if (function_exists('mhash')) {
             return bin2hex(mhash(MHASH_SHA256, $value));
         } elseif (function_exists('hash')) {
             return hash('sha256', $value);
         }
         throw new Exception();
     };
     try {
         $expected = $sha256($value);
         $result = String::hash($value, 'sha256');
         $this->assertEqual($expected, $result);
         $expected = $sha256($salt . $value);
         $result = String::hash($value, 'sha256', $salt);
         $this->assertEqual($expected, $result);
     } catch (Exception $e) {
     }
 }
示例#16
0
 public function trade($key = null)
 {
     if (!$this->request->data) {
         return $this->render(array('json' => array('success' => 0, 'now' => time(), 'error' => "Not submitted through POST.")));
     }
     if ($key == null) {
         return $this->render(array('json' => array('success' => 0, 'now' => time(), 'error' => "Key not specified. Please get your key from your settings page under security.")));
     } else {
         $details = Details::find('first', array('conditions' => array('key' => $key)));
         print_r($details['username']);
         if (count($details) == 0) {
             return $this->render(array('json' => array('success' => 0, 'now' => time(), 'error' => "Incorrect Key! Please get your key from your settings page under security.")));
         } else {
             if (!$this->requestAPI("trade", $details['username'])) {
                 return $this->render(array('json' => array('success' => 0, 'now' => time(), 'error' => "Too many requests from your IP. Try after some time.")));
             }
             $type = $this->request->data['type'];
             $pair = $this->request->data['pair'];
             $amount = $this->request->data['amount'];
             $price = $this->request->data['price'];
             if (!($type == "Buy" || $type == "Sell")) {
                 return $this->render(array('json' => array('success' => 0, 'now' => time(), 'error' => "Type is incorrect! Should be 'Buy' or 'Sell'." . $type)));
             }
             /*				if(!($pair=='BTC_USD' || $pair=='BTC_GBP' || $pair=='BTC_EUR' || $pair=='BTC_LTC' || $pair=='LTC_USD' || $pair=='LTC_GBP' || $pair=='LTC_EUR')){
             					return $this->render(array('json' => array('success'=>0,
             					'now'=>time(),
             					'error'=>"Pair is incorrect! Should be 'BTC_USD','BTC_GBP','BTC_EUR','BTC_LTC','LTC_USD','LTC_GBP','LTC_EUR'.".$pair
             					)));
             				}
             */
             if ((double) $amount <= 0) {
                 return $this->render(array('json' => array('success' => 0, 'now' => time(), 'error' => "Amount less than or equal to ZERO! Should be greater than ZERO." . $amount)));
             }
             if ((double) $price <= 0) {
                 return $this->render(array('json' => array('success' => 0, 'now' => time(), 'error' => "Price less than or equal to ZERO! Should be greater than ZERO." . $price)));
             }
             $first_curr = strtoupper(substr($pair, 0, 3));
             $second_curr = strtoupper(substr($pair, 4, 3));
             //======================Trade========================================================
             $data = array('page.refresh' => true);
             Details::find('all')->save($data);
             $details = Details::find('first', array('conditions' => array('key' => $key)));
             $id = $details['user_id'];
             $user = Users::find('first', array('conditions' => array('_id' => $id)));
             $Action = $type;
             $commission = Parameters::find('first');
             $commissionRate = $commission['value'];
             if ($Action == "Buy") {
                 $PendingAction = 'Sell';
                 $FirstCurrency = $first_curr;
                 $SecondCurrency = $second_curr;
                 $Commission = (double) $commissionRate;
                 $CommissionAmount = number_format((double) $commissionRate * (double) $amount / 100, 8);
                 $CommissionCurrency = $first_curr;
                 $Amount = (double) $amount;
                 $PerPrice = (double) $price;
                 $BalanceAmount = $details['balance'][$second_curr];
                 if ($amount * $price >= $BalanceAmount) {
                     return $this->render(array('json' => array('success' => 0, 'now' => time(), 'error' => "Amount exceeds your balance! Balance: " . $BalanceAmount)));
                 }
                 $NewBalanceAmount = round($BalanceAmount - $amount * $price, 8);
                 $Currency = 'balance.' . $second_curr;
                 // Update balance of user with NewBalance Amount
                 $data = array('balance.' . $second_curr => (double) $NewBalanceAmount);
                 $details = Details::find('first', array('conditions' => array('user_id' => $id)))->save($data);
                 print_r("Buy-Save");
             }
             if ($Action == "Sell") {
                 $PendingAction = 'Buy';
                 $FirstCurrency = $first_curr;
                 $SecondCurrency = $second_curr;
                 $Commission = (double) $commissionRate;
                 $CommissionAmount = number_format((double) $commissionRate * (double) $amount * (double) $price / 100, 8);
                 $CommissionCurrency = $second_curr;
                 $Amount = (double) $amount;
                 $PerPrice = (double) $price;
                 $BalanceAmount = $details['balance'][$first_curr];
                 if ($amount >= $BalanceAmount) {
                     return $this->render(array('json' => array('success' => 0, 'now' => time(), 'error' => "Amount exceeds your balance! Balance: " . $BalanceAmount)));
                 }
                 $NewBalanceAmount = round($BalanceAmount - $amount, 8);
                 $Currency = 'balance.' . $first_curr;
                 // Update balance of user with NewBalance Amount
                 $data = array('balance.' . $first_curr => (double) $NewBalanceAmount);
                 $details = Details::find('first', array('conditions' => array('user_id' => $id)))->save($data);
                 print_r("Sell-Save");
             }
             $data = array('Action' => $Action, 'FirstCurrency' => $first_curr, 'SecondCurrency' => $second_curr, 'CommissionPercent' => (double) $Commission, 'Commission.Amount' => (double) $CommissionAmount, 'Commission.Currency' => $CommissionCurrency, 'Amount' => (double) $Amount, 'PerPrice' => (double) $PerPrice, 'DateTime' => new \MongoDate(), 'Completed' => 'N', 'IP' => $_SERVER['REMOTE_ADDR'], 'username' => $user['username'], 'user_id' => (string) $user['_id']);
             print_r($data);
             // Create Order for the user
             $orders = Orders::create();
             $orders->save($data);
             $order_id = $orders->_id;
             $data = array('refresh' => true);
             Trades::find('all', array('conditions' => array('trade' => $title)))->save($data);
             $ex = new ExController();
             $ex->SendEmails($order_id, $user['_id']);
             //	=Pending Orders=================================================================================
             $FirstCurrency = $first_curr;
             $SecondCurrency = $second_curr;
             $query = array('conditions' => array('Action' => $PendingAction, 'FirstCurrency' => $FirstCurrency, 'SecondCurrency' => $SecondCurrency, 'Completed' => 'N', 'user_id' => array('$ne' => $user['_id']), 'PerPrice' => (double) $PerPrice), 'order' => array('DateTime' => 'ASC'));
             $PendingOrders = Orders::find('all', $query);
             $i = 0;
             foreach ($PendingOrders as $PO) {
                 if ((double) $PO['Amount'] == (double) $Amount) {
                     $data = array('Completed' => 'Y', 'Transact.id' => $order_id, 'Transact.username' => $user['username'], 'Transact.user_id' => $user['_id'], 'Transact.DateTime' => new \MongoDate());
                     $orders = Orders::find('first', array('conditions' => array('_id' => $PO['_id'])))->save($data);
                     $orders = Orders::find('first', array('conditions' => array('_id' => $PO['_id'])));
                     $data = array('Completed' => 'Y', 'Transact.id' => $PO['_id'], 'Transact.username' => $PO['username'], 'Transact.user_id' => $PO['user_id'], 'Transact.DateTime' => new \MongoDate());
                     $orders = Orders::find('first', array('conditions' => array('_id' => $order_id)))->save($data);
                     $ex->updateBalance($order_id);
                     $ex->updateBalance($PO['_id']);
                     $ex->SendOrderCompleteEmails($order_id, $user['_id']);
                     $ex->SendOrderCompleteEmails($PO['_id'], $PO['user_id']);
                     break;
                 }
                 if ((double) $PO['Amount'] > (double) $Amount) {
                     // Update Previous Order with New Order Amount and New Commission and Transact User
                     if ($PO['Action'] == "Buy") {
                         $PrevCommAmount = round($PO['CommissionPercent'] * $Amount / 100, 8);
                         $CurrCommAmount = round($PO['CommissionPercent'] * ($PO['Amount'] - $Amount) * $PO['PrePrice'] / 100, 8);
                         $PrevCommCurr = $PO['FirstCurrency'];
                         $CurrCommCurr = $PO['SecondCurrency'];
                     } else {
                         $PrevCommAmount = round((double) $PO['CommissionPercent'] * (double) $Amount * (double) $PerPrice / 100, 8);
                         $CurrCommAmount = round($PO['CommissionPercent'] * $Amount / 100, 8);
                         $PrevCommCurr = $PO['SecondCurrency'];
                         $CurrCommCurr = $PO['FirstCurrency'];
                     }
                     $data = array('Commission.Amount' => (double) $PrevCommAmount, 'Amount' => (double) $Amount, 'Completed' => 'Y', 'Transact.id' => $order_id, 'Transact.username' => $user['username'], 'Transact.user_id' => $user['_id'], 'Transact.DateTime' => new \MongoDate(), 'Order' => 'P>C: Update Previous Commission and Amount and Complete Order');
                     $orders = Orders::find('first', array('conditions' => array('_id' => $PO['_id'])))->save($data);
                     // --------------------Complete
                     // Create new Order for Previous Order so that the order tallies
                     if ($PO['Action'] == "Buy") {
                         $PrevCommAmount = round((double) round((double) $PO['Amount'] - (double) $Amount, 8) * (double) $PO['CommissionPercent'] / 100, 8);
                     } else {
                         $PrevCommAmount = round((double) round((double) $PO['Amount'] - (double) $Amount, 8) * (double) $PO['PerPrice'] * (double) $PO['CommissionPercent'] / 100, 8);
                     }
                     $data = array('Amount' => (double) round((double) $PO['Amount'] - (double) $Amount, 8), 'Action' => $PO['Action'], 'FirstCurrency' => $PO['FirstCurrency'], 'SecondCurrency' => $PO['SecondCurrency'], 'CommissionPercent' => (double) $PO['CommissionPercent'], 'Commission.Amount' => (double) $PrevCommAmount, 'Commission.Currency' => $PrevCommCurr, 'PerPrice' => (double) $PO['PerPrice'], 'DateTime' => $PO['DateTime'], 'Completed' => 'N', 'IP' => $PO['IP'], 'username' => $PO['username'], 'user_id' => $PO['user_id'], 'Order' => 'P>C: Create New Previous Order with Balance details');
                     $orders = Orders::create();
                     $orders->save($data);
                     //-------------------Complete
                     //Update New order with Transact User
                     $data = array('Completed' => 'Y', 'Transact.id' => $PO['_id'], 'Transact.username' => $PO['username'], 'Transact.user_id' => $PO['user_id'], 'Transact.DateTime' => new \MongoDate(), 'Order' => 'P>C: Update current order no change in commission or amount');
                     $orders = Orders::find('first', array('conditions' => array('_id' => $order_id)))->save($data);
                     //---------------------Complete
                     //To update Balance
                     $ex->updateBalance($order_id);
                     $ex->updateBalance($PO['_id']);
                     $ex->SendOrderCompleteEmails($order_id, $user['_id']);
                     $ex->SendOrderCompleteEmails($PO['_id'], $PO['user_id']);
                     break;
                 }
                 if ((double) $PO['Amount'] < (double) $Amount) {
                     // Update Previous Order with New Order Amount and New Commission and Transact User
                     if ($PO['Action'] == "Buy") {
                         $PrevCommAmount = round($PO['CommissionPercent'] * ($PO['Amount'] - $Amount) / 100, 8);
                         $CurrCommAmount = round($PO['CommissionPercent'] * ($PO['Amount'] - $Amount) * $PO['PrePrice'] / 100, 8);
                         $PrevCommCurr = $PO['FirstCurrency'];
                         $CurrCommCurr = $PO['SecondCurrency'];
                     } else {
                         $PrevCommAmount = round($PO['CommissionPercent'] * ($PO['Amount'] - $Amount) * $PO['PerPrice'] / 100, 8);
                         $CurrCommAmount = round($PO['CommissionPercent'] * ($PO['Amount'] - $Amount) / 100, 8);
                         $PrevCommCurr = $PO['SecondCurrency'];
                         $CurrCommCurr = $PO['FirstCurrency'];
                     }
                     if ($PO['Action'] == "Buy") {
                         $PrevCommAmount = round($PO['CommissionPercent'] * $PO['Amount'] / 100, 8);
                     } else {
                         $PrevCommAmount = round($PO['CommissionPercent'] * $PO['Amount'] * $PO['PerPrice'] / 100, 8);
                     }
                     $data = array('Commission.Amount' => (double) $PrevCommAmount, 'Amount' => (double) $PO['Amount'], 'Completed' => 'Y', 'Transact.id' => $order_id, 'Transact.username' => $user['username'], 'Transact.user_id' => $user['_id'], 'Transact.DateTime' => new \MongoDate(), 'Order' => 'P<C: Update Previous Record');
                     $orders = Orders::find('first', array('conditions' => array('_id' => $PO['_id'])))->save($data);
                     //--------------------Complete
                     // Update current order with new commission and amount
                     if ($PO['Action'] == "Buy") {
                         $CurrCommAmount = round($PO['CommissionPercent'] * $PO['Amount'] * $PO['PerPrice'] / 100, 8);
                     } else {
                         $CurrCommAmount = round($PO['CommissionPercent'] * $PO['Amount'] / 100, 8);
                     }
                     $data = array('Commission.Amount' => (double) $CurrCommAmount, 'Amount' => (double) $PO['Amount'], 'Completed' => 'Y', 'Transact.id' => $PO['_id'], 'Transact.username' => $PO['username'], 'Transact.user_id' => $PO['user_id'], 'Transact.DateTime' => new \MongoDate(), 'Order' => 'P<C: Update current record');
                     $orders = Orders::find('first', array('conditions' => array('_id' => $order_id)))->save($data);
                     //--------------------Complete
                     //Create a new order of pending amount
                     if ($PO['Action'] == 'Buy') {
                         $CurrCommAmount = round($PO['CommissionPercent'] * (double) round((double) $Amount - (double) $PO['Amount'], 8) * $PerPrice / 100, 8);
                     } else {
                         $CurrCommAmount = round($PO['CommissionPercent'] * (double) round((double) $Amount - (double) $PO['Amount'], 8) / 100, 8);
                     }
                     $data = array('Action' => $Action, 'FirstCurrency' => $FirstCurrency, 'SecondCurrency' => $SecondCurrency, 'CommissionPercent' => (double) $Commission, 'Commission.Amount' => (double) $CurrCommAmount, 'Commission.Currency' => $CurrCommCurr, 'Amount' => (double) round((double) $Amount - (double) $PO['Amount'], 8), 'PerPrice' => (double) $PerPrice, 'DateTime' => new \MongoDate(), 'Completed' => 'N', 'IP' => $_SERVER['REMOTE_ADDR'], 'username' => $user['username'], 'user_id' => $user['_id'], 'Order' => 'P<C: Create New Previous Order with Balance details');
                     $orders = Orders::create();
                     $orders->save($data);
                     $ex->updateBalance($order_id);
                     $ex->updateBalance($PO['_id']);
                     $ex->SendOrderCompleteEmails($order_id, $user['_id']);
                     $ex->SendOrderCompleteEmails($PO['_id'], $PO['user_id']);
                     break;
                 }
             }
             //  =Pending orders=================================================================================
             //======================Trade========================================================
             $Order = Orders::find('first', array('conditions' => array('_id' => $order_id)));
             $result = array('Order_id' => String::hash($Order['_id']), 'pair' => $pair, 'type' => $type, 'Commission.Amount' => $Order['Commission']['Amount'], 'Commission.Currency' => $Order['Commission']['Currency'], 'amount' => $Order['Amount'], 'price' => $Order['PerPrice'], 'time' => $Order['DateTime']->sec, 'Completed' => $Order['Completed'], 'username' => $Order['username']);
             return $this->render(array('json' => array('success' => 1, 'now' => time(), 'result' => $result)));
         }
     }
 }
 public function edit()
 {
     // Check Author authentication Session
     if (!Auth::check('default')) {
         return $this->redirect('Authors::login');
     }
     // Retrieve current Author id
     $author_id = Auth::check('default')->data['id'];
     $author = Authors::find($this->request->id);
     if ($this->request->data) {
         if (strlen($this->request->data['password'])) {
             $this->request->data['password'] = \lithium\util\String::hash($this->request->data['password']);
         } else {
             unset($this->request->data['password']);
         }
         if ($author->save($this->request->data)) {
             Session::write('message', 'Your author account has been edit');
             $this->redirect(array('Authors::dashboard'));
         } else {
             Session::write('message', 'Your author account can not be edited');
         }
     }
     return compact('author', 'author_id');
 }
示例#18
0
 /**
  * Generates (or regenerates) a cryptographically-secure token to be used for the life of the
  * client session, and stores the token using the `Session` class.
  *
  * @see lithium\util\String::hash()
  * @param array $options An array of options to be used when generating or storing the token:
  *              - `'regenerate'` _boolean_: If `true`, will force the regeneration of a the
  *                token, even if one is already available in the session. Defaults to `false`.
  *              - `'sessionKey'` _string_: The key used for session storage and retrieval.
  *                Defaults to `'security.token'`.
  *              - `'salt'` _string_: If the token is being generated (or regenerated), sets a
  *                custom salt value to be used by `String::hash()`.
  *              - `'type'` _string_: The hashing algorithm used by `String::hash()` when
  *                generating the token. Defaults to `'sha512'`.
  * @return string Returns a cryptographically-secure client session token.
  */
 public static function get(array $options = array())
 {
     $defaults = array('regenerate' => false, 'sessionKey' => 'security.token', 'salt' => null, 'type' => 'sha512');
     $options += $defaults;
     $session = static::$_classes['session'];
     if ($options['regenerate'] || !($token = $session::read($options['sessionKey']))) {
         $token = String::hash(uniqid(microtime(true)), $options);
         $session::write($options['sessionKey'], $token);
     }
     return $token;
 }
示例#19
0
				class=" tooltip-x label label-success" rel="tooltip-x" data-placement="top" title="Add to receive alerts from <?php 
            echo $RF['_id']['TransactUsercode'];
            ?>
"
				style="font-weight:bold "><i class="glyphicon glyphicon-plus"></i> <?php 
            echo $RF['_id']['TransactUsercode'];
            ?>
</a>
			<?php 
        } else {
            ?>
			<a  href="/<?php 
            echo $locale;
            ?>
/ex/RemoveFriend/<?php 
            echo String::hash($RF['_id']['TransactUser_id']);
            ?>
/<?php 
            echo $RF['_id']['TransactUser_id'];
            ?>
/<?php 
            echo $RF['_id']['TransactUsercode'];
            ?>
" class="tooltip-x label label-warning" rel="tooltip-x" data-placement="top" title="Already a friend <?php 
            echo $RF['_id']['TransactUsercode'];
            ?>
 Remove!">
<i class="glyphicon glyphicon-minus"></i>			<?php 
            echo $RF['_id']['TransactUsercode'];
            ?>
</a>