Skip to content

node.js socket.io: socket bakotzeko sesiñue sortu: txat-an bigarren partie

Bueno ba hamen gabiltzez node.js eta socket.io-gaz barriro be, 1go partie ikusteko hamen linke:
http://zital.hackinbadakigu.net/?p=273
functions.js:

module.exports =
{
        in_array: function (needle, haystack, argStrict)
        {
                // Checks if the given value exists in the array
                //
                // version: 1109.2015
                // discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
                // +   improved by: vlado houba
                // +   input by: Billy
                // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
                // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
                // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
                // *     returns 2: false
                // *     example 3: in_array(1, ['1', '2', '3']);
                // *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
                // *     returns 3: true
                // *     example 4: in_array(1, ['1', '2', '3'], true);
                // *     returns 4: false
                var key = '',        strict = !! argStrict;

                if (strict)
                {
                        for (key in haystack)
                        {
                                if (haystack[key] === needle)
                                {
                                        return true;
                                }
                        }
                }
                else
                {
                        for (key in haystack)
                        {
                                if (haystack[key] == needle)
                                {
                                        return true;
                                }
                        }
                }
                return false;
        }
};

server.js:

var functions = require('./functions');

var users_available = ['zital', 'hqh'];
var clients = {};

var server = require("socket.io").listen(6969);

server.sockets.on("connection", function(message)
{
        message.on("login", function(user)
        {
                if(functions.in_array(user, users_available))
                {
                        clients[message.id] = message;
                        clients[message.id].emit("isLogged");
                }
        });

        message.on("newMessage", function(data)
        {
                for(i in clients)
                        clients[i].emit("sendMessage", data);
        });

        message.on("logout", function()
        {
                var tmp = {};
                for(i in clients)
                {
                        if(i!=message.id)
                                tmp[i] = clients[i];
                }
                clients = tmp;
        });
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Online chat</title>
<style>
body
{
    color: #fff;
    background: #333;
    font-family: "Helvetica", Arial;
    font-size: 14px;
    text-align: center;
}
.container
{
    background: #ccc;
    border-radius: 1em;
    box-shadow: 0px 5px 5px rgba(0,0,0,0.5);
    text-shadow: 5px 5px 5px rgba(0,0,0,0.5);
    margin: 1em auto;
    padding: 1em;
    width: 90%;
}

input
{
    display: block;
    font-size: 12px;
    margin: 1em auto;
    padding: 0.5em;
    width: 95%;
}

span
{
    display: block;
    font-size: 12px;
    margin: 1em auto;
    padding: 0.5em;
    width: 95%;
    text-align: left;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="socket.io.js"></script>
<script type="text/javascript">
<!--
// IP PUBLIKUE IMIÑI HAMEN
var websocket = io.connect("http://10.211.252.10:6969");

$(document).on('ready', function()
{
    $('#f_user').css('display', 'none');
    $('#f_message').css('display', 'none');
    $('#login').trigger('focus');

    websocket.on("isLogged", function()
    {        
        var login = $('#login');
        var user = login.val();

        $('#f_user > label').html('welcome: '+user);        

        $('#f_user').css('display', 'block');
        $('#f_message').css('display', 'block');
        $('#f_login').css('display', 'none');

        $('#message').trigger('focus');
    });

    websocket.on("sendMessage", function(data)
    {
        var chat = $('#zchat');
        var span = $('<span>'+data+'</span>');

        if (chat.children().length > 0 )
            chat.find(">:first-child").before(span);
        else
            chat.append(span);
    });

    $('#f_user').on('submit', function(e)
    {
        e.preventDefault();
        websocket.emit("logout", {});
        $('#f_user').css('display', 'none');
        $('#f_message').css('display', 'none');
        $('#f_login').css('display', 'block');
    });    

    $('#f_login').on('submit', function(e)
    {
        e.preventDefault();
        websocket.emit("login", $('#login').val());        
    });       

    $('#f_message').on('submit', function(e)
    {
        e.preventDefault();
        websocket.emit("newMessage", $('#message').val());
        $('#message').val('');
        $('#message').trigger('focus');
    });    
});
//-->
</script>
</head>
<body>
<div>
    <form id="f_user">
        <label></label>
        <input type="submit" value="logout" />
    </form>
    <form id="f_login">
        <label>login: </label>
        <input type="text" name="login" id="login" required />
        <input type="submit" />
    </form>
    <form id="f_message">
        <label>Message: </label>
        <input type="text" name="message" id="message" required />
        <input type="submit" />
    </form>
</div>
<div id="zchat">
</div>
</body>
</html>

socket.io.js:
http://pastebin.com/shJTm0JE

Oin martxan imintzeko:
server.js eta functions.js path bardiñen on bidiez, eta index.html eta socket.io.js bebai :)

node server.js

eta nabegadoretik index.html igiri

Non dau trukue? clients bariablien barruen sartutiegaz konektaten dizen erabiltzailiek, ta gero logout einkeran bertatik kendu.

Tagged , , , , ,

php: reflection bidez metodo dinamikuek erabili

php-ntzako reflection API-dxe erabilitze, al’tzagu dinamismue emon geure programari, adibidez metodo dinamikueri deitsu, jakin barik ze motatako metodue dan, adibidez:

<?php
$class = 'a';
$method = 'b';
$params = array('d' => 'e');

// klasie existiten badan
if(class_exists($class))
{
        // metodue existiten badan
        if(method_exists($class, $method))
        {
                // reflection objetue sortu
                $reflection = new ReflectionMethod($class, $method);
                // metodue estatikue badan
                if($reflection->isStatic())
                {
                        $f = $class."::".$method;
                        $result = call_user_func($f, $params);
                }
                // metodue publikue badan leleu klasien instantzidxe sortu bi'de
                elseif($reflection->isPublic())
                {
                        $instance = new $class();
                        $result = $instance->$method($params);
                }
        }
}
if(isset($result))
{
        echo "<pre>";
        print_r($result);
        echo "</pre>";
}

class a
{
        public static function b($params = NULL)
        {
                return array('b' => $params);
        }
        public function c($params = NULL)
        {
                return array('c' => $params);
        }
}
?>

Erantzune:
<pre>Array                                                 
(                                                        
    [b] => Array                                                                                                                                                                   
        (                                                                                                                                                                          
            [d] => e                                                                                                      
        )                                                        
)                                                        
</pre>

Oin metodue ‘c’ imindxe:

$method = 'c';

Erantzune:

<pre>Array                                                 
(                                                        
    [c] => Array                                                                                                                                                                   
        (                                                                                                                                                                          
            [d] => e                                                                                                      
        )                                                        
)                                                        
</pre>

Gauze gidxau al diez egin, horretarako leidu RELECTION PHP API-dxe :)

Tagged , , , , , , ,

ftp: binary vs ascii – checksum vs checksum

Zelan emon lei artxibo bardiñen checksum-ek ezberdin?

# binaidxo
md5sum -b config.xml
263fe7751b96df9fc94fa4d6af2cfbb7 *config.xml
# texto moduen
md5sum -t config.xml
263fe7751b96df9fc94fa4d6af2cfbb7 *config.xml
# binaidxo
md5sum -b config.xml.bak
e96f4aa7b3a207778b904780db8d141f *config.xml.bak
# texto moduen
md5sum -t config.xml.bak
e96f4aa7b3a207778b904780db8d141f *config.xml.bak

Sistema bakotzak beran “enter“-ak sortuten dauzelako kontuz okin biher da FTP bidez BINARY edo ASCII moduen gauzek botatiegaz:

file config.xml
config.xml: UTF-8 Unicode text

file config.xml.bak
config.xml.bak: UTF-8 Unicode text, with CRLF line terminators

Ikusten dan moduen ezta bardiñe FTP bidez ASCII moduen edo BINARY moduen botatie, holakorik ez pasateko bota beti BINARY moduen duderik dakozuieniko :)

Tagged , , , , ,

debian: proxy anonimo bat sortu squid-egaz

Programaziño bidezko soluziñuek ibil nai topaten baie ez dot topa ezer dezenterik, orduen proxy bet montaten anime nai, batzuk lagunek dakuzelako internet zentsureten dauien herrialdietan, ta honegaz ba aukerie dakoie oingoz geuretzako askie dan internet erabiltzeko ;)

su
aptitude install squid apache2-utils
cd /etc/squid
mv squid.conf squid.conf.bak
nano squid.conf

squid.conf

# portue, baporana ez eh :D
http_port 8080
# autentifikaziño metodue eta ze artxibo erabili
auth_param basic program /usr/lib/squid/ncsa_auth /etc/squid/users
# "password" izeneko filtrue sortu esaten password-a eskatuteko
acl password proxy_auth REQUIRED
# "all" izeneko filtro bat sortu
acl all src 0.0.0.0/0.0.0.0
# "all" filtrueri esan user/passwd eskatuteko
http_access allow all password
#anonimotasune emoteko
forwarded_for off

Oin users artxibue sortu eta baimenak emon pasahitzek bertan gordeteko, horretarako apache-n htpasswd erabilku

htpasswd -c users usuaidxue
chmod 0644 users

/etc/init.d/squid restart
exit

Gero nabegadoran, adibidez firefox-en:

Edit -> Preferences -> Advanced -> Network

http://i.imgur.com/xiBM5.png

Ba betikulez IP aldatu ;)

Gero nabegakeran eskatukosku usuaidxue eta password-a, sartun ta abante!!!

Tagged , , , ,

php array multi-dimensional bat python dict bihurtu

Ba hamen gabilz barriro python-egaz pellikan, oingutan php-tik curl bidez botaku array multi-dimensional bat post edo get bidez eta python-egaz hartun.

Okin biharrekuek: python, web zerbitzaridxe php-gaz eta cgi-gaz

Paketiek instala:

su
aptitude install python-pip php5-curl
pip install querystring-parser
exit

curl.class.php artxibue:

<?php
class curl
{
	public static function getURL($url, $params = array(), $type = 'get', $curl_opts = array())
	{
		if(!function_exists('curl_init'))
			die('curl module missing');				

		$type = trim(strtolower($type));
		if(is_array($params) && count($params)>0)
			$params = self::setParams($params);

		$ch = curl_init();				

		if($type=='post')
		{
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
			curl_setopt($ch, CURLOPT_URL, $url);
		}
		else
			curl_setopt($ch, CURLOPT_URL, $url.$params);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

		// set curl param options
		if(is_array($curl_opts))
		{
			if(count($curl_opts)>0)
			{
				foreach($curl_opts as $key => $value)
					curl_setopt($ch, $key, $value);
			}
		}
		$result = curl_exec($ch);
		return $result;
	}

	public static function setParams($array, $type = 'get')
	{
		$txt = '';
		if(count($array)>0)
		{
			if($type=='get')
				$txt.= '?';
			$txt.= http_build_query($array);
		}
		return $txt;
	}
}
?>

index.php artxibue:

<?php
include('curl.class.php');

$vars = array
(
	'aitxitxe' => array
	(
		'aita' => array
		(
			'semie' => 'iban',
			'alabie' => 'maite'
		)
	)
);

echo curl::getUrl('http://localhost/python/request.py', $vars);
?>

oin python-en partie: request.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, cgi

# request parametruek hartu eta dic baten barruen sartu

params = {}
form = cgi.FieldStorage()

for k in form.keys():
    params[k] = form[k].value

print "Content-type: text/plain\n"
print params

sys.exit()

oin guez: http://localhost/index.php -ra eta hau da erantzune:

{
  'aitxitxe[aita][semie]': 'iban',
  'aitxitxe[aita][alabie]': 'maite'
}

oops, ikusten dun moduen sortu den dict-e ezta multi-dimentsionala unidimentsionala baño, hori konponduteko erabilku: querystring-parser

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, cgi
from querystring_parser import parser

# request parametruek hartu eta dic baten barruen sartu

params = {}
form = cgi.FieldStorage()

for k in form.keys():
    params[k] = form[k].value

# dict -e query-string-era pasateko funtziñue

def dict2querystring(dict):
    text = ''
    count = 0
    for i in dict:
        if count > 0:
            text+= "&"
        text+= str(i) + "=" + str(dict[i])
        count += 1
    return text

# request parametruek query-string-era pasa

params_text = dict2querystring(params)

# query-string-e dict-era pasa

post_dict = parser.parse(params_text)

print "Content-type: text/plain\n"
print post_dict

sys.exit()

Eta oingo erantzune, oin bai :)

{
  'aitxitxe':
  {
    'aita':
    {
      'alabie': 'maite',
      'semie': 'iban'
    }
  }
}

Eskerrak: http://stackoverflow.com/questions/1890013/django-python-is-there-a-simple-way-to-convert-php-style-bracketed-post-keys-t

Tagged , , , , , , , , ,

php: namespace -n erabilerien adibide bat

namespace -k klasiek kapsuleteko erabiltzen da, adibidez izen bardiñeko klasiek erabiltzeko baie erabilera ezberdiñetarako, php-n 5.3-tik aurrera erabili lei:

namespace adibidie

Ikusten dun moduen izen bardiñeko klasiek dakuz, zelan erabili?

lib/login.class.php

<?php
namespace lib;
class login
{
    public function __construct()
    {
        echo "lib: login\n";
    }
}
?>

mvc/model/login.class.php

<?php
namespace model;
require_once('lib/login.class.php');

class login
{
    public function __construct()
    {
        $login = new \lib\login();
        echo "model: login\n";
    }
}
?>

mvc/controller/login.class.php

<?php
namespace controller;
require_once('mvc/model/login.class.php');

class login
{
    public function __construct()
    {
        $login = new \model\login();
        echo "controller: login\n";
    }
}
?>

index.php

<?php
require_once('mvc/controller/login.class.php');
header("Content-Type:text/plain");
$login = new \controller\login();
?>

Zelan deitsu core-ko klasieri?

lib/login.class.php

<?php
namespace lib;
class login
{
    public function __construct()
    {
        echo "lib: login\n";
        new DOMDocument();
    }
}
?>

ERRORIE:

PHP Fatal error:  Class 'lib\\DOMDocument' not found in lib/login.class.php on line 8

Hau konponduteko \ bat sartun hasikeratan:

lib/login.class.php

<?php
namespace lib;
class login
{
    public function __construct()
    {
        echo "lib: login\n";
        new \DOMDocument();
    }
}
?>

index.php nabegatzailien:

lib: login
model: login
controller: login
Tagged , , , ,

debian / python: sqlalchemy -gaz oracle -ra konekta

Paketiek instala:

su
aptitude install python-sqlalchemy alien libaio1
exit

Jakitzeko ze bertsiño dakun python-ena:

python -V

erantzune:

Python 2.7.2+

Jakitzeko oracle-n bertsiñue:

select * from product_component_version;

erantzune:

NLSRTL                                  11.2.0.2.0 Production
Oracle Database 11g Enterprise Edition  11.2.0.2.0 64bit Production
PL/SQL                                  11.2.0.2.0 Production
TNS for 64-bit Windows:                 11.2.0.2.0 Production

Nire kasuen: python 2.7 eta oracle 11.2

Orduen hurrengo web-an topa biherku paketie:

http://cx-oracle.sourceforge.net/

Nire kasuen: “Download 5.1.1 released October 10, 2011″ atalien:

CentOS 5 x86_64 RPM (Oracle 11g, Python 2.7)

RPM-ie DEB-era pasateko:

su
alien -d cx_Oracle-5.1-11g-py27-1.x86_64.rpm
ls | grep .deb$
cx-oracle_5.1-2_amd64.deb

paketie instala

dpkg -i cx-oracle_5.1-2_amd64.deb
ln -s /usr/lib/python2.7/site-packages/cx_Oracle.so /usr/lib/python2.7/dist-packages/cx_Oracle.so
exit

Adibide script bet sortu

nano proba.py

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from sqlalchemy import create_engine

connection = create_engine('oracle://USER:PASSWD@IP:PORT/DDBB').connect()

result = connection.execute("select * from product_component_version")
for v in result:
  for column, value in v.items():
    print('{0}: {1}'.format(column, value))

connection.close()

Baimenak emon al izateko igiri eta ejekute:

chmod +x proba.py
./proba.py

ERROR:

ImportError: /usr/lib/python2.7/dist-packages/cx_Oracle.so: undefined symbol:PyUnicodeUCS2_AsEncodedString

Bueno hori errorie ez urteteko beste pakete bat instala dot:

“Download 5.1 released March 19, 2011″ ataleko:
CentOS 5 x86_64 RPM (Oracle 11g, Python 2.7)

Desinstalateko:

su
aptitude purge cx-oracle
rm -rf /usr/lib/python2.7/dist-packages/cx_Oracle.so
exit

eta lengo pausuek jarraitu ;)

adibide onan erantzune:

product: NLSRTL
version: 11.2.0.2.0
status: Production
product: Oracle Database 11g Enterprise Edition
version: 11.2.0.2.0
status: 64bit Production
product: PL/SQL
version: 11.2.0.2.0
status: Production
product: TNS for 64-bit Windows:
version: 11.2.0.2.0
status: Production
Tagged , , ,

debian: node.js eta socket.io-gaz txat bat egin

node.js instalateko oin momentutan SID-en dau :)

su
aptitude install nodejs npm
exit
npm install socket.io
nano server.js
var server = require("socket.io").listen(6969);

server.sockets.on("connection", function(message)
{
	message.on("newMessage", function(data)
	{
		server.sockets.emit("sendEvent", data);
	});
});
nano index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Online chat</title>
<style>
body
{
	color: #333;
	background: #333;
	font-family: "Helvetica", Arial;
	font-size: 14px;
	text-align: center;
}
.container
{
	background: #ccc;
	border-radius: 1em;
	box-shadow: 0px 5px 5px rgba(0,0,0,0.5);
	text-shadow: 5px 5px 5px rgba(0,0,0,0.5);
	margin: 1em auto;
	padding: 1em;
	width: 90%;
}

input
{
	display: block;
	font-size: 12px;
	margin: 1em auto;
	padding: 0.5em;
	width: 95%;
}

span
{
	display: block;
	font-size: 12px;
	margin: 1em auto;
	padding: 0.5em;
	width: 95%;
	text-align: left;
}
</style>
<script src="http://clab.nodester.com/socket.io/socket.io.js"></script>
<script type="text/javascript">
<!--
// IP PUBLIKUE IMIÑI HAMEN
var websocket = io.connect("http://192.168.100.103:6969");

window.onload = function()
{
	websocket.on("sendEvent", function(data)
	{
		var chat = document.getElementById('zchat');
		var span = document.createElement('span');
		var txt = document.createTextNode(data);
		span.appendChild(txt);
		if(chat.hasChildNodes())
			chat.insertBefore(span, chat.firstChild);
		else
			chat.appendChild(span);
	});

	var form = document.getElementById('zform');
	var message = document.getElementById('zmessage');
	form.onsubmit = function(e)
	{
		websocket.emit("newMessage", message.value);
		message.value = '';
		return false;
	};

	message.value = '';
	message.focus();
};
//-->
</script>
</head>
<body>
<div class="container">
<form id="zform">
	<label>Message: </label>
	<input type="text" name="zmessage" id="zmessage" placeholder="Please insert message" required />
	<input type="submit" />
</form>
</div>
<div id="zchat" class="container">
</div>
</body>
</html>

Zerbitzaridxe abante imiñi:

node server.js

Eta oin nabegatzailien igiri index.html eta hasi sartzien mensajiek :)

Eskerrak: Curso de Node.js, Websockets y HTML5 de #mejorandola

Edit: Antza adibideko socket.io.js ezta existiten, bueno geure sistemako socket.io.js imintzeko:

find / | grep socket.io.js

erantzunen adibidie:

/home/zital/.node_libraries/.npm/socket.io-client/0.8.7/package/dist/socket.io.js
/home/zital/.node_libraries/.npm/.cache/socket.io-client/0.8.7/package/dist/socket.io.js
/home/zital/.node_libraries/.npm/.cache/socket.io/0.8.7/package/lib/socket.io.js
/home/zital/.node_libraries/.npm/socket.io/0.8.7/package/lib/socket.io.js

kopidxe horretariko edozein index.html dakozuien karpetara eta listo :), gero html-ien hau aldatu


Tagged , , , , , , ,

debian: php oracle-ntzako pdo modulue instala

Bueno ba goiz guztidxe ogon dast hau popatik emoten baie azkanien atara dot, guzan ba:

1.go gauzie okinbidena kontuten, non dakozuien oracle instalata, dana dala hau post-a elegante etorko datzuie: php + oci8 Oracle bezero (kliente) moduen imintzeko gnu/linux-en

Neure kasuen: /opt/oracle-instantclient-11-2 karpetan dakot dana.

ls -l /opt/oracle-instantclient-11-2

-rwxr-xr-x 1 zital zital    25588 abu 15  2009 adrci
-rw-r--r-- 1 zital zital      439 abu 15  2009 BASIC_README
-rwxr-xr-x 1 zital zital    44963 abu 15  2009 genezi
-r--r--r-- 1 zital zital      342 abu 15  2009 glogin.sql
-rwxr-xr-x 1 zital zital 48797739 abu 15  2009 libclntsh.so
lrwxrwxrwx 1 zital zital       12 abe  2 10:47 libclntsh.so.11.1 -> libclntsh.so
-r-xr-xr-x 1 zital zital  7899997 abu 15  2009 libnnz11.so
-rwxr-xr-x 1 zital zital  1261302 abu 15  2009 libocci.so.11.1
-rwxr-xr-x 1 zital zital 89382994 abu 15  2009 libociei.so
-r-xr-xr-x 1 zital zital   165157 abu 15  2009 libocijdbc11.so
-r-xr-xr-x 1 zital zital  1504295 abu 15  2009 libsqlplusic.so
-r-xr-xr-x 1 zital zital  1470768 abu 15  2009 libsqlplus.so
-rw-r--r-- 1 zital zital   472664 urt 14  2010 oci8.so
-r--r--r-- 1 zital zital  1996228 abu 15  2009 ojdbc5.jar
-r--r--r-- 1 zital zital  2111220 abu 15  2009 ojdbc6.jar
drwxr-xr-x 4 zital zital     4096 abu 15  2009 sdk
-r-xr-xr-x 1 zital zital     9320 abu 15  2009 sqlplus
-rw-r--r-- 1 zital zital      443 abu 15  2009 SQLPLUS_README
-rw-r--r-- 1 zital zital     8220 abe  2 11:09 tnsnames.ora
-rw-r--r-- 1 iban iban    37807 abu 15  2009 xstreams.jar
ls -l /opt/oracle-instantclient-11-2/sdk/include

-r-xr-xr-x 1 zital zital  42534 abu 15  2009 ldap.h
-r--r--r-- 1 zital zital  34157 abu 15  2009 nzerror.h
-r--r--r-- 1 zital zital  74787 abu 15  2009 nzt.h
-r--r--r-- 1 zital zital  11586 abu 15  2009 occiAQ.h
-r--r--r-- 1 zital zital  34750 abu 15  2009 occiCommon.h
-r--r--r-- 1 zital zital  70685 abu 15  2009 occiControl.h
-r--r--r-- 1 zital zital  39751 abu 15  2009 occiData.h
-r--r--r-- 1 zital zital   2115 abu 15  2009 occi.h
-r--r--r-- 1 zital zital  24778 abu 15  2009 occiObjects.h
-r-xr-xr-x 1 zital zital   7203 abu 15  2009 oci1.h
-r--r--r-- 1 zital zital  10361 abu 15  2009 oci8dp.h
-r--r--r-- 1 zital zital 431290 abu 15  2009 ociap.h
-r-xr-xr-x 1 zital zital   6204 abu 15  2009 ociapr.h
-r--r--r-- 1 zital zital  43001 abu 15  2009 ocidef.h
-r-xr-xr-x 1 zital zital   4048 abu 15  2009 ocidem.h
-r--r--r-- 1 zital zital  11339 abu 15  2009 ocidfn.h
-r--r--r-- 1 zital zital   8953 abu 15  2009 ociextp.h
-r--r--r-- 1 zital zital 170958 abu 15  2009 oci.h
-r-xr-xr-x 1 zital zital   6494 abu 15  2009 ocikpr.h
-r--r--r-- 1 zital zital   4670 abu 15  2009 ocixmldb.h
-r--r--r-- 1 zital zital  94528 abu 15  2009 ocixstream.h
-r--r--r-- 1 zital zital  23266 abu 15  2009 odci.h
-r-xr-xr-x 1 zital zital   6540 abu 15  2009 oratypes.h
-r--r--r-- 1 zital zital  15083 abu 15  2009 orid.h
-r--r--r-- 1 zital zital 102775 abu 15  2009 ori.h
-r--r--r-- 1 zital zital 157901 abu 15  2009 orl.h
-r--r--r-- 1 zital zital  42626 abu 15  2009 oro.h
-r--r--r-- 1 zital zital 116645 abu 15  2009 ort.h
-r-xr-xr-x 1 zital zital   9892 abu 15  2009 xa.h

Zeuok jakitzeko zer koño dakoten karpetan barruen ;)

Abante!!!

su
cd /usr/src
pecl download pdo_oci
tar -zxvf PDO_OCI-1.0.tgz
cd PDO_OCI-1.0
phpize

Nahiz eta 11.2 okin, 10.2-rarte dau preparata konpileteko script-e, orduen haulan ezango lekide konpilaziñoko katie:

./configure --with-pdo-oci=instantclient,/opt/oracle-instantclient-11-2,10.2

ERROR!!!!

"checking for oci.h... configure: error: I'm too dumb to figure out where the include dir is in your instant client install"

Bueno hasi gara, config.m4 edite biherku:

nano config.m4

topa hau katie:

nl $Id: config.m4,v 1.14.2.1 2005/09/24 23:23:24 sniper Exp $

if test "$PHP_PDO" != "no"; then

eta haunegaizik aldatu:

nl $Id: config.m4,v 1.14.2.1 2005/09/24 23:23:24 sniper Exp $

Z_INCLUDE=/opt/oracle-instantclient-11-2/sdk/include

if test "$PHP_PDO" != "no"; then

eta beste hau be topa:

  if test "instantclient" = "`echo $PDO_OCI_DIR | cut -d, -f1`" ; then
    PDO_OCI_IC_PREFIX="`echo $PDO_OCI_DIR | cut -d, -f2`"
    PDO_OCI_IC_VERS="`echo $PDO_OCI_DIR | cut -d, -f3`"
    AC_MSG_CHECKING([for oci.h])
    if test -f $PDO_OCI_IC_PREFIX/include/oracle/$PDO_OCI_IC_VERS/client/oci.h ; then
      PHP_ADD_INCLUDE($PDO_OCI_IC_PREFIX/include/oracle/$PDO_OCI_IC_VERS/client)
      AC_MSG_RESULT($PDO_OCI_IC_PREFIX/include/oracle/$PDO_OCI_IC_VERS/client)
    elif test -f $PDO_OCI_IC_PREFIX/lib/oracle/$PDO_OCI_IC_VERS/client/include/oci.h ; then
      PHP_ADD_INCLUDE($PDO_OCI_IC_PREFIX/lib/oracle/$PDO_OCI_IC_VERS/client/include)
      AC_MSG_RESULT($PDO_OCI_IC_PREFIX/lib/oracle/$PDO_OCI_IC_VERS/client/include)
    elif test -f $PDO_OCI_IC_PREFIX/lib/oracle/$PDO_OCI_IC_VERS/client/include/oci.h ; then
      PHP_ADD_INCLUDE($PDO_OCI_IC_PREFIX/lib/oracle/$PDO_OCI_IC_VERS/client/include)
      AC_MSG_RESULT($PDO_OCI_IC_PREFIX/lib/oracle/$PDO_OCI_IC_VERS/client/include)
    else
      AC_MSG_ERROR([I'm too dumb to figure out where the include dir is in your instant client install])
    fi

eta haunegaitzik aldatu:

  if test "instantclient" = "`echo $PDO_OCI_DIR | cut -d, -f1`" ; then
    PDO_OCI_IC_PREFIX="`echo $PDO_OCI_DIR | cut -d, -f2`"
    PDO_OCI_IC_VERS="`echo $PDO_OCI_DIR | cut -d, -f3`"
    AC_MSG_CHECKING([for oci.h])
    if test -f $PDO_OCI_IC_PREFIX/include/oracle/$PDO_OCI_IC_VERS/client/oci.h ; then
      PHP_ADD_INCLUDE($PDO_OCI_IC_PREFIX/include/oracle/$PDO_OCI_IC_VERS/client)
      AC_MSG_RESULT($PDO_OCI_IC_PREFIX/include/oracle/$PDO_OCI_IC_VERS/client)
    elif test -f $PDO_OCI_IC_PREFIX/lib/oracle/$PDO_OCI_IC_VERS/client/include/oci.h ; then
      PHP_ADD_INCLUDE($PDO_OCI_IC_PREFIX/lib/oracle/$PDO_OCI_IC_VERS/client/include)
      AC_MSG_RESULT($PDO_OCI_IC_PREFIX/lib/oracle/$PDO_OCI_IC_VERS/client/include)
    elif test -f $PDO_OCI_IC_PREFIX/lib/oracle/$PDO_OCI_IC_VERS/client/include/oci.h ; then
      PHP_ADD_INCLUDE($PDO_OCI_IC_PREFIX/lib/oracle/$PDO_OCI_IC_VERS/client/include)
      AC_MSG_RESULT($PDO_OCI_IC_PREFIX/lib/oracle/$PDO_OCI_IC_VERS/client/include)
    elif test -f $Z_INCLUDE/oci.h ; then
      PHP_ADD_INCLUDE($Z_INCLUDE)
      AC_MSG_RESULT($Z_INCLUDE)
    else
      AC_MSG_ERROR([I'm too dumb to figure out where the include dir is in your instant client install])
    fi

bueno barriro intenta’ku:

phpize
./configure --with-pdo-oci=instantclient,/opt/oracle-instantclient-11-2,10.2

ERROR!!!!

"configure: error: Cannot find php_pdo_driver.h."

Konponduteko:

find / | grep php_pdo_driver.h

erantzune-n adibidie:

/usr/include/php5/ext/pdo/php_pdo_driver.h

konpilaziñoko fitxerue aldatu’ku: configure

nano configure

hau topa:

    if test -f $abs_srcdir/include/php/ext/pdo/php_pdo_driver.h; then
      pdo_inc_path=$abs_srcdir/ext
    elif test -f $abs_srcdir/ext/pdo/php_pdo_driver.h; then
      pdo_inc_path=$abs_srcdir/ext
    elif test -f $prefix/include/php/ext/pdo/php_pdo_driver.h; then
      pdo_inc_path=$prefix/include/php/ext
    fi

eta haunegaitzik aldatu:

    if test -f /usr/include/php5/ext/pdo/php_pdo_driver.h; then
      pdo_inc_path=/usr/include/php5/ext/pdo
    elif test -f $abs_srcdir/ext/pdo/php_pdo_driver.h; then
      pdo_inc_path=$abs_srcdir/ext
    elif test -f $prefix/include/php/ext/pdo/php_pdo_driver.h; then
      pdo_inc_path=$prefix/include/php/ext
    fi

ia barriro intenta’ku ia…

./configure --with-pdo-oci=instantclient,/opt/oracle-instantclient-11-2,10.2

ERROR!!!!!

/usr/bin/ld: cannot find -lclntsh

ia konponduteko:

find / | grep libclntsh.so

erantzune-n adibidie:

/usr/local/lib/libclntsh.so.11.1
/usr/lib/libclntsh.so.11.1

konponduteko enlaze sinbolikuek sortu’kuz:

ln -s /usr/local/lib/libclntsh.so.11.1 /usr/local/lib/libclntsh.so
ln -s /usr/lib/libclntsh.so.11.1 /usr/lib/libclntsh.so

eta barriro intenta:

./configure --with-pdo-oci=instantclient,/opt/oracle-instantclient-11-2,10.2

Ondo in badauen:

make clean
make
make install
echo "extension=pdo_oci.so" > /etc/php5/conf.d/pdo_oci.ini
/etc/init.d/apache2 restart

Probateko kodigue:

<?php
$tns = "
(DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.0.1)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = EITBCOM)
    )
  )
       ";
$db_username = 'USER';
$db_password = 'PASSWD';
try
{
    $conn = new PDO("oci:dbname=".$tns, $db_username, $db_password);
	echo 'yeah';
}
catch(PDOException $e)
{
    echo ($e->getMessage());
}
?>
Tagged , , , , , , ,

php: recaptcha klase bihurtute

Eztaitz iñoiz recaptcha-gaz inbazuien bihar baie funtziño sueltuekaz bihar eitzie ez dast gustaten bapez eta klase batera pasa dot:

recaptcha.class.php

<?php
/*
* This is a PHP library that handles calling reCAPTCHA.
*    - Documentation and latest version
*          http://recaptcha.net/plugins/php/
*    - Get a reCAPTCHA API Key
*          https://www.google.com/recaptcha/admin/create
*    - Discussion group
*          http://groups.google.com/group/recaptcha
*
* Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
* AUTHORS:
*   Mike Crawford
*   Ben Maurer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

class recaptcha
{
  const RECAPTCHA_API_SERVER = 'http://www.google.com/recaptcha/api';
  const RECAPTCHA_API_SECURE_SERVER = 'https://www.google.com/recaptcha/api';

  const RECAPTCHA_VERIFY_SERVER = 'www.google.com';

  public $publickey;
  public $privatekey;

  private $error;

  /**
  * Encodes the given data into a query string format
  * @param $data - array of string elements to be encoded
  * @return string - encoded request
  */
  private function _recaptcha_qsencode($data)
  {
    $req = "";
    foreach ($data as $key => $value)
      $req .= $key . '=' . urlencode(stripslashes($value)) . '&';

    // Cut the last '&'
    $req = substr($req, 0, strlen($req) - 1);
    return $req;
  }

  /**
  * Submits an HTTP POST to a reCAPTCHA server
  * @param string $host
  * @param string $path
  * @param array $data
  * @param int port
  * @return array response
  */
  private function _recaptcha_http_post($host, $path, $data, $port = 80)
  {
    $req = $this -> _recaptcha_qsencode($data);

    $http_request = "POST $path HTTP/1.0\r\n";
    $http_request .= "Host: $host\r\n";
    $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
    $http_request .= "Content-Length: " . strlen($req) . "\r\n";
    $http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
    $http_request .= "\r\n";
    $http_request .= $req;

    $response = '';
    if (false == ($fs = @fsockopen($host, $port, $errno, $errstr, 10)))
      die('Could not open socket');

    fwrite($fs, $http_request);

    while (!feof($fs))
      $response .= fgets($fs, 1160);

    // One TCP-IP packet
    fclose($fs);
    $response = explode("\r\n\r\n", $response, 2);

    return $response;
  }

  /**
  * Gets the challenge HTML (javascript and non-javascript version).
  * This is called from the browser, and the resulting reCAPTCHA HTML widget
  * is embedded within the HTML form it was called from.
  * @param string $pubkey A public key for reCAPTCHA
  * @param string $error The error given by reCAPTCHA (optional, default is null)
  * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)

  * @return string - The HTML to be embedded in the user's form.
  */
  public function get_html($use_ssl = false)
  {
    $pubkey = $this -> publickey;

    if ($pubkey == null || $pubkey == '')
      die("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");

    if ($use_ssl)
      $server = self::RECAPTCHA_API_SECURE_SERVER;
    else
      $server = self::RECAPTCHA_API_SERVER;

    $errorpart = "";
    if ($this -> error)
      $errorpart = "&amp;error=" . $this -> error;

    return '<script type="text/javascript" src="' . $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
    <noscript>
    <iframe src="' . $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
    <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
    <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
    </noscript>';
  }

  /**
  * Calls an HTTP POST function to verify if the user's guess was correct
  * @param string $privkey
  * @param string $remoteip
  * @param string $challenge
  * @param string $response
  * @param array $extra_params an array of extra variables to post to the server
  * @return ReCaptchaResponse
  */
  public function check_answer($remoteip, $challenge, $response, $extra_params = array())
  {
    $this -> resetError();
    $privkey = $this -> privatekey;

    if ($privkey == null || $privkey == '')
      die("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");

    if ($remoteip == null || $remoteip == '')
      die("For security reasons, you must pass the remote ip to reCAPTCHA");

    //discard spam submissions
    if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0)
    {
      $this -> error = 'incorrect-captcha-sol';
      return false;
    }

    $response = $this -> _recaptcha_http_post(self::RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify", array('privatekey' => $privkey, 'remoteip' => $remoteip, 'challenge' => $challenge, 'response' => $response) + $extra_params);

    $answers = explode("\n", $response[1]);

    if (trim($answers[0]) == 'true')
      return true;
    else
      $this -> error = $answers[1];
    return false;
  }

  /**
  * gets a URL where the user can sign up for reCAPTCHA. If your application
  * has a configuration page where you enter a key, you should provide a link
  * using this function.
  * @param string $domain The domain where the page is hosted
  * @param string $appname The name of your application
  */
  private function recaptcha_get_signup_url($domain = null, $appname = null)
  {
    return "https://www.google.com/recaptcha/admin/create?" . $this -> _recaptcha_qsencode(array('domains' => $domain, 'app' => $appname));
  }

  private function _recaptcha_aes_pad($val)
  {
    $block_size = 16;
    $numpad = $block_size - (strlen($val) % $block_size);
    return str_pad($val, strlen($val) + $numpad, chr($numpad));
  }

  /* Mailhide related code */

  private function _recaptcha_aes_encrypt($val, $ky)
  {
    if (!function_exists("mcrypt_encrypt"))
      die("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");

    $mode = MCRYPT_MODE_CBC;
    $enc = MCRYPT_RIJNDAEL_128;
    $val = $this -> _recaptcha_aes_pad($val);
    return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
  }

  private function _recaptcha_mailhide_urlbase64($x)
  {
    return strtr(base64_encode($x), '+/', '-_');
  }

  /* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
  public function mailhide_url($email)
  {
    $pubkey = $this -> publickey;
    $privkey = $this -> privatekey;

    if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null)
      die("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " . "you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");

    $ky = pack('H*', $privkey);
    $cryptmail = $this -> _recaptcha_aes_encrypt($email, $ky);

    return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . $this -> _recaptcha_mailhide_urlbase64($cryptmail);
  }

  /**
  * gets the parts of the email to expose to the user.
  * eg, given johndoe@example,com return ["john", "example.com"].
  * the email is then displayed as john...@example.com
  */
  private function _recaptcha_mailhide_email_parts($email)
  {
    $arr = preg_split("/@/", $email);

    if (strlen($arr[0]) <= 4)
      $arr[0] = substr($arr[0], 0, 1);
    else if (strlen($arr[0]) <= 6)
      $arr[0] = substr($arr[0], 0, 3);
    else
      $arr[0] = substr($arr[0], 0, 4);

    return $arr;
  }

  /**
  * Gets html to display an email address given a public an private key.
  * to get a key, go to:
  *
  * http://www.google.com/recaptcha/mailhide/apikey
  */
  public function mailhide_html($email)
  {
    $pubkey = $this -> publickey;
    $privkey = $this -> privatekey;

    $emailparts = $this -> _recaptcha_mailhide_email_parts($email);
    $url = $this -> mailhide_url($pubkey, $privkey, $email);

    return htmlentities($emailparts[0]) . "<a href='" . htmlentities($url) . "' onclick=\"window.open('" . htmlentities($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>@" . htmlentities($emailparts[1]);
  }

  private function resetError()
  {
    $this -> error = NULL;
  }

  public function getError()
  {
    if ($this -> error)
      return $this -> error;
    return false;
  }
}
?>

probateko:
recaptcha.example.php

<?php
require_once('recaptcha.class.php');

$captcha = new recaptcha();
$captcha->privatekey = 'PRIVATEKEY';
$captcha->publickey = 'PUBLICKEY';

if ($_POST["recaptcha_response_field"])
{
  $resp = $captcha->check_answer
  (
    $_SERVER["REMOTE_ADDR"],
    $_POST["recaptcha_challenge_field"],
    $_POST["recaptcha_response_field"]
  );

  if ($resp)
    echo "You got it!";
  else
    echo $captcha->getError();
}
?>
<html>
<body>
<form action="" method="post">
<br/>
<?php
echo $captcha->get_html();
?>
<input type="submit" value="submit" />
</form>
</body>
</html>

 

mailhide:
recaptcha.mailhide.php

<?php
require_once ("recaptcha.class.php");
$captcha = new recaptcha();
$captcha->privatekey = 'PRIVATEKEY';
$captcha->publickey = 'PUBLICKEY';
?>
<html><body>
The Mailhide version of example@example.com is
<? echo $captcha->mailhide_html("example@example.com"); ?>. <br>

The url for the email is:
<? echo $captcha->mailhide_url ("example@example.com"); ?> <br>

</body></html>
Tagged , ,