/
Identifier.php
109 lines (98 loc) · 3.05 KB
/
Identifier.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
namespace Concrete\Core\Utility\Service;
use Concrete\Core\Database\Connection\Connection;
use Concrete\Core\Support\Facade\Application;
/**
* \@package Helpers
* @subpackage Validation
*
* @author Andrew Embler <andrew@concrete5.org>
* @copyright Copyright (c) 2003-2008 Concrete5. (http://www.concrete5.org)
* @license http://www.concrete5.org/license/ MIT License
*/
/**
* A helper that allows the creation of unique strings, for use when creating hashes, identifiers.
*
* \@package Helpers
* @subpackage Validation
*
* @author Andrew Embler <andrew@concrete5.org>
* @copyright Copyright (c) 2003-2008 Concrete5. (http://www.concrete5.org)
* @license http://www.concrete5.org/license/ MIT License
*/
class Identifier
{
/**
* Like generate() below, but simply appends an ever increasing number to what you provide
* until it comes back as not found.
*/
public function generateFromBase($string, $table, $key)
{
$foundRecord = false;
$db = Application::make(Connection::class);
$i = '';
$_string = '';
while ($foundRecord == false) {
$_string = $string . $i;
$cnt = $db->GetOne("select count(" . $key . ") as total from " . $table . " where " . $key . " = ?",
array($_string));
if ($cnt < 1) {
$foundRecord = true;
} else {
if ($i == '') {
$i = 0;
}
++$i;
}
}
return $_string;
}
/**
* Generates a unique identifier for an item in a database table. Used, among other places, in generating
* User hashes for email validation.
*
* @param string $table
* @param string $key
* @param int $length
* @param bool $lowercase
*
* @return string
*/
public function generate($table, $key, $length = 12, $lowercase = false)
{
$foundHash = false;
$db = Application::make(Connection::class);
while ($foundHash == false) {
$string = $this->getString($length);
if ($lowercase) {
$string = strtolower($string);
}
$cnt = $db->GetOne("select count(" . $key . ") as total from " . $table . " where " . $key . " = ?",
array($string));
if ($cnt < 1) {
$foundHash = true;
}
}
return $string;
}
/**
* Generate a cryptographically secure random string
* @param int $length
* @return string
*/
public function getString($length = 12)
{
$size = ceil($length / 2);
try {
$bytes = random_bytes($size);
} catch (\Exception $e) {
die('Could not generate a random string.');
}
return substr(bin2hex($bytes), 0, $length);
}
public function deleteKey($table, $keyCol, $uHash)
{
$db = Application::make(Connection::class);
$db->Execute("DELETE FROM " . $table . " WHERE " . $keyCol . "=?", array($uHash));
}
}