#StackBounty: #magento-1.9 #php #csv #inventory #import-script Multiple Inventory slots for Different warehouses

Bounty: 50

I have found a great script that allows for quick inventory updating via a php script, and it does work well. I am able to just go by SKU, quantity, and set each as is_in_stock.

My question then becomes, we have two main warehouses, call them Main and West, would it be possibly to add a secondary inventory slot to each product, and via the same script with few adjustments, be able to upload two different values for each warehouse?

Implementation of the display would be simple enough as currently it is just:

<?php 
$qty = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty();
if ($qty<=0) { ?>

//Backordered

<?php } else { ?>    

//Echo Quantity
<?php echo $qty; } ?>

<?php endif; ?>

And adding another slot could turn into (what I assume) just $qty_secondary with similar loading format.


As a side note, I see the work it goes through with each product, is it as optimized as it could be? It was created back in 2010, and I imagine a lot of things have changed since then and it could be changed for the better I’m sure.


System: Magento 1.9.0.1 & PHP 5.6


Get this bounty!!!

#StackBounty: #php How does "array_diff_ukey" function in php evaluate the arguments?

Bounty: 50

I executed the following code and its result made me confused! I pass two arrays and a function named “myfunction” as arguments to array_diff_ukey function. myfunction have been called 13 times (while it should be called at most 9 times) and the more amazing is that it compares the keys of the same array, too. In both column of the output, I saw the key “e” while only the second array has it (the fact is true for the other keys).

<?php
function myfunction($a,$b)
{
    echo $a . "   ".$b."<br>";
    if ($a===$b)
    {
        return 0;
    }
    return ($a>$b)?1:-1;
}

$a1=array("a"=>"green","b"=>"blue","c"=>"red");
$a2=array("d"=>"blue","e"=>"black","f"=>"blue");

$result=array_diff_ukey($a1,$a2,"myfunction");
print_r($result);
?> 

Output:
Screenshot and eval.in


Get this bounty!!!

#StackBounty: #php #arrays #json #string #shopify Creating multiple metafields with different key showing Error

Bounty: 50

I want to Create multiple Meta fields with different key but it displaying me following error:

‘metafield’ => ‘expected Array to be a Hash’,

This is my code:

    $prodcut_variant = array(

    'metafield'=>array(
       array('namespace'=>'orbital_response',
             'key'=>'Os Purchases',
             'value'=>'0',
             'value_type'=>integer,),
       array('namespace'=>'orbital_response',
             'key'=>'Stock Status',
             'value'=>'C',
             'value_type'=>integer,)

));

$request_update = $shopify('POST /admin/products/{#ID}/metafields.json',array(),$prodcut_variant);


Get this bounty!!!

#StackBounty: #php #mongodb #function #php-mongodb PHP MongoDB – Use of the aggregate command without the cursor option is deprecated. …

Bounty: 300

I have updated mongo and now in the log the following error appears:
Use of the aggregate command without the cursor option is deprecated

Mongo says that I should put a second REQUIRED parameter to aggregate function, because my current usage is deprecated.

I currently use the following code PHP (now is deprecated):

$this->db->{$collection}->aggregate($options);

And return this format:

{"result":[
    {
    "_id":"xxxxxx",
    "update":[
    {
    "firstUpdateTime":xxxxxx,
    "updateTime":xxxxxxx,
    }
    ],
    "media":[
    {
    "xxxx":{ ...

To not use an deprecated code I add the new second parameter (but I do not understand what to put):

$this->db->{$collection}->aggregate($options, array('cursor' => array('batchSize' => 1)));

And this returns the same information but varies the initial structure:

{"cursor":{
"id":{
"value":"xxxxxx"
},
"ns":"xxxxxx.instagram",
"firstBatch":[
{
"_id":"xxxxxx",
"update":[
{
"firstUpdateTime":xxxxxx,
"updateTime":xxxxxx,
}
],
"media":[
{
"xxxxxx":{ ...

After the update Mongo forces me to change the way I read the data.
I don’t understand what value I should put in that second parameter called “cursor”…

What should I put in that second parameter?
Can I set a default value without altering the structure of results?

Doc:
https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/
http://php.net/manual/es/mongocollection.aggregate.php


Get this bounty!!!

#StackBounty: #php #phpexcel #pie-chart #options PHPExcel Pie Chart Series Options 25% on primary axis

Bounty: 50

I was able to create 2 pie charts programmatically (im using PHP), using the PHPExcel library (no need to list the code since it’s too large) but i can not find a way to increase the distance between the pie’s pieces like in the picture below. Basically, im trying to programmatically increase the Series Options on primary axis by 25%.enter image description here


Get this bounty!!!

#StackBounty: #php #wordpress #woocommerce WordPress Woocommrece try on service for product

Bounty: 50

I am developing a eCommerce site and my client want to product on rent functionality.

for e.g :- On Add To Cart page a product has delivery + return date on add to cart page

Suppose i have select date from 24 to 28 and I would product on try on specific date so when I add to cart product then trial product also added with charge.

E.g Screenshot attached:

enter image description here


Get this bounty!!!

#StackBounty: #php #templates #pagination Static Frontpage Pagination – Custom loop

Bounty: 100

I created a custom content template, assigned it to a page and coded the query.

Everything appears to be working as they should. The only issue I have is with the pagination. So, when I go the second page I get a “No posts were found.”

What I’ve tried so far:

  • I set another paginated grid (3rd party plugin) as a homepage.
    Fiddling with the pagination of that plugin gave me the same
    devastating result.

This is my source

            <?php
            if ( get_query_var('paged') ) {
                 $paged = get_query_var('paged');
                 } elseif ( get_query_var('page') ) {
                 $paged = get_query_var('page');
                 } else {
                 $paged = 1;
                 }
              $args=array(
                 'post_type' => 'gadget',
                 'post_status' => 'publish',
                 'posts_per_page' => 36,
                 'paged' => $paged,
                 'nopaging' => false
                );

              $fp_query = null;
              $fp_query = new WP_Query($args);

              if( $fp_query->have_posts() ) {

                $i = 0;
                while ($fp_query->have_posts()) : $fp_query->the_post();
                global $post;
                $postidlt = get_the_id($post->ID);

              // modified to work with 3 columns
              // output an open 
if($i % 3 == 0) { ?>
">
"true", "url"=>"true","id"=>"$postidlt")); } ?>);">
,
"FIELD_NAME : $ FIELD_VALUE", "id"=>"$postidlt")); if($discountbg) : ?>
<?php endif; ?> <!-- Video Condition -->
<!-- Crowdfunding Condition --> <?php if ( has_term('crowdfunding', 'gadget-categories', $post->ID) ): ?>
<?php endif; ?> </div> </div> </a> </div>
</div>
"FIELD_NAME : $ FIELD_VALUE", "id"=>"$postidlt")); $discountedprice = types_render_field("discount", array("style" => "FIELD_NAME : $ FIELD_VALUE", "id"=>"$postidlt")); $tba = types_render_field("tba-n", array("output" => "raw", "id"=>"$postidlt")); $currency = types_render_field("currency", array()); if ($initalprice && empty($discountedprice) && empty($tba)) { echo($currency),($initalprice); } elseif ($discountedprice && empty($tba)) { echo($currency),($discountedprice); } elseif ($tba) { echo("TBA"); } ?>
ID , 'gadget_categories' ); foreach ( $terms as $index => $term ) { if ($index == 0) { // The $term is an object, so we don't need to specify the $taxonomy. $term_link = get_term_link( $term ); // If there was an error, continue to the next term. if ( is_wp_error( $term_link ) ) { continue; } // We successfully got a link. Print it out. echo '' . $term->name . ''; } } ?> ID , 'gadget_categories' ); echo '
'; foreach ( $terms_rst as $index => $term ) { if ($index > 0) { // The $term is an object, so we don't need to specify the $taxonomy. $term_link = get_term_link( $term ); // If there was an error, continue to the next term. if ( is_wp_error( $term_link ) ) { continue; } // We successfully got a link. Print it out. echo '' . $term->name . ''; } } echo '
'; ?> </div> </div> </div>
</div>
true ); do_action('gd_mylist_btn',$arg); ?>
</div> </div>
</div> </div> <?php $i++; // Closing the grid row div if($i != 0 && $i % 3 == 0) { ?> </div><!--/.row-->
<?php } ?> <!-- Random Category Snippet Generation --> <?php if( $i % 12 == 0 ) { $max = 1; //number of categories to display $taxonomy = 'gadget_categories'; $terms = get_terms($taxonomy, 'orderby=name&order= ASC&hide_empty=0'); // Random order shuffle($terms); // Get first $max items $terms = array_slice($terms, 0, $max); // Sort by name usort($terms, function($a, $b){ return strcasecmp($a->name, $b->name); }); // Echo random terms sorted alphabetically if ($terms) { foreach($terms as $term) { $termID = $term->term_id; echo '
$termID, "output" =>"raw") ).')">
'; } } } ?> <?php endwhile; } wp_reset_postdata(); ?>

You can see a live representation of the issue by visiting this link and clicking on “Newer Posts” at the bottom of the page.

EDIT

You can see that at the moment there is a lazyloader at the bottom of the page. Using this template I almost achieved the desired result here. However, I still get nothing on the frontpage (keep in mind that the frontpage and the page I provided before are using the same exact template.


Get this bounty!!!

#StackBounty: #performance #php #authentication #laravel #steam Steam Auth for Laravel

Bounty: 100

I’m not expert on OpenID, so i don’t know if my package is correct and safe. I’ve realized that after login on Steam community, take about 2/3 seconds to return to my page. It’s my issue or is from steam?

{
/**
 * The application instance.
 *
 * @var IlluminateContractsFoundationApplication
 */
private $app;
/**
 * The HTTP Client instance.
 *
 * @var GuzzleHttpClient
 */
private $httpClient;
/**
 * The custom parameters to be sent with the request.
 *
 * @var array
 */
private $parameters = [];
/**
 * The type of the encoding in the query.
 *
 * @var int Can be either PHP_QUERY_RFC3986 or PHP_QUERY_RFC1738.
 */
private $encodingType = PHP_QUERY_RFC3986;
/**
 * Create a new Steamlite manager instance.
 *
 * @param IlluminateContractsFoundationApplication $app
 * @return void
 */
public function __construct(Application $app)
{
    $this->app = $app;
}
/**
 * {@inheritdoc}
 */
public function redirect()
{
    return new RedirectResponse($this->getAuthUrl());
}
/**
 * {@inheritdoc}
 */
public function user()
{
    if ($this->hasInvalidSignature($query = $this->app['request']->query())) {
        throw new InvalidSignatureException();
    }
    return $this->mapUserToObject($this->getUserByToken($this->getAccessToken($query)));
}
/**
 * Get the raw user for the given access token.
 *
 * @param string $token
 * @return array
 */
private function getUserByToken($token)
{
    $userUrl = 'https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='.$this->app['config']['services.steam']['key'].'&steamids='.$token;
    $response = $this->getHttpClient()->get($userUrl);
    $user = json_decode($response->getBody(), true);
    return Arr::get($user, 'response.players.0');
}
/**
 * Map the raw user array to a User instance.
 *
 * @param array $user
 * @return Lai0nSteamliteUser
 */
private function mapUserToObject(array $user)
{
    return (new User)->setRaw($user)->map([
        'id' => $user['steamid'], 'nickname' => $user['personaname'], 'name' => Arr::get($user, 'realname', null),
        'avatar' => $user['avatar'], 'visibility' => $user['communityvisibilitystate'],
    ]);
}
/**
 * Parse the access token from identity url.
 *
 * @param array $query
 * @return string
 */
private function getAccessToken(array $query)
{
    preg_match('//id/(d+)$/i', $query['openid_identity'], $matches);
    return $matches[1];
}
/**
 * Get the URL for the steam authentication screen.
 *
 * @return string
 */
private function getAuthUrl()
{
    return $this->buildAuthUrl('https://steamcommunity.com/openid/login');
}
/**
 * Build the authentication URL with the OpenID and custom parameters.
 *
 * @param string $url
 * @return string
 */
private function buildAuthUrl($url)
{
    return $url.'?'.http_build_query($this->getCodeFields(), '', '&', $this->encodingType);
}
/**
 * Get the GET parameters for the code request.
 *
 * @return array
 */
private function getCodeFields()
{
    $fields = [
        'openid.ns' => 'http://specs.openid.net/auth/2.0',
        'openid.mode' => 'checkid_setup',
        'openid.realm' => $this->app['config']['app.url'],
        'openid.return_to' => $this->app['config']['services.steam']['redirect'],
        'openid.identity' => 'http://specs.openid.net/auth/2.0/identifier_select',
        'openid.claimed_id' => 'http://specs.openid.net/auth/2.0/identifier_select',
    ];
    return array_merge($fields, $this->parameters);
}
/**
 * Determine if the current request has a mismatching signature.
 *
 * @param array $query
 * @return bool
 */
private function hasInvalidSignature(array $query)
{
    $postKey = (version_compare(ClientInterface::VERSION, '6') === 1) ? 'form_params' : 'body';
    $response = $this->getHttpClient()->post('https://steamcommunity.com/openid/login', [
        $postKey => $this->getCheckAuthFields($query)
    ]);
    return preg_match('/is_valids*:s*false/i', $response->getBody());
}
/**
 * Get the fields for check authentication.
 *
 * @param array $query
 * @return array
 */
private function getCheckAuthFields(array $query)
{
    $fields = [];
    foreach ($query as $index => $item) {
        $position = strpos($index, '_');
        if ($position !== false) {
            $index = substr_replace($index, '.', $position, strlen('_'));
        }
        $fields[$index] = $item;
    }
    $fields['openid.mode'] = 'check_authentication';
    return $fields;
}
/**
 * Get a instance of the Guzzle HTTP client.
 *
 * @return GuzzleHttpClient
 */
private function getHttpClient()
{
    if (is_null($this->httpClient)) {
        $this->httpClient = new Client();
    }
    return $this->httpClient;
}
/**
 * Set the Guzzle HTTP client instance.
 *
 * @param GuzzleHttpClient $client
 * @return $this
 */
public function setHttpClient(Client $client)
{
    $this->httpClient = $client;
    return $this;
}
/**
 * Set the custom parameters of the request.
 *
 * @param array $parameters
 * @return $this
 */
public function with(array $parameters)
{
    $this->parameters = $parameters;
    return $this;
}


Get this bounty!!!

#StackBounty: #php #ajax #laravel #render #laravel-blade Render multiple blade view sections on ajax request

Bounty: 50

When request is ajax, i am rendering content section and inserting it to DOM. It is working as expected.

However.. i can’t find out the way, how to render multiple sections, like content and title and more in the same time.

Controller:

public function awesome(Request $request) {
   if($request->ajax()){
       return view('awesome')->renderSections()['content'];
   }
   return view('awesome');
}

Ajax and pushstate

var load = function (url) {
    $.get(url).done(function (data) {
      $("#content").html(data);
    })
};

$(document).on('click', 'a[data-request="push"]', function (e) {
    e.preventDefault();
    var $this = $(this),
    url = $this.attr("href"),
    title = $this.attr('title');

    history.pushState({
       url: url,
       title: title
    }, title, url);

    // document.title = title;

    load(url);
});

layouts.app

<title>@yield('title')</title>
<meta name="description" content="@yield('desc')"/>

<a data-request="push" title="AWESOME" href="<?= url('/'); ?>/awesome">Awesome</a>
<a data-request="push" title="RANDOM" href="<?= url('/'); ?>/random">Random</a>

@yield('content')

Blade:

@extends('layouts.app')

@section('title', 'Awesome')
@section('desc', 'About awesome')

@section('content')
  some text from awesome page
@endsection

Question:

How to render both or more of them in same time? Should i use an array or something else? Please give example or full explanation.

Thanks for any answers.


Get this bounty!!!

#StackBounty: #php #node.js #redis #publish-subscribe #autobahn Real time chat in PHP +Redis +Pub/Sub +WebSockets (+NodeJS)

Bounty: 50

I want to develop real time chat with channels and these are my needs:

  • PHP backend to manage site
  • Redis as session and data primary storage
  • Pub/Sub to send messages only to channel’s interested users
  • one WebSocket connection with which the messages will be send and received.
  • (optional) NodeJS to use great npm packages like timesync or socket.io

I see two different architectures to achieve this:

  • with Socket.io

    socket.io

  • with Crossbar.io

    crossbar.io

These are my questions:

  1. Which architecture I should choose and why?
  2. The key is the user id cannot be obtained from client, because it can be malformed. So in the first architecture I think on every socket message I should attach PHPSESSID value from cookie and on sever-side retrieve PHP session from Redis. Am I right or there is better way to get user id?
  3. I wonder if getting user id in second architecture can be done differently?

Edit:

I choosed Crossbar.io, cause it is very powerful and allows to communicate many different language applications in real time. After studying examples, I come up with this:

  • On every login user have generated secret key in database.
  • PHP client (Thruway) connect to Crossbar server and register custom WAMP-CRA authenticator

  • User’s browser connect to Crossbar server and is challenged. Secret and auth_id (user id) are loaded from DB with page load, so it
    can accomplish challenge and send response.

  • PHP authenticator search in DB for user with provided secret and id equal to auth_id. If there is, then it successfully authenticate
    session. Now we can trust that auth_id is real user id.

These are my question:

  1. How I can get auth_id on subscribe?
  2. I also added cookie authentication and browser is remembered after authentication. But when I look in Chrome DevTools there is any cookie nor value in local storage. Even after clearing cache my browser is still remember by Crossbar. I wonder how it is possible?


Get this bounty!!!