Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: Generator Tokenów
Forum PHP.pl > Forum > Gotowe rozwiązania > Algorytmy, klasy, funkcje
Balon
  1. <?php
  2. /**
  3.  * License
  4.  *
  5.  * This library is free software; you can redistribute it and/or
  6.  * modify it under the terms of the GNU Lesser General Public
  7.  * License as published by the Free Software Foundation; either
  8.  * version 2.1 of the License, or (at your option) any later version.
  9.  *
  10.  * This library is distributed in the hope that it will be useful,
  11.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13.  * Lesser General Public License for more details.
  14.  *
  15.  * You should have received a copy of the GNU Lesser General Public
  16.  * License along with this library; if not, write to the Free Software
  17.  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18.  **/
  19. /**
  20.  * @author Krzysztof (Balon) Jagiełło <balonyo@gmail.com>
  21.  * @copyright 2007 Krzysztof Jagiełło.
  22.  * @version 1.0
  23.  */
  24.  
  25. class Token {
  26. /** Kod na tokenie */
  27. var $_tokenText;
  28.  
  29. /** Adres folderu czcionek */
  30. var $_fontDir = '';
  31.  
  32. /** Nazwy czcionek */
  33. var $_fontFiles = array(
  34. 'georgia.TTF'
  35. );
  36.  
  37. /** Typ obrazka */
  38. var $_imgType = 'gif';
  39.  
  40. /** Długość kodu na tokenie */
  41. var $_length;
  42.  
  43. /** Kolor tła */
  44. var $_backColor = '#ffffff';
  45.  
  46. /** Kolor czcionki */
  47. var $_fontColor = '#466900';
  48.  
  49. /** Kolor elementów tłą */
  50. var $_elemsColor = '#E1E1E1';
  51.  
  52. /** Szerokość tokena */
  53. var $_width;
  54.  
  55. /** Wyskość tokena */
  56. var $_height = 25;
  57.  
  58. /** Obiekt tła */
  59. var $_bgObject;
  60.  
  61. /** Obrazek tokena */
  62. var $_image;
  63.  
  64. /** Nazwa klucza sesji z tokenem */
  65. var $_tokenId = 'token';
  66.  
  67. /** Dozwolone rozszerzenia */
  68. var $_allowedTypes = array( 
  69. 'gif', 'jpg', 'png' 
  70. );
  71.  
  72. /** Komunikaty błędów */
  73. var $_errorMsg = array(
  74. 'wrong_color'  => 'Format koloru (%s) jest nieprawidłowy.',
  75. 'wrong_object' => 'Podany obiekt nie istnieje.',
  76. 'wrong_img_type'=> 'Podany typ ("%s") jest nieprawidłowy.',
  77. 'wrong_file' => 'Czcionka "%s" nie istnieje .' 
  78. );
  79.  
  80. /**
  81.  * Konstruktor klasy
  82.  *
  83.  * @param integer $length - długość tekstu na tokenie 
  84.  */
  85. function Token( $length, $bgObject ){
  86. $this->_length = $length;
  87. $this->_tokenText = substr(md5(uniqid(time())), 0 - $length);
  88. $this->_width = $length * 15 + 10;
  89. $this->_image = imagecreate( $this->_width, $this->_height);
  90. if( !is_object( $bgObject ) )
  91. trigger_error( $this->_errorMsg['wrong_object'], E_USER_WARNING );
  92. $this->_bgObject = $bgObject;
  93. }
  94.  
  95. /**
  96.  * Tworzy token, zapisuje go w sesji i wyświetla.
  97.  */
  98. function getToken(){
  99. // kolorki
  100. $this->_backColor = $this->MakeColor( $this->_image, $this->_backColor );
  101. $this->_fontColor = $this->MakeColor( $this->_image, $this->_fontColor );
  102. $this->_elemsColor = $this->MakeColor( $this->_image, $this->_elemsColor );
  103.  
  104. $this->Background();
  105. $this->Text();
  106.  
  107. $_SESSION[$this->_tokenId] = $this->_tokenText;
  108.  
  109. if( !in_array( $this->_imgType, $this->_allowedTypes ) )
  110. trigger_error( sprintf( $this->_errorMsg['wrong_img_type'], $this->_imgType ), E_USER_ERROR );
  111. header( 'Content-type: image/' . $this->_imgType );
  112. $this->Display();
  113. }
  114.  
  115. /**
  116.  * Tworzy tekst na tokenie
  117.  */
  118. function Text(){
  119. for($i = 0; $i < strlen($this->_tokenText); $i++){
  120.  imagettftext( $this->_image, rand(14, 16), rand(-10, 10), rand(3, 5) + $i * 15, 18 + rand(-3, 3), $this->_fontColor, $this->getFontDir() . $this->_fontFiles[rand(0,count($this->_fontFiles)-1)], $this->_tokenText{$i});
  121. }
  122. return true;
  123. }
  124.  
  125. /**
  126.  * Tworzy tło korzystając z podanej klasy tła
  127.  * 
  128.  * @return true
  129.  */
  130. function Background(){
  131. $this->_bgObject->process( &$this->_image, get_object_vars( $this ) );
  132. return true;
  133. }
  134.  
  135. /**
  136.  * Wyświetla token w wybranym formacie
  137.  */
  138. function Display(){
  139. if( !in_array( $this->_imgType, $this->_allowedTypes ) )
  140. trigger_error( sprintf( $this->_errorMsg['wrong_img_type'], $this->_imgType ), E_USER_ERROR );
  141. call_user_func( 'image' . $this->_imgType, $this->_image );
  142. }
  143.  
  144. /**
  145.  * Dodaje czcionki to tablicy. Są one potem losowo używane w tokenie.
  146.  */
  147. function assignFonts(){
  148. $fonts = func_get_args();
  149. foreach( $fonts as $font ){
  150. if( !file_exists( $this->getFontDir() . $font ) )
  151. trigger_error( sprintf( $this->_errorMsg['wrong_file'], $font ), E_USER_ERROR );
  152. else
  153. $this->_fontsFiles[] = $font;
  154. }
  155. }
  156.  
  157. /**
  158.  * Zwraca katalog z czcionkami
  159.  */
  160. function getFontDir(){
  161. return $this->_fontDir == '' ? '' : $this->_fontDir . '/';
  162. }
  163.  
  164. /**
  165.  * Zwraca kolor dla obrazka
  166.  * 
  167.  * @param resource $img
  168.  * @param string $color - kolor w formacie hexagonalny
  169.  * @return integer
  170.  */
  171. function MakeColor( $img, $color ){
  172. if( !preg_match('/^[#]{0,1}[a-f0-9]{6}$/i', $color ) )
  173. trigger_error( sprintf( $this->_errorMsg['wrong_color'], $color ), E_USER_ERROR );
  174.  
  175. $color = str_replace('#', '', $color);
  176. $return = array(
  177. 'r' => hexdec(substr($color, 0, 2)),
  178. 'g' => hexdec(substr($color, 2, 2)),
  179. 'b' => hexdec(substr($color, 4, 2))
  180. );
  181. return imagecolorallocate( $img, $return['r'], $return['g'], $return['b']);
  182. }
  183. }
  184.  
  185. class TokenBackground_Dots {
  186. function process( $image, $params ){
  187. $pts = array();
  188. for($i = 0; $i < round($params['_width'] / 1.5); $i++) {
  189. $x = rand(0, $params['_width'] );
  190. $y = rand(0, $params['_height'] );  
  191.  
  192. if( !in_array( $x.'_'.$y, $pts ) ){
  193. imageellipse( $image, $x, $y, rand(2, 7), rand(3, 6), $params['_elemsColor'] );
  194. $pts[] = $x.'_'.$y;
  195. }
  196. else {
  197. $i--;
  198. }
  199. }
  200. }
  201. }
  202.  
  203. class TokenBackground_Slashes {
  204. function process( $image, $params ){
  205. $step = 5;
  206. for($i = 0; $i < round($params['_width']) + ($step*10); $i+= $step) {
  207. imageline( $image, $i, 0, 0, $i, $params['_elemsColor'] );
  208. }
  209. }
  210. }
  211.  
  212. class TokenBackground_Grid {
  213. function process( $image, $params ){
  214. for($i = 0; $i < round($params['_width']); $i+= 5) {
  215. // poziome linie
  216. imageline( $image, 0, $i, $params['_width'], $i, $params['_elemsColor'] );
  217. // pionowe linie
  218. imageline( $image, $i, 0, $i, $params['_height'], $params['_elemsColor'] );
  219. }
  220. }
  221. }
  222.  
  223. $token = new Token(32, new TokenBackground_Dots );
  224. $token->getToken();
  225. ?>


Klasa tokena.

Najważniejsze cechy:
- Proste tworzenie nowych efektów tła,
- duża konfigurowalność działania klasy.

Przykładowe efekty tła:
  1. <?php
  2. /** Ładne kółeczka - zgapiłem z jakiegoś innego tokena ;) */
  3. class TokenBackground_Dots {
  4. function process( $image, $params ){
  5. $pts = array();
  6. for($i = 0; $i < round($params['_width'] / 1.5); $i++) {
  7. $x = rand(0, $params['_width'] );
  8. $y = rand(0, $params['_height'] );  
  9.  
  10. if( !in_array( $x.'_'.$y, $pts ) ){
  11. imageellipse( $image, $x, $y, rand(2, 7), rand(3, 6), $params['_elemsColor'] );
  12. $pts[] = $x.'_'.$y;
  13. }
  14. else {
  15. $i--;
  16. }
  17. }
  18. }
  19. }
  20. /** Ukośne paski */
  21. class TokenBackground_Slashes {
  22. function process( $image, $params ){
  23. $step = 5;
  24. for($i = 0; $i < round($params['_width']) + ($step*10); $i+= $step) {
  25. imageline( $image, $i, 0, 0, $i, $params['_elemsColor'] );
  26. }
  27. }
  28. }
  29.  
  30. /** Najzwyklejsza kratka */
  31. class TokenBackground_Grid {
  32. function process( $image, $params ){
  33. for($i = 0; $i < round($params['_width']); $i+= 5) {
  34. // poziome linie
  35. imageline( $image, 0, $i, $params['_width'], $i, $params['_elemsColor'] );
  36. // pionowe linie
  37. imageline( $image, $i, 0, $i, $params['_height'], $params['_elemsColor'] );
  38. }
  39. }
  40. }
  41. ?>


Sposób użycia:
Kod
<?php
// ... tutaj klasa tokena
// ... tutaj klasa efektu

$token = new Token(20, new TokenBackground_Dots );
$token->getToken();
?>

.
hwao
Kod wygląda super:)

Ale prosił bym o dodanie np jakiś 4 przykładowych (z tłem/bez) tokenów wygenerowanych i na http://imageshack.us/ przyjemnie było by zobaczyć i uniknie się wielu "pytań".

Moderatorze
Po tym jak autor doda do posta głównego przykładowe obrazki, można tego posta usunąć.
grzesio
Jak to uruchomić ?
nie działa mi ten skrypt !

  1. <?php
  2.  
  3. include ("token_class.php"); // ... tutaj klasa tokena
  4. include ("token_efekt.php");  // ... tutaj klasa efektu
  5.  
  6.  
  7.  
  8. ?>
Daimos
ciekawa klasa, ale mi brakuje dwoch rzeczy:
- nie mozna powiekszyc czcionki w prosty sposob
- kolor czcionki moglby byc w tablicy i kolor kazdej literki losowo smile.gif

-----
jeszcze skoro mozna podac folder z czcionkami to po co je wymieniac? mozna by przeciez automatycznie pobierac do tablicy wszystkie z danego katalogu
Balon
Cytat(my salsa @ 20.05.2007, 22:53:51 ) *
ciekawa klasa, ale mi brakuje dwoch rzeczy:
- nie mozna powiekszyc czcionki w prosty sposob
- kolor czcionki moglby byc w tablicy i kolor kazdej literki losowo smile.gif

-----
jeszcze skoro mozna podac folder z czcionkami to po co je wymieniac? mozna by przeciez automatycznie pobierac do tablicy wszystkie z danego katalogu


hmmm dzięki za pomysł ; Jak to uruchomić ?
nie działa mi ten skrypt !) będzie chwila to dorobie takie funkcje, bo pomysł nie jest zły winksmiley.jpg

Cytat
Jak to uruchomić ?
nie działa mi ten skrypt !


A to zrobiłeś ? Drugi argument dla konstruktora to obiekt tła
  1. <?php
  2. $token = new Token(20, new TokenBackground_Dots );
  3. $token->getToken();
  4. ?>


Dodałem wszystko o czym pisaliście prócz wielkości czcionek winksmiley.jpg Dzisiaj wieczorem jak będzie czas to to zrobię winksmiley.jpg
  1. <?php
  2. /**
  3.  * License
  4.  *
  5.  * This library is free software; you can redistribute it and/or
  6.  * modify it under the terms of the GNU Lesser General Public
  7.  * License as published by the Free Software Foundation; either
  8.  * version 2.1 of the License, or (at your option) any later version.
  9.  *
  10.  * This library is distributed in the hope that it will be useful,
  11.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13.  * Lesser General Public License for more details.
  14.  *
  15.  * You should have received a copy of the GNU Lesser General Public
  16.  * License along with this library; if not, write to the Free Software
  17.  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18.  **/
  19. /**
  20.  * @author Krzysztof (Balon) Jagiełło <balonyo@gmail.com>
  21.  * @copyright 2007 Krzysztof Jagiełło.
  22.  * @version 1.0
  23.  * @license <a href="http://opensource.org/licenses/lgpl-license.php" target="_blank">http://opensource.org/licenses/lgpl-license.php</a> GNU Lesser General Public License
  24.  */
  25.  
  26. class Token {
  27. /** Kod na tokenie */
  28. var $_tokenText;
  29.  
  30. /** Adres folderu czcionek */
  31. var $_fontDir = '';
  32.  
  33. /** Nazwy czcionek */
  34. var $_fontFiles = array();
  35.  
  36. /** Automatyczne ładowanie czcionek */
  37. var $_autoFont = true;
  38.  
  39. /** Typ obrazka */
  40. var $_imgType = 'gif';
  41.  
  42. /** Długość kodu na tokenie */
  43. var $_length;
  44.  
  45. /** Kolor tła */
  46. var $_backColor = '#ffffff';
  47.  
  48. /** Kolor czcionki */
  49. var $_fontColor = array(
  50. '#466900'
  51. );
  52.  
  53. /** Kolor elementów tłą */
  54. var $_elemsColor = '#E1E1E1';
  55.  
  56. /** Szerokość tokena */
  57. var $_width;
  58.  
  59. /** Wyskość tokena */
  60. var $_height = 30;
  61.  
  62. /** Obiekt tła */
  63. var $_bgObject;
  64.  
  65. /** Obrazek tokena */
  66. var $_image;
  67.  
  68. /** Nazwa klucza sesji z tokenem */
  69. var $_tokenId = 'token';
  70.  
  71. /** Dozwolone rozszerzenia */
  72. var $_allowedTypes = array( 
  73. 'gif', 'jpg', 'png' 
  74. );
  75.  
  76. /** Komunikaty błędów */
  77. var $_errorMsg = array(
  78. 'wrong_color'  => 'Format koloru (%s) jest nieprawidłowy.',
  79. 'wrong_object' => 'Podany obiekt nie istnieje.',
  80. 'wrong_img_type'=> 'Podany typ ("%s") jest nieprawidłowy.',
  81. 'wrong_file' => 'Czcionka "%s" nie istnieje .' 
  82. );
  83.  
  84. /**
  85.  * Konstruktor klasy
  86.  *
  87.  * @param integer $length - długość tekstu na tokenie
  88.  * @param object $bgObject - obiekt efektu tła
  89.  * @param bool $autoFont - automatyczne pobieranie czcionek z katalogu 
  90.  */
  91. function Token( $length, $bgObject, $autoFont = false ){
  92. $this->_length = $length;
  93. $this->_tokenText = substr(md5(uniqid(time())), 0 - $length);
  94. $this->_width = $length * 15 + 10;
  95. $this->_image = imagecreate( $this->_width, $this->_height);
  96. if( !is_object( $bgObject ) )
  97. trigger_error( $this->_errorMsg['wrong_object'], E_USER_WARNING );
  98. $this->_bgObject = $bgObject;
  99. $this->_autoFont = $autoFont ? true : false;
  100. }
  101.  
  102. /**
  103.  * Tworzy token, zapisuje go w sesji i wyświetla.
  104.  */
  105. function getToken(){
  106. // kolorki
  107. $this->_backColor = $this->MakeColor( $this->_image, $this->_backColor );
  108. $this->_elemsColor = $this->MakeColor( $this->_image, $this->_elemsColor );
  109. for( $i = 0; $i < count( $this->_fontColor ); $i++ )
  110. $this->_fontColor[$i] = $this->MakeColor( $this->_image, $this->_fontColor[$i] );
  111.  
  112. $this->Background();
  113.  
  114. if( $this->_autoFont )
  115. $this->autoLoadFonts();
  116. $this->Text();
  117.  
  118. $_SESSION[$this->_tokenId] = $this->_tokenText;
  119.  
  120. if( !in_array( $this->_imgType, $this->_allowedTypes ) )
  121. trigger_error( sprintf( $this->_errorMsg['wrong_img_type'], $this->_imgType ), E_USER_ERROR );
  122. header( 'Content-type: image/' . $this->_imgType );
  123. $this->Display();
  124. }
  125.  
  126. /**
  127.  * Tworzy tekst na tokenie
  128.  */
  129. function Text(){
  130. for($i = 0; $i < strlen($this->_tokenText); $i++){
  131.  imagettftext( $this->_image, rand(14, 16), rand(-10, 10), rand(3, 5) + $i * 15, 20 + rand(-3, 3), $this->_fontColor[rand(0,count($this->_fontColor)-1)], $this->getFontDir() . $this->_fontFiles[rand(0,count($this->_fontFiles)-1)], $this->_tokenText{$i});
  132. }
  133. return true;
  134. }
  135.  
  136. /**
  137.  * Tworzy tło korzystając z podanej klasy tła
  138.  * 
  139.  * @return true
  140.  */
  141. function Background(){
  142. $this->_bgObject->process( &$this->_image, get_object_vars( $this ) );
  143. return true;
  144. }
  145.  
  146. /**
  147.  * Wyświetla token w wybranym formacie
  148.  */
  149. function Display(){
  150. if( !in_array( $this->_imgType, $this->_allowedTypes ) )
  151. trigger_error( sprintf( $this->_errorMsg['wrong_img_type'], $this->_imgType ), E_USER_ERROR );
  152. call_user_func( 'image' . $this->_imgType, $this->_image );
  153. }
  154.  
  155. /**
  156.  * Dodaje czcionki do tablicy. Są one potem losowo używane w tokenie.
  157.  */
  158. function assignFonts(){
  159. $fonts = func_get_args();
  160. foreach( $fonts as $font ){
  161. if( !file_exists( $this->getFontDir() . $font ) )
  162. trigger_error( sprintf( $this->_errorMsg['wrong_file'], $font ), E_USER_ERROR );
  163. else
  164. $this->_fontFiles[] = $font;
  165. }
  166. }
  167.  
  168. /**
  169.  * Dodaje kolory czcionek do tablicy. Są one potem losowo używane w tokenie.
  170.  */
  171. function assignFontsColors(){
  172. $colors = func_get_args();
  173. $this->_fontColor = array();
  174. foreach( $colors as $color ){
  175. if( !preg_match('/^[#]{0,1}[a-f0-9]{6}$/i', $color ) )
  176. trigger_error( sprintf( $this->_errorMsg['wrong_color'], $color ), E_USER_ERROR );
  177. else
  178. array_push( $this->_fontColor, $color ); 
  179. }
  180. }
  181.  
  182. /**
  183.  * Automatycznie ładuje pliki czcionek
  184.  * z określonego folderu
  185.  */
  186. function autoLoadFonts(){
  187. $dir = dir( $this->_fontDir );
  188. while( false !== ( $font = $dir->read() ) ){
  189. if( strpos( strtolower( $font ), '.ttf' ) !== false )
  190. array_push( $this->_fontFiles, $font ); 
  191. }
  192. $dir->close();
  193. }
  194.  
  195. /**
  196.  * Zwraca katalog z czcionkami
  197.  */
  198. function getFontDir(){
  199. return $this->_fontDir == '' ? '' : $this->_fontDir . '/';
  200. }
  201.  
  202. /**
  203.  * Zwraca kolor dla obrazka
  204.  * 
  205.  * @param resource $img
  206.  * @param string $color - kolor w formacie hexagonalny
  207.  * @return integer
  208.  */
  209. function MakeColor( $img, $color ){
  210. if( !preg_match('/^[#]{0,1}[a-f0-9]{6}$/i', $color ) )
  211. trigger_error( sprintf( $this->_errorMsg['wrong_color'], $color ), E_USER_ERROR );
  212.  
  213. $color = str_replace('#', '', $color);
  214. $return = array(
  215. 'r' => hexdec(substr($color, 0, 2)),
  216. 'g' => hexdec(substr($color, 2, 2)),
  217. 'b' => hexdec(substr($color, 4, 2))
  218. );
  219. return imagecolorallocate( $img, $return['r'], $return['g'], $return['b']);
  220. }
  221. }
  222.  
  223. class TokenBackground_Dots {
  224. function process( $image, $params ){
  225. $pts = array();
  226. for($i = 0; $i < round($params['_width'] / 1.5); $i++) {
  227. $x = rand(0, $params['_width'] );
  228. $y = rand(0, $params['_height'] );  
  229.  
  230. if( !in_array( $x.'_'.$y, $pts ) ){
  231. imageellipse( $image, $x, $y, rand(2, 7), rand(3, 6), $params['_elemsColor'] );
  232. $pts[] = $x.'_'.$y;
  233. }
  234. else {
  235. $i--;
  236. }
  237. }
  238. }
  239. }
  240.  
  241. class TokenBackground_Slashes {
  242. function process( $image, $params ){
  243. $step = 5;
  244. for($i = 0; $i < round($params['_width']) + ($step*10); $i+= $step) {
  245. imageline( $image, $i, 0, 0, $i, $params['_elemsColor'] );
  246. }
  247. }
  248. }
  249.  
  250. class TokenBackground_Grid {
  251. function process( $image, $params ){
  252. for($i = 0; $i < round($params['_width']); $i+= 5) {
  253. // poziome linie
  254. imageline( $image, 0, $i, $params['_width'], $i, $params['_elemsColor'] );
  255. // pionowe linie
  256. imageline( $image, $i, 0, $i, $params['_height'], $params['_elemsColor'] );
  257. }
  258. }
  259. }
  260. ?>


Przykład użycia różnych fontów oraz kolorów czcionek:
Kod
require_once( 'token.class.php' );

$token = new Token(20, new TokenBackground_Dots, true );
$token->_fontDir = 'fonts/';
$token->assignFontsColors( '#466900', '#000000', '#777777' );
$token->getToken();


Cytat
Ale prosił bym o dodanie np jakiś 4 przykładowych (z tłem/bez) tokenów wygenerowanych i na http://imageshack.us/ przyjemnie było by zobaczyć i uniknie się wielu "pytań".

Nie zauważyłem Twojego posta winksmiley.jpg Oczywiście, proszę bardzo !
http://bambo.pl/tmp/token/example.php
ChowiX
Prosze napisac tak dokładniej ja użyć tego tokena ..
bo tak wrzuciłem caly kod tz
  1. <?php
  2. /**
  3.  * License
  4.  *
  5.  * This library is free software; you can redistribute it and/or
  6.  * modify it under the terms of the GNU Lesser General Public
  7.  * License as published by the Free Software Foundation; either
  8.  * version 2.1 of the License, or (at your option) any later version.
  9.  *
  10.  * This library is distributed in the hope that it will be useful,
  11.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13.  * Lesser General Public License for more details.
  14.  *
  15.  * You should have received a copy of the GNU Lesser General Public
  16.  * License along with this library; if not, write to the Free Software
  17.  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  18.  **/
  19. /**
  20.  * @author Krzysztof (Balon) Jagiełło <balonyo@gmail.com>
  21.  * @copyright 2007 Krzysztof Jagiełło.
  22.  * @version 1.0
  23.  * @license <a href="http://opensource.org/licenses/lgpl-license.php" target="_blank">http://opensource.org/licenses/lgpl-license.php</a> GNU Lesser General Public License
  24.  */
  25.  
  26. class Token {
  27.     /** Kod na tokenie */
  28.     var $_tokenText;
  29.     
  30.     /** Adres folderu czcionek */
  31.     var $_fontDir = '';
  32.     
  33.     /** Nazwy czcionek */
  34.     var $_fontFiles = array();
  35.     
  36.     /** Automatyczne ładowanie czcionek */
  37.     var $_autoFont = true;
  38.     
  39.     /** Typ obrazka */
  40.     var $_imgType = 'gif';
  41.     
  42.     /** Długość kodu na tokenie */
  43.     var $_length;
  44.     
  45.     /** Kolor tła */
  46.     var $_backColor = '#ffffff';
  47.     
  48.     /** Kolor czcionki */
  49.     var $_fontColor = array(
  50.       '#466900'
  51.     );
  52.     
  53.     /** Kolor elementów tłą */
  54.     var $_elemsColor = '#E1E1E1';
  55.     
  56.     /** Szerokość tokena */
  57.     var $_width;
  58.     
  59.     /** Wyskość tokena */
  60.     var $_height = 30;
  61.     
  62.     /** Obiekt tła */
  63.     var $_bgObject;
  64.     
  65.     /** Obrazek tokena */
  66.     var $_image;
  67.     
  68.     /** Nazwa klucza sesji z tokenem */
  69.     var $_tokenId = 'token';
  70.     
  71.     /** Dozwolone rozszerzenia */
  72.     var $_allowedTypes = array( 
  73.         'gif', 'jpg', 'png' 
  74.     );
  75.     
  76.     /** Komunikaty błędów */
  77.     var $_errorMsg = array(
  78.       'wrong_color'   => 'Format koloru (%s) jest nieprawidłowy.',
  79.       'wrong_object'  => 'Podany obiekt nie istnieje.',
  80.       'wrong_img_type'=> 'Podany typ ("%s") jest nieprawidłowy.',
  81.       'wrong_file'        => 'Czcionka "%s" nie istnieje .' 
  82.     );
  83.     
  84.     /**
  85.      * Konstruktor klasy
  86.      *  
  87.      * @param integer $length - długość tekstu na tokenie
  88.      * @param object $bgObject - obiekt efektu tła
  89.      * @param bool $autoFont - automatyczne pobieranie czcionek z katalogu 
  90.      */
  91.     function Token( $length, $bgObject, $autoFont = false ){
  92.         $this->_length = $length;
  93.         $this->_tokenText = substr(md5(uniqid(time())), 0 - $length);
  94.         $this->_width = $length * 15 + 10;
  95.         $this->_image = imagecreate( $this->_width, $this->_height);
  96.         if( !is_object( $bgObject ) )
  97.           trigger_error( $this->_errorMsg['wrong_object'], E_USER_WARNING );
  98.         $this->_bgObject = $bgObject;
  99.         $this->_autoFont = $autoFont ? true : false;
  100.     }
  101.     
  102.     /**
  103.      * Tworzy token, zapisuje go w sesji i wyświetla.
  104.      */
  105.     function getToken(){
  106.         // kolorki
  107.         $this->_backColor = $this->MakeColor( $this->_image, $this->_backColor );
  108.         $this->_elemsColor = $this->MakeColor( $this->_image, $this->_elemsColor );
  109.         for( $i = 0; $i < count( $this->_fontColor ); $i++ )
  110.           $this->_fontColor[$i] = $this->MakeColor( $this->_image, $this->_fontColor[$i] );
  111.  
  112.         $this->Background();
  113.         
  114.         if( $this->_autoFont )
  115.           $this->autoLoadFonts();
  116.         $this->Text();
  117.         
  118.         $_SESSION[$this->_tokenId] = $this->_tokenText;
  119.         
  120.         if( !in_array( $this->_imgType, $this->_allowedTypes ) )
  121.           trigger_error( sprintf( $this->_errorMsg['wrong_img_type'], $this->_imgType ), E_USER_ERROR );
  122.         header( 'Content-type: image/' . $this->_imgType );
  123.         $this->Display();
  124.     }
  125.     
  126.     /**
  127.      * Tworzy tekst na tokenie
  128.      */
  129.     function Text(){
  130.         for($i = 0; $i < strlen($this->_tokenText); $i++){
  131.      imagettftext( $this->_image, rand(14, 16), rand(-10, 10), rand(3, 5) + $i * 15, 20 + rand(-3, 3), $this->_fontColor[rand(0,count($this->_fontColor)-1)], $this->getFontDir() . $this->_fontFiles[rand(0,count($this->_fontFiles)-1)], $this->_tokenText{$i});
  132.     }
  133.     return true;
  134.     }
  135.     
  136.     /**
  137.      * Tworzy tło korzystając z podanej klasy tła
  138.      * 
  139.      * @return true
  140.      */
  141.     function Background(){        
  142.         $this->_bgObject->process( &$this->_image, get_object_vars( $this ) );
  143.         return true;
  144.     }
  145.     
  146.     /**
  147.      * Wyświetla token w wybranym formacie
  148.      */
  149.     function Display(){
  150.         if( !in_array( $this->_imgType, $this->_allowedTypes ) )
  151.           trigger_error( sprintf( $this->_errorMsg['wrong_img_type'], $this->_imgType ), E_USER_ERROR );
  152.         call_user_func( 'image' . $this->_imgType, $this->_image );
  153.     }
  154.     
  155.     /**
  156.      * Dodaje czcionki do tablicy. Są one potem losowo używane w tokenie.
  157.      */
  158.     function assignFonts(){
  159.         $fonts = func_get_args();
  160.         foreach( $fonts as $font ){
  161.             if( !file_exists( $this->getFontDir() . $font ) )
  162.               trigger_error( sprintf( $this->_errorMsg['wrong_file'], $font ), E_USER_ERROR );
  163.             else
  164.               $this->_fontFiles[] = $font;
  165.         }
  166.     }
  167.     
  168.     /**
  169.      * Dodaje kolory czcionek do tablicy. Są one potem losowo używane w tokenie.
  170.      */
  171.     function assignFontsColors(){
  172.         $colors = func_get_args();
  173.         $this->_fontColor = array();
  174.         foreach( $colors as $color ){
  175.             if( !preg_match('/^[#]{0,1}[a-f0-9]{6}$/i', $color ) )
  176.             trigger_error( sprintf( $this->_errorMsg['wrong_color'], $color ), E_USER_ERROR );
  177.           else
  178.               array_push( $this->_fontColor, $color ); 
  179.         }
  180.     }
  181.     
  182.     /**
  183.      * Automatycznie ładuje pliki czcionek
  184.      * z określonego folderu
  185.      */
  186.     function autoLoadFonts(){
  187.         $dir = dir( $this->_fontDir );
  188.     while( false !== ( $font = $dir->read() ) ){
  189.         if( strpos( strtolower( $font ), '.ttf' ) !== false )
  190.           array_push( $this->_fontFiles, $font ); 
  191.     }
  192.     $dir->close();
  193.     }
  194.     
  195.     /**
  196.      * Zwraca katalog z czcionkami
  197.      */
  198.     function getFontDir(){
  199.         return $this->_fontDir == '' ? '' : $this->_fontDir . '/';
  200.     }
  201.     
  202.     /**
  203.      * Zwraca kolor dla obrazka
  204.      * 
  205.      * @param resource $img
  206.      * @param string $color - kolor w formacie hexagonalny
  207.      * @return integer
  208.      */
  209.     function MakeColor( $img, $color ){
  210.         if( !preg_match('/^[#]{0,1}[a-f0-9]{6}$/i', $color ) )
  211.           trigger_error( sprintf( $this->_errorMsg['wrong_color'], $color ), E_USER_ERROR );
  212.           
  213.       $color = str_replace('#', '', $color);
  214.       $return = array(
  215.         'r' => hexdec(substr($color, 0, 2)),
  216.         'g' => hexdec(substr($color, 2, 2)),
  217.         'b' => hexdec(substr($color, 4, 2))
  218.       );
  219.       return imagecolorallocate( $img, $return['r'], $return['g'], $return['b']);
  220.     }
  221. }
  222.  
  223. class TokenBackground_Dots {
  224.     function process( $image, $params ){
  225.         $pts = array();
  226.       for($i = 0; $i < round($params['_width'] / 1.5); $i++)    {    
  227.         $x = rand(0, $params['_width'] );    
  228.         $y = rand(0, $params['_height'] );       
  229.     
  230.           if( !in_array( $x.'_'.$y, $pts ) ){    
  231.             imageellipse( $image, $x, $y, rand(2, 7), rand(3, 6), $params['_elemsColor'] );
  232.             $pts[] = $x.'_'.$y;    
  233.           }    
  234.           else {
  235.             $i--;    
  236.           }
  237.         }
  238.   }
  239. }
  240.  
  241. class TokenBackground_Slashes {
  242.     function process( $image, $params ){
  243.         $step = 5;
  244.         for($i = 0; $i < round($params['_width']) + ($step*10); $i+= $step)    {    
  245.         imageline( $image, $i, 0, 0, $i, $params['_elemsColor'] );
  246.         }
  247.   }
  248. }
  249.  
  250. class TokenBackground_Grid {
  251.     function process( $image, $params ){
  252.         for($i = 0; $i < round($params['_width']); $i+= 5)    {    
  253.         // poziome linie
  254.         imageline( $image, 0, $i, $params['_width'], $i, $params['_elemsColor'] );
  255.         // pionowe linie
  256.         imageline( $image, $i, 0, $i, $params['_height'], $params['_elemsColor'] );
  257.         }
  258.   }
  259. }
  260. ?>
  261. <?php
  262. $token = new Token(20, new TokenBackground_Dots );
  263. $token->getToken();
  264. ?>


do pliku i wiem ze cos zle zrobilem bo nie dziala...
Spirit86
musisz jeszcze skopiować obiekt tła:

  1. <?php
  2. /** Ładne kółeczka - zgapiłem z jakiegoś innego tokena ;) */
  3. class TokenBackground_Dots {
  4. function process( $image, $params ){
  5. $pts = array();
  6. for($i = 0; $i < round($params['_width'] / 1.5); $i++) {
  7. $x = rand(0, $params['_width'] );
  8. $y = rand(0, $params['_height'] );  
  9.  
  10. if( !in_array( $x.'_'.$y, $pts ) ){
  11. imageellipse( $image, $x, $y, rand(2, 7), rand(3, 6), $params['_elemsColor'] );
  12. $pts[] = $x.'_'.$y;
  13. }
  14. else {
  15. $i--;
  16. }
  17. }
  18. }
  19. ...
  20. ?>
Balon
Cytat
do pliku i wiem ze cos zle zrobilem bo nie dziala...

co dokładniej nie działa ?
graft
Kurczeeeee, fajnie, tylko że klasy nigdy nie były moją mocną stroną aaevil.gif

A jak zrobić porównanie czy wygenerowany token jest taki sam jak wpisany przez użytkownika?

Gdzie jest przechowywany ten token? Wydaje mnie się że sesji, ale jak wyświetlić tą SESSION? (te wszystkie this'y mnie przerażają)

------------->
Mógłby się ktoś wypowiedzieć jeszcze o bezpieczeństwie tego tokena...
Ze skryptów, które przeglądałem ten jest najbardziej wypasiony party.gif
Balon
Standardowo poprzez $_SESSION['token'] winksmiley.jpg
Sedziwoj
Na pewno wywalił bym ustawienie długości do set'a, sprawdzeie przekazywanego obiektu za is_a() (w ogóle bym przerobił na PHP5 i dodał interfejs)
A dla czego set'a bym użył a nie konstruktora? Bo jak czyta się kod od razu wiadomo co to robi, nie trzeba czytać dokumentacji, czy się domyślać.
Dodać informacje o wymaganych biblotekach, lub sprawdzenie czy są.
Np. funkcja imagettftext() wymaga jednej niestandardowej, co prawda można ją zastąpić inna, nie będzie tak ładne, ale będzie działać.
ActivePlayer
  1. <?php
  2. class TokenChecker{
  3. function checkToken($sTokenKey){
  4. if($sTokenKey==$_SESSION['token']){
  5. return true;
  6. }
  7. return false;
  8. }
  9. }
  10. TokenChecker::checkToken('wartosc z formularza');
  11. ?>

troche prowizorka, ale moze sie komus przyda jako dodadek. trzeba by to przepisac na php5, tla jako dekorator dac, configi jako static jak już, wtedy by mozna jakos lepiej ten checker napisac.
Taifun
czemu jak dam
  1. <?php
  2.  
  3. require_once( 'token.class.php' );
  4.  
  5. $token = new Token(3, new TokenBackground_Grid );
  6. $token->getToken();
  7.  
  8.  
  9. echo "gh";
  10.  
  11. ?>

to nie wyswietla mi echo a token juz tak ;/
MiFlo
Nie wyświetla Ci tego co wypisałeś bo nagłówki zostały ustawione na typ obrazka.
kacpereczek
Mam takie pytanie:
Czy moglibyście pokazać jak wstawić skrypt na stronę na której ma być pokazany? worriedsmiley.gif
.radex
Cytat(kacpereczek @ 15.08.2008, 18:21:51 ) *
Mam takie pytanie:
Czy moglibyście pokazać jak wstawić skrypt na stronę na której ma być pokazany? worriedsmiley.gif


Dwa sposoby:

1. Generujesz (tak jak pisze powyżej) obrazek i zapisujesz go do pliku. Na stronie "odpalasz" go za pomocą <img>.

2. Tworzysz php, który dynamicznie generuje obrazek (tzn. jest plikiem php, ale zachowuje się, jak by był zwykłym, statycznym obrazkiem) i także go odpalasz <img>iem na stronie.
kacpereczek
Cytat(.radex @ 15.08.2008, 22:28:26 ) *
Dwa sposoby:

1. Generujesz (tak jak pisze powyżej) obrazek i zapisujesz go do pliku. Na stronie "odpalasz" go za pomocą <img>.

2. Tworzysz php, który dynamicznie generuje obrazek (tzn. jest plikiem php, ale zachowuje się, jak by był zwykłym, statycznym obrazkiem) i także go odpalasz <img>iem na stronie.


Ale co należy zrobić, aby tekst, który jest wyświetlany na obrazku był porównywany z tym w oknie do wpisania?
.radex
hmmm...

jak masz powiedzmy obrazek o nazwie token14.jpg z treścią na przykład "abcde", to możesz gdzieś zapisać (np. w bazie danych), że ten token14 ma treść "abcde". Chodzi o to, żeby w miejscu niewidocznym dla użytkownika przypisać nazwę obrazka do jego zawartości.
kacpereczek
Bardzo poproszę o przykładowy kod, ale nie na bazie mysql, bo jej nie mam tylko na plikach txt/php.
hinduseek
Nie polecam tego zabezpieczenia na boty. Przechodzą przez to jak przez masło. Zmiana nazwy sesji nic nie daje. Może jak zmienię położenie obrazka to ich zmyli. W każdym razie na podstawowym kodzie załączonym wyżej nie warto wrzucać na stronę.
DonJeday
Dobra klasa elegancko działa, ale powiedzcie mi jak zmniejszyć czcionkę, zmniejszyć ilość wyświetlanych znaków np. do 5
hinduseek
  1. <?php
  2. $token = new Token(6, new TokenBackground_Grid, true );
  3. ?>

Gdzie 6 to ilość cyfr
crackcomm
Kod
<?php
/**
* License
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
**/
/**
* @author Krzysztof (Balon) Jagiełło <balonyo@gmail.com>
* @copyright 2007 Krzysztof Jagiełło.
* @version 1.0
*/

class Token {
    
    /** Kod na tokenie */
    var $_tokenText;

    /** Adres folderu czcionek */
    var $_fontDir = '';

    /** Nazwy czcionek */
    var $_fontFiles = array(
        'georgia.TTF'
    );

    /** Typ obrazka */
    var $_imgType = 'gif';

    /** Długość kodu na tokenie */
    var $_length;

    /** Kolor tła */
    var $_backColor = '#ffffff';

    /** Kolor czcionki */
    var $_fontColor = '#A61D09';

    /** Kolor elementów tłą */
    var $_elemsColor = '#E1E1E1';

    /** Szerokość tokena */
    var $_width;

    /** Wyskość tokena */
    var $_height = 25;

    /** Obiekt tła */
    var $_bgObject;

    /** Obrazek tokena */
    var $_image;

    /** Nazwa klucza sesji z tokenem */
    var $_tokenId = 'token';

    /** Dozwolone rozszerzenia */
    var $_allowedTypes = array(
        'gif', 'jpg', 'png'
    );


    
    /** Komunikaty błędów */
    var $_errorMsg = array(
      'wrong_color'   => 'Format koloru (%s) jest nieprawidłowy.',
      'wrong_object'  => 'Podany obiekt nie istnieje.',
      'wrong_img_type'=> 'Podany typ ("%s") jest nieprawidłowy.',
      'wrong_file'        => 'Czcionka "%s" nie istnieje .'
    );

    /**
     * Konstruktor klasy
     *
     * @param integer $length - długość tekstu na tokenie
     */
    
    function randcolor()
    {
    $r   = rand(10,195);
    $g = rand(10,195);
    $b  = rand(10,195);
    return imagecolorallocate( $this->_image, $r, $g, $b);
    }
    
    function Token( $length, $bgObject ){
        if($bgObject=='rand') {
        $Rand = rand(1,3);
        switch ($Rand) {
        case 1:
        $bgObject = new TokenBackground_Dots;
        break;
        case 2:
        $bgObject = new TokenBackground_Slashes;
        break;
        case 3:
        $bgObject = new TokenBackground_Grid;
        break;
        }
        }
        $this->_length = $length;
        $this->_tokenText = substr(md5(uniqid(time())), 0 - $length);
        $this->_width = $length * 15 + 10;
        $this->_image = imagecreate( $this->_width, $this->_height);
        if( !is_object( $bgObject ) )
          trigger_error( $this->_errorMsg['wrong_object'], E_USER_WARNING );
        $this->_bgObject = $bgObject;
    }

    /**
     * Tworzy token, zapisuje go w sesji i wyświetla.
     */
    function getToken(){
        // kolorki
        $this->_backColor = $this->MakeColor( $this->_image, $this->_backColor );
        $this->_fontColor = $this->MakeColor( $this->_image, $this->_fontColor );
        $this->_elemsColor = $this->MakeColor( $this->_image, $this->_elemsColor );

        $this->Background();
        $this->Text();

        $_SESSION[$this->_tokenId] = $this->_tokenText;

        if( !in_array( $this->_imgType, $this->_allowedTypes ) )
          trigger_error( sprintf( $this->_errorMsg['wrong_img_type'], $this->_imgType ), E_USER_ERROR );
        header( 'Content-type: image/' . $this->_imgType );
        $this->Display();
    }

    /**
     * Tworzy tekst na tokenie
     */
    function Text(){
        for($i = 0; $i < strlen($this->_tokenText); $i++){

     imagettftext( $this->_image, rand(14, 16), rand(-10, 10), rand(3, 5) + $i * 15, 18 + rand(-3, 3), $this->randcolor(), $this->getFontDir() . $this->_fontFiles[rand(0,count($this->_fontFiles)-1)], $this->_tokenText{$i});
    }
    return true;
    }

    /**
     * Tworzy tło korzystając z podanej klasy tła
     *
     * @return true
     */
    function Background(){
        $this->_bgObject->process( &$this->_image, get_object_vars( $this ) );
        return true;
    }

    /**
     * Wyświetla token w wybranym formacie
     */
    function Display(){
        if( !in_array( $this->_imgType, $this->_allowedTypes ) )
          trigger_error( sprintf( $this->_errorMsg['wrong_img_type'], $this->_imgType ), E_USER_ERROR );
        call_user_func( 'image' . $this->_imgType, $this->_image );
    }

    /**
     * Dodaje czcionki to tablicy. Są one potem losowo używane w tokenie.
     */
    function assignFonts(){
        $fonts = func_get_args();
        foreach( $fonts as $font ){
            if( !file_exists( $this->getFontDir() . $font ) )
              trigger_error( sprintf( $this->_errorMsg['wrong_file'], $font ), E_USER_ERROR );
            else
              $this->_fontsFiles[] = $font;
        }
    }

    /**
     * Zwraca katalog z czcionkami
     */
    function getFontDir(){
        return $this->_fontDir == '' ? '' : $this->_fontDir . '/';
    }

    /**
     * Zwraca kolor dla obrazka
     *
     * @param resource $img
     * @param string $color - kolor w formacie hexagonalny
     * @return integer
     */
    function MakeColor( $img, $color ){
        if( !preg_match('/^[#]{0,1}[a-f0-9]{6}$/i', $color ) )
          trigger_error( sprintf( $this->_errorMsg['wrong_color'], $color ), E_USER_ERROR );

      $color = str_replace('#', '', $color);
      $return = array(
        'r' => hexdec(substr($color, 0, 2)),
        'g' => hexdec(substr($color, 2, 2)),
        'b' => hexdec(substr($color, 4, 2))
      );
      return imagecolorallocate( $img, $return['r'], $return['g'], $return['b']);
    }
}

class TokenBackground_Dots {
    function process( $image, $params ){
        $pts = array();
      for($i = 0; $i < round($params['_width'] / 1.5); $i++)    {
        $x = rand(0, $params['_width'] );
        $y = rand(0, $params['_height'] );

          if( !in_array( $x.'_'.$y, $pts ) ){
            imageellipse( $image, $x, $y, rand(2, 7), rand(3, 6), $params['_elemsColor'] );
            $pts[] = $x.'_'.$y;
          }
          else {
            $i--;
          }
        }
  }
}

class TokenBackground_Slashes {
    function process( $image, $params ){
        $step = 5;
        for($i = 0; $i < round($params['_width']) + ($step*10); $i+= $step)    {
        imageline( $image, $i, 0, 0, $i, $params['_elemsColor'] );
        }
  }
}

class TokenBackground_Grid {
    function process( $image, $params ){
        for($i = 0; $i < round($params['_width']); $i+= 5)    {
        // poziome linie
        imageline( $image, 0, $i, $params['_width'], $i, $params['_elemsColor'] );
        // pionowe linie
        imageline( $image, $i, 0, $i, $params['_height'], $params['_elemsColor'] );
      }
  }
}

$token = new Token(6, 'rand' );
$token->getToken();
?>


Małe udoskonalenie kodu. Losuje tło oraz kolor czcionki.
smarcz
Nie wiem dlaczego ale nie zapisuje mi się do SESJI KOD który został wygenerowany na obrazku - do porównania! smile.gif

Dlaczego! Classe tokea wywołuję w pliku token.php i wstawiam go do kodu za pomocą <img src="token.php"> obok generuje pole do wpisania tokena - wyślij - sesja pusta, nie ma kodu - czemu?
skowron-line
@smarcz pokaż kod może czegoś ci brakuje
np.
  1. <?php
  2. ?>
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2024 Invision Power Services, Inc.