urn new WP_Query($pr);
} else {
return new WP_Query($pr);
}
}
public function update_page_field($product_id, $field_key, $value, $field_type = '', $additional_attr = array()) {
if (!$product_id) {
return FALSE;
}
$fields = $this->settings->get_fields();
//***
//lets check if current user is not administrator and is he can edit this field
if (!$this->is_current_user_can_edit_field($field_key)) {
return esc_html__('forbidden', 'woo-bulk-editor');
}
//***
$value = apply_filters('woobe_before_update_product_field', $value, $product_id, $field_key);
$product = $this->get_product($product_id);
$answer = '';
if (empty($field_type)) {
$field_type = $fields[$field_key]['field_type'];
}
//***
do_action('woobe_before_update_page_field', $field_key, $product_id, $product->get_parent_id());
//***
if ($field_key == 'post_content') {
//fix for description of a variation
if ($product->is_type('variation')) {
$field_key = '_variation_description';
$field_type = 'meta';
}
}
if ($field_key == "attribute_visibility") {
$field_type = 'meta';
}
//***
if (isset($fields[$field_key]['sanitize']) AND $fields[$field_key]['sanitize'] == 'array' AND!empty($value)) {
$value = WOOBE_HELPER::string_to_array($value); //in db its keeps as array, so lets conver it
}
if (isset($_REQUEST['num_rounding']) AND $_REQUEST['num_rounding'] > 0 AND $fields[$field_key]['type'] === 'number') {
if (isset($fields[$field_key]['sanitize']) AND $fields[$field_key]['sanitize'] === 'floatval') {
$round_to = intval($_REQUEST['num_rounding']);
$decimals = wc_get_price_decimals();
$div = intval('1' . str_repeat('0', $decimals));
if ($decimals > 0) {
switch ($round_to) {
case 100:
$value = round($value,0);
break;
case 5:
$value = ceil($value / 0.05) * 0.05;
break;
case 10:
$value = ceil($value * 10) / 10;
break;
case 9:
case 19:
case 29:
case 39:
case 49:
case 59:
case 69:
case 79:
case 89:
case 99:
$value = intval($value) + floatval($round_to / $div);
default:
break;
}
}
}
}
//***
if ($fields[$field_key]['type'] === 'number' AND isset($fields[$field_key]['sanitize']) AND $fields[$field_key]['sanitize'] === 'floatval') {
$value = apply_filters('woobe_number_field_manipulation', $value, $field_key, $product_id);
}
//***
//echo $field_type . ' + ' . $value . ' + ';
switch ($field_type) {
case 'meta':
if ($field_key == "attribute_visibility") {
$meta = get_post_meta($product_id, '_product_attributes', true);
if (!is_array($meta)) {
$meta = array();
}
if (!is_array($value)) {
$value = array($value);
}
foreach ($meta as $pa_key => $item) {
if (in_array($item['name'], $value)) {
$meta[$pa_key]['is_visible'] = 1;
} else {
$meta[$pa_key]['is_visible'] = 0;
}
}
update_post_meta($product_id, '_product_attributes', $meta);
break;
}
// if ($field_key == "_thumbnail_id") {
// set_post_thumbnail( $product_id, intval($value) );
// break;
// }
if ($fields[$field_key]['edit_view'] == 'switcher') { //do switcher
$value = WOOBE_HELPER::over_switcher_swicher_to_val($value, $field_key);
}
if (isset($_REQUEST['is_serialized']) AND $_REQUEST['is_serialized'] AND is_string($value)) {
parse_str($value, $value); //for serialized meta data saving
}
if ($fields[$field_key]['edit_view'] == 'meta_popup_editor') {
$value = $this->process_jsoned_meta_data($value);
$answer = json_encode($value, JSON_HEX_QUOT | JSON_HEX_TAG);
} else {
$answer = $value;
}
if ($fields[$field_key]['edit_view'] == 'gallery_popup_editor') {
$value = isset($value['woobe_gallery_images']) ? $value['woobe_gallery_images'] : array();
}
update_post_meta($product_id, $field_key, $value);
$this->_call_hooks_after_product_update($product);
if ($fields[$field_key]['edit_view'] == 'gallery_popup_editor') {
$answer = WOOBE_HELPER::draw_gallery_popup_editor_btn($field_key, $product_id);
}
break;
case 'prop':
//fix for stock_quantity + manage_stock
if ($field_key == 'stock_quantity' AND $value > 0) {
if (apply_filters('woobe_stock_quantity_dependency', true)) {
$product->set_props(array(
'manage_stock' => 1
));
}
}
//fix IF sale_price > regular_price
if ($field_key == 'sale_price' AND $value > 0) {
$rp = $product->get_regular_price();
if (floatval($value) >= floatval($rp)) {
$div = intval('1' . str_repeat('0', wc_get_price_decimals()));
$value = $rp - floatval(1 / $div);
}
}
if ($field_key == 'sale_price' OR $field_key == 'regular_price' AND $value > 0) {
$value = number_format(floatval($value), wc_get_price_decimals(), ".", "");
if ($field_key == 'sale_price' AND $value <= 0) {
$value = false;
}
// wpml price sync
if (apply_filters('woobe_wpml_sync_prices', false) && function_exists('icl_object_id')) {
$icl_langs = icl_get_languages();
foreach ($icl_langs as $ln => $data) {
if ($icl_langs == $ln) {
continue;
}
$product_lcl_id = icl_object_id($product_id, 'post', false, $ln);
$product_lcl = $this->get_product($product_lcl_id);
if ($product_lcl) {
$product_lcl->set_props(array(
$field_key => $value
));
$product_lcl->save();
}
}
}
}
//***
//$field_key - catalog_visibility for example
if ($field_key == "purchase_note") {
$allowed_html = wp_kses_allowed_html('post');
$product->set_props(array(
$field_key => wp_kses($value, $allowed_html)
));
}elseif($field_key == "sku"){
update_post_meta($product_id, '_sku', $value);
$product->set_sku( $value );
}else {
if ('stock_status' == $field_key && 0 == $value) {
$value = 'outofstock';
}
$product->set_props(array(
$field_key => wc_clean($value)
));
// if (function_exists('icl_object_id') && 'stock_quantity' == $field_key) {
// $icl_langs = icl_get_languages();
// foreach ($icl_langs as $ln => $data) {
// if ($icl_langs == $ln) {
// continue;
// }
//
// $product_lcl_id = icl_object_id($product_id, 'post', false, $ln);
// $product_lcl = $this->get_product($product_lcl_id);
//
// if ($product_lcl) {
// $product_lcl->set_props(array(
// $field_key => wc_clean($value)
// ));
// $product_lcl->save();
// }
// }
// }
}
$product->save();
$func_name = 'get_' . $field_key;
if (method_exists($product, $func_name)) {
$answer = $product->$func_name();
}
break;
case 'taxonomy':
if ($fields[$field_key]['type'] === 'array') {
if (!is_array($value)) {
$value = array(intval($value));
} else {
foreach ($value as $k => $tid) {
$value[$k] = intval($tid);
}
}
} else {
//string, do nothing
}
wp_set_post_terms($product_id, $value, $fields[$field_key]['taxonomy'], false);
$this->_call_hooks_after_product_update($product);
break;
case 'attribute':
$this->set_product_attributes($product_id, $field_key, $value, $additional_attr);
$this->_call_hooks_after_product_update($product);
break;
case 'downloads':
if (!is_array($value)) {
//from Product Editor
parse_str($value, $value);
}
$downloads = $this->prepare_downloads(
isset($value['_wc_file_names']) ? $value['_wc_file_names'] : array(), isset($value['_wc_file_urls']) ? $value['_wc_file_urls'] : array(), isset($value['_wc_file_hashes']) ? $value['_wc_file_hashes'] : array()
);
//***
//for bulk editing operation
if (isset($_REQUEST['action']) AND $_REQUEST['action'] === 'woobe_bulk_products') {
$woobe_bulk = $this->storage->get_val('woobe_bulk_' . WOOBE_HELPER::sanitize_bulk_key($_REQUEST['bulk_key']));
$behavior = $woobe_bulk['download_files']['behavior'];
if ($behavior !== 'new') {
$prev_downloads = $product->get_downloads();
//+++
switch ($behavior) {
case 'delete':
if (!empty($downloads)) {
foreach ($downloads as $d) {
foreach ($prev_downloads as $ked => $ed) {
if ($ed->get_file() === $d['file']) {
unset($prev_downloads[$ked]);
}
}
}
}
$downloads = $prev_downloads;
break;
case 'add':
if (!empty($downloads)) {
foreach ($downloads as $d) {
$prev_downloads[] = $d;
}
$downloads = $prev_downloads;
}
break;
default:
//new
//do nothing
break;
}
}
}
//***
$product->set_downloads($downloads);
$product->save();
$answer = WOOBE_HELPER::draw_downloads_popup_editor_btn($field_key, $product->get_id());
break;
case 'gallery':
if (!is_array($value)) {
//from Product Editor
parse_str($value, $value);
}
$value = isset($value['woobe_gallery_images']) ? $value['woobe_gallery_images'] : array();
//***
//for bulk editing operation
if (isset($_REQUEST['action']) AND $_REQUEST['action'] === 'woobe_bulk_products') {
$woobe_bulk = $this->storage->get_val('woobe_bulk_' . WOOBE_HELPER::sanitize_bulk_key($_REQUEST['bulk_key']));
$behavior = $woobe_bulk['gallery']['behavior'];
if ($behavior !== 'new') {
$prev_ids = $product->get_gallery_image_ids();
switch ($behavior) {
case 'delete_forever':
if (!empty($value)) {
foreach ($value as $attachment_id) {
wp_delete_attachment($attachment_id, true);
}
}
$value = array_diff($prev_ids, $value);
break;
case 'delete':
$value = array_diff($prev_ids, $value);
break;
case 'add':
$value = array_merge($prev_ids, $value);
break;
default:
//new
//do nothing
break;
}
}
}
//***
$product->set_gallery_image_ids($value);
$product->save();
$answer = WOOBE_HELPER::draw_gallery_popup_editor_btn($field_key, $product->get_id());
break;
case 'upsells':
if (!is_array($value)) {
$value = str_replace("&", "&", $value);
//from Product Editor
parse_str($value, $value);
}
$value = (isset($value['woobe_prod_ids'])) ? $value['woobe_prod_ids'] : array();
//***
//for bulk editing operation
if (isset($_REQUEST['action']) AND $_REQUEST['action'] === 'woobe_bulk_products') {
$woobe_bulk = $this->storage->get_val('woobe_bulk_' . WOOBE_HELPER::sanitize_bulk_key($_REQUEST['bulk_key']));
$behavior = $woobe_bulk['upsell_ids']['behavior'];
if ($behavior !== 'new') {
$prev_ids = $product->get_upsell_ids();
switch ($behavior) {
case 'delete':
$value = array_diff($prev_ids, $value);
break;
case 'add':
$value = array_merge($prev_ids, $value);
break;
default:
//new
//do nothing
break;
}
}
}
//***
$product->set_upsell_ids($value);
$product->save();
$answer = WOOBE_HELPER::draw_upsells_popup_editor_btn($field_key, $product->get_id());
break;
case 'cross_sells':
if (!is_array($value)) {
$value = str_replace("&", "&", $value);
//from Product Editor
parse_str($value, $value);
}
$value = (isset($value['woobe_prod_ids'])) ? $value['woobe_prod_ids'] : array();
//***
//for bulk editing operation
if (isset($_REQUEST['action']) AND $_REQUEST['action'] === 'woobe_bulk_products') {
$woobe_bulk = $this->storage->get_val('woobe_bulk_' . WOOBE_HELPER::sanitize_bulk_key($_REQUEST['bulk_key']));
$behavior = $woobe_bulk['cross_sell_ids']['behavior'];
if ($behavior !== 'new') {
$prev_ids = $product->get_cross_sell_ids();
switch ($behavior) {
case 'delete':
$value = array_diff($prev_ids, $value);
break;
case 'add':
$value = array_merge($prev_ids, $value);
break;
default:
//new
//do nothing
break;
}
}
}
//***
$product->set_cross_sell_ids($value);
$product->save();
$answer = WOOBE_HELPER::draw_cross_sells_popup_editor_btn($field_key, $product->get_id());
break;
case 'grouped':
if ($product->get_type() === 'grouped') {
if (!is_array($value)) {
//from Product Editor
parse_str($value, $value);
}
$value = (isset($value['woobe_prod_ids'])) ? $value['woobe_prod_ids'] : array();
//***
//for bulk editing operation
if (isset($_REQUEST['action']) AND $_REQUEST['action'] === 'woobe_bulk_products') {
$woobe_bulk = $this->storage->get_val('woobe_bulk_' . WOOBE_HELPER::sanitize_bulk_key($_REQUEST['bulk_key']));
$behavior = $woobe_bulk['grouped_ids']['behavior'];
if ($behavior !== 'new') {
$prev_ids = $product->get_children();
switch ($behavior) {
case 'delete':
$value = array_diff($prev_ids, $value);
break;
case 'add':
$value = array_merge($prev_ids, $value);
break;
default:
//new
//do nothing
break;
}
}
}
//***
$product->set_children($value);
$product->save();
$answer = WOOBE_HELPER::draw_grouped_popup_editor_btn($field_key, $product->get_id());
}
break;
default:
//fix for product variations statuses
if ($field_key === 'post_status') {
if ($product->is_type('variation')) {
if ($value != 'publish') {
$value = 'private';
}
}
}
if ('post_date' == $field_key) {
$new_key = 'post_date_gmt';
$new_value = gmdate('Y-m-d H:i:s', strtotime($value));
wp_update_post(array(
'ID' => $product_id,
$new_key => $new_value
));
}
// if ($field_key === 'post_content') {
// if(is_array($value)){
//$value=implode(" ", $value);
//
//$value=strval ($value);
//
// }
// }
// fix for variation
if ($field_key === 'post_author') {
$children = $product->get_children();
if (!empty($children)) {
foreach ($children as $var_id) {
wp_update_post(array(
'ID' => $var_id,
$field_key => $value
));
}
}
}
//***
//table field
wp_update_post(array(
'ID' => $product_id,
$field_key => $value
));
$answer = get_post_field($field_key, $product_id);
$this->_call_hooks_after_product_update($product);
break;
}
//***
//speedfix comment line -0.5sek
//wc_delete_product_transients($product_id);
//***
if ($fields[$field_key]['edit_view'] == 'textinput') {
$answer = $this->sanitize_answer_value($field_key, (isset($fields[$field_key]['sanitize']) ? $fields[$field_key]['sanitize'] : ''), $answer);
}
//***
//FOR ANY FLEXIBLE COMPATIBILITY
do_action('woobe_after_update_page_field', $product_id, $product, $field_key, $value, $field_type);
//update products cache
$this->cached_products[$product_id] = $product;
return $answer;
return stripcslashes($answer);
}
//util
private function _call_hooks_after_product_update(&$product) {
$product_id = $product->get_id();
$pp = get_post($product_id);
do_action('save_post', $product_id, $pp, true);
do_action("save_post_product", $product_id, $pp, true);
do_action('edit_post', $product_id, $pp);
$this->clear_caches($product);
flush_rewrite_rules();
//***
if ($product->get_type() === 'variation') {
do_action('woocommerce_update_product_variation', $product_id, $product);
} else {
do_action('woocommerce_update_product', $product_id, $product);
}
}
//service
public function sanitize_answer_value($field_key, $sanitize, $val) {
$res = $val;
switch ($sanitize) {
case 'sanitize_key':
$res = sanitize_key($val);
break;
case 'esc_url':
$res = esc_url($val);
break;
case 'urldecode':
$res = urldecode($val);
break;
case 'floatval':
$val = str_replace(',', '.', $val);
$val = str_replace(' ', '', $val);
if (in_array($field_key, array('regular_price', 'sale_price'))) {
$res = number_format(floatval($val), wc_get_price_decimals());
} else {
$res = floatval($val);
}
break;
case 'intval':
$res = intval($val);
break;
case 'array':
if (is_array($val) AND!empty($val)) {
$res = WOOBE_HELPER::array_to_string($val);
}
break;
}
return $res;
}
public function set_product_attributes_visible($product_id, $attributes, $visible) {
$meta = get_post_meta($product_id, '_product_attributes', true);
if (!is_array($meta)) {
$meta = array();
}
if (!is_array($attributes)) {
$attributes = array($attributes);
}
foreach ($meta as $pa_key => $item) {
if (in_array($item['name'], $attributes)) {
$meta[$pa_key]['is_visible'] = $visible;
}
}
update_post_meta($product_id, '_product_attributes', $meta);
}
public function set_product_attributes($product_id, $field_key, $value, $mode = 'replace', $attr_data = array()) {
if (!is_array($value)) {
$value = array(intval($value));
} else {
foreach ($value as $k => $tid) {
$value[$k] = intval($tid);
}
}
//***
$product = $this->get_product($product_id);
$attributes = array();
$product_attributes = $product->get_attributes();
//*** fix for empty value
if (count($value) === 1) {
if (intval($value[0]) === 0) {
$value = array();
}
}
//***
if (!empty($product_attributes)) {
//wp-content\plugins\woocommerce\includes\admin\meta-boxes\class-wc-meta-box-product-data.php
//public static function prepare_attributes
foreach ($product_attributes as $pa_key => $a) {
if (is_object($a)) {
$attribute = new WC_Product_Attribute();
$attribute->set_id($a->get_id());
$attribute->set_name($a->get_name());
if ($a->get_name() == $field_key) {
//detach attributes if there is no selected terms!!
if (empty($value)) {
continue;
}
//***
switch ($mode) {
case 'append':
//using in bulk
$attribute->set_options(array_unique(array_merge($a->get_options(), $value)));
break;
case 'replace':
case 'new':
//using in bulk AND in editor
$attribute->set_options($value);
break;
case 'remove':
//using in bulk
$attribute->set_options(array_values(array_diff($a->get_options(), $value)));
break;
case 'visible':
//using in bulk
$a->set_visible($value);
break;
default :
$attribute->set_options($value);
}
} else {
$attribute->set_options($a->get_options());
}
$attribute->set_position($a->get_position());
$attribute->set_visible($a->get_visible());
$attribute->set_variation($a->get_variation());
$attributes[] = $attribute;
}
}
}
//***
//if such attribute not applied in the product
if (!isset($product_attributes[$field_key]) AND!isset($product_attributes[strtolower(urlencode($field_key))])) {
$attribute = new WC_Product_Attribute();
$attribute_taxonomies = wc_get_attribute_taxonomies();
foreach ($attribute_taxonomies as $a) {
if ('pa_' . $a->attribute_name == $field_key) {
if (!empty($value)) {
$attribute->set_id($a->attribute_id);
$attribute->set_name('pa_' . $a->attribute_name);
$attribute->set_options($value);
$attribute->set_position(count($attributes));
$attribute->set_visible(1);
if (in_array('set_variation', $attr_data)) {
$attribute->set_variation(true);
} else {
$attribute->set_variation(false);
}
$attributes[] = $attribute;
}
break;
}
}
}
$product->set_attributes($attributes);
$product->save();
}
//for saving downloads
private function prepare_downloads($file_names, $file_urls, $file_hashes) {
$downloads = array();
if (!empty($file_urls)) {
$file_url_size = sizeof($file_urls);
for ($i = 0; $i < $file_url_size; $i++) {
if (!empty($file_urls[$i])) {
$downloads[] = array(
'name' => wc_clean($file_names[$i]),
'file' => wp_unslash(trim($file_urls[$i])),
'previous_hash' => wc_clean($file_hashes[$i]),
);
}
}
}
return $downloads;
}
//++++++++++++++++++++++++++++++++++++++++
public function get_post_field($product_id, $field_key, $post_parent = 0) {
if (!$product_id) {
return FALSE;
}
//***
$res = '';
$field_type = $this->settings->get_fields()[$field_key]['field_type'];
//fix for description of one variation
if ($field_key == 'post_content' AND $post_parent > 0) {
$field_type = 'meta';
$field_key = '_variation_description';
}
//***
switch ($field_type) {
case 'meta':
//$this->settings->get_fields()[$field_key]["edit_view"]=="calendar";
$res = get_post_meta($product_id, $field_key, true);
break;
case 'field':
$res = get_post_field($field_key, $product_id);
break;
case 'prop':
$product = $this->get_product($product_id);
//$field_key - for example: catalog_visibility
$func_name = 'get_' . $field_key;
//for example get_product_url() and get_button_text() exists only for external products
if (method_exists($product, $func_name)) {
$res = $product->$func_name();
}
break;
case 'taxonomy':
$res = wp_get_post_terms($product_id, $this->settings->get_fields()[$field_key]['taxonomy'], array(
//'fields' => 'ids',
'hide_empty' => false,
));
break;
case 'attribute':
$product = $this->get_product($product_id);
$attributes = $product->get_attributes();
if (!empty($attributes)) {
if (!$product->is_type('variation')) {
$res = array();
foreach ($attributes as $a) {
if (is_object($a)) {
if ($a->get_name() == $field_key) {
$res = $a->get_options();
break;
}
}
}
} else {
//a variation has NOT attributes as it is an attribute self
//echo get_class($product);
foreach ($attributes as $a) {
if (is_object($a) AND method_exists($a, 'get_name')) {
if ($a->get_name() == $field_key) {
$t = get_term_by('slug', $a, $field_key);
if (!empty($t)) {
$res = array($t->term_id);
}
break;
}
}
}
}
}
break;
case 'attribute_visibile':
$product = $this->get_product($product_id);
$attributes = $product->get_attributes();
if (!empty($attributes)) {
if (!$product->is_type('variation')) {
$res = array();
foreach ($attributes as $a) {
if (is_object($a)) {
if ($a->get_visible()) {
$res[] = $a->get_visible();
}
}
}
}
// else {
// //a variation has NOT attributes as it is an attribute self
// //echo get_class($product);
// foreach ($attributes as $a) {
// if (is_object($a) AND method_exists($a, 'get_name')) {
// if ($a->get_name() == $field_key) {
// $t = get_term_by('slug', $a, $field_key);
// if (!empty($t)) {
// $res = array($t->term_id);
// }
// break;
// }
// }
// }
// }
}
break;
case 'gallery':
$product = $this->get_product($product_id);
try {
$res = $product->get_gallery_image_ids();
} catch (Exception $e) {
$res = array();
}
break;
case 'downloads':
try {
$product = $this->get_product($product_id);
$res = $product->get_downloads('edit');
} catch (Exception $e) {
$res = array();
}
break;
case 'upsells':
try {
$product = $this->get_product($product_id);
$res = $product->get_upsell_ids();
} catch (Exception $e) {
$res = array();
}
break;
case 'cross_sells':
try {
$product = $this->get_product($product_id);
$res = $product->get_cross_sell_ids();
} catch (Exception $e) {
$res = array();
}
break;
case 'grouped':
try {
$product = $this->get_product($product_id);
$res = $product->get_children('edit');
} catch (Exception $e) {
$res = array();
}
break;
}
return $res;
}
public function get_product($product_id, $use_cache = true) {
$product_id = intval($product_id);
if ($use_cache) {
if (!isset($this->cached_products[$product_id])) {
$this->cached_products[$product_id] = wc_get_product($product_id);
}
return $this->cached_products[$product_id];
} else {
return wc_get_product($product_id);
}
/*
$product_type = WC_Product_Factory::get_product_type($product_id);
$classname = WC_Product_Factory::get_product_classname($product_id, $product_type);
return new $classname($product_id);
*
*/
}
public function normalize_calendar_date($value, $field_key) {
if ($field_key == 'post_date') {
$date = new DateTime();
$date->setTimestamp(strtotime($value));
$value = $date->format('Y-m-d H:i:s');
return $value;
}
if ($value != 0 && $value != null) {//if not clearing
// $value = explode('-', $value);
if (isset($this->settings->active_fields[$field_key]['set_day_end']) AND $this->settings->active_fields[$field_key]['set_day_end']) {
//$value = mktime(23, 59, 59, intval($value['1']), intval($value['2']), intval($value['0']));
$value = date('Y-m-d 23:59:59', intval(strtotime($value)));
} else {
//$value = mktime(0, 0, 0, intval($value['1']), intval($value['2']), intval($value['0']));
$value = date('Y-m-d 00:00:00', intval(strtotime($value)));
}
$value = strtotime($value) - intval(get_option('gmt_offset')) * 3600;
//***
//$gmt_offset = intval(get_option('gmt_offset')) * 3600;
//$value += $gmt_offset;
//***
if ($this->settings->active_fields[$field_key]['type'] === 'timestamp'
AND $this->settings->active_fields[$field_key]['field_type'] === 'field') {
$date = new DateTime();
$date->setTimestamp($value);
$value = $date->format('Y-m-d H:i:s');
}
}
return $value;
}
public function get_attributes($product_id, $type = "all") {
$product = $this->get_product($product_id);
$attributes = $product->get_attributes();
$res = array();
if (!empty($attributes)) {
if ($type == "visible") {
$res = [];
foreach ($attributes as $a) {
if (is_object($a)) {
if ($a->get_visible()) {
$res[] = $a;
}
}
}
} else {
$res = $attributes;
}
}
return $res;
}
//service
public function string_replacer($val, $product_id) {
if (is_string($val)) {
if (stripos($val, '{TITLE}') !== false) {
$val = str_ireplace('{TITLE}', $this->get_post_field($product_id, 'post_title'), $val);
}
if (stripos($val, '{ID}') !== false) {
$val = str_ireplace('{ID}', $product_id, $val);
}
if (stripos($val, '{SKU}') !== false) {
$val = str_ireplace('{SKU}', $this->get_post_field($product_id, 'sku'), $val);
}
//***
if (stripos($val, '{PARENT_TITLE}') !== false) {
$p = $this->get_product($product_id);
if ($p->is_type('variation')) {
$val = str_ireplace('{PARENT_TITLE}', $this->get_post_field($p->get_parent_id(), 'post_title'), $val);
} else {
$val = str_ireplace('{PARENT_TITLE}', $this->get_post_field($product_id, 'post_title'), $val);
}
}
if (stripos($val, '{PARENT_SKU}') !== false) {
$p = $this->get_product($product_id);
if ($p->is_type('variation')) {
$val = str_ireplace('{PARENT_SKU}', $this->get_post_field($p->get_parent_id(), 'sku'), $val);
} else {
$val = str_ireplace('{PARENT_SKU}', $this->get_post_field($product_id, 'sku'), $val);
}
}
if (stripos($val, '{PARENT_ID}') !== false) {
$p = $this->get_product($product_id);
if ($p->is_type('variation')) {
$val = str_ireplace('{PARENT_ID}', $p->get_parent_id(), $val);
} else {
$val = str_ireplace('{PARENT_ID}', $product_id, $val);
}
}
if (stripos($val, '{MENU_ORDER}') !== false) {
$val = str_ireplace('{MENU_ORDER}', $this->get_post_field($product_id, 'menu_order'), $val);
}
if (stripos($val, '{REGULAR_PRICE}') !== false) {
$val = str_ireplace('{REGULAR_PRICE}', $this->get_post_field($product_id, 'regular_price'), $val);
}
if (stripos($val, '{SALE_PRICE}') !== false) {
$val = str_ireplace('{SALE_PRICE}', $this->get_post_field($product_id, 'sale_price'), $val);
}
//***
if (stripos($val, '{meta:') !== false) {
//{meta:_woocs_regular_price_USD} - lets take data from metafield
$matches = array();
preg_match("/(?<={meta:)(.*)(?=})/", $val, $matches);
if (isset($matches[1])) {
//$meta = $this->get_post_field($product_id, trim($matches[1]));
$meta = get_post_meta($product_id,trim($matches[1]), true);
if (!empty($meta)) {
$val = str_ireplace('{meta:' . $matches[1] . "}", $meta, $val);
} else {
$val = str_ireplace('{meta:' . $matches[1] . "}", "", $val);
}
}
}
if (stripos($val, '{attribute:') !== false) {
//{attribute:pa_size}
$matches = array();
preg_match("/(?<={attribute:)(.*)(?=})/", $val, $matches);
if (isset($matches[1])) {
$prod = $this->get_product($product_id);
$attr = $prod->get_attribute(trim($matches[1]));
if (!empty($attr)) {
$val = str_ireplace('{attribute:' . $matches[1] . "}", $attr, $val);
} else {
$val = str_ireplace('{attribute:' . $matches[1] . "}", "", $val);
}
}
}
}
return apply_filters('woobe_apply_string_replacer', $val);
}
public function string_macros($val, $field_key, $product_id) {
if (!is_string($val)) {
return $val;
}
$original_val = $this->get_post_field($product_id, $field_key);
if (is_string($original_val)) {
if (stripos($val, '{DO_STRING_UP}') !== false) {
$val = str_ireplace('{DO_STRING_UP}', mb_strtoupper($original_val), $val);
}
if (stripos($val, '{DO_STRING_DOWN}') !== false) {
$val = str_ireplace('{DO_STRING_DOWN}', mb_strtolower($original_val), $val);
}
if (stripos($val, '{DO_STRING_TITLE}') !== false) {
$val = str_ireplace('{DO_STRING_TITLE}', mb_convert_case($original_val, MB_CASE_TITLE, "UTF-8"), $val);
}
if (stripos($val, '{DO_STRING_UP_FIRST}') !== false) {
$fc = mb_strtoupper(mb_substr($original_val, 0, 1));
$original_val = $fc . mb_substr($original_val, 1);
$val = str_ireplace('{DO_STRING_UP_FIRST}', $original_val, $val);
}
}
return $val;
}
/**
* Generates a title with attribute information for a variation.
* Products will get a title of the form "Name - Value, Value" or just "Name".
*
* @since 3.0.0
* @param WC_Product
* @return string
*/
public function generate_product_title($product) {
$attributes = (array) $product->get_attributes();
// Do not include attributes if the product has 10+ attributes.
$should_include_attributes = count($attributes) < 10;
// Do not include attributes if an attribute name has 2+ words and the
// product has multiple attributes.
if ($should_include_attributes && 1 < count($attributes)) {
foreach ($attributes as $name => $value) {
if (false !== strpos($name, '-')) {
$should_include_attributes = false;
break;
}
}
}
$should_include_attributes = apply_filters('woocommerce_product_variation_title_include_attributes', $should_include_attributes, $product);
$separator = apply_filters('woocommerce_product_variation_title_attributes_separator', ' - ', $product);
//$parent_product = $this->get_product($product->get_parent_id());
$title_base = get_post_field('post_title', $product->get_parent_id());
if ($should_include_attributes) {
$title_suffix = wc_get_formatted_variation($product, true, false);
if (!empty($attributes)) {
$title_suffix .= ' [';
$title_suffix .= implode(', ', array_map(
function ($str) {
return str_replace('pa_', '', $str);
}, array_map('urldecode', array_keys($attributes))
));
$title_suffix .= ']';
}
} else {
$title_suffix = '';
}
//$title_suffix = $should_include_attributes ? wc_get_formatted_variation($product, true, false) : '';
return apply_filters('woocommerce_product_variation_title', $title_suffix ? $title_base . $separator . $title_suffix : $title_base, $product, $title_base, $title_suffix);
}
public function is_current_user_can_edit_field($field_key) {
if (!in_array($this->settings->current_user_role, apply_filters('woobe_permit_special_roles', ['administrator']))) {
$shop_manager_visibility = $this->settings->get_shop_manager_visibility();
$user_can = apply_filters('woobe_user_can_edit', $shop_manager_visibility[$field_key], $field_key, $shop_manager_visibility);
if (!intval($user_can)) {
return FALSE;
}
}
return TRUE;
}
//service function to process serialized meta data
public function process_jsoned_meta_data($raw_data) {
$result = array();
//*** //for js arrays
if (isset($raw_data['keys']) AND!empty($raw_data['keys'])) {
$tmp = array();
foreach ($raw_data['keys'] as $kk => $kv) {
if (!is_null($kv)) {
if (!is_array($kv) AND isset($raw_data['keys'][$kv]) AND is_array($raw_data['keys'][$kv])) {
if (!empty($raw_data['keys'][$kv])) {
$tmp[WOOBE_HELPER::prepare_meta_keys($kv)] = array();
foreach ($raw_data['keys'][$kv] as $kkk => $vvv) {
if (isset($raw_data['values'][$kv][$kkk])) {
$tmp[WOOBE_HELPER::prepare_meta_keys($kv)][WOOBE_HELPER::prepare_meta_keys($vvv)] = $raw_data['values'][$kv][$kkk];
}
}
}
} else {
if (!is_array($kv)) {
if (isset($raw_data['values'][WOOBE_HELPER::prepare_meta_keys($kk)])) {
$tmp[WOOBE_HELPER::prepare_meta_keys($kv)] = $raw_data['values'][WOOBE_HELPER::prepare_meta_keys($kk)];
}
}
}
}
} $result = $tmp;
}
//*** //for js objects
if (isset($raw_data['keys2']) AND!empty($raw_data['keys2'])) {
$tmp = array();
foreach ($raw_data['keys2'] as $k => $keys) {
if (!empty($keys)) {
$o = array();
foreach ($keys as $kk => $key) {
if ($this->is_json($raw_data['values2'][$k][$kk])) {
$o[$key] = json_decode($raw_data['values2'][$k][$kk], ARRAY_A);
} else {
$o[$key] = $raw_data['values2'][$k][$kk];
}
} $tmp[$k] = $o;
}
} $result = array_merge($result, $tmp);
}
//*** //if meta value is just string or number
if (empty($result)) {
$result = $raw_data;
}
return $result;
}
protected function clear_caches(&$product) {
wc_delete_product_transients($product->get_id());
if ($product->get_parent_id('edit')) {
wc_delete_product_transients($product->get_parent_id('edit'));
WC_Cache_Helper::invalidate_cache_group('product_' . $product->get_parent_id('edit'));
}
WC_Cache_Helper::invalidate_attribute_count(array_keys($product->get_attributes()));
WC_Cache_Helper::invalidate_cache_group('product_' . $product->get_id());
}
function is_json($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
public function get_product_type($pr) {
if (is_object($pr)) {
$pr = $pr->get_id();
}
$type = 'simple';
$terms = wp_get_object_terms( $pr, 'product_type' );
if (is_array($terms)) {
$type = $terms[0]->slug;
}
return $type;
}
}
* @param int $comment_id Comment ID.
*/
$message_headers = apply_filters( 'comment_moderation_headers', $message_headers, $comment_id );
foreach ( $emails as $email ) {
wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers );
}
if ( $switched_locale ) {
restore_previous_locale();
}
return true;
}
endif;
if ( ! function_exists( 'wp_password_change_notification' ) ) :
/**
* Notifies the blog admin of a user changing password, normally via email.
*
* @since 2.7.0
*
* @param WP_User $user User object.
*/
function wp_password_change_notification( $user ) {
/*
* Send a copy of password change notification to the admin,
* but check to see if it's the admin whose password we're changing, and skip this.
*/
if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) ) {
/* translators: %s: User name. */
$message = sprintf( __( 'Password changed for user: %s' ), $user->user_login ) . "\r\n";
/*
* The blogname option is escaped with esc_html() on the way into the database in sanitize_option().
* We want to reverse this for the plain text arena of emails.
*/
$blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
$wp_password_change_notification_email = array(
'to' => get_option( 'admin_email' ),
/* translators: Password change notification email subject. %s: Site title. */
'subject' => __( '[%s] Password Changed' ),
'message' => $message,
'headers' => '',
);
/**
* Filters the contents of the password change notification email sent to the site admin.
*
* @since 4.9.0
*
* @param array $wp_password_change_notification_email {
* Used to build wp_mail().
*
* @type string $to The intended recipient - site admin email address.
* @type string $subject The subject of the email.
* @type string $message The body of the email.
* @type string $headers The headers of the email.
* }
* @param WP_User $user User object for user whose password was changed.
* @param string $blogname The site title.
*/
$wp_password_change_notification_email = apply_filters( 'wp_password_change_notification_email', $wp_password_change_notification_email, $user, $blogname );
wp_mail(
$wp_password_change_notification_email['to'],
wp_specialchars_decode( sprintf( $wp_password_change_notification_email['subject'], $blogname ) ),
$wp_password_change_notification_email['message'],
$wp_password_change_notification_email['headers']
);
}
}
endif;
if ( ! function_exists( 'wp_new_user_notification' ) ) :
/**
* Emails login credentials to a newly-registered user.
*
* A new user registration notification is also sent to admin email.
*
* @since 2.0.0
* @since 4.3.0 The `$plaintext_pass` parameter was changed to `$notify`.
* @since 4.3.1 The `$plaintext_pass` parameter was deprecated. `$notify` added as a third parameter.
* @since 4.6.0 The `$notify` parameter accepts 'user' for sending notification only to the user created.
*
* @param int $user_id User ID.
* @param null $deprecated Not used (argument deprecated).
* @param string $notify Optional. Type of notification that should happen. Accepts 'admin' or an empty
* string (admin only), 'user', or 'both' (admin and user). Default empty.
*/
function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) {
if ( null !== $deprecated ) {
_deprecated_argument( __FUNCTION__, '4.3.1' );
}
// Accepts only 'user', 'admin' , 'both' or default '' as $notify.
if ( ! in_array( $notify, array( 'user', 'admin', 'both', '' ), true ) ) {
return;
}
$user = get_userdata( $user_id );
/*
* The blogname option is escaped with esc_html() on the way into the database in sanitize_option().
* We want to reverse this for the plain text arena of emails.
*/
$blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
/**
* Filters whether the admin is notified of a new user registration.
*
* @since 6.1.0
*
* @param bool $send Whether to send the email. Default true.
* @param WP_User $user User object for new user.
*/
$send_notification_to_admin = apply_filters( 'wp_send_new_user_notification_to_admin', true, $user );
if ( 'user' !== $notify && true === $send_notification_to_admin ) {
$switched_locale = switch_to_locale( get_locale() );
/* translators: %s: Site title. */
$message = sprintf( __( 'New user registration on your site %s:' ), $blogname ) . "\r\n\r\n";
/* translators: %s: User login. */
$message .= sprintf( __( 'Username: %s' ), $user->user_login ) . "\r\n\r\n";
/* translators: %s: User email address. */
$message .= sprintf( __( 'Email: %s' ), $user->user_email ) . "\r\n";
$wp_new_user_notification_email_admin = array(
'to' => get_option( 'admin_email' ),
/* translators: New user registration notification email subject. %s: Site title. */
'subject' => __( '[%s] New User Registration' ),
'message' => $message,
'headers' => '',
);
/**
* Filters the contents of the new user notification email sent to the site admin.
*
* @since 4.9.0
*
* @param array $wp_new_user_notification_email_admin {
* Used to build wp_mail().
*
* @type string $to The intended recipient - site admin email address.
* @type string $subject The subject of the email.
* @type string $message The body of the email.
* @type string $headers The headers of the email.
* }
* @param WP_User $user User object for new user.
* @param string $blogname The site title.
*/
$wp_new_user_notification_email_admin = apply_filters( 'wp_new_user_notification_email_admin', $wp_new_user_notification_email_admin, $user, $blogname );
wp_mail(
$wp_new_user_notification_email_admin['to'],
wp_specialchars_decode( sprintf( $wp_new_user_notification_email_admin['subject'], $blogname ) ),
$wp_new_user_notification_email_admin['message'],
$wp_new_user_notification_email_admin['headers']
);
if ( $switched_locale ) {
restore_previous_locale();
}
}
/**
* Filters whether the user is notified of their new user registration.
*
* @since 6.1.0
*
* @param bool $send Whether to send the email. Default true.
* @param WP_User $user User object for new user.
*/
$send_notification_to_user = apply_filters( 'wp_send_new_user_notification_to_user', true, $user );
// `$deprecated` was pre-4.3 `$plaintext_pass`. An empty `$plaintext_pass` didn't sent a user notification.
if ( 'admin' === $notify || true !== $send_notification_to_user || ( empty( $deprecated ) && empty( $notify ) ) ) {
return;
}
$key = get_password_reset_key( $user );
if ( is_wp_error( $key ) ) {
return;
}
$switched_locale = switch_to_user_locale( $user_id );
/* translators: %s: User login. */
$message = sprintf( __( 'Username: %s' ), $user->user_login ) . "\r\n\r\n";
$message .= __( 'To set your password, visit the following address:' ) . "\r\n\r\n";
$message .= network_site_url( "wp-login.php?action=rp&key=$key&login=" . rawurlencode( $user->user_login ), 'login' ) . "\r\n\r\n";
$message .= wp_login_url() . "\r\n";
$wp_new_user_notification_email = array(
'to' => $user->user_email,
/* translators: Login details notification email subject. %s: Site title. */
'subject' => __( '[%s] Login Details' ),
'message' => $message,
'headers' => '',
);
/**
* Filters the contents of the new user notification email sent to the new user.
*
* @since 4.9.0
*
* @param array $wp_new_user_notification_email {
* Used to build wp_mail().
*
* @type string $to The intended recipient - New user email address.
* @type string $subject The subject of the email.
* @type string $message The body of the email.
* @type string $headers The headers of the email.
* }
* @param WP_User $user User object for new user.
* @param string $blogname The site title.
*/
$wp_new_user_notification_email = apply_filters( 'wp_new_user_notification_email', $wp_new_user_notification_email, $user, $blogname );
wp_mail(
$wp_new_user_notification_email['to'],
wp_specialchars_decode( sprintf( $wp_new_user_notification_email['subject'], $blogname ) ),
$wp_new_user_notification_email['message'],
$wp_new_user_notification_email['headers']
);
if ( $switched_locale ) {
restore_previous_locale();
}
}
endif;
if ( ! function_exists( 'wp_nonce_tick' ) ) :
/**
* Returns the time-dependent variable for nonce creation.
*
* A nonce has a lifespan of two ticks. Nonces in their second tick may be
* updated, e.g. by autosave.
*
* @since 2.5.0
* @since 6.1.0 Added `$action` argument.
*
* @param string|int $action Optional. The nonce action. Default -1.
* @return float Float value rounded up to the next highest integer.
*/
function wp_nonce_tick( $action = -1 ) {
/**
* Filters the lifespan of nonces in seconds.
*
* @since 2.5.0
* @since 6.1.0 Added `$action` argument to allow for more targeted filters.
*
* @param int $lifespan Lifespan of nonces in seconds. Default 86,400 seconds, or one day.
* @param string|int $action The nonce action, or -1 if none was provided.
*/
$nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS, $action );
return ceil( time() / ( $nonce_life / 2 ) );
}
endif;
if ( ! function_exists( 'wp_verify_nonce' ) ) :
/**
* Verifies that a correct security nonce was used with time limit.
*
* A nonce is valid for 24 hours (by default).
*
* @since 2.0.3
*
* @param string $nonce Nonce value that was used for verification, usually via a form field.
* @param string|int $action Should give context to what is taking place and be the same when nonce was created.
* @return int|false 1 if the nonce is valid and generated between 0-12 hours ago,
* 2 if the nonce is valid and generated between 12-24 hours ago.
* False if the nonce is invalid.
*/
function wp_verify_nonce( $nonce, $action = -1 ) {
$nonce = (string) $nonce;
$user = wp_get_current_user();
$uid = (int) $user->ID;
if ( ! $uid ) {
/**
* Filters whether the user who generated the nonce is logged out.
*
* @since 3.5.0
*
* @param int $uid ID of the nonce-owning user.
* @param string|int $action The nonce action, or -1 if none was provided.
*/
$uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
}
if ( empty( $nonce ) ) {
return false;
}
$token = wp_get_session_token();
$i = wp_nonce_tick( $action );
// Nonce generated 0-12 hours ago.
$expected = substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
if ( hash_equals( $expected, $nonce ) ) {
return 1;
}
// Nonce generated 12-24 hours ago.
$expected = substr( wp_hash( ( $i - 1 ) . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
if ( hash_equals( $expected, $nonce ) ) {
return 2;
}
/**
* Fires when nonce verification fails.
*
* @since 4.4.0
*
* @param string $nonce The invalid nonce.
* @param string|int $action The nonce action.
* @param WP_User $user The current user object.
* @param string $token The user's session token.
*/
do_action( 'wp_verify_nonce_failed', $nonce, $action, $user, $token );
// Invalid nonce.
return false;
}
endif;
if ( ! function_exists( 'wp_create_nonce' ) ) :
/**
* Creates a cryptographic token tied to a specific action, user, user session,
* and window of time.
*
* @since 2.0.3
* @since 4.0.0 Session tokens were integrated with nonce creation.
*
* @param string|int $action Scalar value to add context to the nonce.
* @return string The token.
*/
function wp_create_nonce( $action = -1 ) {
$user = wp_get_current_user();
$uid = (int) $user->ID;
if ( ! $uid ) {
/** This filter is documented in wp-includes/pluggable.php */
$uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
}
$token = wp_get_session_token();
$i = wp_nonce_tick( $action );
return substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
}
endif;
if ( ! function_exists( 'wp_salt' ) ) :
/**
* Returns a salt to add to hashes.
*
* Salts are created using secret keys. Secret keys are located in two places:
* in the database and in the wp-config.php file. The secret key in the database
* is randomly generated and will be appended to the secret keys in wp-config.php.
*
* The secret keys in wp-config.php should be updated to strong, random keys to maximize
* security. Below is an example of how the secret key constants are defined.
* Do not paste this example directly into wp-config.php. Instead, have a
* {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just
* for you.
*
* define('AUTH_KEY', ' XakmM%G4Yt>f`z]MON');
* define('SECURE_AUTH_KEY', 'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~');
* define('LOGGED_IN_KEY', '|i|Ux`9z7X>QYR0Z_XnZ@|');
* define('AUTH_SALT', 'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW');
* define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W*c(u`g~EJBf#8u#R{mUEZrozmm');
* define('NONCE_SALT', 'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT');
*
* Salting passwords helps against tools which has stored hashed values of
* common dictionary strings. The added values makes it harder to crack.
*
* @since 2.5.0
*
* @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php
*
* @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce).
* @return string Salt value
*/
function wp_salt( $scheme = 'auth' ) {
static $cached_salts = array();
if ( isset( $cached_salts[ $scheme ] ) ) {
/**
* Filters the WordPress salt.
*
* @since 2.5.0
*
* @param string $cached_salt Cached salt for the given scheme.
* @param string $scheme Authentication scheme. Values include 'auth',
* 'secure_auth', 'logged_in', and 'nonce'.
*/
return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
}
static $duplicated_keys;
if ( null === $duplicated_keys ) {
$duplicated_keys = array(
'put your unique phrase here' => true,
);
/*
* translators: This string should only be translated if wp-config-sample.php is localized.
* You can check the localized release package or
* https://i18n.svn.wordpress.org//branches//dist/wp-config-sample.php
*/
$duplicated_keys[ __( 'put your unique phrase here' ) ] = true;
foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) {
foreach ( array( 'KEY', 'SALT' ) as $second ) {
if ( ! defined( "{$first}_{$second}" ) ) {
continue;
}
$value = constant( "{$first}_{$second}" );
$duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] );
}
}
}
$values = array(
'key' => '',
'salt' => '',
);
if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) ) {
$values['key'] = SECRET_KEY;
}
if ( 'auth' === $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) ) {
$values['salt'] = SECRET_SALT;
}
if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ), true ) ) {
foreach ( array( 'key', 'salt' ) as $type ) {
$const = strtoupper( "{$scheme}_{$type}" );
if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) {
$values[ $type ] = constant( $const );
} elseif ( ! $values[ $type ] ) {
$values[ $type ] = get_site_option( "{$scheme}_{$type}" );
if ( ! $values[ $type ] ) {
$values[ $type ] = wp_generate_password( 64, true, true );
update_site_option( "{$scheme}_{$type}", $values[ $type ] );
}
}
}
} else {
if ( ! $values['key'] ) {
$values['key'] = get_site_option( 'secret_key' );
if ( ! $values['key'] ) {
$values['key'] = wp_generate_password( 64, true, true );
update_site_option( 'secret_key', $values['key'] );
}
}
$values['salt'] = hash_hmac( 'md5', $scheme, $values['key'] );
}
$cached_salts[ $scheme ] = $values['key'] . $values['salt'];
/** This filter is documented in wp-includes/pluggable.php */
return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
}
endif;
if ( ! function_exists( 'wp_hash' ) ) :
/**
* Gets hash of given string.
*
* @since 2.0.3
*
* @param string $data Plain text to hash.
* @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce).
* @return string Hash of $data.
*/
function wp_hash( $data, $scheme = 'auth' ) {
$salt = wp_salt( $scheme );
return hash_hmac( 'md5', $data, $salt );
}
endif;
if ( ! function_exists( 'wp_hash_password' ) ) :
/**
* Creates a hash (encrypt) of a plain text password.
*
* For integration with other applications, this function can be overwritten to
* instead use the other package password checking algorithm.
*
* @since 2.5.0
*
* @global PasswordHash $wp_hasher PHPass object.
*
* @param string $password Plain text user password to hash.
* @return string The hash string of the password.
*/
function wp_hash_password( $password ) {
global $wp_hasher;
if ( empty( $wp_hasher ) ) {
require_once ABSPATH . WPINC . '/class-phpass.php';
// By default, use the portable hash from phpass.
$wp_hasher = new PasswordHash( 8, true );
}
return $wp_hasher->HashPassword( trim( $password ) );
}
endif;
if ( ! function_exists( 'wp_check_password' ) ) :
/**
* Checks the plaintext password against the encrypted Password.
*
* Maintains compatibility between old version and the new cookie authentication
* protocol using PHPass library. The $hash parameter is the encrypted password
* and the function compares the plain text password when encrypted similarly
* against the already encrypted password to see if they match.
*
* For integration with other applications, this function can be overwritten to
* instead use the other package password checking algorithm.
*
* @since 2.5.0
*
* @global PasswordHash $wp_hasher PHPass object used for checking the password
* against the $hash + $password.
* @uses PasswordHash::CheckPassword
*
* @param string $password Plaintext user's password.
* @param string $hash Hash of the user's password to check against.
* @param string|int $user_id Optional. User ID.
* @return bool False, if the $password does not match the hashed password.
*/
function wp_check_password( $password, $hash, $user_id = '' ) {
global $wp_hasher;
// If the hash is still md5...
if ( strlen( $hash ) <= 32 ) {
$check = hash_equals( $hash, md5( $password ) );
if ( $check && $user_id ) {
// Rehash using new hash.
wp_set_password( $password, $user_id );
$hash = wp_hash_password( $password );
}
/**
* Filters whether the plaintext password matches the encrypted password.
*
* @since 2.5.0
*
* @param bool $check Whether the passwords match.
* @param string $password The plaintext password.
* @param string $hash The hashed password.
* @param string|int $user_id User ID. Can be empty.
*/
return apply_filters( 'check_password', $check, $password, $hash, $user_id );
}
/*
* If the stored hash is longer than an MD5,
* presume the new style phpass portable hash.
*/
if ( empty( $wp_hasher ) ) {
require_once ABSPATH . WPINC . '/class-phpass.php';
// By default, use the portable hash from phpass.
$wp_hasher = new PasswordHash( 8, true );
}
$check = $wp_hasher->CheckPassword( $password, $hash );
/** This filter is documented in wp-includes/pluggable.php */
return apply_filters( 'check_password', $check, $password, $hash, $user_id );
}
endif;
if ( ! function_exists( 'wp_generate_password' ) ) :
/**
* Generates a random password drawn from the defined set of characters.
*
* Uses wp_rand() to create passwords with far less predictability
* than similar native PHP functions like `rand()` or `mt_rand()`.
*
* @since 2.5.0
*
* @param int $length Optional. The length of password to generate. Default 12.
* @param bool $special_chars Optional. Whether to include standard special characters.
* Default true.
* @param bool $extra_special_chars Optional. Whether to include other special characters.
* Used when generating secret keys and salts. Default false.
* @return string The random password.
*/
function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
if ( $special_chars ) {
$chars .= '!@#$%^&*()';
}
if ( $extra_special_chars ) {
$chars .= '-_ []{}<>~`+=,.;:/?|';
}
$password = '';
for ( $i = 0; $i < $length; $i++ ) {
$password .= substr( $chars, wp_rand( 0, strlen( $chars ) - 1 ), 1 );
}
/**
* Filters the randomly-generated password.
*
* @since 3.0.0
* @since 5.3.0 Added the `$length`, `$special_chars`, and `$extra_special_chars` parameters.
*
* @param string $password The generated password.
* @param int $length The length of password to generate.
* @param bool $special_chars Whether to include standard special characters.
* @param bool $extra_special_chars Whether to include other special characters.
*/
return apply_filters( 'random_password', $password, $length, $special_chars, $extra_special_chars );
}
endif;
if ( ! function_exists( 'wp_rand' ) ) :
/**
* Generates a random non-negative number.
*
* @since 2.6.2
* @since 4.4.0 Uses PHP7 random_int() or the random_compat library if available.
* @since 6.1.0 Returns zero instead of a random number if both `$min` and `$max` are zero.
*
* @global string $rnd_value
*
* @param int $min Optional. Lower limit for the generated number.
* Accepts positive integers or zero. Defaults to 0.
* @param int $max Optional. Upper limit for the generated number.
* Accepts positive integers. Defaults to 4294967295.
* @return int A random non-negative number between min and max.
*/
function wp_rand( $min = null, $max = null ) {
global $rnd_value;
/*
* Some misconfigured 32-bit environments (Entropy PHP, for example)
* truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats.
*/
$max_random_number = 3000000000 === 2147483647 ? (float) '4294967295' : 4294967295; // 4294967295 = 0xffffffff
if ( null === $min ) {
$min = 0;
}
if ( null === $max ) {
$max = $max_random_number;
}
// We only handle ints, floats are truncated to their integer value.
$min = (int) $min;
$max = (int) $max;
// Use PHP's CSPRNG, or a compatible method.
static $use_random_int_functionality = true;
if ( $use_random_int_functionality ) {
try {
// wp_rand() can accept arguments in either order, PHP cannot.
$_max = max( $min, $max );
$_min = min( $min, $max );
$val = random_int( $_min, $_max );
if ( false !== $val ) {
return absint( $val );
} else {
$use_random_int_functionality = false;
}
} catch ( Error $e ) {
$use_random_int_functionality = false;
} catch ( Exception $e ) {
$use_random_int_functionality = false;
}
}
/*
* Reset $rnd_value after 14 uses.
* 32 (md5) + 40 (sha1) + 40 (sha1) / 8 = 14 random numbers from $rnd_value.
*/
if ( strlen( $rnd_value ) < 8 ) {
if ( defined( 'WP_SETUP_CONFIG' ) ) {
static $seed = '';
} else {
$seed = get_transient( 'random_seed' );
}
$rnd_value = md5( uniqid( microtime() . mt_rand(), true ) . $seed );
$rnd_value .= sha1( $rnd_value );
$rnd_value .= sha1( $rnd_value . $seed );
$seed = md5( $seed . $rnd_value );
if ( ! defined( 'WP_SETUP_CONFIG' ) && ! defined( 'WP_INSTALLING' ) ) {
set_transient( 'random_seed', $seed );
}
}
// Take the first 8 digits for our value.
$value = substr( $rnd_value, 0, 8 );
// Strip the first eight, leaving the remainder for the next call to wp_rand().
$rnd_value = substr( $rnd_value, 8 );
$value = abs( hexdec( $value ) );
// Reduce the value to be within the min - max range.
$value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 );
return abs( (int) $value );
}
endif;
if ( ! function_exists( 'wp_set_password' ) ) :
/**
* Updates the user's password with a new encrypted one.
*
* For integration with other applications, this function can be overwritten to
* instead use the other package password checking algorithm.
*
* Please note: This function should be used sparingly and is really only meant for single-time
* application. Leveraging this improperly in a plugin or theme could result in an endless loop
* of password resets if precautions are not taken to ensure it does not execute on every page load.
*
* @since 2.5.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $password The plaintext new user password.
* @param int $user_id User ID.
*/
function wp_set_password( $password, $user_id ) {
global $wpdb;
$hash = wp_hash_password( $password );
$wpdb->update(
$wpdb->users,
array(
'user_pass' => $hash,
'user_activation_key' => '',
),
array( 'ID' => $user_id )
);
clean_user_cache( $user_id );
/**
* Fires after the user password is set.
*
* @since 6.2.0
*
* @param string $password The plaintext password just set.
* @param int $user_id The ID of the user whose password was just set.
*/
do_action( 'wp_set_password', $password, $user_id );
}
endif;
if ( ! function_exists( 'get_avatar' ) ) :
/**
* Retrieves the avatar `
` tag for a user, email address, MD5 hash, comment, or post.
*
* @since 2.5.0
* @since 4.2.0 Added the optional `$args` parameter.
* @since 5.5.0 Added the `loading` argument.
* @since 6.1.0 Added the `decoding` argument.
* @since 6.3.0 Added the `fetchpriority` argument.
*
* @param mixed $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash,
* user email, WP_User object, WP_Post object, or WP_Comment object.
* @param int $size Optional. Height and width of the avatar in pixels. Default 96.
* @param string $default_value URL for the default image or a default type. Accepts:
* - '404' (return a 404 instead of a default image)
* - 'retro' (a 8-bit arcade-style pixelated face)
* - 'robohash' (a robot)
* - 'monsterid' (a monster)
* - 'wavatar' (a cartoon face)
* - 'identicon' (the "quilt", a geometric pattern)
* - 'mystery', 'mm', or 'mysteryman' (The Oyster Man)
* - 'blank' (transparent GIF)
* - 'gravatar_default' (the Gravatar logo)
* Default is the value of the 'avatar_default' option,
* with a fallback of 'mystery'.
* @param string $alt Optional. Alternative text to use in the avatar image tag.
* Default empty.
* @param array $args {
* Optional. Extra arguments to retrieve the avatar.
*
* @type int $height Display height of the avatar in pixels. Defaults to $size.
* @type int $width Display width of the avatar in pixels. Defaults to $size.
* @type bool $force_default Whether to always show the default image, never the Gravatar.
* Default false.
* @type string $rating What rating to display avatars up to. Accepts:
* - 'G' (suitable for all audiences)
* - 'PG' (possibly offensive, usually for audiences 13 and above)
* - 'R' (intended for adult audiences above 17)
* - 'X' (even more mature than above)
* Default is the value of the 'avatar_rating' option.
* @type string $scheme URL scheme to use. See set_url_scheme() for accepted values.
* Default null.
* @type array|string $class Array or string of additional classes to add to the img element.
* Default null.
* @type bool $force_display Whether to always show the avatar - ignores the show_avatars option.
* Default false.
* @type string $loading Value for the `loading` attribute.
* Default null.
* @type string $fetchpriority Value for the `fetchpriority` attribute.
* Default null.
* @type string $decoding Value for the `decoding` attribute.
* Default null.
* @type string $extra_attr HTML attributes to insert in the IMG element. Is not sanitized.
* Default empty.
* }
* @return string|false `
` tag for the user's avatar. False on failure.
*/
function get_avatar( $id_or_email, $size = 96, $default_value = '', $alt = '', $args = null ) {
$defaults = array(
// get_avatar_data() args.
'size' => 96,
'height' => null,
'width' => null,
'default' => get_option( 'avatar_default', 'mystery' ),
'force_default' => false,
'rating' => get_option( 'avatar_rating' ),
'scheme' => null,
'alt' => '',
'class' => null,
'force_display' => false,
'loading' => null,
'fetchpriority' => null,
'decoding' => null,
'extra_attr' => '',
);
if ( empty( $args ) ) {
$args = array();
}
$args['size'] = (int) $size;
$args['default'] = $default_value;
$args['alt'] = $alt;
$args = wp_parse_args( $args, $defaults );
if ( empty( $args['height'] ) ) {
$args['height'] = $args['size'];
}
if ( empty( $args['width'] ) ) {
$args['width'] = $args['size'];
}
// Update args with loading optimized attributes.
$loading_optimization_attr = wp_get_loading_optimization_attributes( 'img', $args, 'get_avatar' );
$args = array_merge( $args, $loading_optimization_attr );
if ( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ) {
$id_or_email = get_comment( $id_or_email );
}
/**
* Allows the HTML for a user's avatar to be returned early.
*
* Returning a non-null value will effectively short-circuit get_avatar(), passing
* the value through the {@see 'get_avatar'} filter and returning early.
*
* @since 4.2.0
*
* @param string|null $avatar HTML for the user's avatar. Default null.
* @param mixed $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash,
* user email, WP_User object, WP_Post object, or WP_Comment object.
* @param array $args Arguments passed to get_avatar_url(), after processing.
*/
$avatar = apply_filters( 'pre_get_avatar', null, $id_or_email, $args );
if ( ! is_null( $avatar ) ) {
/** This filter is documented in wp-includes/pluggable.php */
return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
}
if ( ! $args['force_display'] && ! get_option( 'show_avatars' ) ) {
return false;
}
$url2x = get_avatar_url( $id_or_email, array_merge( $args, array( 'size' => $args['size'] * 2 ) ) );
$args = get_avatar_data( $id_or_email, $args );
$url = $args['url'];
if ( ! $url || is_wp_error( $url ) ) {
return false;
}
$class = array( 'avatar', 'avatar-' . (int) $args['size'], 'photo' );
if ( ! $args['found_avatar'] || $args['force_default'] ) {
$class[] = 'avatar-default';
}
if ( $args['class'] ) {
if ( is_array( $args['class'] ) ) {
$class = array_merge( $class, $args['class'] );
} else {
$class[] = $args['class'];
}
}
// Add `loading`, `fetchpriority`, and `decoding` attributes.
$extra_attr = $args['extra_attr'];
if ( in_array( $args['loading'], array( 'lazy', 'eager' ), true )
&& ! preg_match( '/\bloading\s*=/', $extra_attr )
) {
if ( ! empty( $extra_attr ) ) {
$extra_attr .= ' ';
}
$extra_attr .= "loading='{$args['loading']}'";
}
if ( in_array( $args['fetchpriority'], array( 'high', 'low', 'auto' ), true )
&& ! preg_match( '/\bfetchpriority\s*=/', $extra_attr )
) {
if ( ! empty( $extra_attr ) ) {
$extra_attr .= ' ';
}
$extra_attr .= "fetchpriority='{$args['fetchpriority']}'";
}
if ( in_array( $args['decoding'], array( 'async', 'sync', 'auto' ), true )
&& ! preg_match( '/\bdecoding\s*=/', $extra_attr )
) {
if ( ! empty( $extra_attr ) ) {
$extra_attr .= ' ';
}
$extra_attr .= "decoding='{$args['decoding']}'";
}
$avatar = sprintf(
"
",
esc_attr( $args['alt'] ),
esc_url( $url ),
esc_url( $url2x ) . ' 2x',
esc_attr( implode( ' ', $class ) ),
(int) $args['height'],
(int) $args['width'],
$extra_attr
);
/**
* Filters the HTML for a user's avatar.
*
* @since 2.5.0
* @since 4.2.0 Added the `$args` parameter.
*
* @param string $avatar HTML for the user's avatar.
* @param mixed $id_or_email The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash,
* user email, WP_User object, WP_Post object, or WP_Comment object.
* @param int $size Height and width of the avatar in pixels.
* @param string $default_value URL for the default image or a default type. Accepts:
* - '404' (return a 404 instead of a default image)
* - 'retro' (a 8-bit arcade-style pixelated face)
* - 'robohash' (a robot)
* - 'monsterid' (a monster)
* - 'wavatar' (a cartoon face)
* - 'identicon' (the "quilt", a geometric pattern)
* - 'mystery', 'mm', or 'mysteryman' (The Oyster Man)
* - 'blank' (transparent GIF)
* - 'gravatar_default' (the Gravatar logo)
* @param string $alt Alternative text to use in the avatar image tag.
* @param array $args Arguments passed to get_avatar_data(), after processing.
*/
return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
}
endif;
if ( ! function_exists( 'wp_text_diff' ) ) :
/**
* Displays a human readable HTML representation of the difference between two strings.
*
* The Diff is available for getting the changes between versions. The output is
* HTML, so the primary use is for displaying the changes. If the two strings
* are equivalent, then an empty string will be returned.
*
* @since 2.6.0
*
* @see wp_parse_args() Used to change defaults to user defined settings.
* @uses Text_Diff
* @uses WP_Text_Diff_Renderer_Table
*
* @param string $left_string "old" (left) version of string.
* @param string $right_string "new" (right) version of string.
* @param string|array $args {
* Associative array of options to pass to WP_Text_Diff_Renderer_Table().
*
* @type string $title Titles the diff in a manner compatible
* with the output. Default empty.
* @type string $title_left Change the HTML to the left of the title.
* Default empty.
* @type string $title_right Change the HTML to the right of the title.
* Default empty.
* @type bool $show_split_view True for split view (two columns), false for
* un-split view (single column). Default true.
* }
* @return string Empty string if strings are equivalent or HTML with differences.
*/
function wp_text_diff( $left_string, $right_string, $args = null ) {
$defaults = array(
'title' => '',
'title_left' => '',
'title_right' => '',
'show_split_view' => true,
);
$args = wp_parse_args( $args, $defaults );
if ( ! class_exists( 'WP_Text_Diff_Renderer_Table', false ) ) {
require ABSPATH . WPINC . '/wp-diff.php';
}
$left_string = normalize_whitespace( $left_string );
$right_string = normalize_whitespace( $right_string );
$left_lines = explode( "\n", $left_string );
$right_lines = explode( "\n", $right_string );
$text_diff = new Text_Diff( $left_lines, $right_lines );
$renderer = new WP_Text_Diff_Renderer_Table( $args );
$diff = $renderer->render( $text_diff );
if ( ! $diff ) {
return '';
}
$is_split_view = ! empty( $args['show_split_view'] );
$is_split_view_class = $is_split_view ? ' is-split-view' : '';
$r = "\n";
if ( $args['title'] ) {
$r .= "$args[title]\n";
}
if ( $args['title_left'] || $args['title_right'] ) {
$r .= '';
}
if ( $args['title_left'] || $args['title_right'] ) {
$th_or_td_left = empty( $args['title_left'] ) ? 'td' : 'th';
$th_or_td_right = empty( $args['title_right'] ) ? 'td' : 'th';
$r .= "\n";
$r .= "\t<$th_or_td_left>$args[title_left]$th_or_td_left>\n";
if ( $is_split_view ) {
$r .= "\t<$th_or_td_right>$args[title_right]$th_or_td_right>\n";
}
$r .= "
\n";
}
if ( $args['title_left'] || $args['title_right'] ) {
$r .= "\n";
}
$r .= "\n$diff\n\n";
$r .= '
';
return $r;
}
endif;