Sorry if I have done wrong , is my first question on StackOverflow.
I want to write the value of var after doing several checks that are within the functions and as a result if everything is okey want to print the variables in a particular div. I have created three different div , one to display errors , one to show var and other one for the form.
What I Do That IS THIS:
https://mega.co.nz/#!3EQGQSAL!94ao1u6UhARYaYdjJzfFqY6ln1oPyO9JQ4_ElT7WEkA
Code:
<html>
<head>
<meta charset="UTF-8">
<title>Agenda Alex Ventura</title>
<style type="text/css">
#errores {
display: block;
background-color: grey;
border-color: red;
border-top-style: double;
border-right-style: double;
border-bottom-style: double;
border-left-style: double;
}
#contactos {
margin-top: 20px;
background-color: aquamarine;
}
#formulario{
margin-top: 50px;
}
</style>
</head>
<body>
<div id="errores">
<?php
if (!(isset($_POST['enviar']))) {
//Primera vez
$nombre = "";
$telefono = "";
} else {
if (errores()) {
//Segunda o siguientes veces con error
$nombre = "";
$telefono = "";
} else {
//Todo ok
$nombre = $_POST['nombre'];
$telefono = $_POST['telefono'];
imprimir_datos();
}
}
function errores() {
$nombre = $_POST['nombre'];
$telefono = $_POST['telefono'];
if ((empty($nombre)) || (empty($telefono))) {
echo "Los campos de usuariio y telefono no pueden estar vacíos";
return true;
}
if (strlen($telefono) < 9) {
echo "El telefono debe tener 9 digitos " . strlen($telefono);
return true;
}
if (strlen($telefono) > 9) {
echo "El telefono debe tener 9 digitos " . strlen($telefono);
return true;
}
$expresion = '[0-9]';
if (preg_match($expresion, $telefono) != true) {
echo "El telefono debe tener solo numeros " . ($telefono);
return true;
}
return false;
}
?>
</div>
<div id="contactos">
<?php
function imprimir_datos() {
$nombre = $_POST['nombre'];
$telefono = $_POST['telefono'];
echo "Nombre: $nombre, Telefono: $telefono</br>";
}
?>
</div>
<div id="formulario">
<form action=<?php echo $_SERVER['PHP_SELF'] ?> method="POST">
Nombre : <input type="text" name="nombre" value="<?php echo "$nombre"; ?>"/>
Telefono: <input type="text" name="telefono" value="<?php echo "$telefono"; ?>"/>`enter code here`
<input TYPE="submit" VALUE="Enviar" name="enviar"/>
</form>
</div>
</body>
https://mega.co.nz/#!CA5TmCQJ!utWGpH7PZwpPcHbDK3eTG6JMuTRz_Z6KKAFWtbqPm1o
oh, i see now. Patterns needs delimiters.
change this:
if (preg_match($expresion, $telefono) != true) {
to this:
if (preg_match("/" . $expresion . "/", $telefono) != true)
And for the printing the details, try this. Move the function outside from the div, and call it within the div.
<div id="contactos"><?php imprimir_datos(); ?></div>
<?php
function imprimir_datos() {
$nombre = $_POST['nombre'];
$telefono = $_POST['telefono'];
echo "Nombre: $nombre, Telefono: $telefono</br>";
}
?>
Related
This is the script
<?php
//$choix_Id= 521
//Partie SQL
//$sql = "SELECT noperiode FROM Reservations WHERE ref_Choix = //$choix_Id;
//$nopériode= $période+10;
// Fuseau horaire de Toronto (le plus près surpporté selon manuel php)
date_default_timezone_set('America/Toronto');
// Passer d'un mois à l'autre
if (isset($_GET['ym'])) {
$mois = $_GET['ym'];
} else {
// Le mois consulté
$mois = date('Y-m');
}
// "strtotime Transforme un texte anglais en timestamp" - manuel php
$timestamp = strtotime($mois . '-01');
if ($timestamp === false) {
$mois = date('Y-m');
$timestamp = strtotime($mois . '-01');
}
// Aujourdhui
$aujourdhui = date('Y-m-j', time());
// Titre calendrier/mois
$titre_mois = date('Y / m', $timestamp);
// lien du mois suivant ou précédent
$précedant = date('Y-m', strtotime('-1 month', $timestamp));
$suivant = date('Y-m', strtotime('+1 month', $timestamp));
// Nombre de jours dans le mois
$nb_jours = date('t', $timestamp);
// 0:Dim 1:Lun 2:Mar ...
$str = date('w', $timestamp);
// Création du calendrier
$semaines = array();
$semaine = '';
// Création de cellules vides
$semaine .= str_repeat('<td></td>', $str);
$nosemcal= 3;
$noperiodecal=array(2,3,5);
$len_noper = count($noperiodecal)-1;
echo $len_noper;
for ( $jour = 1; $jour <= $nb_jours; $jour++, $str++) {
//for($i=0; $i<=$len_noper;$i++){
$date = $mois . '-' . $jour;
$semainecal = date("W",strtotime($date))-13;
$periodecal = date("w",strtotime($date));
//for ($i=0; $i<=$len_noper;$i++){
if ($nosemcal==$semainecal and $noperiodecal[2]==$periodecal) {
$semaine .= '<td class="reserve">' . $jour;
}else {
$semaine .= '<td class="dispo">' . $jour;
}
// Fin de la semaine ou du mois
if ($str % 7 == 6 || $jour == $nb_jours) {
if ($jour == $nb_jours) {
// nouvelle cellule vide
$semaine .= str_repeat('<td></td>', 6 - ($str % 7));
}
$semaines[] = '<tr>' . $semaine . '</tr>';
// Début d'une nouvelle semaine
$semaine = '';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Calendrier Disponibilités</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonmoisous">
<link href="https://fonts.googleapis.com/css?family=Noto+Sans" rel="stylesheet">
<style>
.fond {
font-family: 'Noto Sans', sans-serif;
margin-top: 80px;
}
h3 {
margin-bottom: 30px;
}
th {
height: 30px;
text-align: center;
}
td {
height: 100px;
}
.dispo {
background: green;
}
.reserve {
background: red;
}
</style>
</head>
<body>
<div class="fond">
<h3>< <?php echo $titre_mois; ?> ></h3>
<table class="table table-bordered">
<tr>
<th>D</th>
<th>L</th>
<th>M</th>
<th>M</th>
<th>J</th>
<th>V</th>
<th>S</th>
</tr>
<?php
foreach ($semaines as $semaine) {
echo $semaine;
}
?>
</table>
</div>
</body>
</html>
This is the result
enter image description here
What i want is all the days in the array $noperiodecal to be in red not just one and without repeating the days of the calendar or the calendar itself. So the 19th, 20th and 22th of April 2022 but not manually like I did for the 19th. I've tried to move the for($i) loop but it changes the whole calendar each times.
This is the message i am getting on my log.
Fatal error: Class 'PHPMailer' not found in
/home/intergroup/public_html/view/envio_contato.php on line 90
But when i press crtl+g on sublime he finds the classes with means the includes are correct.
this is my code: (This text right here is just because StackOverflor dont allows me to post my question, he says i have too much code and i need to explain better and give more details, so: How can i solve this problem, like, what kind of actions can i take to debug?)
<?php
$robots = 'nao';
include '_definicoes.php';
include_once '_header.php';
$pagina_atual = 'envio_contato';
$link_encaminhar_erro = $dominio;
$link_encaminhar_concluido = $dominio;
$title = $nome_site;
$description = $description;
$keywords = $keywords;
// resposta vazia
$response = null;
// verifique a chave secreta
// $reCaptcha = new ReCaptcha($secret);
// if (isset($_POST['submit'])) {
// se submetido, verifique a resposta
// if ($_POST["g-recaptcha-response"]) {
// $response = $reCaptcha->verifyResponse(
// $_SERVER["REMOTE_ADDR"], $_POST["g-recaptcha-response"]
// );
// }
// if ($response == null) {
// echo "<script>alert('Por favor assinale o campo de verificação!');history.back();</script>";
// exit;
// }
// Verifica a resposta do Captcha
if ($response != null && $response->success) {
$nome_site_utf8 = utf8_decode($nome_site);
$nome_contato = utf8_decode($_POST['nome_contato']);
$email_contato = $_POST['email_contato'];
$telefone_contato = $_POST['telefone_contato'];
$assunto_contato_utf8 = utf8_decode($_POST['assunto_contato']);
$mensagem_contato = utf8_decode(nl2br($_POST['mensagem_contato']));
$link_anterior = $_POST['link_anterior'];
//checando se o e-mail é válido
$email_contato = strtolower($email_contato);
$qtd_email = explode("#", $email_contato);
if (count($qtd_email) <= 1) {
//se não possuir # aparece a mensagem
echo "<script>alert('Por favor, insira um e-mail válido!');history.back();</script>";
exit;
} else if (count($qtd_email) == 2) {
$ip = gethostbyname($qtd_email[1]);
//função gethostbyname recupera o ip do domínio, se não tiver ip aparece a mensagem
if ($ip == $qtd_email[1]) {
echo "<script>alert('Por favor, insira um e-mail válido!');history.back();</script>";
exit;
}
}
if ($assunto_contato_utf8 == '') {
echo "<script>alert('Por favor, preencha um Assunto!');history.back();</script>";
exit;
}
$nome_contato = ucwords(strtolower($nome_contato));
$email_conteudo = "<html>
<body>
<font face='Arial' style='color: #606060;'>
<table border='0' style='width: 400px;>
<tr> <td style='height: 40px; text-align: left; font-size: 14px; color: #606060;'> <b>Assunto:</b><br/> $assunto_contato_utf8<br/><br/> </td> </tr>
<tr> <td style='height: 40px; text-align: left; font-size: 14px; color: #606060;'> <b>Nome:</b><br/> $nome_contato<br/> </td> </tr>
<tr> <td style='height: 40px; text-align: left; font-size: 14px; color: #606060;'> <b>E-mail:</b><br/> $email_contato<br/> </td> </tr>
<tr> <td style='height: 40px; text-align: left; font-size: 14px; color: #606060;'> <b>Telefone:</b><br/> $telefone_contato<br/> </td> </tr>
<tr> <td style='text-align: left; font-size: 14px; color: #606060;'> <b>Mensagem:</b><br/> $mensagem_contato<br/> </td> </tr>
<tr> <td style='height: 20px;'></td> </tr>
<tr> <td style='height: 40px; text-align: left; font-size: 14px; color: #606060;'> <b>Página de Referência:</b><br/> $link_anterior<br/> </td> </tr>
<tr> <td style='padding-top: 20px;'></td> </tr>
</table>
</font>
</body>
</html>";
/** Montagem e Envio do e-mail * */
date_default_timezone_set('Etc/UTC');
include 'phpmailer/class.phpmailer.php';
include 'phpmailer/class.smtp.php';
require 'phpmailer/PHPMailerAutoload.php';
}
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
//$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = $mail_host;
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = $mail_port;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = $mail_user;
//Password to use for SMTP authentication
$mail->Password = $mail_pass;
//Set who the message is to be sent from
$mail->setFrom("$mail_send", "$nome_contato");
//Set an alternative reply-to address
$mail->addReplyTo("$email_contato", "$nome_contato");
//Set who the message is to be sent to
$mail->addAddress("$email_formulario", "$nome_site_utf8");
$mail->addAddress("suporte#cgdw.com.br,suporte1#cgdw.com.br");
//$mail->addAddress("$email_formulario2", "$nome_site");
//Set the subject line
$mail->Subject = $assunto_contato_utf8 . " - ".$nome_site_utf8;
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->Body = $email_conteudo;
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo "<script>alert('Desculpe, ocorreu um erro ao enviar, tente novamente!');window.open('" . $link_encaminhar_erro . "', '_self');</script>";
exit;
} else {
echo "<script>alert('Sua mensagem foi enviada, agradecemos seu contato!');window.open('" . $link_encaminhar_concluido . "', '_self');</script>";
exit;
}
?>
i solve the problem this way :
Delete ALL de old code (that was made for someone else) and star fresh. ending up with this code that work
<?php
if (isset($_POST['enviar'])) {
require_once 'phpmailer/PHPMailerT.class.php';
$json = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=6LfEGGoUAAAAAOQQe3y9EkneINSI9bEQLYOATrfr&response=' . $_POST['g-recaptcha-response']));
if (!is_object($json) || $json->success != true) {
echo "<script>alert('Por favor assinale o campo de verificação!');history.back();</script>";
}
$nome_contato = ($_POST['nome_contato']);
$telefone_contato = ($_POST['telefone_contato']);
$email_contato = ($_POST['email_contato']);
$assunto_contato = ($_POST['assunto_contato']);
$mensagem_contato = ($_POST['mensagem_contato']);
$Content = "
<p><b>Nome:</b> " . ($nome_contato) . "</p>
<p><b>Telefone:</b> " . ($telefone_contato) . "</p>
<p><b>Email:</b> " . ($email_contato) . "</p>
<p><b>Assunto:</b> " . ($assunto_contato) . "</p>
<p><b>Mensagem:</b> " . ($mensagem_contato) . "</p>";
$PHPMailer = new PHPMailerT();
$PHPMailer->IsSMTP();
$PHPMailer->SMTPAuth = true;
$PHPMailer->SMTPDebug = 1;
$PHPMailer->SMTPSecure = '';
$PHPMailer->Port = 587;
$PHPMailer->Host = 'mail.server.com.br';
$PHPMailer->Username = 'envio#server.com.br';
$PHPMailer->Password = '';
$PHPMailer->Subject = 'Contato do Site - Intergroup';
$PHPMailer->SetFrom($email_contato, $nome_contato);
$PHPMailer->AddAddress('contato#server.com.br');
$PHPMailer->AddAddress('suporte1#cgdw.com.br');
$ContentSend = "<table width=\"600\">";
$ContentSend .= "<tr>";
$ContentSend .= "<td>$Content<td>";
$ContentSend .= "</tr>";
$ContentSend .= "</table>";
$PHPMailer->MsgHTML($ContentSend);
if ($PHPMailer->Send()) {
echo "<script>alert('Mensagem enviada com sucesso.');history.back();</script>";
} else {
$msgReturn = '<div class="msgErro">Ocorreu um erro, tente mais tarde!</div>';
}
}
echo $msgReturn;
?>
I need to create a basic search engine with PHP to search for an ID within a .txt file but still don't know how to do it, I'm new programming :(
Any help would be much appreciated.
Here's the code I have so far.
<style type="text/css">
td {
font-family:verdana,arial;
font-size:8pt;
border-color:#ccc; }
.header{
background-color:66b50b;
border-style:solid;
border-color:#32661e;
border-width:1px;
font-weight:bold;
font-size:10pt;
color:ffffff; }
.estiloceldaw{
background-color:ffffff;
border-style:solid;
border-color:666666;
border-width:1px; }
.estiloceldag{
background-color:ddeeff;
color:333333;
font-weight:bold;
font-size:10pt; }
</style>
<?php
$criterioid=$_POST["id"];
echo $criterioid;
$critrionombre=$_POST["nombre"];
$catalogo= array();
$datospelicula = array("clave","titulo","sinopsis","genero","anio","precio","status");
function TraeCatalogo()
{
$numregistros=0;
$ar=fopen("catalogo.txt","r") or
die("No se pudo abrir el archivo");
while (!feof($ar)) {
$linea=fgets($ar);
$catalogo[] = $datospelicula =explode("|",$linea);
$numregistros=$numregistros+1;
}
fclose($ar);
echo "numero de registros".$numregistros;
return $catalogo;
}
function Muestralistado($catalogo,$criterioid,$criterionombre)
{
$tabla= "<table><tr colspan=6><td>Clave</td><td>Nombre</td><td>Sinopsis</td><td>Genero</td><td>Año</td><td>precio</td><td>Status</td></tr>";
if (!isset($criterioid) || trim($criterioid) == "")
{
foreach ($catalogo as $k => $pelicula)
{
$clave=$catalogo[$k][0];
$titulo=$catalogo[$k][1];
$sinopsis=$catalogo[$k][2];
$genero=$catalogo[$k][3];
$anio=$catalogo[$k][4];
$precio=$catalogo[$k][5];
$status=$catalogo[$k][6];
$tabla.="<tr><td>".$clave."</td><td>".$titulo."</td><td>".$sinopsis."</td><td>".$genero."</td><td>".$anio."</td><td>".$precio."</td><td>".$status."</td></tr>";}
}else
{
$tabla.="<tr><td colspan=6>hay un criterio de busqueda!</td></tr>";
} $tabla.="<table>";
echo $tabla;
}
$catalogo2=TraeCatalogo("wa");
Muestralistado($catalogo2);
//var_dump($catalogo2);
?>
<html>
<body> Buscar Pelicula: <form action="index.php" method="post">
Nombre: <input type="text" name="nombre"> id: <input type="text" name="id"> <input type="submit">
</form>
</body>
</html>
$foundText = array(); // Create an array to store your found words
Then, once you've opened the file:
while (!feof($ar))
{
$dataBuffer = fgets($ar); // Load some text into buffer
$explodedText = explode($dataBuffer, "|");
foreach($explodedText as $item){
if(strpos($item, $clave) != false)
$foundText[] = $dataBuffer ;
}
}
}
And then you can iterate through each found item:
foreach($foundText as $textItem){
echo 'Word found: ' . $textItem . ' <br>';
}
I just bought a module for the prestashop the guy told me that it was ok for PS 1.5 but in fact it was not.
I had a lot of mistakes and with some help I removed them step by step.
Actually I have a last one:
It told me Fatal error: Call to a member function getProductLink() on a non-object in /htdocs/modules/googleshopping/googleshopping.php on line 420
Here is the entire function
<?php
/*
*
* Google Shopping
* Licence d'utilisation requise (voir readme.txt)
*
*
*/
require_once(_PS_MODULE_DIR_.'googleshopping'.DIRECTORY_SEPARATOR.'class'.DIRECTORY_SEPARATOR.'myTools.php');
require_once(_PS_MODULE_DIR_.'googleshopping'.DIRECTORY_SEPARATOR.'class'.DIRECTORY_SEPARATOR.'html2text.inc.php');
require_once(_PS_MODULE_DIR_.'googleshopping'.DIRECTORY_SEPARATOR.'fonctions.php'); // fonctions
class GoogleShopping extends Module
{
function __construct()
{
$this->name = 'googleshopping';
$this->tab = 'Igwane.com';
$this->version = '2.0';
parent::__construct();
$config = Configuration::getMultiple(array('IGW_DOMAIN', 'IGW_LICNUM'));
if (isset($config['IGW_DOMAIN']))
$this->_domain = $config['IGW_DOMAIN'];
if (isset($config['IGW_LICNUM']))
$this->_licnum = $config['IGW_LICNUM'];
if ($this->_domain!=$_SERVER['SERVER_NAME']):
$this->warning = $this->l('L\'utilisation de ce module n\'est pas autorisée sur ce domaine');
else:
try {
$handle = fopen("http://www.igwane.com/check_licence.php?domain=".$this->_domain.'&licence='.$this->_licnum, "rb");
$valid_licence = '';
while (!feof($handle)) {
$valid_licence .= fread($handle, 8192);
}
fclose($handle);
if ($valid_licence!='OK'):
$this->_licnum=null;
endif;
if (empty($this->_domain) OR empty($this->_licnum))
$this->warning = $this->l('L\'utilisation de ce module n\'est pas autorisée sur ce domaine sans licence (gratuite) - www.igwane.com');
$handle = fopen("http://www.igwane.com/googleshopping_current_version.txt", "rb");
$current_version = '';
while (!feof($handle)) {
$current_version .= fread($handle, 8192);
}
fclose($handle);
if ($current_version!=$this->version)
$this->warning = $this->l('Une nouvelle version (v'.$current_version.') est disponible.');
} catch (Exception $e) {
}
endif;
$this->page = basename(__FILE__, '.php');
$this->displayName = $this->l('Google Shopping by Igwane.com');
$this->description = $this->l('Exportez vos produits vers Google Shopping.');
}
function install()
{
if(!parent::install())
{
return false;
}
return true;
}
public function getContent()
{
if(isset($_POST['generate']))
{
if(isset($_POST['shipping']))
{
Configuration::updateValue('GS_SHIPPING', $_POST['shipping']);
}
if(isset($_POST['image']))
{
Configuration::updateValue('GS_IMAGE', $_POST['image']);
}
// Récupération des langues actives pour la boutique
$languages = Language::getLanguages();
foreach ($languages as $i => $lang)
{
if(isset($_POST['product_type_'.$lang['iso_code']]))
{
Configuration::updateValue('GS_PRODUCT_TYPE_'.$lang['iso_code'], $_POST['product_type_'.$lang['iso_code']]);
}
}
if(isset($_POST['DOMAIN']))
{
Configuration::updateValue('IGW_DOMAIN', rtrim($_POST['DOMAIN']));
}
if(isset($_POST['LICNUM']))
{
Configuration::updateValue('IGW_LICNUM', $_POST['LICNUM']);
}
// Endroit où générer les fichiers
if(isset($_POST['generate_root']) && $_POST['generate_root'] === "on")
{
Configuration::updateValue('GENERATE_FILE_IN_ROOT', intval(1));
} else {
Configuration::updateValue('GENERATE_FILE_IN_ROOT', intval(0));
#mkdir($path_parts["dirname"].'/file_exports', 0755, true);
#chmod($path_parts["dirname"].'/file_exports', 0755);
}
// Gtin - Code EAN13
if(isset($_POST['gtin']) && $_POST['gtin'] === "on")
{
Configuration::updateValue('GTIN', intval(1));
} else {
Configuration::updateValue('GTIN', intval(0));
}
// Référence fabricant
if(isset($_POST['mpn']) && $_POST['mpn'] === "on")
{
Configuration::updateValue('MPN', intval(1));
} else {
Configuration::updateValue('MPN', intval(0));
}
// Quantité
if(isset($_POST['quantity']) && $_POST['quantity'] === "on")
{
Configuration::updateValue('QUANTITY', intval(1));
} else {
Configuration::updateValue('QUANTITY', intval(0));
}
// Marque
if(isset($_POST['brand']) && $_POST['brand'] === "on")
{
Configuration::updateValue('BRAND', intval(1));
} else {
Configuration::updateValue('BRAND', intval(0));
}
// Description
if(isset($_POST['description']) && $_POST['description'] != 0)
{
Configuration::updateValue('DESCRIPTION', intval($_POST['description']));
}
//Offre spéciale
if(isset($_POST['featured_product']) && $_POST['featured_product'] === "on")
{
Configuration::updateValue('FEATURED_PRODUCT', intval(1));
} else {
Configuration::updateValue('FEATURED_PRODUCT', intval(0));
}
self::generateFileList();
}
$output = '<h2>'.$this->displayName.'</h2>';
$output .= $this->_displayForm();
// Bloc liens vers les fichiers générés
$output .= '<fieldset class="space width3">
<legend>'.$this->l('Fichiers').'</legend>
<p><b>'.$this->l('Liens des fichiers générés').'</b></p>';
// Récupération des langues actives pour la boutique
$languages = Language::getLanguages();
foreach ($languages as $i => $lang)
{
if(Configuration::get('GENERATE_FILE_IN_ROOT') == 1)
{
$get_file_url = 'http://'.myTools::getHttpHost(false, true).__PS_BASE_URI__.'googleshopping-'.$lang['iso_code'].'.xml';
} else {
$get_file_url = 'http://'.myTools::getHttpHost(false, true).__PS_BASE_URI__.'modules/'.$this->getName().'/file_exports/googleshopping-'.$lang['iso_code'].'.xml';
}
$output .=''.$get_file_url.'<br />';
}
$output .='<hr><p><b>Génération automatique des fichiers</b></p>
'.$this->l('Vous devez installer une règle CRON qui appellera le fichier suivant chaque jour ').'<br/>http://'.myTools::getHttpHost(false, true).__PS_BASE_URI__.'modules/'.$this->getName().'/cron.php'.'</p>
</fieldset>';
return $output;
}
private function _displayForm()
{
$options = '';
$mpn = '';
$generate_file_in_root = '';
$quantity = '';
$brand = '';
$gtin = '';
$selected_short = '';
$selected_long = '';
$featured_product = '';
// Checked sur la generate_root box si on veut générer les fichiers à la racine du site
if(Configuration::get('GENERATE_FILE_IN_ROOT') == 1)
{
$generate_file_in_root = "checked";
}
// Balises googleshopping optionnelles
if(Configuration::get('GTIN') == 1)
{
$gtin = "checked";
}
if(Configuration::get('MPN') == 1)
{
$mpn = "checked";
}
if(Configuration::get('QUANTITY') == 1)
{
$quantity = "checked";
}
if(Configuration::get('BRAND') == 1)
{
$brand = "checked";
}
if(Configuration::get('FEATURED_PRODUCT') == 1)
{
$featured_product = "checked";
}
(intval(Configuration::get('DESCRIPTION')) === intval(1)) ? $selected_short = "selected" : $selected_long = "selected";
$form = '
<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
<fieldset style="float: right; width: 255px">
<legend>'.$this->l('A propos').'</legend>
<p style="font-size: 1.5em; font-weight: bold; padding-bottom: 0">'.$this->displayName.' '.$this->version.'</p>
<p style="clear: both">
'.$this->description.'
</p>
<p><center><img src="http://www.igwane.com/images/logo.jpg"><img src="http://www.igwane.com/images/devis-gratuit.gif"></center></p>
<p><center>'.$this->l('Lire les dernières mises à jour (readme.txt)').'</p>
<p>'.($this->_licnum?'':'<a style="color: #7ba45b; text-decoration: underline;" href="http://www.igwane.com/fr/contact" target="_blank">Demandez votre licence d\'utilisation gratuite (précisez votre nom de domaine)</a>').'</p>
</fieldset>
<fieldset class="space width3">
<legend>'.$this->l('Paramètres').'</legend>';
if (!$this->_licnum):
$form.='
<label>'.$this->l('Licence accordée à').' </label>
<div class="margin-form">
<input type="text" name="DOMAIN" value="'.Configuration::get('IGW_DOMAIN').'" size="40">
</div>
<label>'.$this->l('Numéro de licence').' </label>
<div class="margin-form">
<input type="text" name="LICNUM" value="'.Configuration::get('IGW_LICNUM').'" size="40">
</div>
';
else:
$form.='
<label>'.$this->l('Licence accordée à').' </label>
<div class="margin-form">
<input type="text" name="DOMAIN" readonly value="'.Configuration::get('IGW_DOMAIN').' "size="40">
</div>
';
endif;
$form.='
<label>'.$this->l('Type de description').' </label>
<div class="margin-form">
<select name="description">
<option value="1" '.$selected_short.'>'.$this->l('Description courte').'</option>
<option value="2" '.$selected_long.'>'.$this->l('Description longue').'</option>
</select>
</div>';
// Récupération des langues actives pour la boutique
$languages = Language::getLanguages();
foreach ($languages as $i => $lang)
{
$form.='<label title="product_type_'.$lang['iso_code'].'">'.$this->l('Catégorie Google').' '.strtoupper($lang['iso_code']).'</label>
<div class="margin-form">
<input type="text" name="product_type_'.$lang['iso_code'].'" value="'.Configuration::get('GS_PRODUCT_TYPE_'.$lang['iso_code']).'" size="40">
<br />('.$this->l('Voir Catégorie Google').')
</div>';
}
$form.='<label title="[shipping]">'.$this->l('Frais de port').' </label>
<div class="margin-form">
<input type="text" name="shipping" value="'.Configuration::get('GS_SHIPPING').'">
</div>
<label title="[image]">'.$this->l('Type de l\'image').' </label>
<div class="margin-form">
<input type="text" name="image" value="'.((Configuration::get('GS_IMAGE')!='')?(Configuration::get('GS_IMAGE')):'large').'">
</div>
<hr>
<table>
<tr>
<td><label>'.$this->l('Générer les fichiers à la racine du site').'</label></td>
<td><input type="checkbox" name="generate_root" '.$generate_file_in_root.'></td>
</tr>
<tr>
<td><label>'.$this->l('Références fabricants').'</label></td>
<td><input type="checkbox" name="mpn" '.$mpn.' title="'.$this->l('Recommandé par Google').'"></td>
</tr>
<tr>
<td><label>'.$this->l('Quantité de produits').'</label></td>
<td><input type="checkbox" name="quantity" '.$quantity.' title="'.$this->l('Recommandé par Google').'"></td>
</tr>
<tr>
<td><label title="[brand]">'.$this->l('Marque').'</label></td>
<td><input type="checkbox" name="brand" '.$brand.' title="'.$this->l('Recommandé par Google').'"></td>
</tr>
<tr>
<td><label>'.$this->l('Code EAN13').'</label></td>
<td><input type="checkbox" name="gtin" '.$gtin.' title="'.$this->l('Recommandé par Google').'"></td>
</tr>
<tr>
<td><label>'.$this->l('En solde').'</label></td>
<td><input type="checkbox" name="featured_product" '.$featured_product.'></td>
</tr>
</table>
<br>
<center><input name="generate" type="submit" value="'.$this->l('Générer les fichiers').'"></center>
</fieldset>
</form>
';
return $form;
}
public function getName()
{
$output = $this->name;
return $output;
}
public function uninstall()
{
Configuration::deleteByName('GS_PRODUCT_TYPE');
Configuration::deleteByName('GS_SHIPPING');
Configuration::deleteByName('IGW_DOMAIN');
Configuration::deleteByName('IGW_LICNUM');
return parent::uninstall();
}
public static function generateFileList()
{
// Récupération des langues actives pour la boutique
$languages = Language::getLanguages();
foreach ($languages as $i => $lang)
{
self::generateFile($lang);
}
}
private static function generateFile($lang)
{
global $link;
$path_parts = pathinfo(__FILE__);
if (Configuration::get('GENERATE_FILE_IN_ROOT')):
$generate_file_path = '../googleshopping-'.$lang['iso_code'].'.xml';
else:
$generate_file_path = $path_parts["dirname"].'/file_exports/googleshopping-'.$lang['iso_code'].'.xml';
endif;
//Google Shopping XML
$xml = '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
$xml .= '<feed xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0" encoding="UTF-8" >'."\n";
$xml .= '<title>'.Configuration::get('PS_SHOP_NAME').'</title>'."\n";
$xml .= '<link href="http://'.myTools::getHttpHost(false, true).__PS_BASE_URI__.'" rel="alternate" type="text/html"/>'."\n";
$xml .= '<modified>'.date('Y-m-d').'T01:01:01Z</modified><author><name>'.Configuration::get('PS_SHOP_NAME').'</name></author>'."\n";
$googleshoppingfile = fopen($generate_file_path,'w');
fwrite($googleshoppingfile, $xml);
$sql='SELECT * FROM '._DB_PREFIX_.'product p'.
' LEFT JOIN '._DB_PREFIX_.'product_lang pl ON p.id_product = pl.id_product'.
' WHERE p.active = 1 AND pl.id_lang='.$lang['id_lang'];
$products = Db::getInstance()->ExecuteS($sql);
$site_base = __PS_BASE_URI__; // préfix du site
$url_site = myTools::getHttpHost(false, true); // url du site base Serveur
$url_site_base_prestashop = $url_site.$site_base;
$title_limit = 70;
$description_limit = 10000;
$languages = Language::getLanguages();
$tailleTabLang = sizeof($languages);
foreach($products as $product)
{
$xml_googleshopping ='';
$cat_link_rew = Category::getLinkRewrite($product['id_category_default'], intval($lang));
$product['details'] = new Product((int)($product['id_product']), false, $lang['id_lang']);
$product_link = $link->getProductLink((int)($product['details']->id), $product['details']->link_rewrite, $cat_link_rew, $product['details']->ean13, $lang['id_lang']);
$title_crop = $product['name'];
if(strlen($product['name']) > $title_limit)
{
$title_crop = substr($title_crop, 0, ($title_limit-1));
$title_crop = substr($title_crop, 0, strrpos($title_crop," "));
}
if(intval(Configuration::get('DESCRIPTION')) === intval(2))
{
$description_crop = $product['description'];
} else {
$description_crop = $product['description_short'];
}
$description_crop = myTools::f_convert_text("", $description_crop, false);
if(strlen($description_crop) > $description_limit)
{
$description_crop = substr($description_crop, 0, ($description_limit-1));
$description_crop = substr($description_crop, 0, strrpos($description_crop," "));
}
$xml_googleshopping .= '<entry>'."\n";
$xml_googleshopping .= '<g:id>'.$product['id_product'].'-'.$lang['iso_code'].'</g:id>'."\n";
$xml_googleshopping .= '<title>'.htmlspecialchars(ucfirst(mb_strtolower($title_crop,'UTF-8'))).'</title>'."\n";
$xml_googleshopping .= '<link>'.$product_link.'</link>'."\n";
$xml_googleshopping .= '<g:price>'.Product::getPriceStatic($product['id_product'],true,NULL,2).'</g:price>'."\n";
$xml_googleshopping .= '<g:description>'.htmlspecialchars($description_crop, null, 'UTF-8', false).'</g:description>'."\n";
$xml_googleshopping .= '<g:condition>new</g:condition>'."\n"; //condition = neuf, occasion, reconditionné OR new, used, refurbished
if(Configuration::get('MPN') && $product['supplier_reference'] != '')
{
$xml_googleshopping .= '<g:mpn>'.$product['supplier_reference'].'</g:mpn>'; //ref fabricant
}
// Pour chaque image
$images = Image::getImages($lang['id_lang'], $product['id_product']);
$indexTabLang = 0;
if($tailleTabLang >1 ){
while(sizeof($images) < 1 && $indexTabLang<$tailleTabLang){
if($languages[$indexTabLang]['id_lang']!=$lang['id_lang']){
$images = Image::getImages($languages[$indexTabLang]['id_lang'], $product['id_product']);
}
$indexTabLang++;
}
}
$nbimages=0;
$image_type=Configuration::get('GS_IMAGE');
if ($image_type=='') $image_type='large';
foreach($images as $im)
{
// Old URL
//$image='http://'.$url_site_base_prestashop.'img/p/'.$product['id_product'].'-'.$im['id_image'].'-large.jpg';
$image= $link->getImageLink($product['link_rewrite'], $product['id_product'] .'-'. $im['id_image'],$image_type);
// BUG :
//if (!strpos($url_site_base_prestashop,$image))
// $image = 'http://'.$url_site_base_prestashop.$image;
$xml_googleshopping .= '<g:image_link>'.$image.'</g:image_link>'."\n";
if (++$nbimages == 10) break;
}
// Quantité et disponibilité
if(Configuration::get('QUANTITY') == 1)
{
if ($product['quantity'] != '' && $product['quantity'] != '0')
{
$xml_googleshopping .= '<g:quantity>'.$product['quantity'].'</g:quantity>'."\n";
$xml_googleshopping .= '<g:availability>in stock</g:availability>'."\n";
}
else{
$xml_googleshopping .= '<g:quantity>0</g:quantity>'."\n";
$xml_googleshopping .= '<g:availability>out of stock</g:availability>'."\n";
}
}
// Marque
if(Configuration::get('BRAND') && $product['id_manufacturer'] != '0')
{
$xml_googleshopping .= '<g:brand>'.htmlspecialchars(Manufacturer::getNameById(intval($product['id_manufacturer'])), null, 'UTF-8', false).'</g:brand>'."\n";
}
// Catégorie
if(Configuration::get('GS_PRODUCT_TYPE_'.$lang['iso_code']))
{
$product_type = str_replace('>', '>', Configuration::get('GS_PRODUCT_TYPE_'.$lang['iso_code']));
$product_type = str_replace('&', '&', $product_type);
$xml_googleshopping .= '<g:google_product_category>'.$product_type.'</g:google_product_category>'."\n";
$xml_googleshopping .= '<g:product_type>'.$product_type.'</g:product_type>'."\n";
}
// Frais de port
if(Configuration::get('GS_SHIPPING'))
{
$xml_googleshopping .= '<g:shipping>'."\n";
$xml_googleshopping .= '<g:country>FR</g:country>'."\n";
$xml_googleshopping .= '<g:service>Standard</g:service>'."\n";
$xml_googleshopping .= '<g:price>'.Configuration::get('GS_SHIPPING').'</g:price>'."\n";
$xml_googleshopping .= '</g:shipping>'."\n";
}
//Poids
if($product['weight'] != '0')
{
$xml_googleshopping .= '<g:shipping_weight>'.$product['weight'].' kilograms</g:shipping_weight>'."\n";
}
// Offre spéciale
if(Configuration::get('FEATURED_PRODUCT') == 1 && $product['on_sale'] != '0')
{
$xml_googleshopping .= '<g:featured_product>o</g:featured_product>'."\n";
}
if(Configuration::get('GTIN') && $product['ean13'] != '')
{
$xml_googleshopping .= '<g:gtin>'.$product['ean13'].'</g:gtin>'."\n";
}
$xml_googleshopping .= '</entry>'."\n";
// Ecriture du produit dans l'XML googleshopping
fwrite($googleshoppingfile, $xml_googleshopping);
}
$xml = '</feed>';
fwrite($googleshoppingfile, $xml);
fclose($googleshoppingfile);
#chmod($generate_file_path, 0777);
return true;
}
}
?>
the line concerned is this one on the line 420 :
$product_link = $link->getProductLink((int)($product['details']->id), $product['details']->link_rewrite, $cat_link_rew, $product['details']->ean13, $lang['id_lang']);
I really do not know where doesd it come from but I have this fatal error Fatal error: Call to a member function getProductLink() on a non-object in /htdocs/modules/googleshopping/googleshopping.php on line 420
anykind of help will be much appreciated.
Change:
$link->getProductLink
to:
Context::getContext()->link->getProductLink
You will have another error in this same file with var getImageLink
Do the same thing. Change:
$link->getImageLink
to:
Context::getContext()->link->getImageLink
The function generateFile uses the global $link variable.
You have probably forgotten to include an additional file (which instantiates the object in the $link variable).
The script expects a variable named $link which is supposedly not set. Since it's global, it can be defined outside the function
Look for the file that defines $link and include it correctly
I've got a part of a PHP script, but it gives a T_CLASS error.
But i'm not sure how to convert the VAR element into a php5 compliant code...
Can somebody help me?
<?php // Defining the "calc" class
if (!class_exists('calc'))
class calc {
var $number1;
}
?>
p.s. this is just part of a bigger code, but it keeps saying: "PHP Syntax Check: Parse error: syntax error, unexpected T_CLASS in your code on line 3". So the error should be either in "class calc {" or in "var $number1;". Please help :P
I had to place the entire code. Just adding the brackets gave me a new error.
<?php // Defining the "calc" class
if (class_exists('calc')) {
class calc {
var $number1;
}
}
function boek($number1)
{
$result =$number1 * 2;
echo "Om een tekst van $number1 pagina's te redigeren, rekenen wij: <strong>€ $result,-*</strong></br>";
echo "<small>*Deze prijs is slechts een indicatie. Om een vrijblijvende offerte aan te vragen kunt u gebruikmaken van het contactformulier onderaan de pagina. <br/><span style=\"text-decoration: underline;\">Let op: studenten krijgen op vertoon van hun studentenpas 25% korting.</span></small>";
}
}
//Creating object of class
$calc = new calc();
?>
<style type="text/css">
.calcbutton {
Cursor: pointer;
display: block;
text-indent: -5000px;
width: 136px;
height: 44px;
border: none;
background-image: url('http://www.mijncreaties.com/wp-content/themes/GoedVerwoord/images/buttons.png');
background-repeat: no-repeat;
}
.calcbutton {background-position: top left;}
.calcbutton:hover {background-position: center left;}
.calcbutton:active {background-position: bottom left;}
</style>
<form name="calc" action="" method="POST">
<table>
<tr>
<td>Aantal pagina's: </td>
<td><input type="text" style="padding-left: 3px;" class="calc-form wpcf7-text" name="value1" value="0" onfocus="if (this.value == '0') {this.value = '';}" onblur="if (this.value == '') {this.value = '0';}"><br>
<input type="hidden" name="oper" value="boek">
</td>
</tr>
</table>
<input type="submit" value="Bereken prijs" name="submit" class="calcbutton">
</form>
<?
if($_POST['submit']){
$number1 = $_POST['value1'];
$oper = $_POST['oper'];
if(!$number1){
echo "<p><font color=\"red\">Vul a.u.b. een getal in.</font></p>";
}
if($oper == "boek"){
$calc->boek($number1);
}
}
?>
Try wrapping it in an extra set of braces:
<?php // Defining the "calc" class
if (!class_exists('calc')) {
class calc {
var $number1;
}
}
?>
Editted to add:
if (class_exists('calc')) {
class calc {
var $number1;
function boek($number1)
{
$result =$number1 * 2;
echo "Om een tekst van $number1 pagina's te redigeren, rekenen wij: <strong>€ $result,-*</strong></br>";
echo "<small>*Deze prijs is slechts een indicatie. Om een vrijblijvende offerte aan te vragen kunt u gebruikmaken van het contactformulier onderaan de pagina. <br/><span style=\"text-decoration: underline;\">Let op: studenten krijgen op vertoon van hun studentenpas 25% korting.</span></small>";
}
}
}
Your closing bracket was in the wrong place.
Wrap brackets around that if:
<?php
// Defining the "calc" class
if (!class_exists('calc')){
class calc {
var $number1;
}
}
?>
You will have the same issue when conditionally creating functions:
<?php
if (!function_exists('new_function')){
function new_function{
return 'awesome';
}
}
?>