So I am trying to manually update the Subscription Dates and show a notice on the for the subsrriptions here. The goal is to make all the subscriptions trigger on the 1st of every month let's say.
So in the wp_posts meta we have post_date and post_date_gmt
class ChiChi_SubscriptionMetaBoxes
{
/**
* To load Schedule meta box
* */
public static function redateSchedule()
{
add_meta_box('chichi-redate-schedule', _x('Redate Schedule', 'meta box title'), 'ChiChi_SubscriptionMetaBoxes::output', 'shop_subscription', 'side', 'default');
}
/**
* To display Redate Schedule
*
* #param object $post
* */
public static function output($post)
{
global $theorder;
if (wcs_is_subscription($theorder) && !$theorder->has_status(wcs_get_subscription_ended_statuses())) {
include(get_theme_file_path('/lib/woocommerce/templates/html-redate-schedule.php'));
}
}
public static function save($order_id)
{
global $wpdb;
if (!isset($_POST['redate_schedule_date_nonce']) || !isset($_POST['redate_schedule'])) {
return $order_id;
}
$nonce = $_REQUEST['redate_schedule_date_nonce'];
if (!is_numeric($_POST['redate_schedule'])) {
return $order_id;
}
$newDay = (int)$_POST['redate_schedule'];
//Verify that the nonce is valid.
if (!wp_verify_nonce($nonce) || wp_is_post_revision($order_id)) {
return $order_id;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $order_id;
}
// Check the user's permissions.
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $order_id)) {
return $order_id;
}
} else {
if (!current_user_can('edit_post', $order_id)) {
return $order_id;
}
}
// Update the meta field in the database.
$subscription = wcs_get_subscription($order_id);
$pending_status = 'pending';
if (class_exists('ActionScheduler_Store')) {
$pending_status = ActionScheduler_Store::STATUS_PENDING;
}
$amSchedule = '_action_manager_schedule';
try {
$redatedShedule = [];
$schedules = as_get_scheduled_actions([
'hook' => 'woocommerce_subscription_upfront_renewal',
'args' => [
'subscription_id' => $subscription->get_id()
],
'status' => $pending_status,
'per_page' => 100
]);
if (!empty($schedules)) {
foreach ($schedules as $key => $schedule) {
$scheduledPost = get_post($key);
if (!empty($scheduledPost)) {
$originalDateTs = strtotime($scheduledPost->post_date);
$originalGmtDateTs = strtotime($scheduledPost->post_date_gmt);
$newDate = date("Y-m-" . $newDay . " H:i:s", $originalDateTs);
$gmtDate = get_gmt_from_date($newDate);
// Update Post
wp_update_post([
'ID' => $key,
'post_date' => $newDate,
'post_date_gmt' => $gmtDate
]);
// Update meta time stamps
$sql = "UPDATE " . $wpdb->postmeta . " SET meta_value = REPLACE(meta_value, '" . $_schedule_start . "', '" . strtotime($gmtDate) . "') WHERE `post_id` = '" . esc_sql($key) . "' AND `meta_key` = '" . $wpdb->escape($amSchedule) . "'";
$wpdb->get_results($sql);
$redatedShedule[] = $gmtDate;
}
}
if (count($redatedShedule) > 0) {
// Update End Date
$dates['end'] = date('Y-m-d H:i:s', strtotime(end($redatedShedule) . '+1 month'));
$subscription->update_dates($dates);
$order = new WC_Order($order_id);
$order->add_order_note("Subscription has been manually re-dated to: <br/>" . implode('<br>', $redatedShedule));
}
}
return $order_id;
// wp_cache_delete($post_id, 'posts');
} catch (Exception $e) {
wcs_add_admin_notice($e->getMessage(), 'error');
}
}
}
add_action('add_meta_boxes', 'ChiChi_SubscriptionMetaBoxes::redateSchedule', 26);
add_action('woocommerce_before_save_order_items', 'ChiChi_SubscriptionMetaBoxes::save', 10, 1);
let me know please if someone spots any issue. The code itself is commented so you know what the specific sections of code are doing.
thanks
How can we check by code in Opencart 2.0.3 that Cart contains Gift Certificate?
I want to disable cash on delivery (cod) payment mode if cart has Gift Certificate (opencart 2.0.3). Any code or idea to achieve this?
Yes you can do that , In products you can set a status that you product is Gift Certificate or not , after that some case will arrive while order:
Customer can order products with Gift Certificate so you have to check if any product is with Gift Certificate status that shipped will not be COD
You can edit the cod.php model (catalog/model/payment/cod.php) and add condition if gift certificates exist.
Do you mean "voucher" with "gift certificate"
This is the actual model
<?php
class ModelPaymentCOD extends Model {
public function getMethod($address, $total) {
$this->load->language('payment/cod');
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('cod_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");
if ($this->config->get('cod_total') > 0 && $this->config->get('cod_total') > $total) {
$status = false;
} elseif (!$this->config->get('cod_geo_zone_id')) {
$status = true;
} elseif ($query->num_rows) {
$status = true;
} else {
$status = false;
}
$method_data = array();
if ($status) {
$method_data = array(
'code' => 'cod',
'title' => $this->language->get('text_title'),
'terms' => '',
'sort_order' => $this->config->get('cod_sort_order')
);
}
return $method_data;
}
}
You can add this condition:
if(isset($this->session->data['vouchers'])){
$status = false;
}
It works for me.
If you don't have experience with php replace the code from file with this :
<?php
class ModelPaymentCOD extends Model {
public function getMethod($address, $total) {
$this->load->language('payment/cod');
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('cod_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");
if ($this->config->get('cod_total') > 0 && $this->config->get('cod_total') > $total) {
$status = false;
} elseif (!$this->config->get('cod_geo_zone_id')) {
$status = true;
} elseif ($query->num_rows) {
$status = true;
} else {
$status = false;
}
if(isset($this->session->data['vouchers'])){
$status = false;
}
$method_data = array();
if ($status) {
$method_data = array(
'code' => 'cod',
'title' => $this->language->get('text_title'),
'terms' => '',
'sort_order' => $this->config->get('cod_sort_order')
);
}
return $method_data;
}
}
I have Yii2 project. And there I also have api written by Symfony.
In Symfony part I have method in the class which send request to Yii controller.
$buzz = $this->container->get('buzz');
$buzz->getClient()->setVerifyHost(false);
$buzz->getClient()->setVerifyPeer(false);
$buzz->getClient()->setTimeOut(false);
$url = $this->container->getParameter('integra_sync_prices');
$sendResult = $buzz->post($url, array('authorization' => $this->container->getParameter('load_token')), array('products' =>
json_encode($productPrices)));
$resultJson = json_decode($sendResult->getContent(), true);
if (isset($resultJson['error']))
throw new \Exception('Site: '.$resultJson['error'], 500);
class IntegraController extends Controller{
public function actionIndex()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$headers = Yii::$app->request->getHeaders();
foreach ($headers as $key => $value) {
if(strtolower(trim($key)) == 'authorization') {
$token = trim($value[0]);
break;
}
}
$products = json_decode(Yii::$app->request->post('products'));
$post_products = Yii::$app->request->post('products');
if('111' == $token) {
if(isset($post_products) && $products) {
foreach ($products as $product) {
echo $product->price." = ".$product->productId."<br>";
Yii::$app->db->createCommand("UPDATE oc_product SET quantity = '" . (int)$product->quantity . "', price = '" . (float)$product->price . "' WHERE product_id = '" . (int)$product->productId . "'")->execute();
}
$json['success'] = 'complete';
} else {
$json['error'] = 'empty data';
}
} else {
$json['error'] = 'authorization error';
}
Yii::$app->controller->enableCsrfValidation = false;
echo json_encode($json);
}
I expect that data in my database will be updated by this controller. But there in nothing changes.
What do I do wrong? Maybe I should send some another headers? Thanks a lot )
For some odd reason im unable to retrieve group memebers from domain users or any group for that batter.
Base DN is set to dc=domain,dc=com Ive hits block here. When I use the test tool im able to authenticate [NOTICE] Authentication successfull for "rpimentel#domain.com"
Something is missing. Something simple, that im over looking. What could it be?
// Extend the ADIntegrationPlugin class
class BulkImportADIntegrationPlugin extends ADIntegrationPlugin {
/**
* Output formatted debug informations
*
* #param integer level
* #param string $notice
*/
protected function _log($level = 0, $info = '') {
if ($level <= $this->_loglevel) {
switch ($level) {
case ADI_LOG_DEBUG:
$class = 'debug';
$type = '[DEBUG] ';
break;
case ADI_LOG_INFO:
$class = 'info';
$type = '[INFO] ';
break;
case ADI_LOG_NOTICE:
$class = 'notice';
$type = '[NOTICE] ';
break;
case ADI_LOG_WARN:
$class = 'warn';
$type = '[WARN] ';
break;
case ADI_LOG_ERROR:
$class = 'error';
$type = '[ERROR] ';
break;
case ADI_LOG_FATAL:
$class = 'fatal';
$type = '[FATAL] ';
break;
default:
$class = '';
$type = '';
}
$output = '<span class="'.$class.'">'.$type;
$output .= str_replace("\n","<br /> ",$info).'</span><br />';
echo $output;
if (WP_DEBUG) {
if ($fh = #fopen($this->_logfile,'a+')) {
fwrite($fh,$type . str_replace("\n","\n ",$info) . "\n");
fclose($fh);
}
}
}
}
/**
* Do Bulk Import
*
* #param string $authcode
* #return bool true on success, false on error
*/
public function bulkimport($authcode)
{
global $wp_version;
global $wpdb;
$this->setLogFile(dirname(__FILE__).'/import.log');
$this->_log(ADI_LOG_INFO,"-------------------------------------\n".
"START OF BULK IMPORT\n".
date('Y-m-d / H:i:s')."\n".
"-------------------------------------\n");
$time = time();
$all_users = array();
// Is bulk import enabled?
if (!$this->_bulkimport_enabled) {
$this->_log(ADI_LOG_INFO,'Bulk Import is disabled.');
return false;
}
// DO we have the correct Auth Code?
if ($this->_bulkimport_authcode !== $authcode) {
$this->_log(ADI_LOG_ERROR,'Wrong Auth Code.');
return false;
}
$ad_password = $this->_decrypt($this->_bulkimport_pwd);
// Log informations
$this->_log(ADI_LOG_INFO,"Options for adLDAP connection:\n".
"- base_dn: $this->_base_dn\n".
"- domain_controllers: $this->_domain_controllers\n".
"- ad_username: $this->_bulkimport_user\n".
"- ad_password: **not shown**\n".
"- ad_port: $this->_port\n".
"- use_tls: ".(int) $this->_use_tls."\n".
"- network timeout: ". $this->_network_timeout);
// Connect to Active Directory
try {
$this->_adldap = #new adLDAP(array(
"base_dn" => $this->_base_dn,
"domain_controllers" => explode(';', $this->_domain_controllers),
"ad_username" => $this->_bulkimport_user, // Bulk Import User
"ad_password" => $ad_password, // password
"ad_port" => $this->_port, // AD port
"use_tls" => $this->_use_tls, // secure?
"network_timeout" => $this->_network_timeout // network timeout
));
} catch (Exception $e) {
$this->_log(ADI_LOG_ERROR,'adLDAP exception: ' . $e->getMessage());
return false;
}
$this->_log(ADI_LOG_NOTICE,'adLDAP object created.');
$this->_log(ADI_LOG_INFO,'Domain Controller: ' . $this->_adldap->get_last_used_dc());
// Let's give us some more time (60 minutes)
$max_execution_time = ini_get('max_execution_time');
if ($max_execution_time < 3600) {
ini_set('max_execution_time', 3600);
}
if (ini_get('max_execution_time') < 3600) {
$this->_log(ADI_LOG_ERROR,'Can not increase PHP configuration option "max_execution_time".');
return false;
}
// get all users of the chosen security groups from
$groups = explode(";",$this->_bulkimport_security_groups);
if (count($groups) < 1) {
$this->_log(ADI_LOG_WARN,'No security group.');
return false;
}
foreach ($groups AS $group) {
// get all members of group
$group = trim($group);
if ($group != '') {
// do we have a groupid?
if (($pos = stripos($group,'id:')) !== false) {
$pgid = substr($group,$pos+3);
$members = $this->_adldap->group_members_by_primarygroupid($pgid, true);
} else {
$members = $this->_adldap->group_members($group, true);
}
if ($members) {
$this->_log(ADI_LOG_INFO,count($members).' Members of group "'.$group.'".');
$this->_log(ADI_LOG_DEBUG,'Members of group "'.$group.'": ' . implode(', ',$members));
foreach ($members AS $user) {
$all_users[strtolower($user)] = $user;
}
} else {
$this->_log(ADI_LOG_ERROR,'Error retrieving group members for group "'.$group.'".');
}
} else {
$this->_log(ADI_LOG_WARN,'No group. Nothing to do.');
}
}
// Adding all local users with non empty entry adi_samaccountname in usermeta
$blogusers=$wpdb->get_results(
'
SELECT
users.user_login
FROM
'. $wpdb->users . ' users
INNER JOIN
' . $wpdb->usermeta ." meta ON meta.user_id = users.ID
where
meta.meta_key = 'adi_samaccountname'
AND
meta.meta_value IS NOT NULL
AND
meta.meta_value <> ''
AND
users.ID <> 1
"
);
if (is_array($blogusers)) {
foreach ($blogusers AS $user) {
$all_users[strtolower($user->user_login)] = $user->user_login;
}
}
$elapsed_time = time() - $time;
$this->_log(ADI_LOG_INFO,'Number of users to import/update: '.count($all_users).' (list generated in '. $elapsed_time .' seconds)');
if (version_compare($wp_version, '3.1', '<')) {
require_once(ABSPATH . WPINC . DIRECTORY_SEPARATOR . 'registration.php');
}
// import all relevant users
$added_users = 0;
$updated_users = 0;
foreach ($all_users AS $username) {
$ad_username = $username;
// getting user data
//$user = get_userdatabylogin($username); // deprecated
$user = get_user_by('login', $username);
// role
$user_role = $this->_get_user_role_equiv($ad_username); // important: use $ad_username not $username
// userinfo from AD
$this->_log(ADI_LOG_DEBUG, 'ATTRIBUTES TO LOAD: '.print_r($this->_all_user_attributes, true));
$userinfo = $this->_adldap->user_info($ad_username, $this->_all_user_attributes);
$userinfo = $userinfo[0];
$this->_log(ADI_LOG_DEBUG,"USERINFO[0]: \n".print_r($userinfo,true));
if (empty($userinfo)) {
$this->_log(ADI_LOG_INFO,'User "' . $ad_username . '" not found in Active Directory.');
if (isset($user->ID) && ($this->_disable_users)) {
$this->_log(ADI_LOG_WARN,'User "' . $username . '" disabled.');
$this->_disable_user($user->ID, sprintf(__('User "%s" not found in Active Directory.', 'ad-integration'), $username));
}
} else {
// Only user accounts (UF_NORMAL_ACCOUNT is set and other account flags are unset)
if (($userinfo["useraccountcontrol"][0] & (UF_NORMAL_ACCOUNT | ADI_NO_UF_NORMAL_ACOUNT)) == UF_NORMAL_ACCOUNT) {
//&& (($userinfo["useraccountcontrol"][0] & ADI_NO_UF_NORMAL_ACOUNT) == 0)) {
// users with flag UF_SMARTCARD_REQUIRED have no password so they can not logon with ADI
if (($userinfo["useraccountcontrol"][0] & UF_SMARTCARD_REQUIRED) == 0) {
// get display name
$display_name = $this->_get_display_name_from_AD($username, $userinfo);
// create new users or update them
if (!$user OR (strtolower($user->user_login) != strtolower($username))) { // use strtolower!!!
$user_id = $this->_create_user($ad_username, $userinfo, $display_name, $user_role, '', true);
$added_users++;
} else {
$user_id = $this->_update_user($ad_username, $userinfo, $display_name, $user_role, '', true);
$updated_users++;
}
// load user object (this shouldn't be necessary)
if (!$user_id) {
$user_id = username_exists($username);
$this->_log(ADI_LOG_NOTICE,'user_id: '.$user_id);
}
// if the user is disabled
if (($userinfo["useraccountcontrol"][0] & UF_ACCOUNT_DISABLE) == UF_ACCOUNT_DISABLE)
{
$this->_log(ADI_LOG_INFO,'The user "' . $username .'" is disabled in Active Directory.');
if ($this->_disable_users) {
$this->_log(ADI_LOG_WARN,'Disabling user "' . $username .'".');
$this->_disable_user($user_id, sprintf(__('User "%s" is disabled in Active Directory.', 'ad-integration'), $username));
}
} else {
// Enable user / turn off user_disabled
$this->_log(ADI_LOG_INFO,'Enabling user "' . $username .'".');
$this->_enable_user($user_id);
}
} else {
// Flag UF_SMARTCARD_REQUIRED is set
$this->_log(ADI_LOG_INFO,'The user "' . $username .'" requires a SmartCard to logon.');
if (isset($user->ID) && ($this->_disable_users)) {
$this->_log(ADI_LOG_WARN,'Disabling user "' . $username .'".');
$this->_disable_user($user->ID, sprintf(__('User "%s" requires a SmartCard to logon.', 'ad-integration'), $username));
}
}
} else {
// not a normal user account
$this->_log(ADI_LOG_INFO,'The user "' . $username .'" has no normal user account.');
if (isset($user->ID) && ($this->_disable_users)) {
$this->_log(ADI_LOG_WARN,'Disabling user "' . $username .'".');
$this->_disable_user($user->ID, sprintf(__('User "%s" has no normal user account.', 'ad-integration'), $username));
}
}
}
}
// Logging
$elapsed_time = time() - $time;
$this->_log(ADI_LOG_INFO,$added_users . ' Users added.');
$this->_log(ADI_LOG_INFO,$updated_users . ' Users updated.');
$this->_log(ADI_LOG_INFO,'In '. $elapsed_time . ' seconds.');
$this->_log(ADI_LOG_INFO,"-------------------------------------\n".
"END OF BULK IMPORT\n".
date('Y-m-d / H:i:s')."\n".
"-------------------------------------\n");
return true;
}
It looks like this is where I fails. But why wouldn't it be able to get group?
foreach ($groups AS $group) {
// get all members of group
$group = trim($group);
if ($group != '') {
// do we have a groupid?
if (($pos = stripos($group,'id:')) !== false) {
$pgid = substr($group,$pos+3);
$members = $this->_adldap->group_members_by_primarygroupid($pgid, true);
} else {
$members = $this->_adldap->group_members($group, true);
}
if ($members) {
$this->_log(ADI_LOG_INFO,count($members).' Members of group "'.$group.'".');
$this->_log(ADI_LOG_DEBUG,'Members of group "'.$group.'": ' . implode(', ',$members));
foreach ($members AS $user) {
$all_users[strtolower($user)] = $user;
}
} else {
$this->_log(ADI_LOG_ERROR,'Error retrieving group members for group "'.$group.'".');
}
I removed
$ad_password = $this->_decrypt($this->_bulkimport_pwd);
and added
$ad_password = 'my_password_here';
And it worked
Seems that this decrypt password is broken.
[INFO] 1000 Members of group "id:513".
[INFO] Number of users to import/update: 3439
I had the same problem when I filled twice the field "Bulk Import User Password". I launched the bulk import, which failed (all the users were disabled!). My Apache log below:
PHP Warning: mcrypt_decrypt(): Key of size 27 not supported by this
algorithm.Only keys of sizes 16, 24 or 32 supported in
/var/www/html/wordpress/wp-content/plugins/active-directory-integration/ad-integration.php
The problem seems come from the function mcrypt used to encrypt the password. We can see in the file ad-integration.php that the function used the Wordpress constant AUTH_SALT, which is defined by default like "put your unique phrase here", thus 27 char. So I defined this constant with a string of 32 char (you can define this in wp-config.php). I refilled the Bulk Import User Password and it works.
I am trying to download all my listings from ebay into my database using following code:
$client = new eBaySOAP($session);
$ebay_items_array = array();
try {
$client = new eBaySOAP($session);
$params = array(
'Version' => $Version,
'GranularityLevel' => "Fine",
'OutputSelector' => "ItemID,SKU,Title",
'EndTimeFrom' => date("c", mktime(date("H"), date("i")+10, date("s"), date("n"), date("j"), date("Y"))),
'EndTimeTo' => date("c", mktime(date("H"), date("i"), date("s"), date("n"), date("j")+120, date("Y"))),
'Pagination' => array(
'PageNumber' => $_GET['linkebaynum'],
'EntriesPerPage' => "20"
)
);
$results = $client->GetSellerList($params);
if($results->Ack == "Success")
{
$c = 0;
if(is_array($results->ItemArray->Item))
{
foreach($results->ItemArray->Item as $key => $value)
{
array_push($ebay_items_array, $value->ItemID);
$Qcheck = tep_db_query('select ebay_productstoitems_items_id from ' . TABLE_EBAY_PRODUCTS_TO_ITEMS . ' where ebay_productstoitems_items_id = ' . $value->ItemID);
$check = tep_db_fetch_array($Qcheck);
if($check == 0) {
if($check['ebay_productstoitems_items_id'] = $value->ItemID) {
echo 'Not in Database - Inserting ' . $value->ItemID . '<br>';
tep_db_query("insert ebay_productstoitems set ebay_productstoitems_items_id = '" . $value->ItemID . "'");
}
}else{
echo 'Found - ' . $value->ItemID . ' Nothing to Change<br>';
tep_db_query("update ebay_productstoitems set ebay_productstoitems_items_id = '" . $value->ItemID . "' where ebay_productstoitems_items_id = '" . $value->ItemID . "'");
}
}
$c++;
}
}
} catch (SOAPFault $f) {
print "error<br>";
}
print "Request:<br>".ebay_formatxmlstring($client->__getLastRequest())."<br><br>";
print "Response:<br>".ebay_formatxmlstring($client->__getLastResponse())."<br><br>";
But it will not recover the SKU (or CustomLabel).
Can anyone explain what I am missing to get the SKU into the database along with the ItemID.
Or would I have to recover lists of ItemID and then do a second call to recover the SKU or CustomLabel?
Found out what the problem was the Sandbox does not appear to pass the SKU back. I switched to the live site and hey presto the SKU is being retrieved along with the Itemid.