Archive for the 'js calls php' Category

11th jul 2009

Mostrando o potencial da JS Calls PHP #5 – geolocalização

Fazia muito tempo que não postava nada sobre a JS Calls PHP – muito trabalho, pouco tempo livre… coisas da vida.

Aproveitei um tempinho livre nesse sábado para integrar uma classe que vi de geolocalização com a biblioteca, possibilitando que sejam retornados dados como cidade e estado relativos a um IP via javascript, requisitando assincronamente uma classe PHP.

Veja aqui uma página de exemplo!

A classe original pode ser baixada aqui, só tive que fazer algumas modificações na mesma, conforme o código abaixo:

<?php
include 'PHP45.XML.php';

class GeoLocalizacao {
// XML document
var $doc  = null;
// string describing the host of the geo location service
var $host = "http://api.hostip.info/?ip=<IP>";

// string describing the city
public $city      = 'unknown';
// string describing the country
public $country   = 'unknown';
// longitude
public $longitude = '0';
// latitude
public $latitude  = '0';

public function __construct() {

}

public function geoLocation($ip) {

$this->doc = new PHP45XML();
$this->doc->preserveWhiteSpace = false;

// prepare url of service
$host  = str_replace( "<IP>", $ip, $this->host);

$reply = $this->fetch($host);

// decode the reply and make it available
//echo $reply;
//return false;
$this->decode($reply);
return array("city"=>$this->city, "country"=>$this->country, "lng"=>$this->longitute, "lat"=>$this->latitude);
}

function fetch($host) {
$reply = 'error';
// try curl or fopen
if( function_exists('curl_init') ) {
// use curl too fetch site
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL           , $host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$reply = curl_exec($ch);
curl_close ($ch);
} else {
// fall back on fopen
$reply = file_get_contents($host, 'r');
}
return $reply;
}

function decode($text) {
// load in php version independent manner
$this->doc->loadXML($text);
// use the PHP4/5 XML wrapper to decode the result
$result = $this->doc->xpath("//gml:name");

$this->city      = $result['city'];

$this->country   = $result['country'];
$this->longitude = $result['lng'];
$this->latitude  = $result['lat'];
}
}
?>

Essa classe utiliza a API do site http://api.hostip.info, que passando um endereço IP retorna um XML com as informações. A classe trata esses dados e retorna um array com as chaves/valores para cidade, estado, longitude e latitude.

Depois de expor essa classe no config.php (conforme explicado na documentação oficial) sob o nome geo, o único trabalho foi fazer um html que chama o método geoLocation passando o valor de um input como parâmetro, e no retorno dou um alert exibindo a cidade e o estado.

<!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>IP</title>
<script type="text/javascript" src="../engine.js"></script>
<script type="application/javascript" src="../interface/geo.js"></script>
<script type="application/javascript">
window.onload = function() {
document.getElementById("submit").onclick = function() {

var ip = document.getElementById("ip").value;

geo.geoLocation(ip, function(myIp) {
alert("cidade: " + myIp.city + "\npaís: " + myIp.country);
})

}
}
</script>
</head>
<body>

Digite um endereço de IP para ver qual a cidade e país de origem:
<input type="text" name="ip" id="ip" />
<input type="button" value="checar" id="submit" />
</body>
</html>

Funcionamento simples, como sempre, com a JS Calls PHP!

Faça download da JS Calls PHP aqui

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

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 »

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 »

14th mai 2009

Página de debug na JS Calls PHP

Já havia feito há algum tempo a página de debug/testes da JS Calls PHP, mas estava testando-a primeiro. Me parece que está bem estável e por isso resolvi disponibilizar.

O que ela faz é listar todos os as classes expostas no arquivo de configuração, e todos os métodos das mesmas, para que o desenvolvedor possa fazer testes unitários dos métodos expostos.
A página de debug gera automaticamente os campos para os testes, como pode ser visto nesse exemplo em que expûs todas as classes usadas nos exemplos que acompanham o pacote da JS Calls PHP.

Faça download da JS Calls PHP aqui

Para acessar a sua página de debug, é só acessar debug.php dentro do contexto onde está instalada a biblioteca (por exemplo: http://localhost/meusite/jscallsphp/debug/php)

Ainda aproveitei essa atualização para corrigir um bug reportado pelo André nas páginas de exemplos, que gerava erro no IE (o erro era nos htmls dos exemplos, nada a ver com a biblioteca).

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

03rd mai 2009

Mostrando o potencial da JS Calls PHP #2

Outro exemplo do que é possível fazer com a JS Calls PHP: listar arquivos de um certo diretório.

Uma classe simples com um método que recebe o caminho de uma pasta e retorna a lista de arquivos, como a seguinte

<?php
class FileSystemBrowser {
function __construct() {

}

function getFilesFromFolder($path) {
//pastas que não devem ser listadas a partir delas
if(strstr($path, “../../”) || strstr($path, “/blog”))
return “Not allowed”;

if ($handle = opendir($path)) {
$files = array();
while (false !== ($file = readdir($handle))) {
if ($file != “.” && $file != “..” && !is_dir($path . $file)) {
array_push($files, $file);
}
}
closedir($handle);
return $files;
}
}

}
?>

quando exposta no arquivo de configuração da forma apropriada (ver a página principal da JS Calls PHP) pode ter uma implementação javascript que espera um caminho de uma pasta do servidor e lista os arquivos dela, após fazer uma requisição no backend ao método getFilesFromFolder($path) da classe FileSystemBrowser:

<html>
<head>
<script type=”application/javascript” src=”../engine.js”></script>
<script type=”application/javascript” src=”../interface/fileSystem.js”></script>
<script type=”application/javascript”>

function getFiles() {
fileSystem.getFilesFromFolder(document.getElementById(“texto”).value, function(cb) {

var ul = document.getElementById(“files”);
ul.innerHTML = “”;
for(var i=0; i<cb.length; i++) {
var li = document.createElement(“li”);
li.innerHTML = cb[i];
ul.appendChild(li);
}

});
}

</script>
</head>
<body>
<h1>JS Calls PHP</h1>
<h2>Exemplo de uso – listando arquivos de uma pasta</h2>
<label for=”texto”>Seu texto:</label><input type=”text” name=”texto” id=”texto” value=”../jscallsphp/” />
<a href=”#” onClick=”getFiles(); return false;”>listar arquivos</a><br /><br />
<ul id=”files”></ul>
</body>
</html>

Você pode ver esse exemplo funcionando aqui. Alguns caminhos para testar: ../jscallsphp, ../, ../files/

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

26th abr 2009

Mostrando o potencial da JS Calls PHP #1

Já faz alguns meses que tive a idéia de criar uma biblioteca PHP, opensource, para facilitar as interações entre javascript e PHP. Batizei a mesma de JS Calls PHP, e com ela é possível acessar métodos de classes PHP de uma forma simples, com sintaxe clara e orientada a objetos.

Veja a página completa da biblioteca aqui.

Então resolvi criar uma série de posts onde vou mostrar o que é possível fazer com essa biblioteca. Basicamente, ela possibilita qualquer interação da interface com o backend desde que esse seja em PHP e o que você quiser que interaja esteja orientado a objetos.
Vale ressaltar que sempre me perguntam se é uma biblioteca AJAX; tecnicamente falando, não, ela não é. Ela utiliza requisicões assíncronas via javascript com troca de dados no formato JSON, e não dá suporte nenhum a manipulação DOM, como uma jQuery ou Prototype faz. Mas o que nela é diferente do que tem por aí? Possibilita você acessar métodos do PHP, colocando toda abstração de orientação a objetos (nome_da_classe.nome_do_metodo([argumentos])) sem precisar utilizar, por exemplo. o método load() ou $.ajax() da jQuery ou a classe Ajax da Prototype passando URLs inteiras como caminho.

Nesse primeiro post, criei uma rotina que chama via javascript um método de uma classe do PHP que recebe três parâmetros: largura, altura e um texto e cria no sistema de arquivos uma imagem com fundo preto e o texto passado como parâmetro em vermelho, e quando ela acaba de ser executada, no javascript dou reload na imagem.

Veja o exemplo rodando aqui.

Utilizei esse exemplo que postei no O Desenvolvedor de manipulação de imagens no PHP com a biblioteca GD como base.

Código da classe:

<?php
class GDTest {
function __construct() {

}

function createImageWithText($width, $height, $txt) {
//cria uma imagem com largura x altura definida pelo usuário
$im = imagecreatetruecolor($width, $height);
//aloca as cores para imagem
$text_color = imagecolorallocate($im, 233, 14, 91);
//escreve o texto na imagem
imagestring($im, 1, 5, 5,  $txt, $text_color);

//iunicia buffer
ob_start();
// cria imagem de saída, formato jpeg, bom 85% de qualidade
imagejpeg($im, NULL, 85);
//captura saída para string
$contents = ob_get_contents();
//finaliza captura
ob_end_clean();
//libera memória
imagedestroy($im);
//escreve arquivo em disco, usando os comando básicos do PHP
$fh = fopen(“temp/img2.jpg”, “w+” );
fwrite( $fh, $contents );
fclose( $fh );
return true;

}

}

?>

Então expus essa classe na JS Calls PHP sob o nome gd e habilitei o método a ser acessado, no arquivo de configuração (config.php) e criei o html que faz essa chamada.

<html>
<head>
<script type=”application/javascript” src=”../engine.js”></script>
<script type=”application/javascript” src=”../interface/gd.js”></script>
<script type=”application/javascript”>

function getImg() {
gd.createImageWithText(300, 100, document.getElementById(“texto”).value, function(cb) {
if(cb) {

document.getElementById(“myImage”).src = “../temp/img2.jpg?date=” + new Date();
}
});
}

</script>
</head>
<body>
<h1>JS Calls PHP</h1>
<h2>Exemplo de uso</h2>
<label for=”texto”>Seu texto:</label><input type=”text” name=”texto” id=”texto” />
<a href=”#” onClick=”getImg(); return false;”>criar/atualizar imagem</a><br /><br />
<img src=”#” id=”myImage” />
</body>
</html>

Espero que o exemplo tenha ficado bem explicado e que seja de utilidade. Se tiverem dúvidas ou sugestões de exemplos, enviem :)

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