mercredi 6 mai 2015

Laravel echo strange characters

Hey i wan't to echo something with belongsTo but the output gives me some strange characters back.

class Leviews extends Entity
{
public $table = 'reviews';


public function ravatar()
{
  return $this->belongsTo('User', 'author', 'username')->select('avatar');

}

now when i echo the data with {{ $item->ravatar }} im getting this

{"avatar":"avatars\/1.jpg"} 

and it should be

avatars/1.jpg    

what im doing wrong?

edit here is the Controller

<?php

use Carbon\Carbon;
use Lib\Reviews\LeviewsRepository;
use Lib\Services\Scraping\Scraper;
use Lib\Services\Validation\LeviewsValidator;

class LeviewsController extends \BaseController {

/**
 * Leviews repository instance.
 * 
 * @var Lib\Leviews\LeviewsRepository
 */
protected $repo;

/**
 * validator instance.
 * 
 * @var Lib\Services\Validation\LeviewsCreateValidator
 */
private $validator;

/**
 * Leviews scraper isntance.
 * 
 * @var Lib\Services\Scraping\NewScraper;
 */
private $scraper;

public function __construct(LeviewsRepository $lreviews, LeviewsValidator $validator, Scraper $scraper)
{
    $this->beforeFilter('csrf', array('on' => 'post'));
    $this->beforeFilter('logged', array('except' => array('index', 'show', 'paginate')));
    $this->beforeFilter('news:create', array('only' => array('create', 'store')));
    $this->beforeFilter('news:edit', array('only' => array('edit', 'update')));
    $this->beforeFilter('news:delete', array('only' => 'destroy'));
    $this->beforeFilter('news:update', array('only' => 'updateFromExternal'));

    $this->repo = $lreviews;
    $this->scraper = $scraper;
    $this->validator = $validator;
}

/**
 * Display list of paginated news.
 *
 * @return View
 */
public function index()
{
    return View::make('Leviews.Index');
}

/**
 * Display form for creating new news items.
 *
 * @return View
 */
public function create()
{
    return View::make('Leviews.Create');
}

/**
 * Store a newly created news item.
 *
 * @return Redirect
 */
public function store()
{
    $input = Input::except('_token');

    if ( ! $this->validator->with($input)->passes())
    {
        return Redirect::back()->withErrors($this->validator->errors())->withInput($input);
    }

    //escape double qoutes
    $input['title'] = htmlspecialchars($input['title']);

    $this->repo->store($input);

    return Redirect::back()->withSuccess( trans('main.news create success') );
}

/**
 * Display single news items.
 *
 * @param  int  $id
 * @return View
 */
public function show($id)
{
    $lreviews = $this->repo->byId($id);

    if ($lreviews->full_url && ! $lreviews->fully_scraped)
    {
        $lreviews = $this->repo->getFullLeviewsItem($lreviews);
    }

    return View::make('Leviews.Show')->with(compact('news'))->withRecent($this->repo->latest());
}

/**
 * Displays form for editing news item.
 *
 * @param  int  $id
 * @return View
 */
public function edit($id)
{
    $lreviews = $this->repo->byId($id);

    return View::make('Leviews.Edit')->withLeviews($lreviews);
}

/**
 * Updates the news item.
 *
 * @param  int  $id
 * @return Redirect
 */
public function update($id)
{
    $input = Input::except('_token', '_method');

    $lreviews = $this->repo->byId($id);

    if ($lreviews->title === $input['title'])
    {
        //dont check for title uniqueness when updating if
        //title was not updated.
        $this->validator->rules['title'] = 'required|min:2|max:255';
    }

    if ( ! $this->validator->with($input)->passes())
    {
        return Redirect::back()->withErrors($this->validator->errors())->withInput($input);
    }

    //escape double qoutes
    $input['title'] = htmlspecialchars($input['title']);

    $this->repo->update($lreviews, $input); 

    return Redirect::back()->withSuccess( trans('main.news update success') );
}

/**
 * Delete specified news item.
 *
 * @param  int  $id
 * @return Response
 */
public function destroy($id)
{
    $this->repo->delete($id);       

    return Response::json(trans('main.news delete success'), 200);
}

/**
 * Updates news from external sources.
 * 
 * @return void
 */
public function updateFromExternal()
{
    $this->scraper->updateLeviews();

    Event::fire('Leviews.Updated', Carbon::now());

    return Redirect::back()->withSuccess( trans('dash.updated news successfully') );
}

}

and here the view

    @if ($options->enableNews())

                @foreach($lreviews as $k => $item)

                    {{ $item->body }}
                    {{ $item->ravatar }}

                @endforeach

    @endif

{{ $item->body }} is without strange characters

decode json object sent form android app to php server

I am sending json object from android as such:

//Create JSONObject here
                    JSONObject json = new JSONObject();
                    json.put("key", String.valueOf(args[0]));

                    String postData=json.toString();

                    // Send POST output.
                    printout = new DataOutputStream(urlConn.getOutputStream ());
                    printout.writeUTF(URLEncoder.encode(postData,"UTF-8"));
                    Log.i("NOTIFICATION", "Data Sent");
                    printout.flush ();
                    printout.close ();

When it is sent to the server it looks like the following code snippet. ???%7B%22key%22%3A%22value%22%7D I should add the first ??? are in a diamond each. When I decode the whole json object I get null. In the php server I have

$somevar=json_decode(json, true);

which returns null. Can someone point me on how to retrieve the json value? Thanks so much:)

Paypal IPN INVALID & No POST

I'm trying to use paypal ipn but I don't receive any posts from paypal and the result is always invalid.

I need you kind help.

I'm using the code below :

<?php

// STEP 1: read POST data

// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
// Instead, read raw POST data from the input stream. 
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
  $keyval = explode ('=', $keyval);
  if (count($keyval) == 2)
     $myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
   $get_magic_quotes_exists = true;
} 
foreach ($myPost as $key => $value) {        
   if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) { 
        $value = urlencode(stripslashes($value)); 
   } else {
        $value = urlencode($value);
   }
   $req .= "&$key=$value";
}


// STEP 2: POST IPN data back to PayPal to validate

$ch = curl_init('http://ift.tt/xpRUtH');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));

// In wamp-like environments that do not come bundled with root authority certificates,
// please download 'cacert.pem' from "http://ift.tt/piTBkz" and set 
// the directory path of the certificate as shown below:
// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
if( !($res = curl_exec($ch)) ) {
    // error_log("Got " . curl_error($ch) . " when processing IPN data");
    curl_close($ch);
    exit;
}
curl_close($ch);


// STEP 3: Inspect IPN validation result and act accordingly

if (strcmp ($res, "VERIFIED") == 0) {
    // The IPN is verified, process it:
    // check whether the payment_status is Completed
    // check that txn_id has not been previously processed
    // check that receiver_email is your Primary PayPal email
    // check that payment_amount/payment_currency are correct
    // process the notification

    // assign posted variables to local variables
    $item_name = $_POST['item_name'];
    $item_number = $_POST['item_number'];
    $payment_status = $_POST['payment_status'];
    $payment_amount = $_POST['mc_gross'];
    $payment_currency = $_POST['mc_currency'];
    $txn_id = $_POST['txn_id'];
    $receiver_email = $_POST['receiver_email'];
    $payer_email = $_POST['payer_email'];

    // IPN message values depend upon the type of notification sent.
    // To loop through the &_POST array and print the NV pairs to the screen:
    foreach($_POST as $key => $value) {
      echo $key." = ". $value."<br>";
    }
} else if (strcmp ($res, "INVALID") == 0) {
    // IPN invalid, log for manual investigation
    echo "The response from IPN was: <b>" .$res ."</b>";

        // assign posted variables to local variables
    $item_name = $_POST['item_name'];
    $item_number = $_POST['item_number'];
    $payment_status = $_POST['payment_status'];
    $payment_amount = $_POST['mc_gross'];
    $payment_currency = $_POST['mc_currency'];
    $txn_id = $_POST['txn_id'];
    $receiver_email = $_POST['receiver_email'];
    $payer_email = $_POST['payer_email'];

    // IPN message values depend upon the type of notification sent.
    // To loop through the &_POST array and print the NV pairs to the screen:
    foreach($_POST as $key => $value) {
      echo $key." = ". $value."<br>";
    }

}


?>

Thank you for your help in advance.

Kindly ignore the text below:

It looks like your post is mostly code; please add some more details.

It looks like your post is mostly code; please add some more details.

It looks like your post is mostly code; please add some more details.

It looks like your post is mostly code; please add some more details.

script error in javascript

I have an script prices table in javascript and jquery.. and is not working the paypal button and the error functions.. I tryed in my phone and is working property only from pc is not working..

This is my script:

<?
include("../../config.php"); 

   session_start();
    if(!isset($_SESSION['login'])) die;
    $dbres  = mysql_query("SELECT *,UNIX_TIMESTAMP(`online`) AS `online` FROM `users` WHERE `login`='{$_SESSION['login']}'");
$data   = mysql_fetch_object($dbres);
    ?>
<div id="sett-title"> Simple. Easy. Affordable. </div>
We have made the process of buying social media services ultra simple and user friendly. Just simply follow these steps.
</br>
<a class="glyphicons circle_arrow_right"><i></i></a>Choose a service from below</br>
<a class="glyphicons circle_arrow_right"><i></i></a>Select your package</br>
<a class="glyphicons circle_arrow_right"><i></i></a>Enter your details (URL, username etc.)</br>
<a class="glyphicons circle_arrow_right"><i></i></a>Pay for your order</br>
<a class="glyphicons circle_arrow_right"><i></i></a>We deliver your order within 72 hours.</br>

</br>
<div class="infobox"><center>
<a href="javascript:void(0)" onclick="$('#content').load('fb.php'); window.location.hash = 'Shop';" class="button" style="width:120px;text-align:center">Facebook</a></center></div>
<hr style="margin: 20px 20px 20px 20px">
<div align="center">

<table width="100%"><tr><td>
<?php
  $queryRes = mysql_query("SELECT * FROM `shop` ORDER BY `id` ASC");
for($j=1; $shop = mysql_fetch_object($queryRes); $j++) {

?>
<div class="buy_boxs">
        <table width="100%">
            <tr style="height:40px">


                        <div id="title-premium-boxs"><span style="margin: 30px"><span class="glyphicons face"><i></i><?=$shop->name?> </span></span></div>

                    <div class="gray-area">24-72 hour delivery</div>
                    <ul class="special" style="margin: 10px 22px 10px 40px">



<li>
<strong><?=$shop->nr1?></strong>
<?=$shop->media?>
<span class="away">$<?=$shop->price1?></span>
</li>
<li>
<strong><?=$shop->nr2?></strong>
<?=$shop->media?>
<span class="away">$<?=$shop->price2?></span>
</li>
<li>
<strong><?=$shop->nr3?></strong>
<?=$shop->media?>
<span class="away">$<?=$shop->price3?></span>
</li>
<li>
<strong><?=$shop->nr4?></strong>
<?=$shop->media?>
<span class="away">$<?=$shop->price4?></span>
</li>
<li>
<strong><?=$shop->nr5?></strong>
<?=$shop->media?>
<span class="away">$<?=$shop->price5?></span>
</li>
</ul></a>




               <script language="javascript">
                   function setPrice<?=$j?>()
                   {

                       value              = $("#item_number<?=$j?> :selected").val();
                       option_text<?=$j?> = $("#item_number<?=$j?> :selected").text();
                       arr_data<?=$j?>    = option_text<?=$j?>.split("—");
                       price<?=$j?>       = arr_data<?=$j?>[1].replace('$','');
                       custom<?=$j?>      = $("#custom<?=$j?>").val();

                      $("#item_name<?=$j?>").val(option_text<?=$j?>+' '+custom<?=$j?>);
                      $("#item_number<?=$j?>").val(value);
                      $("#amount<?=$j?>").val(price<?=$j?>);

                   }
                </script>       

                <select class="selection" name="item_number<?=$j?>" id="item_number<?=$j?>" style="margin: 10px 22px 10px 25px; width: 201px" onchange="setPrice<?=$j?>();">
                        <option value="">Select</option>
                        <option data-price="15" value="TF1000"> <?=$shop->nr1?> <?=$shop->media?> — $0.02 </option>
                        <option data-price="20" value="TF5000"> <?=$shop->nr3?> <?=$shop->media?> — $<?=$shop->price2?> </option>
                        <option data-price="30" value="TF10000"> <?=$shop->nr3?> <?=$shop->media?> — $<?=$shop->price3?> </option>
                        <option data-price="75" value="TF50000"> <?=$shop->nr4?> <?=$shop->media?> — $<?=$shop->price4?> </option>
                        <option data-price="150" value="TF100000"> <?=$shop->nr5?> <?=$shop->media?> — $<?=$shop->price5?> </option>
                </select>
                    <div class="gray-area extrapadding">
<input style="margin: -14px 23px 10px 25px; width: 188px;" type="text" placeholder="<?=$shop->placeholder?>" name="custom<?=$j?>" id="custom<?=$j?>">
</div>


                <script language="javascript">
                 function checkerror<?=$j?>()
                 {

                    value              = $("#item_number<?=$j?> :selected").val();
                    option_text<?=$j?> = $("#item_number<?=$j?> :selected").text();
                    custom<?=$j?>      = $("#custom<?=$j?>").val();
                    $("#item_name<?=$j?>").val(option_text<?=$j?>+' '+custom<?=$j?>);


                    custom<?=$j?>      = $("#custom<?=$j?>").val();

                    if(custom<?=$j?>=="")
                    {
                      alert("Fanpage URL / Facebook Username is a required filed");
                      return false;
                    }

                 }
                </script>

                    <div style="text-align:right">
<form action="http://ift.tt/rDmnwQ" method="post" onsubmit="return checkerror<?=$j?>();">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" id="business" value="mail@yahoo.com">
<input type="hidden" name="item_name" id="item_name<?=$j?>"  value="<? echo $site->site_brand;?> <? echo $pack->name;?>">
<input type="hidden" name="item_number" id="item_number<?=$j?>" value="<? echo $pack->coins;?>+ Credits">
<input type="hidden" name="custom" value="<? echo $data->id; ?>">
<input type="hidden" name="amount" id="amount<?=$j?>" value="<? echo $pack->price;?>">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="button_subtype" value="services">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="no_shipping" value="2">
<input type="hidden" name="rm" value="1">
<input type="hidden" name="return" value="<?echo $site->site_url;?>/return.php">
<input type="hidden" name="cancel_return" value="<?echo $site->site_url;?>">
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHosted">
<input type="hidden" name="notify_url" value="<?echo $site->site_url;?>/ipn.php">
<!--<input style="width:80px;border:none;background:none;" type="image" src="http://ift.tt/18UOXym" name="submit" alt="PayPal - The safer, easier way to pay online!" /><img alt="" src="http://ift.tt/qzX37J" width="1" height="1" />-->
<input style="width: 151px;border: 1px solid #b6b6b6; margin: 10px 22px 10px 25px; width: 201px" type="submit" name="submit"  value="Buy Now" class="button" />

</form>




                            </div>

                </td>

            </tr>

        </table>

</div>      
<?php } ?>

</td></tr></table>

<br clear="all">
<br>
<b><?=$lang['sp85']?></b><br>
<br>
<span style="font-size: 10pt;font-family: Arial;"><?=$lang['sp86']?></span>
<?

If I use this script without javascript is working..

For see live:

http://goo.gl/5kYwtQ (working version)

usr: xdesign pass: carina

For see here is not working.. click in the menu "Shop" buton.

Thank you very much for your help

Magento: if statement not functioning correctly

I am having an issue getting my if statement to function the way I want it. I have an Appointment Maker that shows up on the bottom of every page. Say they submit the form on the homepage/contact/about page, I want that to direct them to the /success/ page. Now say they are on a product detail page, which they more than likely will, I just want it to revert the success indicator back onto that specific product page they were on to begin with.

This is the coding I have at the moment:

$product = Mage::getModel('catalog/product')->load($data['product_id']);
   Mage::getSingleton('catalog/session')->addSuccess(Mage::helper('appointmentmaker')->getSuccessMessage());
    if($product) {
        $this->_redirectUrl($product->getProductUrl());
    } else {
        $this->_redirectUrl('/success/');
    }
    return; 

I can get the product redirect to work. But if they submit from the homepage, it will try to find the product detail page which of course there isn't one. It doesn't try to use the /success/ page instead.

HTML/PHP Form doesn't sent data to MySQL Database

Hi this is my first question, so tell me if i do something wrong. I'm new to PHP so this is kinda new to me. Anyway im creating a site so i can access my recepies online.

This is the form:

<form action="Form.php" method="post" class="basic-grey">
<h1><a href="index.html">Receita</a>
    <span>Aqui podes adicionar uma nova receita</span>
</h1>
<label>
    <span>Titulo :</span>
    <input id="titulo" type="text" size="20" maxlength="100" name="titulo" placeholder="Introduza o Titulo" />
</label>

<label>
    <span>Categoria :</span><select  maxlength="10" name="categoria">
    <option value="categoria">--- Seleccione aqui a Categoria ---</option>
    <option name=" " value="sopa">Sopa</option>
    <option name="entrada" value="entrada">Entrada</option>
    <option name="carne" value="carne">Carne</option>
    <option name="peixe" value="peixe">Peixe</option>
    <option name="salada" value="salada">Salada</option>
    <option name="sobremesa" value="sobremesa">Sobremesa</option>
    </select>

</label>

<label>
    <span>Ingredientes :</span>
    <textarea id="ingredientes" size="20" maxlength="1000" name="ingredientes" placeholder="Introduza os ingredientes"></textarea>
</label> 
<label>
    <span>Preparação :</span>
    <textarea id="preparacao" size="20" maxlength="1000" name="preparacao" placeholder="Introduza o modo de preparação"></textarea>
</label> 
<label>
    <span>Notas :</span>
    <textarea id="notas" size="20" maxlength="1000" name="notas" placeholder="Aqui pode adicionar uma nota"></textarea>
</label> 
<label>
    <span>&nbsp;</span> 
    <input type="submit" class="button" value="Enviar" /> 
</label>   

</form>

This is the code to handle the form:

<?php
// processing form values


if ($_SERVER['REQUEST_METHOD'] == 'POST'){

$titulo = $_POST['titulo'];
$categoria = $_POST['categoria'];
$ingredientes = $_POST['ingredientes'];
$preparacao = $_POST['preparacao'];
$notas = $_POST['notas'];


if(!empty($titulo) && !empty($categoria) && !empty($ingredientes) && !empty($preparacao) && !empty($notas)){

    include('connection.php');

    mysqli_query($dbc, "INSERT INTO receita(Titulo,Categoria,Ingredientes,Preparacao,Notas) VALUES ('$titulo','$categoria','$ingredientes','$preparacao','$notas')");
    $registered = mysqli_affected_rows($dbc);
    echo $registered." row is affected, everything worked fine!";
}else{
    echo "Please fill all values on the form";
}

}else{

echo "No form has been submitted";

}

?>

And what happens its that if i input something like this it doesn't work:

Titulo:Açorda de camarao

Categoria: Peixe

Ingredientes: 800 g de camarao; 4 dentes de alho; 1 ramo de salsa ou coentros; 3 ovos inteiros; 1.5 dl de Azeite; 1.5 pão por pessoa; sal; piri-piri

Preparação: Coze-se o camarão com sal e piri-piri e reserva-se a agua. De seguida demolha-se o pão na agua do camarão. Aquece-se o azeite com os alhos e os coentros e de seguida junta-se o camarão e por ultimo o pão. Mexe-se tudo para cozer o pão e ganhar consistencia. Por ultimo junta-se os ovos e envolve-se tudo.

Nota: Receita para 4 pessoas

But if i input like this it works:

Titulo:gfdsfdsa

Categoria: Peixe

Ingredientes: hudsbfbdsf fdsfidsfidsfsd, fdsjifjdsifdis 0palpdsandnsaud jkdosakodsakodmnsa jidsjaidsa

Preparação: nfjdbshfbhdbjfdjs dsajijdisandiabuu fjndoisjfojidsanfds

Nota: fbhdubsufbndsnfs

My database table:

Nome    Tipo    Agrupamento (Collation) Atributos   Nulo    Omissao Extra   

1 ID bigint(50) Não None AUTO_INCREMENT Muda Muda Elimina
2 Titulo varchar(100) utf8_general_ci Não None Muda Muda Elimina 3 Categoria varchar(10) utf8_general_ci Não None Muda Muda
4 Ingredientes varchar(1000) utf8_general_ci Não None Muda 5 Preparacao varchar(1000) utf8_general_ci Não None Muda Muda 6 Notas varchar(1000) utf8_general_ci Não None Muda Muda

Sorry if this post its to long. Any ideas how to fix it?

Space and special characters problems on post

I got a problem with blank space and special characters during a POST action using this AJAX function:

function comments(id,postId,user_id) {
        var user_comments = encodeURIComponent($("#commentsId_"+id).val());
        if(user_comments!=''){
            var img = $("#img_"+id).val();
            var username = "<?php echo $this->session->userdata('username'); ?>"
            $.ajax({
                    type: "POST",
                    url: "<?php echo base_url() ?>social/userscomment/" +user_id+"/"+postId+"/"+user_comments,
                    data:{ user_comments : user_comments},
                    success: function(data) { 
                        $("#commentsId_"+id).val('');
                        var $sparkLines = $('.comments_body_'+id);
                        $("#comments_add_"+id).append('<div id="id' + ($sparkLines.length + 1) + '" class="comments_body_"'+id+'><div class="feed-element comments_body_"'+id+'><a class="pull-left"><strong>'+username+' <i class="fa fa-comment-o"></i></strong></a><div class="media-body">'+user_comments+'<br></div><div class="col-lg-12"><a id="span_'+postId+'" onclick="callajaxcommcool('+postId+')" class="btn btn-xs btn-white"><i class="fa fa-star"></i><span id="span1_'+postId+'" style="display:none;">1</span> Cool </a></div></div></div></div>');
                    }
            });
        }
    }

The PHP controller:

public function userscomment($comment_id,$post_id,$user_comments){

    $this->load->model('comments');

    $user_comments = utf8_decode(trim(mysql_real_escape_string($user_comments)));

    if(!empty($user_comments)){

        $data = array("user_id"         => $this->session->userdata('user_id'),
                      "comment_user_id" => $comment_id,
                      "comments"        => $user_comments,
                      "post_id"         => $post_id,
                      "username"        => $this->session->userdata('username')
                );
        $this->comments->insertComments($data);

        //logged user
       $userRow = $this->register->get_login($this->session->userdata('user_id'));
       redirect('social/userprofile/'.$userRow[0]['username']);
    }
}    

When an user post a comment like: "a b c d" the results showed in the view is: a%20b%20c%20d, if an user try to wrote a special characters like € i got this results %E2%82%AC

How can i prevent this problem?