Skip to content

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 , ,

mysql: query-dxek fitxategi batera pasa

mysql -u USER -p -h HOST DATABASENAME

Zerbitzaridxen bertan gordeteko:

select * from taula INTO OUTFILE '/tmp/mysql.txt'

Bezero moduen konektaten bagara:

\T /tmp/mysql_output.txt
select * from taula
select * from bestetaula
\t
  • \T hasteko fitxategidxen gordeten
  • \t akaba fitxategidxen gordeten
Tagged ,

python: gaurko erabiltzaile batzun tweet-ek wordpress-en publike

Hamen azken fiñien script-e akabata

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

import sys
import urllib
import datetime as date
import time
import simplejson as json
import re
import MySQLdb

def getTweets(id):
    now = date.datetime.now().strftime("%Y-%m-%d")
    url = "http://search.twitter.com/search.json?q=+from%3A"+u+"+since%3A"+now
    json_text = urllib.urlopen(url).read()
    json_obj = json.loads(json_text)

    tweets = []
    for result in json_obj['results']:
        tweets.append(result['text'])
    return tweets

def isInArray(text, array):
    for a in array:
        m = re.search(a, text)
        if(m):
            return True
    return None

def text2link(text):
    # links
    m = re.sub(r'(?i)(^|\s+|\A)(http|https|ftp)(\://\S+)(\s+|\Z|$)', '\\1<a href=\"\\1\\2\" onclick=\"window.open(this.href); return false;\">\\2\\3</a>\\4', text)
    # users
    m = re.sub(r'(?i)(^|\s+|\A)(@)(\S+)(\s+|\Z)', '\\1<a href=\"http://twitter.com/\\3\" onclick=\"window.open(this.href); return false;\">\\2\\3</a>\\4', m)
    # hashtag
    m = re.sub(r'(?i)(^|\s+|\A)(#)(\S+)(\s+|\Z)', '\\1<a href=\"https://twitter.com/search?q=%23\\3\" onclick=\"window.open(this.href); return false;\">\\2\\3</a>\\4', m)
    return m

def insert_wordpress(post_content, ddbb_config, id_user):

    now = date.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    now_reduce = date.datetime.now().strftime("%d-%m-%Y")

    conn = MySQLdb.connect (host = ddbb_info['host'], user = ddbb_config['user'], passwd = ddbb_config['passwd'], db = ddbb_config['db'])

    cursor = conn.cursor()
    insert = ''
    insert = insert + "insert `wordpress`.`wp_posts`"
    insert = insert + "(post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status,"
    insert = insert + "comment_status, ping_status, post_password, post_name, to_ping, pinged,"
    insert = insert + "post_modified, post_modified_gmt, post_content_filtered, post_parent,"
    insert = insert + "guid, menu_order, post_type, post_mime_type, comment_count) "
    insert = insert + "values ("
    insert = insert + id_user +", '"+now+"', '"+now+"', '"+post_content+"', 'twitter: "+now_reduce+"', '', 'publish',"
    insert = insert + "'open', 'open', '', 'twitter-"+now_reduce+"', '', '',"
    insert = insert + "'"+now+"', '"+now+"', '', 0,"
    insert = insert + "'', 0, 'post', '', 0)"
    #print insert
    cursor.execute(insert)
    #print "Number of rows inserted: %d" % cursor.rowcount
    cursor.close()
    conn.close ()

# aldatzeko parametroak
users = ['ZiTAL', 'dabidmp', 'josebamartos']
tags = ['#hackinbadakigu', '#gnu', '#linux', '@dabidmp', '@josebamartos']
ddbb_config = {'host': 'localhost', 'user': 'root', 'passwd': 'root', 'db': 'wordpress'}
id_user = 1

text = ''

for u in users:
    tweets = getTweets(u)
    time.sleep(2)

    text_user = "<p>" + text2link("@"+u) + ":</p>\n"
    text_user = text_user + "<p>\n"

    text_tweet = ''
    for tweet in tweets:
            if(isInArray(tweet, tags)):
            text_tweet = text_tweet + text2link(tweet) + "<br />\n"            
    if(text_tweet):
        text = text_user + text_tweet + "</p>\n" 

if(text):
    insert_wordpress(text, ddbb_config, id_user)
    #print text

Azkanien until parametrue ez dabil… baie len batzutan ibiltzen zan, ez dakitz oin zeitzik ez…

Okin kontutan “#aldatzeko parametroak” atalan zeuon datuek iminbizuiela ;)

Gero betikulez ejekute:

./ztwitter.py

Firefox barridxekaz bateragarridxe EZ dan Add-on bat instala

Neurelez firefox-egaz “bersionitis” badakozuie, padako datzuie ezin’zuiela “Add-on” batzuk instala, adibidez nire kasuen firebug, horretarako haunek pausuek jarraitu:
Lehenengo eta behin zip eta unzip instala

su
aptitude install zip unzip
exit

Hasten gara:

cd /tmp
wget http://getfirebug.com/releases/firebug/1.8/firebug-1.8.0.xpi
mv firebug-1.8.0.xpi firebug.zip
mkdir firebug
unzip firebug.zip -d firebug
nano firebug/install.rdf

idatz-zatidxen barruen hurrengo tag-a aldatu zeuon firefox bertsiñora, adibidez nirie 6 da

6.*

Gorde artxibue eta urten, oin konsolan barriro:

cd firebug
zip firebug-new.zip -r *
mv firebug-new.zip firebug-new.xpi
mv firebug-new.xpi ../
cd ..

Oin igiri firefox: File -> open -> firebug-new.xpi

Tagged , , , ,

python: adierazpen erregularrakaz (regex) link-ek html-ra bihurtu

baguez kallue hartzien python-eri, oingutan texto batetik link-ek html-ra pasa’kuz

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

text = "http://aaaaa       https://bbbbb ftp://ccccc\n http://dddddddd"

m = re.sub(r'(?i)(^|\s+|\A)(http|https|ftp)(\://\S+)(\s+|\Z|$)', '\\1<a href=\"\\1\\2\" onclick=\"window.open(this.href); return false;\">\\2\\3</a>\\4', text)

print m

Erantzune:

 

<a href="http://aaaaa" onclick="window.open(this.href); return false;">       <a href="https://bbbbb" onclick="window.open(this.href); return false;"> <a href="ftp://ccccc" onclick="window.open(this.href); return false;">
 <a href="http://dddddddd" onclick="window.open(this.href); return false;">

Badakitz eztala expresiño erregular zehatza, karaktere danak ez dizelako sartzien hor adierazpenan, baie bueno danok dakigu hutsune bat daueniko amaitzuten dala linke edota esaldidxe amaitzuten daniko.

Adierazpenan azalpena:

  • r’(?i) -> maiskule eta minuskulen artien EZ bereiztuteko
  • (^|\s+|\A) -> textu hasikerie edo hutsune bat edo 1go hizkidxe bada
  • (http|https|ftp) -> http EDO https EDO ftp-gaz hasten dizelako linkek
  • (\://\S+) -> : \-gaz eskapa bide gero // eta \S+ edozein karaktere EZ dana hutsunie
  • (\s+|\Z|$) -> hutsinie edo azkaningoko berbie edo esaldi akabukerie bada

Ordezkapenan azalpena:

  • \\1 -ek adierazpenako lehenengo () adierazten dau, hau da: (^|\s+|\A)
  • \\2 -ek adierazpenako bigarren () adierazten dau, hau da: (http|https|ftp)
  • \\3 -ek adierazpenako hirugarren () adierazten dau, hau da: (\://\S+)(\s+|\Z)
  • \\4 -ek adierazpenako laugarren () adierazten dau, hau da: (\s+|\Z)
Tagged , ,

debian: nginx erabilitze web zerbitzaridxen cluster bat sortu

Danok dakigu web zerbitzaridxen txeriffe apache dala, baie beste web zerbitzari batzuk be biarra elegante eitzen dauie, adibidez lighttpd, cherokee edota nginx.

Oingutan nginx-eri emongotzagu sue:

su
aptitude install nginx
nano /etc/nginx/nginx.conf

Oin nginx konfigureku:

# usuaidxue eta grupue zeon gustora imiñi
user zital zital;
worker_processes 4;
pid /var/run/nginx.pid;

events {
	worker_connections 15;
	multi_accept on;
}

http {

	##
	# Basic Settings
	##

	sendfile off;
	tcp_nopush on;
	tcp_nodelay on;
	keepalive_timeout 3;
	types_hash_max_size 2048;

	##
	# Logging Settings
	##

	access_log /var/log/nginx/access.log;
	error_log /var/log/nginx/error.log;

	##
	# Mime types
	##

        #include /etc/nginx/mime.types;
        #default_type application/octet-stream;

	##
	# Virtual Host Configs
	##

	upstream appcluster {
		server localhost:81;
		server 127.0.0.1:81;
		server 10.126.2.52:80;
	}

	server {
		# hamen IP publikue, adibidez:
		listen 10.126.252.10:80;
		server_name hackinbadakigu.net hackinbadakigu.net;

		location / {
			proxy_pass  http://appcluster;
		}
	}
}

ikusten dun moduen upstream appcluster sekziñuen sartun biher’duz zerbitzaridxen IP edo domeinu izenak, hori bai euren artien klonak ezan biher diez ;)

		server localhost:81;
		server 127.0.0.1:81;
		server 10.126.2.52:80;

hamen zerbitzari zerrendie euren portuekaz, eta holan nginx enkargako da kargie zerbitzari desberdiñen artien zatitxuten.

Ez ahaztu/etc/nginx/nginx.conf-en usuaidxue eta grupue zeuon gustora imintzen.

Tagged , , ,

python: web2py apache-gaz imiñi martxan debian gnu/linux-en mod-wsgi bidez

web2py python-en framework bat da web aplikaziñuek python-egaz eitzeko, instalateko hau script-e prepara dot, kanbije usuaidxue, grupue eta proiektuen karpetie zeuon gustora:

1go gauzie root moduen konekta eta script-e sortu:

su
nano web2py_install.sh
#!/bin/bash
user='zital'
group=$user
project_path='/home/projects'
current_path=`echo $PWD`

me=`whoami`

if [ "$me" == "root" ]
then
	aptitude -y install libapache2-mod-wsgi unzip wget
	cd ${project_path}
	wget http://web2py.com/examples/static/web2py_src.zip
	unzip web2py_src.zip
	rm -rf web2py_src.zip
	chown -R ${user}:${group} ${project_path}/web2py
	cd ${current_path}
else
	echo "please log with root user"

fi
exit

oin permisuek emon eta ejekute:

chmod +x web2py_install.sh
./web2py_install.sh

Oin apache konfigureku, lelau:
/etc/apache2/apache2.conf artxibuen topa hau:

Include ports.conf

eta komenta:

#Include ports.conf

Oin sortu web2py-ntzako artxibue:

nano /etc/apache2/sites-available/web2py
Listen 80
NameVirtualHost *:80


	WSGIDaemonProcess web2py user=zital group=zital display-name=%{GROUP}
	WSGIProcessGroup web2py
	WSGIScriptAlias / /home/projects/web2py/wsgihandler.py

	
		AllowOverride None
		Order Allow,Deny
		Deny from all
		
			Allow from all
		
	

	AliasMatch ^/([^/]+)/static/(.*) \
		/home/projects/web2py/applications/$1/static/$2
	
		Order Allow,Deny
		Allow from all
	

	
		Deny from all
	

	
		Deny from all
	

	CustomLog /var/log/apache2/web2py-access.log common
	ErrorLog /var/log/apache2/web2py-error.log

okin kontutan usuaidxue eta grupue aldatu behar’zuiela zeuon gustora, oin lekue aktibe eta apache reinizie:

a2dissite default
a2dissite default-ssl
a2ensite we2bpy
/etc/init.d/apache restart

Oin nabegadoran: http://localhost

eskerrak: http://www.web2pyslices.com/main/slices/take_slice/29

Tagged , , , , ,