#StackBounty: #php #laravel Cart conditions won't save to table in laravel

Bounty: 50

I have products with and without conditions in my cart, when I add my cart data to orders table all my cart data will save except my products conditions.

dd of my cart data:

CartCollection {#699 ▼
  #items: array:1 [▼
    2 => ItemCollection {#670 ▼
      #config: array:6 [▶]
      #items: array:6 [▼
        "id" => 2
        "name" => "product two"
        "price" => 50000.0
        "quantity" => 2
        "attributes" => ItemAttributeCollection {#671 ▼
          #items: array:1 [▼
            "attr" => array:2 [▼
              "name" => "weight"
              "value" => "2"
            ]
          ]
        }
        "conditions" => array:1 [▼
          0 => CartCondition {#672 ▼
            -args: array:4 [▼
              "name" => "12 inch"
              "value" => "25000"
              "type" => "additional"
              "target" => "item"
            ]
            -parsedRawValue: 25000.0
          }
        ]
      ]
    }
  ]
}

dd of same cart when I try to save in orders table:

Order {#680 ▼
  #fillable: array:16 [▶]
  #events: array:1 [▶]
  #casts: array:1 [▶]
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: true
  #attributes: array:15 [▶]
  #original: array:15 [▼
    "product_data" => "{"2":{"id":2,"name":"product two","price":50000,"quantity":2,"attributes":{"attr":{"name":"weight","value":"2"}},"conditions":[{}]}}"
    "user_id" => 1
    "ordernu" => 9358964473
    "address_id" => "1"
    "orderstatus_id" => 1
    "quantity" => 2
    "payment_id" => null
    "buyer_name" => "John Doe"
    "note" => null
    "buyer_email" => "admin@admin.com"
    "phone" => "006281200000000"
    "price" => null
    "updated_at" => "2018-02-18 13:03:41"
    "created_at" => "2018-02-18 13:03:41"
    "id" => 10
  ]

As you see my conditions "conditions":[{}]} is empty.

Here is my save function:

 //save cart to orders table and remove items from it
    public function checkout(Request $request)
    {
      $cartItems = Cart::getContent();

      try {
        $order = new Order();
        $status  = Orderstatus::where('title', 'Witing Payment')->value('id');
        $qty = Cart::getTotalQuantity();
        $order->product_data = $cartItems; //save cart data as json
        $order->user_id = Auth::user()->id;
        $order->ordernu = mt_rand(1000000000, 9999999999);
        $order->address_id = $request->input('address_id');
        $order->orderstatus_id = $status;
        $order->quantity = $qty;
        $order->payment_id = $request->input('payment_id');
        $order->buyer_name = $request->input('buyer_name');
        $order->note = $request->input('note');
        $order->buyer_email = $request->input('buyer_email');
        $order->phone = $request->input('phone');
        $order->price = $request->input('totalPriceInTotal');
        dd(Auth::user()->orders()->save($order)); // dd results
        Auth::user()->orders()->save($order);

        foreach ($cartItems as $item) {
            $product = Product::find($item->id);
            $product->decrement('stock', $item->quantity);
        }

      $user = $order->buyer_email;
      event(new UserOrdered($order));

      //Cart::clear(); //clear cart info
      Session::flash('success', 'Thank you. Your order has been received.');
      return redirect()->route('ordersindex');
      }catch (Exception $e) {
         return response($e->getMessage(), 400);
      }
    }

any idea?

UPDATE

this is how i add products in my cart session:

public function addingItem(Request $request, $id)
    {
      //finding product
      $product = Product::findOrFail($id);
      //get product weight
      $weight = $product->weight;
      //list of discounts
      $discounts = Discount::all();
      //get current time
      $mytime = Carbon::now();

      // get product weight in cart
      $weightArray = [
        'attr' => [
              'name' => 'weight',
              'value' => $weight,
        ]
      ];

      // add product conditions to cart
      $customAttributes = [];
      if(!empty($request->attr)){
          foreach($request->attr as $sub) {
          // find the suboption
              $sub = Suboption::find($sub);
              if (!empty($sub->id)) {
                  $itemCondition1 = new DarryldecodeCartCartCondition(
                    [
                      'name' => $sub->title,
                      'value' => $sub->price,
                      'type' => 'additional',
                      'target' => 'item',
                    ]
                  );
                  array_push($customAttributes, $itemCondition1);
              }
          }
      }

      //adding product and options to cart
      Cart::add(array(
        'id' => $product->id,
        'name' => $product->title,
        'price' => $request->input('harga'),
        'quantity' => $request->input('quantity'),
        'attributes' => $weightArray,
        'conditions' => $customAttributes,
      ));
      //success message in return
      Session::flash('success', 'This product added to your cart successfully.');
      return redirect()->back();
    }

UPDATE 2

Well I’ve been playing with codes and I came to this code:

public function checkout(Request $request)
    {
      $cartItems = Cart::getContent();
      foreach($cartItems as $item){
          if (is_array($item['conditions'])) {
            foreach($item['conditions'] as $condition){
              $arsd = [
                'name' => $condition->getName(),
                'value' => $condition->getValue(),
              ];
             return $arsd;
            }
        }
      }

which is returning this: (what i need)

screen2

    "product_data" => "{

"16":{"id":16,"name":"new product","price":100000,"quantity":"1","attributes":{"attr":{"name":"weight","value":"56"}},"conditions":[{"args":null},{"args":null}]},

"4":{"id":4,"name":"product four","price":1500000,"quantity":"1","attributes":{"attr":{"name":"weight","value":"45"}},"conditions":[{"args":null}]},

"1":{"id":1,"name":"product one","price":10000000,"quantity":"1","attributes":{"attr":{"name":"weight","value":"1"}},"conditions":[]}
} ◀"

now the issue is how to apply this in my conditions part of my code? when I dd my cart while saving to database (orders table) this is what I get:

screen3

Note: products with id 16 & 4 supposed to have conditions and id 1
doesn’t have any condition.

Now, anyone there can help with that?


Get this bounty!!!

#StackBounty: #php #curl PHP 7 – execute code while waiting for curl

Bounty: 50

The following is my working code sample. Just add your own sleep.php which will sleep($_GET['sleep']);

class MultiCurl {
    private $mc;
    private $running;
    private $execStatus;

    public function __construct() {
        $this->mc = curl_multi_init();
    }

    public function addCurl($ch) {
        $code = curl_multi_add_handle($this->mc, $ch);

        if ($code === CURLM_OK || $code === CURLM_CALL_MULTI_PERFORM) {
            do {
                $this->execStatus = curl_multi_exec($this->mc, $this->running);
            } while ($this->execStatus === CURLM_CALL_MULTI_PERFORM);

            return $this->getKey($ch);
        }
        return null;
    }

    public function getNextResult() {
        if ($this->running) {
            while ($this->running && ($this->execStatus == CURLM_OK || $this->execStatus == CURLM_CALL_MULTI_PERFORM)) {
                usleep(2500);
                curl_multi_exec($this->mc, $this->running);

                $responses = $this->readResponses();
                if ($responses !== null) {
                    return $responses;
                }
            }
        } else {
            return $this->readResponses();
        }

        return null;
    }

    private function readResponses() {
        $responses = [];
        while ($done = curl_multi_info_read($this->mc)) {
            $key = $this->getKey($done['handle']);

            $done['response'] = curl_multi_getcontent($done['handle']);
            $done['info'] = curl_getinfo($done['handle']);
            $error = curl_error($done['handle']);
            if ($error) {
                $done['error'] = $error;
            }

            $responses[$key] = $done;

            curl_multi_remove_handle($this->mc, $done['handle']);
            curl_close($done['handle']);
        }

        if (!empty($responses)) {
            return $responses;
        }

        return null;
    }

    private function getKey($ch) {
        return (string)$ch;
    }
}

function getHandle($url) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 5
    ]);
    return $ch;
}

$totalTime = microtime(true);

$multi = new MultiCurl();

$keys = [];
$addCurlHandles = microtime(true);
$keys[] = $multi->addCurl(getHandle('http://localhost/sleep.php?sleep=5'));
for ($i = 0; $i < 5; $i++) {
    $keys[] = $multi->addCurl(getHandle('http://localhost/sleep.php?sleep=' . random_int(1, 4)));
}
echo 'Add curl handles: ' . (microtime(true) - $addCurlHandles) . "n";

/**/
$loop = microtime(true);
while (microtime(true) - $loop < 2) {
    usleep(100);
}
echo 'Loop: ' . (microtime(true) - $loop) . "n";
/**/

$getResults = microtime(true);
while ($result = $multi->getNextResult()) {
    foreach ($result as $key => $response) {
        echo $response['response'] . "n";
    }
}
echo 'Get results: ' . (microtime(true) - $getResults) . "n";

echo 'Total time: ' . (microtime(true) - $totalTime) . "n";

Now play around with the for loop calling $multi->addCurl. When I add 4 handles, the output is something like

Add curl handlers: 0.0007021427154541
Loop: 2.0000491142273
Slept 1
Slept 3
Slept 3
Slept 4
Slept 5
Get results: 5.0043671131134
Total time: 7.0052678585052

But when I add 5 or more, the output is

Add curl handlers: 0.0014941692352295
Loop: 2.00008893013
Slept 1
Slept 2
Slept 4
Slept 4
Slept 4
Slept 5
Get results: 3.0007629394531
Total time: 5.0025300979614

As you can see, the later does more work but finishes faster because the 5 second sleep request was actually sent before the 2 second while loop started working.

With the smaller number of handles, calling curl_multi_select and curl_multi_exec in a loop until curl_multi_select doesn’t return -1 has resolved this but it’s very unreliable. It doesn’t work at all on another computer and will sometimes get stuck with curl_multi_select always returning -1.


Get this bounty!!!

#StackBounty: #php #exchange #ldap Creating a user on exchange through LDAP

Bounty: 50

I have managed to use the LDAP module that comes standard with PHP to find, add, modify, and authenticate user accounts and groups to Active Directory.

The only thing that has me stumped is creating a mailbox for a new user in exchange.

Now I notice that people point to ews, adLDAP, ldaptools.

I am wondering if it is possible to just use LDAP to accomplish this goal. HAs anyone attempted this?

Also when adding user mailboxs in exchange, back-end uses load balancing and automatically distirbutes the accounts between the available DBs, can this be utilized when adding user mailboxes with php?

Is this even possible through plain LDAP? if not what are my choices?


Get this bounty!!!

#StackBounty: #php #symfony #translation #sonata-admin Sonata admin can't get translation to work with sortable

Bounty: 200

I’m trying to configure translations using Gedmo, but Sortable behaviour I’ve enabled earlier seems to be getting in a way:

An exception has been thrown during the rendering of a template (“The
class ‘SonataTranslationBundleModelAbstractTranslatable’ was not
found in the chain configured namespaces GedmoTranslatableEntity,
GedmoTranslatorEntity, GedmoLoggableEntity, GedmoTreeEntity,
AppBundleEntity, VichUploaderBundleEntity,
SonataMediaBundleEntity, ApplicationSonataMediaBundleEntity,
SonataUserBundleEntity, ApplicationSonataUserBundleEntity,
SonataNewsBundleEntity, SonataClassificationBundleEntity,
ApplicationSonataNewsBundleEntity,
ApplicationSonataClassificationBundleEntity,
FOSUserBundleModel”).

The template throwing this exception is the one configured for handling of sortable buttons:

/Pix/SortableBehaviorBundle/Resources/views/Default/_sort.html.twig (line 3) 

It fails on line 3 where it’s attempting on setting last_position(object)

{% if admin.isGranted('EDIT', object) and admin.hasRoute('edit') %}
    {% set current_position = currentObjectPosition(object) %}
    {% set last_position    = lastPosition(object) %}
    {% set enable_top_bottom_buttons = field_description.options.actions.move.enable_top_bottom_buttons ?? true %}
    {% if enable_top_bottom_buttons and current_position < last_position %}
        <a class="btn btn-sm btn-default" href="{{ admin.generateObjectUrl('move', object, {'position': 'bottom'}) }}" title="{{ 'move_to_bottom'|trans }}">
            <i class="fa fa-angle-double-down"></i>

I’m following this translation tutorial:
https://sonata-project.org/bundles/translation/master/doc/reference/orm.html

Doctrine ORM Mappings:

  orm:
    auto_generate_proxy_classes: '%kernel.debug%'
    entity_managers:
      default:
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true
        mappings:
          gedmo_translatable:
            type: annotation
            prefix: GedmoTranslatableEntity
            dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Translatable/Entity"
            alias: GedmoTranslatable # (optional) it will default to the name set for the mapping
            is_bundle: false
          gedmo_translator:
            type: annotation
            prefix: GedmoTranslatorEntity
            dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Translator/Entity"
            alias: GedmoTranslator # (optional) it will default to the name set for the mapping
            is_bundle: false
          gedmo_loggable:
           type: annotation
           prefix: GedmoLoggableEntity
           dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Loggable/Entity"
           alias: GedmoLoggable # (optional) it will default to the name set for the mapping
           is_bundle: false
          gedmo_tree:
            type: annotation
            prefix: GedmoTreeEntity
            dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/Entity"
            alias: GedmoTree # (optional) it will default to the name set for the mapping
            is_bundle: false


Get this bounty!!!

#StackBounty: #php #curl #github-api PHP cURL – Link Header

Bounty: 50

I’ve made a code search application that interacts with GitHubs API, that i want to add pagination to, pagination data is held in the header like so:

Link: <https://api.github.com/user/repos?page=3&per_page=100>; rel="next",
<https://api.github.com/user/repos?page=50&per_page=100>; rel="last"

My code:

    // API CONNECTION
    $url = 'https://api.github.com/search/code?q=' . $term  . '+language:' . $lang . '&per_page=' . $pp;
    $cInit = curl_init();
    curl_setopt($cInit, CURLOPT_URL, $url);
    curl_setopt($cInit, CURLOPT_RETURNTRANSFER, 1); // 1 = TRUE
    curl_setopt($cInit, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); 
    curl_setopt($cInit, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($cInit, CURLOPT_USERPWD, $user . ':' . $pwd);
    curl_setopt($cInit, CURLOPT_HTTPHEADER, array('Accept: application/vnd.github.v3.text-match+json')); // ADD THE HIGHLIGHTED CODE SECTION

    // MAKE CURL OUTPUT READABLE
    $output = curl_exec($cInit);
    $items = json_decode($output, true); 
    curl_close($cInit); // CLOSE OUR API CONNECTION

Now, i’ve added in curl_setopt($cInit, CURLOPT_HEADER, true);

And now, for whatever reason – when i do var_dump($items) which worked before i added CURLOPT_HEADER to my code – instead returns a NULL. Which in turn breaks the entire project.

Doing some debugging i found that var_dump($output) is still outputting data, and as expected has the header included. However, the Link Header looks like this:

Link: ; rel="next", ; rel="last" When it shouldnt. To my knowledge, it looks like the link header has actually broken my code.

I’ve tried various things like trying to urlencode $output before i decode it, but to no avail. So, how do i fix this?


Get this bounty!!!

#StackBounty: #php #session How to continuously push user input data into $_SESSION array and then retrieve it?

Bounty: 50

I am trying to get my head around the way PHP sessions work. I am simply trying a hangman game where the first player inputs a secret word, a second player then starts to guess one letter at a time.

Let’s says that the secret word is cat, player two tries, c then a then s. I would like the final output to be c a _.

  <?php
session_start();

global $word;
global $guess;
global $hangman;


if (isset($_POST['player1'], $_POST['word'])) {
    $_SESSION['word'] = $_POST['word'];
    $word = $_SESSION['word'];
}

if (isset($_POST['player2'], $_POST['guess'])) {
    $_SESSION['guess'] = $_POST['guess'];
    $guess = $_SESSION['guess'];
}

$counter = 0;
$word = strtolower($_SESSION['word']);
$guess = strtolower($_SESSION['guess']);
echo $word . "<br>";
$found = [];

$counter = 0;

for ($i = 0; $i < strlen($word); $i++) {
    if ($counter < strlen($word)) {
        if (strpos($word[$i], $guess) !== false) {
            $found[] = $guess;
            $counter++;
        } else {
            $found[] = " _ ";
        }
    }
}

  print_r($found);

Instead of printing out all the contents the found array, I am only getting one single letter to print every time. However, I would like to see the full concatenated string as I’ve mentioned above.


Here is what the output looks like:

enter image description here


Get this bounty!!!

#StackBounty: #php #.htaccess #ssl #heroku Force Heroku PHP app to use https for both www and non-www versions

Bounty: 50

I have a PHP app on Heroku with an SSL certificate for the www version of the domain name. I need all requests (to both www and non-www) to go to via https, and I have added .htaccess to that affect. However, there are still circumstances where it’s possible for a user to access the http version and I don’t understand why.

Here is my .htaccess:

RewriteEngine on

RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]

My understanding is that this should force all users to access via https://www, but that doesn’t always happen. For example, Google sometimes provides search results without the https and the links open insecure http instead.

Any ideas about what I’m doing wrong?


Get this bounty!!!

#StackBounty: #php #python #c++ #algorithm #sorting Table cells / 2d array sorting algorithm

Bounty: 50

Is there an algorithm that could help sort the left table (which is an abstraction for multidimensional array of scalars or objects) down below so the result would be as in the right one, given that there maybe a limited amount of available depth in the right table (e.g. max of 30 rows)?

enter image description here

And slightly more complex version of the problem (first key in a cell is having precedence over another):

enter image description here

EDIT: And another level of complexity (merge rows/levels if it’s safe to do so to prevent redundancy):

enter image description here


Get this bounty!!!

#StackBounty: #16.04 #apache2 #php Correct way to modify php.ini for Apache and/or CLI

Bounty: 50

I want to change and add some PHP directives, some for apache, some for CLI and some for both. As an example, I want to set the default timezone for all server contexts. There are a couple of different ways I can go about this, but I don’t know which is the best approach.

I can directly edit the master php.ini files, which are here /etc/php/7.0/apache2/php.ini and here /etc/php/7.0/cli/php.ini, but I don’t know whether this file will be overwritten on upgrade. Also for shared settings, such as the timezone, I have to remember to edit two files and keep those changes synchronised.

I can use Apache’s php_admin_value, php_admin_flag, php_value and php_flag directives. The advantage here is that the php settings can be applied on a virtual host by virtual host basis and I can also apply them globally to Apache. However, this doesn’t help with the CLI settings.

The php directory has a similar structure to Apache, allowing files full of directives to be enabled or disabled with the phpenmod command. I can copy this structure, creating the directory /etc/php/7.0/mydirectives, placing php.ini files within this folder, then creating symbolic links from /etc/php/7.0/apache2/conf.d/ to my php.ini directive files. This allows me to have a single directive file which adds directives to both Apache and CLI version of PHP. The only thing I can’t do with this is virtual host by virtual directives.

Any advice on how to do this properly?


Get this bounty!!!

#StackBounty: #php #jquery #ajax #curl Send ajax request through CURL

Bounty: 50

An API request needs to be sent. For some reason, the server is blocking CURL request, but it approves an XHR ajax request. I could send an ajax request, but another problem arises – Mixed content my website is served over HTTPS but the request that needs to be sent is over HTTP so I cannot use ajax.

I am looking for a way to simulate ajax request through CURL, in some way, trick the server to believe that the CURL request is indeed an ajax request.

Here’s what I have tried.

This is my CURL request.

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64)');
curl_setopt($ch, CURLOPT_REFERER, 'server's url');
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept:application/json, text/javascript, */*; q=0.01',
    'Accept-Encoding:gzip, deflate',
    'Accept-Language:en-US,en;q=0.9',
    'Connection:keep-alive',
    'Content-Type: application/json; charset=utf-8',
    'X-Requested-With: XMLHttpRequest',
    '__RequestVerificationToken: $token'
    ));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, base_path().'/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, base_path().'/cookies.txt');
$buffer = curl_exec($ch);
if(curl_error($ch))
{
    $buffer =   curl_error($ch);
}
curl_close($ch);

return $buffer;

This curl request is blocked

But, this ajax request goes through my localhost, but since my live website uses HTTPS I cannot really use it.

$.ajax({
    type: "get",
    xhrFields: { withCredentials:true },
    url: http://apiendpoint.com,
    success: function(data)
    {
      // console.log(data);
    }
})

Actually, the response received through CURL and ajax is different.


Get this bounty!!!