Archive for maio, 2009

31st mai 2009

Mostrando o potencial da JS Calls PHP #4 – enviando e-mail

Estava fazendo para um freela um envio de e-mail num formulário, com backend PHP, e resolvi usar a JS Calls PHP. Demorou mais tempo do que se fizesse um send.php comum, mas serviu para testar a biblioteca e descobrir uma incompatibilidade em alguns momentos com a Prototype – imcompatibilidade essa já corrigida.

Então, vou mostrar um exemplo de como fazer um formulário onde o usuário digita o e-mail dele, um e-mail de destino e uma mensagem, e a JS Calls PHP faz o envio por e-mail dessa mensagem.

Veja aqui uma página de exemplo!

Criei uma classe chamada MailContato e nela um método, simpleSend(), que recebe três parámetros: e-mail de quem envie, e-mail de destino e a mensagem

<?php
class MailContato {
function __construct() {

}

function simpleSend($sender, $receiver, $message) {
$header = “Content-type: text/html; charset=UTF-8\r\n”;
ini_set(’sendmail_from’, $sender);
mail($receiver, “Contato”, $message, $header) or die(“-1″);
return true;

}
}
?>

No config.php da JS Calls PHP expus a classe sob o nome mailContato e, com isso, posso acessar o método simpleSend passandoos três parâmetros, conforme pode ser visto no html abaixo

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />
<title>Untitled Document</title>
<script type=”text/javascript” src=”../engine.js”></script>
<script type=”text/javascript” src=”../interface/mailContato.js”></script>
<script type=”application/javascript”>
window.onload = function() {
document.getElementById(“submit”).onclick = function() {
var sender = document.getElementById(“sender”).value;
var receiver = document.getElementById(“receiver”).value;
var msg = document.getElementById(“message”).value;
mailContato.simpleSend(sender, receiver, msg, function(status) {

if(status==true)
alert(“Mensagem enviada com sucesso”);
})

}
}
</script>
</head>

<body>
<h1>JS Calls PHP</h1>
<h2>Exemplo de uso – mensagem por e-mail</h2>

<form action=”#” id=”commentform” method=”POST” onsubmit=”return false;”>
<label for=”sender”>seu e-mail:</label><input type=”text” id=”sender” /><br />
<label for=”receiver”>e-mail destino:</label><input type=”text” id=”receiver” /><br />
sua mensagem:<br />
<textarea id=”message”></textarea>
<input type=”submit” id=”submit” value=”enviar” />
</form>
</body>
</html>

No retorno da função, exibo a mensagem de sucesso caso a funcão retorne true. Simples!

Faça download da JS Calls PHP aqui

Posted by Posted by Chris under Filed under javascript, js calls php, php Comments 7 Comments »

29th mai 2009

Prototype Plugins

Mais um site, na mesma linha da Scripteka, com muitos plugins javascript em cima da Prototype

http://www.prototype-plugins.com/

Gráficos, efeitos, drag’n drop, formulários. Recomendadíssimo!

Posted by Posted by Chris under Filed under prototype Comments 4 Comments »

28th mai 2009

Linux Wallpapers

Fica a dica rápida de um site com belíssimos wallpapers com linux como tema.

http://www.wallpaperlinux.com

Posted by Posted by Chris under Filed under linux Comments 1 Comment »

26th mai 2009

Mario – viciado em cogumelos

Adoro – como a maioria das pessoas que curtiram video-game nos anos 90 – o personagem Mario, bem como todos outros da franquia.

Até comprei uma camiseta lá do Camiseteria com essa estampa:

1010_tam9

Mas, efetivamente, eu quero essa camiseta aqui

zoom

Idéia sensacional, Mario viciado em cogumelos, comprando no mercado negro \o/

Se alguém quiser me dar de presente, só ir nessa loja e comprar; eu passop o endereço!

1838-store

Posted by Posted by Chris under Filed under fun Comments 2 Comments »

19th mai 2009

Com qual linguagem de programação você mais trabalha?

Enquete meramente de curiosidade, para saber qual a linguagem de programação mais utilizada no dia-a-dia aqui pelo pessoal que visita o blog.

Se estiver faltando alguma, olha, você deve ser parte de uma minoria! hehe

Com qual linguagem de programação você mais trabalha?

View Results

Loading ... Loading ...

Posted by Posted by Chris under Filed under Tecnologia, enquetes Comments 11 Comments »

19th mai 2009

Mostrando o potencial da JS Calls PHP #3 – acessando a API do Youtube

Segue abaixo mais um exemplo do que pode ser feito com a JS Calls PHP: acessar a API do Youtube.

Veja aqui uma página de exemplo!

Como? Primeiro, baixei essa classe que está no repositório do PHPClasses, que faz todo o trabalho de requisitar a API e trabalhar com o retorno, num xml. Só alterer a mesma criando o método searchStreamingLinks(), o qual exponho para a biblioteca.

<?php
define(“ANY”,0);
define(“PC”,1);
define(“MOBILE”,2);

/**
* This class fetching live streaming links of youtube videos, both for mobile (real player) and PC (flash player)
*
*@author Rochak Chauhan [www.dmwtechnologies.com]
*/
class YoutubeAPI {
private $startIndex=1;
private $format=PC;
private $maxResults=10;
private $keyword=”";
private $feedString=”";
private $downloadUrl=”http://demo.dmwtechnologies.com/YouTubeDownloader/index.php”;

public function __construct() {

}

/**
* Function to get the XML code from the YouTubeAPI
*
* @param string $url
* @access private
*
* @return string
*/
private function getXmlCodeViaFopen($url){
$returnStr=”";
$fp=fopen($url, “r”) or die(“ERROR: Illigal YouTube API URL”);
while (!feof($fp)) {
$returnStr.=fgetc($fp);
}
fclose($fp);
return $returnStr;
}

/**
* Function to get the Title from the XML/RSS Feed
*
* @param string $str
* @access private
* @return string
*/
private function getTitle($str) {
$final=array();
$returnArray=array();
$pattern=”/<title type=’text’>(.*)\<\/title\>/Uis”;
preg_match_all($pattern, $str, $returnArray, PREG_SET_ORDER);
if(isset($returnArray[0][1])) {
return $returnArray[0][1];
}
else {
return “NA”;
}
}

/**
* Function to get the FLV/SWF url from the XML/RSS Feed
*
* @param string $str
* @access private
* @return string
*/
private function getFlvUrl($str) {
$final=array();
$returnArray=array();
$pattern=”/<media:player url=’(.*)’/Uis”;
//$pattern=”/<media:content url=’(.*)’ type=’application\/x-shockwave-flash’/Uis”;
preg_match_all($pattern, $str, $returnArray, PREG_SET_ORDER);

if(isset($returnArray[0][1])) {
return $returnArray[0][1];
}
else {
return “#”;
}
}

/**
* Function to get the mobile streaming url from the XML/RSS Feed
*
* @param string $str
* @access private
* @return string
*/
private function getMobileUrl($str) {

$final=array();
$returnArray=array();
$pattern=”/<media:content url=’(.*)’ type=’video\/3gpp’/Uis”;
preg_match_all($pattern, $str, $returnArray, PREG_SET_ORDER);

if(isset($returnArray[1][1])) {
return $returnArray[1][1];
}
else {
return “#”;
}
}

/**
* Function to get the video thumbnail from the XML/RSS Feed
*
* @param string $str
* @access private
* @param boolean $returnAllThumbsAsArray
* @return string
*/
private function getThumbnailUrl($str,$returnAllThumbsAsArray=false) {
$final=array();
$returnArray=array();
$imgArray=array();
$imgPattern=”/<media:thumbnail url=’(.*)’/Uis”;
preg_match_all($imgPattern, $str, $tmp, PREG_SET_ORDER);

$c=count($tmp);
$l=-1;
foreach($tmp as $key=>$value){
$value=$value[1];
$imgArray[]=$value;
}
if($returnAllThumbsAsArray===true){
return $imgArray;
}
else{
return $imgArray[3];
}
}

/**
* Function to get Streaming link info
*
* @param string $feed
* @access public
* @return array
*/
public function getStreamingLinks() {
$feed=$this->feedString;
$final=array();
$returnArray=array();
$pattern=”/<title type=’text’>(.*)<category scheme=’http:\/\/gdata.youtube.com\/schemas\/2007\/keywords.cat’/Uis”;
preg_match_all($pattern, $feed, $returnArray, PREG_SET_ORDER);

for($i=1;$i<count($returnArray);$i++){
$str=$returnArray[$i][0];
$title=$this->getTitle($str);
$flvUrl=$this->getFlvUrl($str);
$mobileUrl=$this->getMobileUrl($str);
$thumbnailUrl=$this->getThumbnailUrl($str);
if ($this->format==PC) {
$final[]=array(“title”=>$title,”flvurl”=>$flvUrl,”thumbnailUrl”=>$thumbnailUrl);
}
elseif ($this->format==MOBILE) {
$final[]=array(“title”=>$title,”mobileurl”=>$mobileUrl,”thumbnailUrl”=>$thumbnailUrl);
}
else {
$final[]=array(“title”=>$title,”flvurl”=>$flvUrl,”mobileurl”=>$mobileUrl,”thumbnailUrl”=>$thumbnailUrl);
}
}
return $final;
}

/**
* Function to get the downloadable link of the flv file
*
* @param string $youtubeUrl
* @return array on success else false
* @access public
*/
public function getDownloadLink($youtubeUrl) {
// get download link Page
$post_data=”url=$youtubeUrl”;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->downloadUrl);
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$htmlCode = curl_exec($ch);
curl_close($ch);
$returnArray=array();
// extract link from the htmlcode
$pattern=”/<a href=’(.*)\<\/a\>/Uis”;
preg_match_all($pattern, $htmlCode, $returnArray, PREG_SET_ORDER);
if(isset($returnArray[0][1])) {
$str=trim($returnArray[0][1]);
$pos=strpos($str,”‘”);
$link=substr($str,0,$pos);
$title=strip_tags($returnArray[0][0]);
return array(“title”=>$title,”link”=>$link);
}
else {
return false;
}
}

public function searchStreamingLinks($keyword,$maxResults=10,$startIndex=1) {
$this->keyword=$keyword;
$this->format=ANY;
$this->maxResults=$maxResults;
$this->startIndex=$startIndex;
$url=”http://gdata.youtube.com/feeds/api/videos?vq=” . urlencode($keyword) .”&start-index=$startIndex&max-results=$maxResults”;
$this->feedString=$this->getXmlCodeViaFopen($url);
return $this->getStreamingLinks();
}

}
?>

No config.php da JS Calls PHP expus a classe sob o nome youtube e, com isso, posso acessar o método searchStreamingLinks passando uma palavra-chave como parâmetro e, ainda, quantos items quero exibir e qual o primeiro item a ser exibido.

<html>
<head>
<script type=”text/javascript” src=”../engine.js”></script>
<script type=”text/javascript” src=”../interface/youtube.js”></script>
<script type=”text/javascript”>

function getVideos() {
document.getElementById(“videos”).innerHTML = “aguarde, buscando…”;
youtube.searchStreamingLinks(document.getElementById(“keyword”).value, 10, 1, function(videos) {
var ul = document.createElement(“ul”);
for(var i=0; i<videos.length; i++) {
var video = videos[i];

var a = document.createElement(“a”);
a.innerHTML = video.title;
a.href = video.flvurl;

var img = document.createElement(“img”);
img.src = video.thumbnailUrl;

var li = document.createElement(“li”);
li.appendChild(img);
li.appendChild(a);

ul.appendChild(li);
}
document.getElementById(“videos”).innerHTML = “”;
document.getElementById(“videos”).appendChild(ul);
});

}

</script>
</head>
<body>
<h1>JS Calls PHP</h1>
<h2>Exemplo de uso – acesso a API do Youtube</h2>
<label for=”keyword”>Palavra-chave:</label><input type=”text” name=”keyword” id=”keyword” />
<a href=”#” onClick=”getVideos(); return false;”>buscar</a><br /><br />
<div id=”videos”></div>
</body>
</html>

No retorno da chamada tenho uma lista de objetos, e cada objeto possui atributos title, flvurl e thumbnailUrl – com os quais posso montar a lista de vídeos!

Faça download da JS Calls PHP aqui

Posted by Posted by Chris under Filed under javascript, js calls php, web 2.0 Comments 2 Comments »