preg_match for regex expression - preg-match

Please help me to convert this code to preg_match
$blacklist = $db->query("SELECT `content` FROM `" . TABLE_PREFIX . "blacklist` WHERE `type`='$type'");
while ($blacklisted = $db->fetch_array($blacklist))
{
if (is_array($input))
{
foreach ($input as $entry)
{
if (eregi($blacklisted['content'], $entry))
print_error($msg);
}
}
else if (eregi($blacklisted['content'], $input))
{
print_error($msg);
}
}

eregi used to be used like that to see if one string is in another. It was not the proper use. You can do the same with stripos
$blacklist = $db->query("SELECT `content` FROM `" . TABLE_PREFIX . "blacklist` WHERE `type`='$type'");
while ($blacklisted = $db->fetch_array($blacklist))
{
if (is_array($input))
{
foreach ($input as $entry)
{
if (false !== stripos($entry, $blacklisted['content']))
print_error($msg);
}
}
else if (false !== stripos($input, $blacklisted['content']))
{
print_error($msg);
}
}

Related

Warning: count(): Parameter must be an array or an object that implements Countable?

I have this error
Warning: count(): Parameter must be an array or an object that implements Countable in /home/arabwindow/public_html/libs/smarty/sysplugins/smarty_internal_templatebase.php(121) : eval()'d code on line 304
and this is file:
`
<?php
/*
* # https://EasyToYou.eu - IonCube v11 Decoder Online
* # PHP 7.2 & 7.3
* # Decoder version: 1.0.6
* # Release: 10/08/2022
*/
/**
* Class with shared template methods
*
* #package Smarty
* #subpackage Template
*/
class Smarty_Internal_TemplateBase extends Smarty_Internal_Data
{
public function fetch($template = NULL, $cache_id = NULL, $compile_id = NULL, $parent = NULL, $display = false, $merge_tpl_vars = true, $no_output_filter = false)
{
if ($template === NULL && $this instanceof $this->template_class) {
$template = $this;
}
if ($cache_id !== NULL && is_object($cache_id)) {
$parent = $cache_id;
$cache_id = NULL;
}
if ($parent === NULL && ($this instanceof Smarty || is_string($template))) {
$parent = $this;
}
$_template = $template instanceof $this->template_class ? $template : $this->smarty->createTemplate($template, $cache_id, $compile_id, $parent, false);
if ($this instanceof Smarty) {
$_template->caching = $this->caching;
}
if ($merge_tpl_vars) {
$save_tpl_vars = $_template->tpl_vars;
$save_config_vars = $_template->config_vars;
$ptr_array = [$_template];
$ptr = $_template;
while (isset($ptr->parent)) {
$ptr_array[] = $ptr = $ptr->parent;
}
$ptr_array = array_reverse($ptr_array);
$parent_ptr = reset($ptr_array);
$tpl_vars = $parent_ptr->tpl_vars;
$config_vars = $parent_ptr->config_vars;
while ($parent_ptr = next($ptr_array)) {
if (!empty($parent_ptr->tpl_vars)) {
$tpl_vars = array_merge($tpl_vars, $parent_ptr->tpl_vars);
}
if (!empty($parent_ptr->config_vars)) {
$config_vars = array_merge($config_vars, $parent_ptr->config_vars);
}
}
if (!Smarty::$global_tpl_vars) {
$tpl_vars = array_merge(Smarty::$global_tpl_vars, $tpl_vars);
}
$_template->tpl_vars = $tpl_vars;
$_template->config_vars = $config_vars;
}
if (!isset($_template->tpl_vars["smarty"])) {
$_template->tpl_vars["smarty"] = new Smarty_Variable();
}
if (isset($this->smarty->error_reporting)) {
$_smarty_old_error_level = error_reporting($this->smarty->error_reporting);
}
if (!$this->smarty->debugging && $this->smarty->debugging_ctrl == "URL") {
if (isset($_SERVER["QUERY_STRING"])) {
$_query_string = $_SERVER["QUERY_STRING"];
} else {
$_query_string = "";
}
if (false !== strpos($_query_string, $this->smarty->smarty_debug_id)) {
if (false !== strpos($_query_string, $this->smarty->smarty_debug_id . "=on")) {
setcookie("SMARTY_DEBUG", true);
$this->smarty->debugging = true;
} else {
if (false !== strpos($_query_string, $this->smarty->smarty_debug_id . "=off")) {
setcookie("SMARTY_DEBUG", false);
$this->smarty->debugging = false;
} else {
$this->smarty->debugging = true;
}
}
} else {
if (isset($_COOKIE["SMARTY_DEBUG"])) {
$this->smarty->debugging = true;
}
}
}
$_template->smarty->merged_templates_func = [];
if ($_template->source->recompiled) {
$_template->caching = false;
}
if (!$_template->source->exists) {
if ($_template->parent instanceof Smarty_Internal_Template) {
$parent_resource = " in '" . $_template->parent->template_resource . "'";
} else {
$parent_resource = "";
}
throw new SmartyException("Unable to load template " . $_template->source->type . " '" . $_template->source->name . "'" . $parent_resource);
}
if (!($_template->caching == Smarty::CACHING_LIFETIME_CURRENT || $_template->caching == Smarty::CACHING_LIFETIME_SAVED) || !$_template->cached->valid) {
if (!$_template->source->uncompiled) {
$_smarty_tpl = $_template;
if ($_template->source->recompiled) {
$code = $_template->compiler->compileTemplate($_template);
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_render($_template);
}
try {
ob_start();
eval("?>" . $code);
unset($code);
} catch (Exception $e) {
ob_get_clean();
throw $e;
}
} else {
if (!$_template->compiled->exists || $_template->smarty->force_compile && !$_template->compiled->isCompiled) {
$_template->compileTemplateSource();
$code = file_get_contents($_template->compiled->filepath);
eval("?>" . $code);
unset($code);
$_template->compiled->loaded = true;
$_template->compiled->isCompiled = true;
}
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_render($_template);
}
if (!$_template->compiled->loaded) {
include $_template->compiled->filepath;
if ($_template->mustCompile) {
$_template->compileTemplateSource();
$code = file_get_contents($_template->compiled->filepath);
eval("?>" . $code);
unset($code);
$_template->compiled->isCompiled = true;
}
$_template->compiled->loaded = true;
} else {
$_template->decodeProperties($_template->compiled->_properties, false);
}
try {
ob_start();
if (empty($_template->properties["unifunc"]) || !is_callable($_template->properties["unifunc"])) {
throw new SmartyException("Invalid compiled template for '" . $_template->template_resource . "'");
}
array_unshift($_template->_capture_stack, []);
$_template->properties["unifunc"]($_template);
if (isset($_template->_capture_stack[0][0])) {
$_template->capture_error();
}
array_shift($_template->_capture_stack);
} catch (Exception $e) {
ob_get_clean();
throw $e;
}
}
} else {
if ($_template->source->uncompiled) {
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_render($_template);
}
try {
ob_start();
$_template->source->renderUncompiled($_template);
} catch (Exception $e) {
ob_get_clean();
throw $e;
}
} else {
throw new SmartyException("Resource '" . $_template->source . "->type' must have 'renderUncompiled' method");
}
}
$_output = ob_get_clean();
if (!$_template->source->recompiled && empty($_template->properties["file_dependency"][$_template->source->uid])) {
$_template->properties["file_dependency"][$_template->source->uid] = [$_template->source->filepath, $_template->source->timestamp, $_template->source->type];
}
if ($_template->parent instanceof Smarty_Internal_Template) {
$_template->parent->properties["file_dependency"] = array_merge($_template->parent->properties["file_dependency"], $_template->properties["file_dependency"]);
foreach ($_template->required_plugins as $code => $tmp1) {
foreach ($tmp1 as $name => $tmp) {
foreach ($tmp as $type => $data) {
$_template->parent->required_plugins[$code][$name][$type] = $data;
}
}
}
}
if ($this->smarty->debugging) {
Smarty_Internal_Debug::end_render($_template);
}
if (!$_template->source->recompiled && ($_template->caching == Smarty::CACHING_LIFETIME_SAVED || $_template->caching == Smarty::CACHING_LIFETIME_CURRENT)) {
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_cache($_template);
}
$_template->properties["has_nocache_code"] = false;
$cache_split = preg_split("!/\\*%%SmartyNocache:" . $_template->properties["nocache_hash"] . "%%\\*\\/(.+?)/\\*/%%SmartyNocache:" . $_template->properties["nocache_hash"] . "%%\\*/!s", $_output);
preg_match_all("!/\\*%%SmartyNocache:" . $_template->properties["nocache_hash"] . "%%\\*\\/(.+?)/\\*/%%SmartyNocache:" . $_template->properties["nocache_hash"] . "%%\\*/!s", $_output, $cache_parts);
$output = "";
foreach ($cache_split as $curr_idx => $curr_split) {
$output .= preg_replace("/(<%|%>|<\\?php|<\\?|\\?>|<script\\s+language\\s*=\\s*[\\\"']?\\s*php\\s*[\\\"']?\\s*>)/", "<?php echo '\$1'; ?>\n", $curr_split);
if (isset($cache_parts[0][$curr_idx])) {
$_template->properties["has_nocache_code"] = true;
$output .= preg_replace("!/\\*/?%%SmartyNocache:" . $_template->properties["nocache_hash"] . "%%\\*/!", "", $cache_parts[0][$curr_idx]);
}
}
if (!$no_output_filter && !$_template->has_nocache_code && (isset($this->smarty->autoload_filters["output"]) || isset($this->smarty->registered_filters["output"]))) {
$output = Smarty_Internal_Filter_Handler::runFilter("output", $output, $_template);
}
$_smarty_tpl = $_template;
try {
ob_start();
eval("?>" . $output);
$_output = ob_get_clean();
} catch (Exception $e) {
ob_get_clean();
throw $e;
}
$_template->writeCachedContent($output);
if ($this->smarty->debugging) {
Smarty_Internal_Debug::end_cache($_template);
}
} else {
if (!empty($_template->properties["nocache_hash"]) && !empty($_template->parent->properties["nocache_hash"])) {
$_output = str_replace((string) $_template->properties["nocache_hash"], $_template->parent->properties["nocache_hash"], $_output);
$_template->parent->has_nocache_code = $_template->parent->has_nocache_code || $_template->has_nocache_code;
}
}
} else {
if ($this->smarty->debugging) {
Smarty_Internal_Debug::start_cache($_template);
}
try {
ob_start();
array_unshift($_template->_capture_stack, []);
$_template->properties["unifunc"]($_template);
if (isset($_template->_capture_stack[0][0])) {
$_template->capture_error();
}
array_shift($_template->_capture_stack);
$_output = ob_get_clean();
} catch (Exception $e) {
ob_get_clean();
throw $e;
}
if ($this->smarty->debugging) {
Smarty_Internal_Debug::end_cache($_template);
}
}
if ((!$this->caching || $_template->has_nocache_code || $_template->source->recompiled) && !$no_output_filter && (isset($this->smarty->autoload_filters["output"]) || isset($this->smarty->registered_filters["output"]))) {
$_output = Smarty_Internal_Filter_Handler::runFilter("output", $_output, $_template);
}
if (isset($this->error_reporting)) {
error_reporting($_smarty_old_error_level);
}
if ($display) {
if ($this->caching && $this->cache_modified_check) {
$_isCached = $_template->isCached() && !$_template->has_nocache_code;
$_last_modified_date = #substr($_SERVER["HTTP_IF_MODIFIED_SINCE"], 0, #strpos($_SERVER["HTTP_IF_MODIFIED_SINCE"], "GMT") + 3);
if ($_isCached && $_template->cached->timestamp <= strtotime($_last_modified_date)) {
switch (PHP_SAPI) {
case "cgi":
case "cgi-fcgi":
case "fpm-fcgi":
header("Status: 304 Not Modified");
break;
case "cli":
if (!empty($_SERVER["SMARTY_PHPUNIT_DISABLE_HEADERS"])) {
$_SERVER["SMARTY_PHPUNIT_HEADERS"][] = "304 Not Modified";
}
break;
default:
header($_SERVER["SERVER_PROTOCOL"] . " 304 Not Modified");
}
} else {
switch (PHP_SAPI) {
case "cli":
if (!empty($_SERVER["SMARTY_PHPUNIT_DISABLE_HEADERS"])) {
$_SERVER["SMARTY_PHPUNIT_HEADERS"][] = "Last-Modified: " . gmdate("D, d M Y H:i:s", $_template->cached->timestamp) . " GMT";
}
break;
default:
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $_template->cached->timestamp) . " GMT");
echo $_output;
}
}
} else {
echo $_output;
}
if ($this->smarty->debugging) {
Smarty_Internal_Debug::display_debug($_template);
}
if ($merge_tpl_vars) {
$_template->tpl_vars = $save_tpl_vars;
$_template->config_vars = $save_config_vars;
}
return NULL;
}
if ($merge_tpl_vars) {
$_template->tpl_vars = $save_tpl_vars;
$_template->config_vars = $save_config_vars;
}
return $_output;
}
public function display($template = NULL, $cache_id = NULL, $compile_id = NULL, $parent = NULL)
{
$this->fetch($template, $cache_id, $compile_id, $parent, true);
}
public function isCached($template = NULL, $cache_id = NULL, $compile_id = NULL, $parent = NULL)
{
if ($template === NULL && $this instanceof $this->template_class) {
return $this->cached->valid;
}
if (!$template instanceof $this->template_class) {
if ($parent === NULL) {
$parent = $this;
}
$template = $this->smarty->createTemplate($template, $cache_id, $compile_id, $parent, false);
}
return $template->cached->valid;
}
public function createData($parent = NULL)
{
return new Smarty_Data($parent, $this);
}
public function registerPlugin($type, $tag, $callback, $cacheable = true, $cache_attr = NULL)
{
if (isset($this->smarty->registered_plugins[$type][$tag])) {
throw new SmartyException("Plugin tag \"" . $tag . "\" already registered");
}
if (!is_callable($callback)) {
throw new SmartyException("Plugin \"" . $tag . "\" not callable");
}
$this->smarty->registered_plugins[$type][$tag] = [$callback, (bool) $cacheable, (array) $cache_attr];
return $this;
}
public function unregisterPlugin($type, $tag)
{
if (isset($this->smarty->registered_plugins[$type][$tag])) {
unset($this->smarty->registered_plugins[$type][$tag]);
}
return $this;
}
public function registerResource($type, $callback)
{
$this->smarty->registered_resources[$type] = $callback instanceof Smarty_Resource ? $callback : [$callback, false];
return $this;
}
public function unregisterResource($type)
{
if (isset($this->smarty->registered_resources[$type])) {
unset($this->smarty->registered_resources[$type]);
}
return $this;
}
public function registerCacheResource($type, Smarty_CacheResource $callback)
{
$this->smarty->registered_cache_resources[$type] = $callback;
return $this;
}
public function unregisterCacheResource($type)
{
if (isset($this->smarty->registered_cache_resources[$type])) {
unset($this->smarty->registered_cache_resources[$type]);
}
return $this;
}
public function registerObject($object_name, $object_impl, $allowed = [], $smarty_args = true, $block_methods = [])
{
if (!empty($allowed)) {
foreach ((array) $allowed as $method) {
if (!is_callable([$object_impl, $method]) && !property_exists($object_impl, $method)) {
throw new SmartyException("Undefined method or property '" . $method . "' in registered object");
}
}
}
if (!empty($block_methods)) {
foreach ((array) $block_methods as $method) {
if (!is_callable([$object_impl, $method])) {
throw new SmartyException("Undefined method '" . $method . "' in registered object");
}
}
}
$this->smarty->registered_objects[$object_name] = [$object_impl, (array) $allowed, (bool) $smarty_args, (array) $block_methods];
return $this;
}
public function getRegisteredObject($name)
{
if (!isset($this->smarty->registered_objects[$name])) {
throw new SmartyException("'" . $name . "' is not a registered object");
}
if (!is_object($this->smarty->registered_objects[$name][0])) {
throw new SmartyException("registered '" . $name . "' is not an object");
}
return $this->smarty->registered_objects[$name][0];
}
public function unregisterObject($name)
{
if (isset($this->smarty->registered_objects[$name])) {
unset($this->smarty->registered_objects[$name]);
}
return $this;
}
public function registerClass($class_name, $class_impl)
{
if (!class_exists($class_impl)) {
throw new SmartyException("Undefined class '" . $class_impl . "' in register template class");
}
$this->smarty->registered_classes[$class_name] = $class_impl;
return $this;
}
public function registerDefaultPluginHandler($callback)
{
if (is_callable($callback)) {
$this->smarty->default_plugin_handler_func = $callback;
return $this;
}
throw new SmartyException("Default plugin handler '" . $callback . "' not callable");
}
public function registerDefaultTemplateHandler($callback)
{
if (is_callable($callback)) {
$this->smarty->default_template_handler_func = $callback;
return $this;
}
throw new SmartyException("Default template handler '" . $callback . "' not callable");
}
public function registerDefaultConfigHandler($callback)
{
if (is_callable($callback)) {
$this->smarty->default_config_handler_func = $callback;
return $this;
}
throw new SmartyException("Default config handler '" . $callback . "' not callable");
}
public function registerFilter($type, $callback)
{
$this->smarty->registered_filters[$type][$this->_get_filter_name($callback)] = $callback;
return $this;
}
public function unregisterFilter($type, $callback)
{
$name = $this->_get_filter_name($callback);
if (isset($this->smarty->registered_filters[$type][$name])) {
unset($this->smarty->registered_filters[$type][$name]);
}
return $this;
}
public function _get_filter_name($function_name)
{
if (is_array($function_name)) {
$_class_name = is_object($function_name[0]) ? get_class($function_name[0]) : $function_name[0];
return $_class_name . "_" . $function_name[1];
}
return $function_name;
}
public function loadFilter($type, $name)
{
$_plugin = "smarty_" . $type . "filter_" . $name;
$_filter_name = $_plugin;
if ($this->smarty->loadPlugin($_plugin)) {
if (class_exists($_plugin, false)) {
$_plugin = [$_plugin, "execute"];
}
if (is_callable($_plugin)) {
$this->smarty->registered_filters[$type][$_filter_name] = $_plugin;
return true;
}
}
throw new SmartyException($type . "filter \"" . $name . "\" not callable");
}
public function unloadFilter($type, $name)
{
$_filter_name = "smarty_" . $type . "filter_" . $name;
if (isset($this->smarty->registered_filters[$type][$_filter_name])) {
unset($this->smarty->registered_filters[$type][$_filter_name]);
}
return $this;
}
private function replaceCamelcase($match)
{
return "_" . strtolower($match[1]);
}
public function __call($name, $args)
{
static $_prefixes = ["set" => true, "get" => true];
static $_resolved_property_name = [];
static $_resolved_property_source = [];
if (method_exists($this->smarty, $name)) {
return call_user_func_array([$this->smarty, $name], $args);
}
$first3 = strtolower(substr($name, 0, 3));
if (isset($_prefixes[$first3]) && isset($name[3]) && $name[3] !== "_") {
if (isset($_resolved_property_name[$name])) {
$property_name = $_resolved_property_name[$name];
} else {
$property_name = strtolower(substr($name, 3, 1)) . substr($name, 4);
$property_name = preg_replace_callback("/([A-Z])/", [$this, "replaceCamelcase"], $property_name);
$_resolved_property_name[$name] = $property_name;
}
if (isset($_resolved_property_source[$property_name])) {
$_is_this = $_resolved_property_source[$property_name];
} else {
$_is_this = NULL;
if (property_exists($this, $property_name)) {
$_is_this = true;
} else {
if (property_exists($this->smarty, $property_name)) {
$_is_this = false;
}
}
$_resolved_property_source[$property_name] = $_is_this;
}
if ($_is_this) {
if ($first3 == "get") {
return $this->{$property_name};
}
return $this->{$property_name} = $args[0];
}
if ($_is_this === false) {
if ($first3 == "get") {
return $this->smarty->{$property_name};
}
return $this->smarty->{$property_name} = $args[0];
}
throw new SmartyException("property '" . $property_name . "' does not exist.");
}
if ($name == "Smarty") {
throw new SmartyException("PHP5 requires you to call __construct() instead of Smarty()");
}
throw new SmartyException("Call of unknown method '" . $name . "'.");
}
}
?>
`
this error show on statistics page, and I change file many times but same error
How can I fix error?

What could be better way to read spreadsheet (Excel File) in laravel?

I am trying to read excel file and store that data in database. This excel file is kind of template. one would be default template and this template could be changed in future. Currently i am reading that file with many if conditions .I personally think that it isn't best way to read excel file so looking for better way.
this procedure is divided into two functions
public function importManifestFile(Request $request)
{
$path = $request->file('manifest_file')->getRealPath();
$spreadsheet = IOFactory::load($path);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
foreach ($sheetData as $rows => $ManifestConsignments) {
if ($rows >= 9 && $rows <= 37) {
$this->manifestConsignment($ManifestConsignments);
}
}
}
//import file manifest consignment function
public function manifestConsignment($ManifestConsignments)
{
$consignment = new Consignment;
foreach ($ManifestConsignments as $key => $ManifestConsignment) {
if ($key == 'A') {
}
if ($key == 'B') {
$consignment->delivery_date = $ManifestConsignment;
}
if ($key == 'C') {
$addressId = $ManifestConsignment;
}
if ($key == 'D') {
$companyName = $ManifestConsignment;
}
if ($key == 'E') {
$streetAddress = $ManifestConsignment;
}
if ($key == 'F') {
$suburb = $ManifestConsignment;
}
if ($key == 'G') {
$state = $ManifestConsignment;
}
if ($key == 'H') {
$postCode = $ManifestConsignment;
}
if (isset($postCode)) {
if (Address::where('company_name', $companyName)->where('street_address', $streetAddress)->where('suburb', $suburb)->where('state', $state)->where('postcode', $postCode)->exists()) {
$deliveryAddress = Address::where('company_name', $companyName)->where('street_address', $streetAddress)->where('suburb', $suburb)->where('state', $state)->where('postcode', $postCode)->first();
$deliveryAddressId = $deliveryAddress->id;
$consignment->delivery_address = $deliveryAddressId;
unset($postCode);
} else {
$address = new Address;
$address->company_name = $companyName;
$address->street_address = $streetAddress;
$address->suburb = $suburb;
$address->postcode = $postCode;
$address->state = $state;
$address->save();
$consignment->delivery_address = $address->id;
unset($postCode);
}
if ($key == 'I') {
$consignment->carton = $ManifestConsignment;
}
if ($key == 'J') {
$consignment->pallet = $ManifestConsignment;
}
if ($key == 'K') {
$consignment->weight = $ManifestConsignment;
}
if ($key == 'L') {
$consignment->invoice_value = $ManifestConsignment;
}
if ($key == 'M') {
if (!empty($ManifestConsignment)) {
$consignment->cash_on_delivery = $ManifestConsignment;
}
}
if ($key == 'N') {
$consignment->product_type_id = 1;
}
if ($key == 'O') {
$consignment->comment = $ManifestConsignment;
}
$consignment->customer_id =1;
$consignment->status = 'In Warehouse';
$consignment->product_type_id = 1;
$consignment->save();
}
}
}
$key
in code is column name of excel file . i am checking what is column name and storing data according to that.

What might be best solution to get camelCase data from angular,integrate with snake_case mysql and send response in camelCase back to angular?

what i did is:
$input = $request->all();
//convert the post camelcase to snakecase
foreach ($input as $key => $val) {
$newKey = snake_case($key);
$input[$newKey] = $val;
if ($newKey != $key) {
unset($input[$key]);
}
}
after integrating data,use helper function to convert snakecase to camelcase again by the following function:
function convert_snakeCase_to_CamelCase($data)
{
if ($data) {
foreach ($data as $key1 => $val1) {
$newKey1 = camel_case($key1);
if ($newKey1 != $key1) {
unset($data[$key1]);
}
$data[$newKey1] = $val1;
if (is_array($val1) && !empty($val1)) {
foreach ($val1 as $key2 => $val2) {
$newKey2 = camel_case($key2);
if ($newKey2 != $key2) {
unset($data[$newKey1][$key2]);
}
$data[$newKey1][$newKey2] = $val2;
if (is_array($val2) && !empty($val2)) {
foreach ($val2 as $key3 => $val3) {
$newKey3 = camel_case($key3);
if ($newKey3 != $key3) {
unset($data[$newKey1][$newKey2][$key3]);
}
$data[$newKey1][$newKey2][$newKey3] = $val3;
if (is_array($val3) && !empty($val3)) {
foreach ($val3 as $key4 => $val4) {
$newKey4 = camel_case($key4);
if ($newKey4 != $key4) {
unset($data[$newKey1][$newKey2][$newKey3][$key4]);
}
$data[$newKey1][$newKey2][$newKey3][$newKey4] = $val4;
if (is_array($val4) && !empty($val4)) {
foreach ($val4 as $key5 => $val5) {
$newKey5 = camel_case($key5);
if ($newKey5 != $key5) {
unset($data[$newKey1][$newKey2][$newKey3][$newKey4][$key5]);
}
$data[$newKey1][$newKey2][$newKey3][$newKey4][$newKey5] = $val5;
if (is_array($val5) && !empty($val5)) {
foreach ($val5 as $key6 => $val6) {
$newKey6 = camel_case($key6);
if ($newKey6 != $key6) {
unset($data[$newKey1][$newKey2][$newKey3][$newKey4][$newKey5][$key6]);
}
$data[$newKey1][$newKey2][$newKey3][$newKey4][$newKey5][$newKey6] = $val6;
}
}
}
}
}
}
}
}
}
}
}
}
return $data;
}
its working absolutely fine.I was wondering is there any solution better plugins for angular or laravel to convert the post data and send response data in required case?

Get the information you entered to ID

This file is the database ID information all the fields and went and came to a Blade, I want to an ID information entered in the same panel Blade I send my face.
class DataGrid extends DataSet
{
protected $fields = array();
/** #var Column[] */
public $columns = array();
public $headers = array();
public $rows = array();
public $output = "";
public $attributes = array("class" => "table");
public $checkbox_form = false;
protected $row_callable = array();
/**
* #param string $name
* #param string $label
* #param bool $orderby
*
* #return Column
*/
public function add($name, $label = null, $orderby = false)
{
$column = new Column($name, $label, $orderby);
$this->columns[$column->name] = $column;
if (!in_array($name,array("_edit"))) {
$this->headers[] = $label;
}
if ($orderby) {
$this->addOrderBy($column->orderby_field);
}
return $column;
}
//todo: like "field" for DataForm, should be nice to work with "cell" as instance and "row" as collection of cells
public function build($view = '')
{
($view == '') and $view = 'rapyd::datagrid';
parent::build();
Persistence::save();
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
$cell = new Cell($column->name);
$sanitize = (count($column->filters) || $column->cell_callable) ? false : true;
$value = $this->getCellValue($column, $tablerow, $sanitize);
$cell->value($value);
$cell->parseFilters($column->filters);
if ($column->cell_callable) {
$callable = $column->cell_callable;
$cell->value($callable($cell->value, $tablerow));
}
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
$this->rows[] = $row;
}
$routeParamters = \Route::current()->parameters();
return \View::make($view, array('dg' => $this, 'buttons'=>$this->button_container, 'label'=>$this->label,
'current_entity' => $routeParamters['entity']));
}
public function buildCSV($file = '', $timestamp = '', $sanitize = true,$del = array())
{
$this->limit = null;
parent::build();
$segments = \Request::segments();
$filename = ($file != '') ? basename($file, '.csv') : end($segments);
$filename = preg_replace('/[^0-9a-z\._-]/i', '',$filename);
$filename .= ($timestamp != "") ? date($timestamp).".csv" : ".csv";
$save = (bool) strpos($file,"/");
//Delimiter
$delimiter = array();
$delimiter['delimiter'] = isset($del['delimiter']) ? $del['delimiter'] : ';';
$delimiter['enclosure'] = isset($del['enclosure']) ? $del['enclosure'] : '"';
$delimiter['line_ending'] = isset($del['line_ending']) ? $del['line_ending'] : "\n";
if ($save) {
$handle = fopen(public_path().'/'.dirname($file)."/".$filename, 'w');
} else {
$headers = array(
'Content-Type' => 'text/csv',
'Pragma'=>'no-cache',
'"Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Disposition' => 'attachment; filename="' . $filename.'"');
$handle = fopen('php://output', 'w');
ob_start();
}
fputs($handle, $delimiter['enclosure'].implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $this->headers) .$delimiter['enclosure'].$delimiter['line_ending']);
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
if (in_array($column->name,array("_edit")))
continue;
$cell = new Cell($column->name);
$value = str_replace('"', '""',str_replace(PHP_EOL, '', strip_tags($this->getCellValue($column, $tablerow, $sanitize))));
$cell->value($value);
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
fputs($handle, $delimiter['enclosure'] . implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $row->toArray()) . $delimiter['enclosure'].$delimiter['line_ending']);
}
fclose($handle);
if ($save) {
//redirect, boolean or filename?
} else {
$output = ob_get_clean();
return \Response::make(rtrim($output, "\n"), 200, $headers);
}
}
protected function getCellValue($column, $tablerow, $sanitize = true)
{
//blade
if (strpos($column->name, '{{') !== false ||
strpos($column->name, '{!!') !== false) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = $this->parser->compileString($column->name, $array);
//eager loading smart syntax relation.field
} elseif (preg_match('#^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$#i',$column->name, $matches) && is_object($tablerow) ) {
//switch to blade and god bless eloquent
$_relation = '$'.trim(str_replace('.','->', $column->name));
$expression = '{{ isset('. $_relation .') ? ' . $_relation . ' : "" }}';
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$value = $this->parser->compileString($expression, $array);
//fieldname in a collection
} elseif (is_object($tablerow)) {
$value = #$tablerow->{$column->name};
if ($sanitize) {
$value = $this->sanitize($value);
}
//fieldname in an array
} elseif (is_array($tablerow) && isset($tablerow[$column->name])) {
$value = $tablerow[$column->name];
//none found, cell will have the column name
} else {
$value = $column->name;
}
//decorators, should be moved in another method
if ($column->link) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$array = $tablerow->getAttributes();
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = ''.$value.'';
}
if (count($column->actions)>0) {
$key = ($column->key != '') ? $column->key : $this->key;
$keyvalue = #$tablerow->{$key};
$routeParamters = \Route::current()->parameters();
$value = \View::make('rapyd::datagrid.actions', array('uri' => $column->uri, 'id' => $keyvalue, 'actions' => $column->actions,
'current_entity' => $routeParamters['entity']));
}
return $value;
}
public function getGrid($view = '')
{
$this->output = $this->build($view)->render();
return $this->output;
}
public function __toString()
{
if ($this->output == "") {
//to avoid the error "toString() must not throw an exception"
//http://stackoverflow.com/questions/2429642/why-its-impossible-to-throw-exception-from-tostring/27307132#27307132
try {
$this->getGrid();
}
catch (\Exception $e) {
$previousHandler = set_exception_handler(function (){ });
restore_error_handler();
call_user_func($previousHandler, $e);
die;
}
}
return $this->output;
}
public function edit($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->add('_edit', $label)->actions($uri, explode('|', $actions))->key($key);
}
public function getColumn($column_name)
{
if (isset($this->columns[$column_name])) {
return $this->columns[$column_name];
}
}
public function addActions($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->edit($uri, $label, $actions, $key);
}
public function row(\Closure $callable)
{
$this->row_callable[] = $callable;
return $this;
}
protected function sanitize($string)
{
$result = nl2br(htmlspecialchars($string));
return Config::get('rapyd.sanitize.num_characters') > 0 ? str_limit($result, Config::get('rapyd.sanitize.num_characters')) : $result;
}
public function rowCount()
{
return count($this->rows);
}
}
This is the source of a rapyd-laravel widget/package, not a custom code.
According to DataGrid/DataSet documentation, you can use many sources:
https://github.com/zofe/rapyd-laravel/wiki/DataSet
DataSet/DataGrid are presenters, you can retrieve all data of your data source using
{{ $item->field }} or {{ $row->field }} respectively
See the docs please
https://github.com/zofe/rapyd-laravel/wiki

magento final_price,min_price,max_price wrong values insertion

Hi
i have problem with the final_price,min_price,max_price in the catalog_product_index_price table its is wrongly inserting the values after function save() during import.
The file is app\code\core\Mage\Catalog\Model\Convert\Adapter\Product.php
The control goes to finish() function
public function finish()
{
Mage::dispatchEvent('catalog_product_import_after', array());
$entity = new Varien_Object();
Mage::getSingleton('index/indexer')->processEntityAction(
$entity, self::ENTITY, Mage_Index_Model_Event::TYPE_SAVE
);
}
where is the insert statement to insert the value in the catalog_product_index_price table?
How this can be resolved?
My saveRow fucnction to populate database.My excel sheet contains the following additional row
Price Type:radio:1
Unit Price:absolute:2691|Case Price:absolute:12420
Unit Price:absolute:762|Case Price:absolute:7029
The save database function is
public function saveRow(array $importData)
{
$product = $this->getProductModel()
->reset();
if (empty($importData['store'])) {
if (!is_null($this->getBatchParams('store'))) {
$store = $this->getStoreById($this->getBatchParams('store'));
} else {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'store');
Mage::throwException($message);
}
}
else {
$store = $this->getStoreByCode($importData['store']);
}
if ($store === false) {
$message = Mage::helper('catalog')->__('Skipping import row, store "%s" field does not exist.', $importData['store']);
Mage::throwException($message);
}
if (empty($importData['sku'])) {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'sku');
Mage::throwException($message);
}
$product->setStoreId($store->getId());
$productId = $product->getIdBySku($importData['sku']);
if ($productId) {
$product->load($productId);
}
else {
$productTypes = $this->getProductTypes();
$productAttributeSets = $this->getProductAttributeSets();
/**
* Check product define type
*/
if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
$value = isset($importData['type']) ? $importData['type'] : '';
$message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type');
Mage::throwException($message);
}
$product->setTypeId($productTypes[strtolower($importData['type'])]);
/**
* Check product define attribute set
*/
if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
$value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
$message = Mage::helper('catalog')->__('Skip import row, the value "%s" is invalid for field "%s"', $value, 'attribute_set');
Mage::throwException($message);
}
$product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);
foreach ($this->_requiredFields as $field) {
$attribute = $this->getAttribute($field);
if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" for new products is not defined.', $field);
Mage::throwException($message);
}
}
}
$this->setProductTypeInstance($product);
if (isset($importData['category_ids'])) {
$product->setCategoryIds($importData['category_ids']);
}
foreach ($this->_ignoreFields as $field) {
if (isset($importData[$field])) {
unset($importData[$field]);
}
}
if ($store->getId() != 0) {
$websiteIds = $product->getWebsiteIds();
if (!is_array($websiteIds)) {
$websiteIds = array();
}
if (!in_array($store->getWebsiteId(), $websiteIds)) {
$websiteIds[] = $store->getWebsiteId();
}
$product->setWebsiteIds($websiteIds);
}
if (isset($importData['websites'])) {
$websiteIds = $product->getWebsiteIds();
if (!is_array($websiteIds)) {
$websiteIds = array();
}
$websiteCodes = explode(',', $importData['websites']);
foreach ($websiteCodes as $websiteCode) {
try {
$website = Mage::app()->getWebsite(trim($websiteCode));
if (!in_array($website->getId(), $websiteIds)) {
$websiteIds[] = $website->getId();
}
}
catch (Exception $e) {}
}
$product->setWebsiteIds($websiteIds);
unset($websiteIds);
}
$custom_options = array();
foreach ($importData as $field => $value) {
if (in_array($field, $this->_inventoryFields)) {
continue;
}
if (in_array($field, $this->_imageFields)) {
continue;
}
$attribute = $this->getAttribute($field);
if (!$attribute) {
/* CUSTOM OPTION CODE */
if(strpos($field,':')!==FALSE && strlen($value)) {
$values=explode('|',$value);
if(count($values)>0) {
#list($title,$type,$is_required,$sort_order) = explode(':',$field);
$title = ucfirst(str_replace('_',' ',$title));
$custom_options[] = array(
'is_delete'=>0,
'title'=>$title,
'previous_group'=>'',
'previous_type'=>'',
'type'=>$type,
'is_require'=>$is_required,
'sort_order'=>$sort_order,
'values'=>array()
);
foreach($values as $v) {
$parts = explode(':',$v);
$title = $parts[0];
if(count($parts)>1) {
$price_type = $parts[1];
} else {
$price_type = 'fixed';
}
if(count($parts)>2) {
$price = $parts[2];
} else {
$price =0;
}
if(count($parts)>3) {
$sku = $parts[3];
} else {
$sku='';
}
if(count($parts)>4) {
$sort_order = $parts[4];
} else {
$sort_order = 0;
}
switch($type) {
case 'file':
/* TODO */
break;
case 'field':
case 'area':
$custom_options[count($custom_options) - 1]['max_characters'] = $sort_order;
/* NO BREAK */
case 'date':
case 'date_time':
case 'time':
$custom_options[count($custom_options) - 1]['price_type'] = $price_type;
$custom_options[count($custom_options) - 1]['price'] = $price;
$custom_options[count($custom_options) - 1]['sku'] = $sku;
break;
case 'drop_down':
case 'radio':
case 'checkbox':
case 'multiple':
default:
$custom_options[count($custom_options) - 1]['values'][]=array(
'is_delete'=>0,
'title'=>$title,
'option_type_id'=>-1,
'price_type'=>$price_type,
'price'=>$price,
'sku'=>$sku,
'sort_order'=>$sort_order,
);
break;
}
}
}
}
/* END CUSTOM OPTION CODE */
continue;
}
$isArray = false;
$setValue = $value;
if ($attribute->getFrontendInput() == 'multiselect') {
$value = explode(self::MULTI_DELIMITER, $value);
$isArray = true;
$setValue = array();
}
if ($value && $attribute->getBackendType() == 'decimal') {
$setValue = $this->getNumber($value);
}
if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);
if ($isArray) {
foreach ($options as $item) {
if (in_array($item['label'], $value)) {
$setValue[] = $item['value'];
}
}
} else {
$setValue = false;
foreach ($options as $item) {
if ($item['label'] == $value) {
$setValue = $item['value'];
}
}
}
}
$product->setData($field, $setValue);
}
if (!$product->getVisibility()) {
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
}
$stockData = array();
$inventoryFields = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()])
? $this->_inventoryFieldsProductTypes[$product->getTypeId()]
: array();
foreach ($inventoryFields as $field) {
if (isset($importData[$field])) {
if (in_array($field, $this->_toNumber)) {
$stockData[$field] = $this->getNumber($importData[$field]);
}
else {
$stockData[$field] = $importData[$field];
}
}
}
$product->setStockData($stockData);
$imageData = array();
foreach ($this->_imageFields as $field) {
if (!empty($importData[$field]) && $importData[$field] != 'no_selection') {
if (!isset($imageData[$importData[$field]])) {
$imageData[$importData[$field]] = array();
}
$imageData[$importData[$field]][] = $field;
}
}
foreach ($imageData as $file => $fields) {
try {
$product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . trim($file), $fields);
}
catch (Exception $e) {}
}
$product->setIsMassupdate(true);
$product->setExcludeUrlRewrite(true);
$product->save();
/* Remove existing custom options attached to the product */
foreach ($product->getOptions() as $o) {
$o->getValueInstance()->deleteValue($o->getId());
$o->deletePrices($o->getId());
$o->deleteTitles($o->getId());
$o->delete();
}
/* Add the custom options specified in the CSV import file */
if(count($custom_options)) {
foreach($custom_options as $option) {
try {
$opt = Mage::getModel('catalog/product_option');
$opt->setProduct($product);
$opt->addOption($option);
$opt->saveOptions();
}
catch (Exception $e) {}
}
}
return true;
}
This section of the code has been quite well tested, so it's unlikely (though conceivable) that this is a bug that you need to correct in the indexer. Can you provide more detail about the discrepancy that you are seeing?
There is a very good chance that you are seeing unexpected results because of some product being enabled/disabled, etc etc.

Resources