Issues (23)

Ocrend/Kernel/Helpers/Strings.php (3 issues)

Labels
Severity
1
<?php
2
3
/*
4
 * This file is part of the Ocrend Framewok 3 package.
5
 *
6
 * (c) Ocrend Software <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ocrend\Kernel\Helpers;
13
14
/**
15
 * Helper con funciones útiles para tratar strings.
16
 *
17
 * @author Brayan Narváez <[email protected]>
18
 */
19
20
final class Strings extends \Twig_Extension {
21
22
  /**
23
   * Convierte un tiempo dado al formato hace 1 minuto, hace 2 horas, hace 1 año ...
24
   *
25
   * @param int $from: Tiempo en segundo desde donde se desea contar
26
   * @param int|null $to: Tiempo en segundo hasta donde se desea contar, si no se pasa por defecto es el tiempo actual
27
   *
28
   * @return string con la forma: hace 20 segundos, hace 1 minuto, hace 2 horas, hace 4 días, hace 1 semana, hace 3 meses, hace 1 año ...
29
  */
30
  public static function amigable_time(int $from, $to = null) : string {   
31
    $intervalos = ['segundo', 'minuto', 'hora', 'día', 'semana', 'mes', 'año'];
32
    $duraciones = ['60','60','24','7','4.35','12'];
33
    $to = $to ?? time();
34
35
    $diferencia = $from - $to;
36
    $tiempo = 'Dentro de';
37
    if($to > $from) {   
38
        $diferencia = $to - $from;
39
        $tiempo = 'Hace';
40
    }
41
    
42
    for($j = 0; $diferencia >= $duraciones[$j] && $j < sizeof($duraciones) - 1 ; $j++) {
43
      $diferencia /= $duraciones[$j];
44
    }
45
    
46
    $diferencia = round($diferencia);
47
    
48
    if($diferencia != 1) {
49
      $intervalos[5].= 'e'; //MESES
50
      $intervalos[$j].= 's';
51
    }
52
   
53
    return $tiempo . ' ' . $diferencia . ' ' . $intervalos[$j];
54
  }
55
  
56
  /**
57
   * Compara un string hash con un string sin hash, si el string sin hash al encriptar posee la misma llave que hash, son iguales
58
   *
59
   * @param string $hash: Hash con la forma $2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G
60
   * @param string $s2: Cadena de texto a comparar
61
   *
62
   * @example Strings::chash('$2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G','123456'); //return true
63
   *
64
   * @return bool true si $s2 contiene la misma llave que $hash, por tanto el contenido de $hash es $s2, de lo contrario false
65
  */
66
  public static function chash(string $hash, string $s2) : bool  {
67
    return $hash == crypt($s2, substr($hash, 0, 29));
68
  }
69
70
  /**
71
   * Encripta un string, utilizando una llave para posteriormente poder desencriptar
72
   *
73
   * @param string $str: Cadena a encriptar
74
   * @param string $key: Llave única para poder encriptar
75
   * 
76
   * @return string : Texto encriptado
77
   */
78
  public static function ocrend_encode(string $str, string $key) : string {
79
    $___s___ = openssl_encrypt($str,
80
    "AES-128-ECB",
81
    $key);
82
83
    return base64_encode($___s___);
84
  }
85
86
  /**
87
   * Desencripta un string, utilizando una llave que se ocupó al encriptar
88
   *
89
   * @param string $str: Cadena a desencriptar
90
   * @param string $key: Llave única para poder desencriptar
91
   * 
92
   * @return string : Texto desencriptado
93
   */
94
  public static function ocrend_decode(string $str, string $key) : string {
95
    $data = base64_decode($str);
96
    
97
    return openssl_decrypt($data,
98
    "AES-128-ECB",
99
    $key);
100
  }
101
102
  /**
103
   * Devuelve un hash DINÁMICO, para comparar un hash con un elemento se utiliza chash
104
   *
105
   * @param string $p: Cadena de texto a encriptar
106
   *
107
   * @return string Hash, con la forma $2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G
108
   */
109
  public static function hash(string $p) : string {
110
    return crypt($p, '$2a$10$' . substr(sha1(mt_rand()), 0, 22));
111
  }
112
  
113
  /**
114
   * Calcula el tiempo de diferencia entre dos fechas
115
   *
116
   * @param string $ini: Fecha menor con el formato d-m-Y ó d/m/Y
117
   * @param string $fin: Fecha mayor con el formato d-m-Y ó d/m/Y
118
   *
119
   * @return int con la diferencia de tiempo en días
120
   *
121
   */
122
  public static function date_difference(string $ini, string $fin) : int {
123
    $ini_i = explode('-',str_replace('/','-',$ini));
124
    $fin_i = explode('-',str_replace('/','-',$fin));
125
    return (int) floor((mktime(0, 0, 0, $fin_i[1], $fin_i[0], $fin_i[2]) - mktime(0, 0, 0, $ini_i[1], $ini_i[0], $ini_i[2])) / 86400);
0 ignored issues
show
$fin_i[1] of type string is incompatible with the type integer expected by parameter $month of mktime(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

125
    return (int) floor((mktime(0, 0, 0, /** @scrutinizer ignore-type */ $fin_i[1], $fin_i[0], $fin_i[2]) - mktime(0, 0, 0, $ini_i[1], $ini_i[0], $ini_i[2])) / 86400);
Loading history...
$fin_i[2] of type string is incompatible with the type integer expected by parameter $year of mktime(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

125
    return (int) floor((mktime(0, 0, 0, $fin_i[1], $fin_i[0], /** @scrutinizer ignore-type */ $fin_i[2]) - mktime(0, 0, 0, $ini_i[1], $ini_i[0], $ini_i[2])) / 86400);
Loading history...
$fin_i[0] of type string is incompatible with the type integer expected by parameter $day of mktime(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

125
    return (int) floor((mktime(0, 0, 0, $fin_i[1], /** @scrutinizer ignore-type */ $fin_i[0], $fin_i[2]) - mktime(0, 0, 0, $ini_i[1], $ini_i[0], $ini_i[2])) / 86400);
Loading history...
126
  }
127
128
  /**
129
   * Calcula la edad de una persona segun la fecha de nacimiento
130
   *
131
   * @param string $cumple: Fecha de nacimiento con el formato d-m-Y ó d/m/Y
132
   *
133
   * @return int con la edad
134
   *
135
   */
136
  public static function calculate_age(string $cumple) : int {
137
    $age = explode('.', (string) (self::date_difference($cumple, date('d-m-Y', time()))/365));
138
    return (int) $age[0];
139
  }
140
141
  /**
142
   * Calcula cuántos días tiene el mes actual
143
   *
144
   * @return integer con la cantidad de días del mes
145
   *
146
   */
147
  public static function days_of_month() : int {
148
    return cal_days_in_month(CAL_GREGORIAN, (int) date('m',time()), (int) date('Y',time()));
149
  }
150
151
  /**
152
   * Verifica si una cadena de texto tiene forma de email
153
   *
154
   * @param string $address: Cadena de texto con el email
155
   *
156
   * @return mixed devuelve TRUE si es un email y FALSE si no lo es
157
   */
158
  public static function is_email(string $address) {
159
    return filter_var($address, FILTER_VALIDATE_EMAIL);
160
  }
161
162
  /**
163
    * Remueve todos los espacios en blanco de un string
164
    *
165
    * @param string $s: Cadena de texto a convertir
166
    *
167
    * @return string del texto sin espacios
168
  */
169
  public static function remove_spaces(string $s) : string {
170
    return trim(str_replace(' ', '', $s));
171
  }
172
173
  /**
174
   * Analiza si una cadena de texto es alfanumérica
175
   *
176
   * @param string $s: Cadena de texto a verificar
177
   *
178
   * @return bool, verdadero si es alfanumerica, falso si no
179
  */
180
  public static function alphanumeric(string $s) : bool {
181
    return ctype_alnum(self::remove_spaces($s));
182
  }
183
184
185
  /**
186
   * Analiza si una cadena de texto verificando si sólamente tiene letras
187
   *
188
   * @param string $s: Cadena de texto a verificar
189
   *
190
   * @return bool, verdadero si sólamente tiene letras, falso si no
191
  */
192
  public static function only_letters(string $s) : bool {
193
    return ctype_alpha(self::remove_spaces($s));
194
  }
195
196
197
  /**
198
   * Analiza si una cadena de texto contiene sólamente letras y números
199
   *
200
   * @param string $s: Cadena de texto a verificar
201
   *
202
   * @return bool, verdadero si sólamente contiene letras y números, falso si no
203
   */
204
  public static function letters_and_numbers(string $s) : bool {
205
    return (boolean) preg_match('/^[\w.]*$/', self::remove_spaces($s));
206
  }
207
208
209
  /**
210
   * Convierte una expresión de texto, a una compatible con url amigables
211
   *
212
   * @param string $url: Cadena de texto a convertir
213
   *
214
   * @return string Cadena de texto con formato de url amigable
215
  */
216
  public static function url_amigable(string $url) : string {
217
    $url = str_replace(['á', 'é', 'í', 'ó', 'ú', 'ñ'], ['a', 'e', 'i', 'o', 'u', 'n'], $url);
218
    $url = str_replace([' ', '&', '\r\n', '\n', '+', '%'], '-', $url);
219
    return strtolower(preg_replace(['/[^a-zA-Z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/'], ['', '-', ''], $url));
220
  }
221
 
222
223
  /**
224
   * Convierte código BBCode en su equivalente HTML
225
   *
226
   * @param string $string: Código con formato BBCode dentro
227
   *
228
   * @return string del código BBCode transformado en HTML
229
   */
230
  public static function bbcode(string $string) : string {
231
    $BBcode = array(
232
        '/\[i\](.*?)\[\/i\]/is',
233
        '/\[b\](.*?)\[\/b\]/is',
234
        '/\[u\](.*?)\[\/u\]/is',
235
        '/\[s\](.*?)\[\/s\]/is',
236
        '/\[img\](.*?)\[\/img\]/is',
237
        '/\[center\](.*?)\[\/center\]/is',
238
        '/\[h1\](.*?)\[\/h1\]/is',
239
        '/\[h2\](.*?)\[\/h2\]/is',
240
        '/\[h3\](.*?)\[\/h3\]/is',
241
        '/\[h4\](.*?)\[\/h4\]/is',
242
        '/\[h5\](.*?)\[\/h5\]/is',
243
        '/\[h6\](.*?)\[\/h6\]/is',
244
        '/\[quote\](.*?)\[\/quote\]/is',
245
        '/\[url=(.*?)\](.*?)\[\/url\]/is',
246
        '/\[bgcolor=(.*?)\](.*?)\[\/bgcolor\]/is',
247
        '/\[color=(.*?)\](.*?)\[\/color\]/is',
248
        '/\[bgimage=(.*?)\](.*?)\[\/bgimage\]/is',
249
        '/\[size=(.*?)\](.*?)\[\/size\]/is',
250
        '/\[font=(.*?)\](.*?)\[\/font\]/is'
251
    );
252
    $HTML = array(
253
        '<i>$1</i>',
254
        '<b>$1</b>',
255
        '<u>$1</u>',
256
        '<s>$1</s>',
257
        '<img src="$1" />',
258
        '<center>$1</center>',
259
        '<h1>$1</h1>',
260
        '<h2>$1</h2>',
261
        '<h3>$1</h3>',
262
        '<h4>$1</h4>',
263
        '<h5>$1</h5>',
264
        '<h6>$1</h6>',
265
        '<blockquote style="background:#f1f5f7;color:#404040;padding:4px;border-radius:4px;">$1</blockquote>',
266
        '<a href="$1" target="_blank">$2</a>',
267
        '<div style="background: $1;">$2</div>',
268
        '<span style="color: $1;">$2</span>',
269
        '<div style="background: url(\'$1\');">$2</div>',
270
        '<span style="font-size: $1px">$2</span>',
271
        '<span style="font-family: $1">$2</span>'
272
    );
273
    return nl2br(preg_replace($BBcode, $HTML, $string));
274
  }
275
276
  /**
277
   * Dice si un string comienza con un caracter especificado
278
   *
279
   * @param string $sx: Caracter de inicio
280
   * @param string $str: String a evaluar
281
   * @param bool $case_sensitive: Boolean para definir si será seible a mayúsculas o no
282
   *
283
   * @return bool True si comienza con el caracter especificado, False si no
284
   */
285
  public static function begin_with(string $sx, string $str) : bool {
286
    return (bool) (strlen($str) > 0 and $str[0] == $sx);
287
  }
288
 
289
  /**
290
   * Dice si un string termina con una caracter especificado
291
   *
292
   * @param string $sx: Caracter del final
293
   * @param string $str: String a evaluar
294
   *
295
   * @return bool True si termina con el caracter especificado, False si no
296
   */
297
  public static function end_with(string $sx, string $str) : bool {
298
    return (bool) (strlen($str) > 0 and $str[strlen($str) - 1] == $sx);
299
  }
300
301
  /**
302
   * Ver si un string está contenido en otro
303
   *
304
   * @param $s: String contenido en $str
305
   * @param $str: String a evaluar
306
   *
307
   * @return bool True si $s está dentro de $str, False si no
308
   */
309
  public static function contain(string $s, string $str) : bool {
310
    return (bool) (strpos($str, $s) !== false);
311
  }
312
313
  /**
314
   * Devuelve la cantidad de palabras en un string
315
   *
316
   * @param $str: String a evaluar
317
   *
318
   * @return int Cantidad de palabras
319
   */
320
  public static function count_words(string $s) : int {
321
    return (int) str_word_count($s,0,'0..9_');
322
  }
323
324
  /**
325
   * Se obtiene de Twig_Extension y sirve para que cada función esté disponible como etiqueta en twig
326
   *
327
   * @return array Todas las funciones con sus respectivos nombres de acceso en plantillas twig
328
   */
329
  public function getFunctions() : array {
330
    return array(
331
      new \Twig_Function('amigable_time', array($this, 'amigable_time')),
332
      new \Twig_Function('chash', array($this, 'chash')),
333
      new \Twig_Function('hash', array($this, 'hash')),
334
      new \Twig_Function('date_difference', array($this, 'date_difference')),
335
      new \Twig_Function('calculate_age', array($this, 'calculate_age')),
336
      new \Twig_Function('days_of_month', array($this, 'days_of_month')),
337
      new \Twig_Function('is_email', array($this, 'is_email')),
338
      new \Twig_Function('remove_spaces', array($this, 'remove_spaces')),
339
      new \Twig_Function('alphanumeric', array($this, 'alphanumeric')),
340
      new \Twig_Function('only_letters', array($this, 'only_letters')),
341
      new \Twig_Function('letters_and_numbers', array($this, 'letters_and_numbers')),
342
      new \Twig_Function('url_amigable', array($this, 'url_amigable')),
343
      new \Twig_Function('bbcode', array($this, 'bbcode')),
344
      new \Twig_Function('begin_with', array($this, 'begin_with')),
345
      new \Twig_Function('end_with', array($this, 'end_with')),
346
      new \Twig_Function('contain', array($this, 'contain')),
347
      new \Twig_Function('count_words', array($this, 'count_words'))
348
    );
349
  }
350
351
  /**
352
   * Identificador único para la extensión de twig
353
   *
354
   * @return string Nombre de la extensión
355
  */
356
  public function getName() : string {
357
    return 'ocrend_framework_helper_strings';
358
  }
359
}