Calculo de Investimentos I

Talvez por os tempos serem de crise, tenho andado a pensar nos últimos tempos como rentabilizar ao máximo os fundos de que disponho actualmente. A ideia é pegar numa determinada quantia e fazer uma aplicação durante alguns anos reinvestindo todos os anos o valor inicial incluindo os juros ganhos.

Criei um simples simples script que me efectua este calculo. Já existem calculadoras destas às paletes, apenas criei uma nova para simular variações nas taxas de juros entre os vários anos.

A ideia é simplesmente utilizar como limites de variação de juros fornecidos pela instituição financeira e assim tentar ter uma ideia mais real (que na realidade até pode ser bem menos real) do resultado final.

Utilizem o seguinte formulário para efectuarem o calculo:

 

[INDISPONIVEL AINDA]

Algoritmo para validar NIB (Número de Identificação bancária).

Depois do último algoritmo para validar o contribuinte, aqui fica uma versão para validar o NIB.

function isValidNib($nib){
$result = "";
if(strlen(intval($nib)) != 21)
return "NIB INVALIDO (Standard: 21 algarismos. Introduzido: " . strlen(intval($nib)) . ")";
 
$nnib = str_split(intval($nib));
 
for($i=0; $i< 19 ; $i++){
        $result = (($result + $nnib[$i]) * 10) % 97;
}
$result = 98 - (($result * 10) % 97);
 
if($result < 10)
        $result = "0" + $result;
 
if(substr($nib, 19, 2) != $result)
        return "NIB INVALIDO";
else
        return "NIB VALIDO";
}

Se preferirem podem trocar o texto enviado no retorno das funções e utilizar um boleano true/false.

EDIT: Agradecimentos ao Nuno Cancelo pela dica de optimização enviada! :)

Algoritmo para validar NIF (Numero de contribuinte)

Já tenho visto por aí vários algoritmos para validar o numero de contribuinte, mas não vi um feito em PHP.

Disponibilizo aqui um pedaço de código em PHP para que possam incluir nos vossos serviços.

function isValidNif($nif){
 
//Verificar se e' um numero e se e' composto exactamente por 9 digitos
if(!is_numeric($nif) || strlen($nif) != 9) return false;
 
$narray = str_split($nif);
 
//verificar se o primeiro digito e' valido. O primeiro digito indica o tipo de contribuinte.
if($narray[0] != 1 && $narray[0] != 2 &&  $narray[0] != 5 && $narray[0] != 6 && $narray[0] != 8 && $narray[0] != 9)
        return false;
 
$checkbit = $narray[0] * 9;
 
for($i=2; $i<=8; $i++){
        $checkbit += $nif[$i-1] * (10 - $i);
}
 
$checkbit = 11 - ($checkbit % 11);
 
if($checkbit >= 10) $checkbit=0;
 
if($nif[8] == $checkbit) return true;
echo "$nif - $checkbit";
return false;
}

Nomes ninja

Escreve o teu nome, ninja style:

Estava sem nada para fazer e resolvi fazer um pequeno script baseado na imagem de cima para criar o nome automaticamente.

http://www.davidgouveia.net/goodies/ninja.php?name=david – Substitui o nome david pelo teu.

O resultado será algo assim :

Utilidade: Nenhuma. Mas já estava enferrujado com a utlização da libgd :)

ClipBucket 2.0.6 XSS vulnerability

I believe I have found a vulnerability in ClipBucket 2.0.6 (haven’t tested with prior versions).

ClipBucket is an open source and free script that will let you start your own Video Sharing (Youtube Clone) website in matter of minutes, ClipBucket is fastest growing script with most video sharing websites and social networking features.
current version: 2.0.6

Summary:
The script handling the search features is not sanitizing user input properly making it possible to produce XSS attacks.

Proof of Concept:

Use the search box of your ClipBucket 2.0.6 installation and Input:

 <script>alert(document.cookie);</script>

This will produce an alert with contents of your cookie.

Problem:
$search->key in search_result.php (line 18) is being directly assigned to the title of the search page without sanitizing its value first.

$search->key = $_GET['query'];

Workaround:
Open file search_result.php. Go to line 39:

Replace this:

Assign('search_type_title',sprintf(lang('searching_keyword_in_obj'),$search->key,$search->search_type[$type]['title']));

By this:

Assign('search_type_title',sprintf(lang('searching_keyword_in_obj'),htmlentities($search->key),$search->search_type[$type]['title']));

The ClipBucket team was already notified and the bug was corrected. Either apply this patch or upgrade your version to 2.0.7

Fix autoplay of default ClipBucket flash player

Many of you have noticed that the default player (CB) does not autoplay movies. While some people suggested that there was a typo in the cbplayer.plug.php, changing autoload to autoload wasn’t enough.

I’ve disassembled the CB player to check which variables it was expecting and I found out that it wasn’t autoplay, but autoPlay.

So … in order to fix this issue, open player/cbplayer/cbplayer.plug.php. Locate :

$code	.= "settingsFile: \"".PLAYER_URL."/cbplayer/settings.php?hqid=".$vdata['videoid']."&amp;autplay=".$data['autoplay']."\"\n";
else
$code	.= "settingsFile: \"".PLAYER_URL."/cbplayer/settings.php?vid=".$vdata['videoid']."&amp;autplay=".$data['autoplay']."\"\n";

replace by :

$code	.= "settingsFile: \"".PLAYER_URL."/cbplayer/settings.php?hqid=".$vdata['videoid']."&amp;autoPlay=".$data['autoplay']."\"\n";
else
$code	.= "settingsFile: \"".PLAYER_URL."/cbplayer/settings.php?vid=".$vdata['videoid']."&amp;autoPlay=".$data['autoplay']."\"\n";

Part II

If you want to use autoplay under every pages except for index (eg. to disable autoplay of editor’s pick movies), add this little snippet :

Open the same file. Locate :

function cbplayer($data,$no_video=false)
	{

Add below :

	if(constant('THIS_PAGE')=='index')
		$data['autoplay'] = 'false';

You shoud now be able to autoplay every video using the CB default player except for the ones on main page.:D

Google analytics MOD to ClipBucket.

Summary: with this mod you will be able to insert any script into your clipbucket. I’m using it to manage google analytics.

1st – Open styles/cbv2new/layout/global_header.html. Find:

<!-- Setting Template Variables -->
{php}
	if(!$_COOKIE['current_style'])
    	$_COOKIE['current_style'] = 'grid_view';
{/php}

Add below:

<!-- Google Analytics -->;
{show_analytics|html_entity_decode}

2nd – includes/common.php. Find:

$Smarty-&gt;register_function('cbtitle','cbtitle');

Add below:

$Smarty-&gt;register_function('show_analytics', 'show_analytics');

3rd – Open includes/functions.php. Find:

	/**
	 * Function used to load clipbucket title
	 */
	function cbtitle($params=false)
	{

Add above:

	/**
	* Function used to load Google Analytics - me( at )davidgouveia.net
	*/
	function show_analytics()
	{
		global $Cbucket;
		// code to convert html entities back useful code.
		echo base64_decode($Cbucket-&gt;configs['google_analytics']);
 
	}

4th – Open admin_area/main.php. Find:

	'gravatars',

Add above:

	'google_analytics',

Find:

	$value = mysql_clean($_POST[$field]);
	if(in_array($field,$num_array))

Add above:

	if($field == 'google_analytics')
		$value = base64_encode($_POST['google_analytics']);
	else

(the “else” MUST be in the line immediately above “$value = mysql_clean($_POST[$field]);”).

Finally, open /admin_area/styles/cbv2/layout/main.html. Find:

            <tr>
              <td valign="top">Meta Description</td>
              <td valign="top"><textarea name="description" id="description" cols="45" rows="5">{$row.description}</textarea></td>
            </tr>

Add below:

       	    <tr>
              <td valign="top">Google Analytics</td>
              <td valign="top"><textarea name="google_analytics" id="google_analytics" cols="45" rows="5">{$row.google_analytics|base64_decode|html_entity_decode}</textarea></td>
            </tr>

Done! You shoud see another option under Web Settings.

Tested under ClipBucket 2.0.6.

PS: I’m using base64_encode/decode because I want to save the script as its original values and I need to avoid using functions like mysql_clean() to sanitize the code. By saving it as a base64 string I avoid potential malicious SQL injection problems. I’m sure there are other ways of doing it but this works OK (I think :p).

ClipBucket MOD – How to Block email domains.

This code was tested with ClupBucket 2.0.6. This will allow you to block specific emails domains. It is partivularly useful to block all email providers used to spam (like mailinator.com or temporaryinbox.com).

1st – Open your database and add a record to your config datatable (default is cb_config) with the value “disallowed_email_providers”.
2nd – Open clipbucket Control Panel and add a new phrase with code “usr_email_blacklisted_err” and value “Invalid email”.

3rd – open the main.html from your template.

Search for :

<tr>
<td valign="top">Disallowed usernames</td>
<td valign="top"><label>
<textarea name="disallowed_usernames" id="disallowed_usernames" cols="45" rows="5">{$row.disallowed_usernames}</textarea>
<br />
separate by commas
</label></td>
</tr>

and add below:

<tr>
<td valign="top">Disallowed email providers</td>
<td valign="top"><label>
<textarea name="disallowed_email_providers" id="disallowed_email_providers" cols="45" rows="5">{$row.disallowed_email_providers}</textarea>
<br />
separate by commas
</label></td>
</tr>

4th – Open admin_area/main.php and find (around line 56):

'disallowed_usernames',

and add below :

'disallowed_email_providers',

5th – Open includes/classes/user.class.php and add this function right above the signup_user function (around line 3160) :

/**
* Function to validate email provider
*/
function blacklisted($email){
global $Cbucket;
 
$providers = explode(",", $Cbucket->configs['disallowed_email_providers']);
 
foreach($providers as $provider){
if(eregi(trim($provider) . "$", $email))
return true;
}
return false;
}

6th – Finally enter function signup_user, locate this :

//checking terms and policy agreement
if($array['agree']!='yes' && !has_access('admin_access',true))
e(lang('usr_ament_err'));

add below :

//Check if email provider is blacklisted
if($this->blacklisted($array['email']))
e(lang('usr_email_blacklisted_err'));

You should now be able to block email providers :)

Script básico para NAGIOS para monitorização de Portas

Estive com uns problemas na empresa relacionados com o sendmail.
Quando nada fazia prever, o sendmail simplesmente crasha começando a recusar activamente todos os pedidos de envio de email.

Criei um script genérico para verificar se uma determinada porta de um servidor está a responder. Basta editar o endereço, porta e opcionalmente definir um timeout máximo para o pedido.

#!/usr/bin/php -q
<?
 
/*****************************************************
 
    Check For Open Ports - David Gouveia
 
*****************************************************/
 
$address = '127.0.0.1';
$port = 25;
$timeout = 5;  //Max time to wait before give up.
 
$checkport = fsockopen($address, $port, $errnum, $errstr, $timeout);
 
if(!$checkport){
        print "CRITICAL: Host $address at port $port not responding!\n";
        fclose($checkport);
        exit(2);
}
 
print "OK: Host $address at port $port is responding!\n";
fclose($checkport);
exit(0);
 
?>

Coloquem na pasta dos plugins e não se esqueçam de dar as permissões correctas (755).
Alternativamente podem passar o valor do IP e porta como argumentos via consola.

basta trocar isto :

    $address = ’127.0.0.1′;
    $port = 25;

por isto :

    $address = $argv[1];
    $port = $argv[2]