My singleton pattern instance seems to lose its instance and becomes null between each request.
Whenever I call validate_api_endpoint_field when the settings are saved, my breakpoint is hit inside in the MyPlugin_Request_Manager::instance() and its value is null.
any tips?
MyPlugin_Settings.php
<?php
defined('ABSPATH') || exit;
if (!class_exists('MyPlugin_Settings')) {
class MyPlugin_Settings
{
const page = "myPlugin-settings";
const option_group_name = 'myPlugin_option_group';
const domain = "myPlugin";
protected static $_instance = null;
public function __construct()
{
self::load_dependencies();
}
public function load_dependencies()
{
require_once PAYDAY_PATH . 'classes/class-myPlugin-repository.php';
require_once PAYDAY_PATH . 'classes/class-myPlugin-request-manager.php';
}
public static function instance()
{
if (is_null(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function admin_menu()
{
// Add a separator before the menu item.
// Bug: Makes the WooCommerce Product menu disappear
// slef::add_admin_menu_separator( 26 );
add_menu_page(
'MyPlugin',
'MyPlugin',
'manage_options',
'myPlugin-settings',
null,
'dashicons-building',
27
);
add_submenu_page('myPlugin', 'MyPlugin Settings', 'Settings', 'manage_options', self::page, array($this, 'render_plugin_settings'));
// TODO: Uncomment when Dashboard will be implemented
// add_submenu_page( 'myPlugin', 'Dashboard', 'Dashboard', 'manage_options', 'myPlugin', array(
// $this,
// 'display_page'
// ) );
}
function add_admin_menu_separator($position)
{
global $menu;
$index = 0;
foreach ($menu as $offset => $section) {
if (substr($section[2], 0, 9) == 'separator') {
$index++;
}
if ($offset >= $position) {
$menu[$position] = array('', 'read', "separator{$index}", '', 'wp-menu-separator');
break;
}
}
ksort($menu);
}
public function admin_init()
{
self::register_api_settings();
self::register_payment_methods_mapping();
self::register_payment_methods_create_invoice_on_order_status_mapping();
self::register_additional_invoice_settings_section();
}
public function admin_footer_text()
{
$current_screen = get_current_screen();
$base = $current_screen->parent_base;
if (substr($base, 0, 6) === "myPlugin") {
echo '<span id="footer-thankyou">' . esc_html__('Developed by MyPlugin ehf.', 'myPlugin') . '</span>';
}
}
public function register_api_settings()
{
$settings_section_id = 'myPlugin_api_section';
add_settings_section(
$settings_section_id,
esc_html__('API Settings', 'myPlugin'),
function () {
echo '<p>' . esc_html__('Access your ClientId and ClientSecret on MyPlugin.is underneath Settings -> Company Settings -> API', 'myPlugin') . '</p>';
},
self::page
);
// ClientId
$client_id_settings_field_id = "myPlugin_client_id";
add_settings_field(
$client_id_settings_field_id,
esc_html__('ClientID', 'myPlugin'),
array($this, 'display_field'),
self::page,
$settings_section_id,
array(
'type' => 'text', // Type of input field
'id' => $client_id_settings_field_id,
'class' => 'input-lg',
'name' => 'myPlugin_client_id',
'value' => get_option($client_id_settings_field_id, '') // The current value of the field, or set default value
)
);
register_setting(self::option_group_name, $client_id_settings_field_id, array($this, 'validate_clientId_field'));
// ClientSecret
$client_secret_settings_field_id = "myPlugin_client_secret";
add_settings_field(
$client_secret_settings_field_id,
esc_html__('ClientSecret', 'myPlugin'),
array($this, 'display_field'),
self::page,
$settings_section_id,
array(
'type' => 'password', // Type of input field
'id' => $client_secret_settings_field_id,
'class' => 'input-lg',
'name' => 'myPlugin_client_secret',
'value' => get_option($client_secret_settings_field_id, '') // The current value of the field, or set default value
)
);
register_setting(self::option_group_name, $client_secret_settings_field_id, array($this, 'validate_clientSecret_field'));
// API Endpoint
$api_endpoint_field_id = 'myPlugin_api_endpoint';
add_settings_field(
$api_endpoint_field_id,
esc_html__('API Endpoint', 'myPlugin'),
array($this, 'display_select_field'),
self::page,
$settings_section_id,
array(
'name' => 'myPlugin_api_endpoint',
'options' => [
esc_html__("Production", 'myPlugin') => "https://api.myPlugin.is",
esc_html__("Test", 'myPlugin') => "https://api.test.myPlugin.is",
esc_html__("Localhost", 'myPlugin') => "http://localhost:57283"
]
)
);
register_setting(self::option_group_name, $api_endpoint_field_id, array($this, 'validate_api_endpoint_field'));
}
public function register_payment_methods_mapping()
{
$settings_section_id = 'myPlugin_payment_methods_mapping_section';
add_settings_section(
$settings_section_id, // ID used to identify this section and with which to register options
// Title to be displayed on the administration page
__("Payment Methods - Mapping", 'myPlugin'),
// Callback used to render the description of the section
function () {
// TODO: Update if needed for redirecting for creating a new Payment Type within MyPlugin
echo '<p>' . __('Make sure the WooCommerce payment methods corresponds to the correct MyPlugin payment type.', 'myPlugin') . '</p>';
echo '<p>' . __('You might need to create a new payment type in MyPlugin first.', 'myPlugin') . '</p>';
},
// The page where to display the section
self::page
);
//$woocommerce_payment_methods = WC_Payment_Gateways::instance()->get_available_payment_gateways();
$woocommerce_payment_methods = WC_Payment_Gateways::instance()->payment_gateways();
$myPlugin_payment_types = MyPlugin_Repository::instance()->get_payment_types();
if (!isset($myPlugin_payment_types)) {
$myPlugin_payment_types = MyPlugin_Request_Manager::instance()->get_sales_payment_types();
MyPlugin_Repository::instance()->set_payment_types($myPlugin_payment_types);
}
$payment_type_select_options = array();
$payment_type_select_options[__('None', 'myPlugin')] = 'None';
if (isset($myPlugin_payment_types)) {
foreach ($myPlugin_payment_types as &$payment_type) {
// key => value
if (isset($payment_type) and gettype($payment_type) === "object") {
$payment_type = get_object_vars($payment_type);
$payment_type_select_options[$payment_type['title']] = $payment_type['id'];
}
if (isset($payment_type) and gettype($payment_type) === "array") {
$payment_type_select_options[$payment_type['title']] = $payment_type['id'];
}
}
}
foreach ($woocommerce_payment_methods as $payment_method) {
if ($payment_method->enabled == 'no') {
continue;
}
$id = $payment_method->id;
$title = $payment_method->get_method_title();
if ($title == "") {
try {
$title = $payment_method->title;
} catch (Exception $e) {
$title = "";
}
}
$field_id = 'myPlugin_payment_method_' . $id;
add_settings_field(
$field_id,
esc_html__($title, 'myPlugin'),
array($this, 'display_select_field'),
self::page,
$settings_section_id,
array(
'name' => esc_html__($field_id, 'myPlugin'),
'options' => $payment_type_select_options
)
);
register_setting(self::option_group_name, $field_id);
}
}
public function register_payment_methods_create_invoice_on_order_status_mapping()
{
$settings_section_id = 'myPlugin_create_invoice_on_order_status_section';
add_settings_section(
$settings_section_id,
'Payment Methods - Action: Create an invoice and mark it as paid',
function () {
echo '<p>' . esc_html__('Please select the corresponding WooCommerce Order Status to execute the following action:', 'myPlugin') . '</p>';
echo '<p>' . esc_html__('Create a new invoice in MyPlugin and mark it as paid.', 'myPlugin') . '</p>';
},
self::page
);
$woocommerce_payment_methods = WC_Payment_Gateways::instance()->payment_gateways();
foreach ($woocommerce_payment_methods as $payment_method) {
if ($payment_method->enabled == 'no') {
continue;
}
$id = $payment_method->id;
$title = $payment_method->get_method_title();
if ($title == "") {
try {
$title = $payment_method->title;
} catch (Exception $e) {
$title = "";
}
}
$field_id = 'myPlugin_payment_method_' . $id . '_create_invoice_on_action';
$order_statuses = wc_get_order_statuses();
add_settings_field(
$field_id,
esc_html__($title, 'myPlugin'),
array($this, 'display_select_field'),
self::page,
$settings_section_id,
array(
'name' => $field_id,
'options' => [
__("None", 'myPlugin') => "None",
__($order_statuses["wc-processing"], 'myPlugin') => "processing",
__($order_statuses["wc-completed"], 'myPlugin') => "completed",
]
)
);
register_setting(self::option_group_name, $field_id);
}
}
public function register_additional_invoice_settings_section()
{
$settings_section_id = 'myPlugin_invoice_settings_section';
add_settings_section(
$settings_section_id,
'Invoice Settings',
function () {
},
self::page
);
$send_email_on_invoice_create_field_id = "myPlugin_send_email_on_invoice_create";
add_settings_field(
$send_email_on_invoice_create_field_id,
esc_html__("Email the invoice as a PDF to customer when created", "myPlugin"),
array($this, 'display_select_field'),
self::page,
$settings_section_id,
array(
'name' => "myPlugin_send_email_on_invoice_create",
'options' => [
esc_html__('Yes', 'myPlugin') => "yes",
esc_html__('No', 'myPlugin') => "no",
]
)
);
register_setting(self::option_group_name, $send_email_on_invoice_create_field_id);
$invoice_date_option = "myPlugin_invoice_date_option";
add_settings_field(
$invoice_date_option,
esc_html__("When Invoice is created, invoice date and due date set to", "myPlugin"),
array($this, 'display_select_field'),
self::page,
$settings_section_id,
array(
'name' => "myPlugin_invoice_date_option",
'options' => [
esc_html__('to the date the order was first created', 'myPlugin') => "0",
esc_html__('to the date when the request is made to create an invoice', 'myPlugin') => "1",
]
)
);
register_setting(self::option_group_name, $invoice_date_option);
}
public function validate_clientId_field($input)
{
$valid = true;
$value = $input;
if (!isset($value) || empty(trim($value))) {
// We must support empty string when we clear cache and set value to empty string
return "";
// $valid = false;
// add_settings_error(
// 'myPlugin_option_group',
// 'myPlugin_clientId_error',
// esc_html__('ClientID is required.', 'myPlugin')
// );
}
if ($valid) {
$value = sanitize_text_field($value);
$value = strtolower($value);
}
if ($valid) {
if (strlen($value) != 32) {
$valid = false;
add_settings_error(
'myPlugin_option_group',
'myPlugin_clientId_error',
esc_html__('Invalid value for ClientID. Value has to be 32 characters long.', 'myPlugin')
);
}
}
if ($valid) {
if (!ctype_xdigit($value) || !self::is_valid_guid($value)) {
$valid = false;
add_settings_error(
'myPlugin_option_group',
'myPlugin_clientId_error',
esc_html__('Invalid value for ClientID. Value has to be a hexadecimal number.', 'myPlugin')
);
}
}
// Ignore the user's changes and use the old database value.
if (!$valid) {
$value = get_option('myPlugin_client_id');
}
return $value;
}
public function validate_clientSecret_field($input)
{
$valid = true;
$value = $input;
if (!isset($value) || empty(trim($value))) {
return "";
// $valid = false;
// add_settings_error(
// 'myPlugin_option_group',
// 'myPlugin_clientSecret_error',
// esc_html__('ClientSecret is required.', 'myPlugin')
// );
}
if ($valid) {
$value = trim($value);
$value = sanitize_text_field($value);
$value = strtolower($value);
}
if ($valid) {
if (strlen($value) != 32) {
$valid = false;
add_settings_error(
'myPlugin_option_group',
'myPlugin_clientSecret_error',
esc_html__('Invalid value for ClientSecret. Value has to be 32 characters long.', 'myPlugin')
);
}
}
if ($valid) {
if (!ctype_xdigit($value) || !self::is_valid_guid($value)) {
$valid = false;
add_settings_error(
'myPlugin_option_group',
'myPlugin_clientSecret_error',
esc_html__('Invalid value for ClientSecret. Value has to be a hexadecimal number.', 'myPlugin')
);
}
}
// Ignore the user's changes and use the old database value.
if (!$valid) {
$value = get_option('myPlugin_client_secret');
}
return $value;
}
// Last of three main credentials validation functions.
// we will validate all three credentials at once if the values have changed. if it is valid we will save the new values to this instance.
public function validate_api_endpoint_field($input)
{
$valid = true;
$value = $input;
$value = trim($value);
if (!isset($value) || empty($value)) {
return "";
// $valid = false;
// add_settings_error(
// 'myPlugin_option_group',
// 'myPlugin_api_endpoint_error',
// esc_html__('API Endpoint is required.', 'myPlugin')
// );
}
$value = sanitize_text_field($value);
if (!filter_var($value, FILTER_VALIDATE_URL)) {
$valid = false;
add_settings_error(
'myPlugin_option_group',
'myPlugin_api_endpoint_error',
esc_html__('Invalid value for API Endpoint. Value has to be a valid URL.', 'myPlugin')
);
}
if ($valid) {
$credential_changed = false;
$old_clientId = MyPlugin_Request_Manager::instance()->get_client_id();
$old_clientSecret = MyPlugin_Request_Manager::instance()->get_client_secret();
$old_api_endpoint = MyPlugin_Request_Manager::instance()->get_api_endpoint();
$new_clientId = get_option('myPlugin_client_id');
$new_clientSecret = get_option('myPlugin_client_secret');
$new_api_endpoint = $value;
if ($new_clientId != $old_clientId)
$credential_changed = true;
if ($new_clientSecret != $old_clientSecret)
$credential_changed = true;
if ($new_api_endpoint != $old_api_endpoint)
$credential_changed = true;
if ($credential_changed) {
if(isset($new_clientId) && !empty(trim($new_clientId))
&& isset($new_clientSecret) && !empty(trim($new_clientSecret))
&& isset($new_api_endpoint) &&! empty(trim($new_api_endpoint))) {
MyPlugin_Request_Manager::instance()->set_client_id($new_clientId);
MyPlugin_Request_Manager::instance()->set_client_secret($new_clientSecret);
MyPlugin_Request_Manager::instance()->set_api_endpoint($new_api_endpoint);
$new_auth_token = MyPlugin_Request_Manager::instance()->get_new_auth_token_and_save();
if (!isset($new_auth_token) || empty($new_auth_token)) {
$valid = false;
add_settings_error(
'myPlugin_option_group',
'myPlugin_api_endpoint_error',
esc_html__('Credentials are invalid. Please check your ClientID, ClientSecret and selected Api Endpoint. Make sure you have the correct values, and that you have saved the settings in MyPlugin.', 'myPlugin')
);
}
}else{
$valid = false;
}
}
}
// Ignore the user's changes and use the old database value.
if (!$valid) {
// $value = get_option('myPlugin_api_endpoint');
// MyPlugin_Request_Manager::instance()->set_client_id(get_option('myPlugin_client_id'));
// MyPlugin_Request_Manager::instance()->set_client_secret(get_option('myPlugin_client_secret'));
// MyPlugin_Request_Manager::instance()->set_api_endpoint(get_option('myPlugin_api_endpoint'));
} else {
add_settings_error(
'myPlugin_option_group',
'myPlugin_api_endpoint_updated',
esc_html('Connection established.', 'myPlugin'),
'updated'
);
}
return $value;
}
public function display_field($args)
{
if ($args['type'] == 'password') {
}
echo "<input class=" . esc_html($args['class']) . " id=" . esc_html($args['id']) . " name=" . esc_html($args['name']) . " type='" . esc_html($args['type']) . "' value='" . esc_html($args['value']) . "' />";
}
public function display_select_field($args)
{
print("<select name=" . $args['name'] . ">");
foreach ($args['options'] as $key => $value) {
print("<option value=" . esc_html($value) . (selected(get_option(esc_html($args['name'])), esc_html($value)) ? " selected>" : ">") . esc_html__($key, 'myPlugin') . "</option>");
}
print("</select>");
}
public function plugin_action_links($links, $file)
{
if (substr($file, 0, 6) === "myPlugin") {
$settings_link = "" . esc_html__('Settings', 'myPlugin') . "";
// Insert in front
array_unshift($links, $settings_link);
}
return $links;
}
// Refresh Values button handler
public function admin_post_myPlugin_settings_refresh()
{
if (isset($_POST['refresh'])) {
$repository = MyPlugin_Repository::instance();
$repository->delete_payment_types();
$myPlugin_payment_types = MyPlugin_Request_Manager::instance()->get_sales_payment_types();
$repository->set_payment_types($myPlugin_payment_types);
wp_safe_redirect(esc_url(admin_url('admin.php?page=' . self::page)));
}
}
// Clear Cache button handler
public function admin_post_myPlugin_settings_clear_cache()
{
if (isset($_POST['clear_cache'])) {
$repository = MyPlugin_Repository::instance();
$repository->delete_payment_types();
$repository->delete_invoice_meta();
$repository->delete_auth_tokens();
$all_options = wp_load_alloptions();
if (isset($all_options)) {
foreach ($all_options as $option_name => $option_value) {
if (substr($option_name, 0, 6) === "myPlugin") {
update_option($option_name, "");
}
}
}
MyPlugin_Request_Manager::instance()->set_client_id("");
MyPlugin_Request_Manager::instance()->set_client_secret("");
MyPlugin_Request_Manager::instance()->set_api_endpoint("");
wp_safe_redirect(esc_url(admin_url('admin.php?page=' . self::page)));
}
}
public function is_valid_guid($str)
{
return preg_match('/^[0-9a-f]{12}[4][0-9a-f]{19}$/', $str);
}
public function render_plugin_settings()
{
?>
<div class="myPlugin_settings_wrap">
<h1><?php echo esc_html__("Settings", 'myPlugin'); ?></h1>
<div class="clear">
<a href="<?php echo esc_url(admin_url('admin.php?page=wc-settings&tab=checkout§ion=myPlugin')); ?>">
<input type="button" class="button" value="<?php echo esc_html__('MyPlugin Claim Service Settings', 'myPlugin') ?>">
</a>
</div>
<?php
if(MyPlugin_Request_Manager::instance()->is_connected_to_endpoint()) {
echo "<h2 style='color:green;'>" . esc_html__("Active.", 'myPlugin') . "</h2>";
}else{
echo "<h2 style='color:red;'>" . esc_html__("This plugin is not active. Please fill in your credentials and save.", 'myPlugin') . "</h2>";
}
?>
<form method="POST" action="options.php">
<?php
settings_errors('myPlugin_option_group');
// Allocate all fields for a option group
settings_fields('myPlugin_option_group');
// Displays all the sections that are assigned to a certain page
do_settings_sections('myPlugin-settings');
// Render a Save Change button
submit_button();
?>
</form>
<!-- Inline Button Row - START -->
<form method="POST" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display: inline-block">
<input type="hidden" name="action" value="myPlugin_settings_refresh">
<input type="submit" id="refresh" name="refresh" class="button" value="<?php echo esc_html__("Refresh Values", 'myPlugin'); ?>">
</form>
<form method="POST" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="display: inline-block; padding-left: 5px;">
<input type="hidden" name="action" value="myPlugin_settings_clear_cache">
<input type="submit" id="Disconnect" name="clear_cache" class="button" value="<?php echo esc_html__("Clear Cache", 'myPlugin'); ?>">
</form>
</div>
<?php
}
}
}
MyPlugin_Request_Manager.php
<?php
defined('ABSPATH') || exit;
if (!class_exists('MyPlugin_Request_Manager')) {
class MyPlugin_Request_Manager
{
// This is the singleton instance
private static $_instance = null;
protected $client_id;
protected $client_secret;
protected $api_endpoint;
protected $token;
protected $token_created_at;
// The constructor is private
// to prevent initiation with outer code.
private function __construct()
{
// Use $this instead of static::$_instance
$this->load_dependencies();
}
public function load_dependencies()
{
require_once MYPLUGIN_PATH . 'classes/class-myPlugin-repository.php';
require_once MYPLUGIN_PATH . 'classes/class-myPlugin-utils.php';
}
public static function instance()
{
if (static::$_instance == null) {
static::$_instance = new MyPlugin_Request_Manager();
static::$_instance->set_client_id(get_option('myPlugin_client_id'));
static::$_instance->set_client_secret(get_option('myPlugin_client_secret'));
static::$_instance->set_api_endpoint(get_option('myPlugin_api_endpoint'));
}
return static::$_instance;
}
public function get_client_id()
{
return static::$_instance->client_id;
}
public function set_client_id(string $client_id)
{
static::$_instance->client_id = $client_id;
}
public function get_client_secret()
{
return static::$_instance->client_secret;
}
public function set_client_secret(string $client_secret)
{
static::$_instance->client_secret = $client_secret;
}
public function get_api_endpoint()
{
return static::$_instance->api_endpoint;
}
public function set_api_endpoint(string $api_endpoint)
{
static::$_instance->api_endpoint = $api_endpoint;
}
}
}
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 a SilverStripe (3.4) Page with a form that would work if I didn't have a DataObject in it.
public function AntwortForm($ID) {
$Nummer = Vortest_Fragen::get()->byID($ID);
if ($Nummer) {
$Art=$Nummer->Art;
}
if ($Art == 'Normal') {
$fields = new FieldList(
TextAreaField::create('Antwort'),
HiddenField::create('ID', 'ID', $ID),
HiddenField::create('VortestID', 'VortestID', $this->request->param('ID')),
HiddenField::create('Aktion', 'Aktion', $this->request->param('Action'))
);
} else {
$Optionen = explode(';', $Nummer->Optionen);
$a = 'A';
for ( $i = 0 ; $i < count ($Optionen); $i++) {
$Op[$a] ='<div style="width:25px;display:inline;">' . $a . ')</div> ' . $Optionen[$i];
$a++;
}
$fields = new FieldList(
CheckboxSetField::create('Antwort', 'Antwort', $Op),
HiddenField::create('ID', 'ID', $ID),
HiddenField::create('VortestID', 'VortestID', $this->request->param('ID')),
HiddenField::create('Aktion', 'Aktion',$this->request->param('Action')),
HiddenField::create('Art', 'Art', $Nummer->Art)
);
}
$actions = new FieldList(
FormAction::create('AntwortEintragen', 'Eintragen')
);
$form = new Form($this, 'AntwortForm', $fields, $actions);
return $form;
}
function AntwortEintragen($data, $form) {
$Antwort = Vortest_Antwort::get()->filter(array('FrageID' => $data['ID'], 'SchreiberID' => Member::currentUserID()));
foreach($Antwort as $item) {
$item->delete();
}
foreach ($data['Antwort'] as $Antwort) {
$Ant .= $Antwort . ',';
}
$Antwort = new Vortest_Antwort();
if ($data['Antwort']) {
$form->saveInto($Antwort);
if ($data['Art'] == 'Mechanics') {
$Antwort->Antwort = $Ant;
}
$Antwort->SchreiberID = Member::currentUserID();
$Antwort->FrageID = $data['ID'];
$Antwort->write();
}
$VID = $data['VortestID'];
if ($data['Aktion'] == 'AlleFragen') {
$this->redirect('/vortest/AlleFragen/' . $VID . '#' . $data['FrageNr']);
} elseif ($data['Aktion'] == 'Einzelfrage') {
$this->redirect('/vortest/Einzelfrage/' . $VID);
} else {
$this->redirect('/vortest/Test/' . $VID.'#' . $data['FrageNr']);
}
}
It works when I change the $ID to a number in this line $Nummer = Vortest_Fragen::get()->byID($ID);
When I don't change it I get the following error:
[Recoverable Error] Object of class SS_HTTPRequest could not be converted to string
How do I fix this problem?
Althought it is not clearly documented, Silverstripe secretly passes a request argument to and form methods on a controller. Your $ID argument is actually not what you think it is, you will find it is actually an SS_HTTPRequest object that Silverstripe has passed (without you realising).
To fix this, change the first line:
public function AntwortForm($ID) {
To:
public function AntwortForm($request, $ID) {
And make sure you update anywhere that you call this method :-)
please see the demo problem at Here i have created my own plugin that can make the video be seen when user share the video. I have made three files , one is hook, the next one is class and other one is for update. My plugins 99% function works here. see
<?php
class VideoLock {
protected static $running = false;
const PLUGIN_PREFIX = "VL";
const SLUG = 'videolock';
protected $sharesTableName;
protected $viewsTableName;
protected $_key;
public function __construct() {
//create the correctly prefixed table name
global $wpdb;
$this->sharesTableName = $wpdb->prefix."videolock_shares";
$this->viewsTableName = $wpdb->prefix."videolock_views";
}
public function tinymceShortcodePlugin($plugin_array) {
$plugin_array['videolock'] = $this->file('/assets/js/shortcodeplugin.js');
return $plugin_array;
}
public function tinymceShortcodeButton($buttons) {
array_push($buttons, "separator", "videolock");
return $buttons;
}
public function init() {
if ( ( current_user_can('edit_posts') || current_user_can('edit_pages') ) &&
get_user_option('rich_editing') ) {
//register admin editor shortcode creator
add_filter("mce_external_plugins", $this->callback('tinymceShortcodePlugin'));
add_filter('mce_buttons', $this->callback('tinymceShortcodeButton'));
}
//register admin tinymce shortcode insert plugin
wp_enqueue_style($this->prefix('locker-style'), $this->file('/assets/css/blocker.css'));
wp_enqueue_script($this->prefix('locker-script'), $this->file('/assets/js/blocker.js?v=2'),
array('jquery','swfobject'));
//enqueue swfobject if not present
if( wp_script_is('swfobject') ) {
wp_enqueue_script('swfobject', $this->file('/assets/js/swfobject.js'));
}
//register plugin options
add_option('facebook-id');
add_option('share-message', 'Unlock this video by sharing it on facebook !');
add_option('video-size', '560x315');
new VideoLockUpdate( $this->getKey() );
}
public static function getVersion() {
$file = dirname(__FILE__) . '/version';
if( file_exists($file)) {
return trim(file_get_contents($file));
}
return '0';
}
public function getKey() {
if( $this->_key ) {
return $this->_key;
}
$file = dirname(__FILE__) . '/licence.php';
if( file_exists($file)) {
include $file;
$this->_key = defined('VIDEOLOCK_LICENCE_KEY') ? VIDEOLOCK_LICENCE_KEY : null;
return $this->_key;
}
return false;
}
public function install() {
global $wpdb;
$key = $this->getKey();
if( !$key ) {
wp_die('Fail to activate this plugin. You need a valid licence key for activation. For more informations contact us at support#wpvideolock.com or the online form<br/>If you bought this plugin, please send your email address used for buying the plugin to resend a functional version.<br/>Thank you!');
}
$request = wp_remote_post('http://update.wpvideolock.com/', array('body' => array('action' => 'validate-key', 'key'=>$key)));
if (!is_wp_error($request) || wp_remote_retrieve_response_code($request) === 200) {
$response = trim($request['body']);
if( $response != 'ok' ) {
wp_die($response);
}
}
update_option('facebook-id', '');
update_option('share-message', 'Share on facebook to unlock this video .');
update_option('video-size', '560x315');
if(!in_array($this->sharesTableName,$wpdb->tables())) {
$sql = "CREATE TABLE `" . $this->sharesTableName . "` (
id INT(11) NOT NULL AUTO_INCREMENT,
url VARCHAR(255) NOT NULL,
ip VARCHAR(40) NOT NULL,
post INT(11) NOT NULL,
time DATETIME,
`share_id` VARCHAR( 255 ) NOT NULL,
`gender` ENUM( 'female', 'male' ),
PRIMARY KEY ( id )
)";
$wpdb->query($sql);
}
if(!in_array($this->viewsTableName,$wpdb->tables())) {
$sql = "CREATE TABLE IF NOT EXISTS `" . $this->viewsTableName . "` (
`post_id` int(11) NOT NULL,
`views` int(11) NOT NULL,
`date` date NOT NULL,
UNIQUE KEY `post_id` (`post_id`,`date`)
)";
$wpdb->query($sql);
}
}
public function uninstall() {
global $wpdb;
$backup = false; // Take it from options after user change settings for the plugin to create backup
if( $backup ) {
$sql = "SELECT * FROM `" . $this->sharesTableName . "`";
$results = $wpdb->get_results($sql);
if( count($results) ) {
$uploads_dir = wp_upload_dir();
$backup_file = $uploads_dir['basedir'].'/videolock_backup.txt';
file_put_contents($backup_file,serialize($results));
}
}
$wpdb->query("DROP TABLE `" . $this->sharesTableName . "`");
$wpdb->query("DROP TABLE `" . $this->viewsTableName . "`");
delete_option('facebook-id', '');
delete_option('share-message', 'Share on facebook to unlock this video .');
delete_option('video-size', '560x315');
}
public function getYoutubeId( $url ) {
$url = strip_tags($url);
$url = parse_url($url);
$query = $url['query'];
//If video is in a format like this
// http://www.youtube.com/watch?v=fKmuUDQdcXc
if($query) {
$id = str_replace("v=","",$query);
return $id;
}
//if video is in a format like this
// http://youtu.be/fKmuUDQdcXc
else {
$path = $url['path'];
$id = str_replace("/","",$path);
return $id;
}
}
public function shortcode( $atts ) {
global $wpdb;
//extract attributes to function scope
extract( shortcode_atts( array(
'url' => false,
'id' => false,
'width' => '420',
'height' => '315',
'expire' => 0,
'message' => get_option('share-message'),
), $atts ) );
//do not show anything if to id or url
if( $url === false && $id === false ) {
return null;
}
//extract the video id in case url is passed
if( $url ) {
$id = $this->getYoutubeId($url);
}
$image = 'http://img.youtube.com/vi/' . $id . '/0.jpg';
$view = new View( dirname(__FILE__) . '/views/blocker.php' );
$view->image = $image;
$view->id = $id;
$view->url = $url;
$view->width = $width;
$view->height = $height;
$view->message = $message;
$view->expire = $expire;
//if there werent any views today insert it
//else increment it
$sql = "INSERT INTO `" . $this->viewsTableName . "`
(`post_id`,`views`,`date`)
VALUES
('" . get_the_ID() . "',1,CURDATE())
ON DUPLICATE KEY UPDATE views=views+1;";
$wpdb->query($sql);
$view->helper('isLocked', $this->callback('isLocked'));
return $view->render();
}
public function actionLinks( $links, $file ) {
$url = admin_url( 'admin.php?page=videolock/dashboard.php' );
if ( $file == plugin_basename( dirname(__FILE__).'/videolock.php' ) ) {
$links[] = ''.__( 'Dashboard' ).'';
}
return $links;
}
public function isLocked( $postid = null ) {
global $wpdb;
$postid = is_numeric($postid) ? $postid : get_the_ID();
$sql = "SELECT COUNT(*) AS total FROM `" . $this->sharesTableName . "` WHERE `post`=%d AND `ip`=%s AND `url`=%s LIMIT 1";
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$sql = $wpdb->prepare($sql, $postid, $_SERVER['REMOTE_ADDR'], $url);
$result = $wpdb->get_results($sql);
if( isset($result[0]) ) {
return $result[0]->total == '0';
}
return true;
}
public function share() {
global $wpdb; // this is how you get access to the database
$url= $wpdb->escape($_POST['link']);
$ip = $_SERVER['REMOTE_ADDR'];
$postId = intval($_POST['post']);
$share = $_POST['share'];
$gender = null;
$share_parts=explode('_', $share);
if(count($share_parts)) {
$share_user = $share_parts[0];
if($share_user) {
try {
$user_data = json_decode(#file_get_contents('http://graph.facebook.com/' . $share_user));
$gender = isset($user_data->gender) ? $user_data->gender : null;
}catch(Exception $e) {}
}
}
$result = $wpdb->insert($this->sharesTableName,array(
'url' => $url,
'ip' => $ip,
'post' => $postId,
'time' => current_time('mysql', 1),
'share_id' => $share,
'gender' => $gender
));
echo $result ? '1':'0';
die();
}
public function shareLogged() {
//not implemented yet for logged users
$this->share();
}
public function queueAdminScripts() {
wp_localize_script( $this->prefix('blocker-jsobj'), 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
wp_enqueue_script($this->prefix('dashboard-script'), $this->file('/assets/js/dashboard.js'), array('jquery', $this->prefix('flot')));
wp_enqueue_script($this->prefix('flot'), $this->file('/assets/js/flot/jquery.flot.js'));
wp_enqueue_script($this->prefix('flot.time'), $this->file('/assets/js/flot/jquery.flot.time.js'));
}
public function createDashboard() {
global $wpdb;
$sql = "SELECT SUM(views) as views, post_id FROM `" . $this->viewsTableName . "` GROUP BY post_id";
$postsViews = $wpdb->get_results($sql);
wp_enqueue_style($this->prefix('fresh'), '/wp-admin/css/colors-fresh.min.css?ver=3.7.1');
wp_enqueue_style($this->prefix('dashboard-theme'), $this->file('/assets/css/dashboard.css'));
include dirname(__FILE__) . '/views/dashboard.php';
}
public function createAdminMenu() {
$menu_icon = $this->file('/assets/images/logo.png');
$content_callback = $this->callback('createDashboard');
//add admin left pannel menu
add_menu_page( __('Video Lock'),
__('Video Lock'),
__('manage_options'),
'videolock/dashboard.php', $content_callback , $menu_icon );
}
private function _getShares($post,$date) {
global $wpdb;
//get timestamp from date
$timestamp = strtotime($date);
//calculate start and end of the day
$startTime = date('Y-m-d 00:00:00',$timestamp);
$endTime = date('Y-m-d 23:59:59',$timestamp);
//select the shares for the day of the timestamp
$sql = "SELECT COUNT(*) as shares FROM `" . $this->sharesTableName . "`
WHERE `post` = %d AND `time` BETWEEN '$startTime' AND '$endTime'";
$sql = $wpdb->prepare($sql, $post);
$result = $wpdb->get_results($sql);
if( isset($result[0]) ) {
return $result[0]->shares;
}
else return 0;
}
public function shareStats() {
global $wpdb;
$response = array();
$postId = $_POST['post'];
//get views per day
$sql = "SELECT views,`date` AS `date` FROM `" . $this->viewsTableName . "` WHERE `post_id`=%d";
$sql = $wpdb->prepare($sql, $postId);
$dates = $wpdb->get_results($sql);
$today = date('Y-m-d');
$hasToday = false;
//generate response
foreach($dates as $date) {
//check if today exists (if not we can add it later)
if($date->date == $today) {
$hasToday = true;
}
$jsDate = strtotime($date->date)*1000;
$response['views'][] = array($jsDate ,$date->views);
$response['shares'][] = array($jsDate , $this->_getShares( $postId, $date->date ));
}
//if we don't have today,
//add it as 0 to the graph
if(!$hasToday) {
$today = strtotime($today) * 1000;
$response['views'][] = array( $today , 0 );
$response['shares'][] = array( $today , 0 );
}
echo json_encode($response);
exit();
}
public function saveSettings() {
$settings = $_POST['data'];
update_option('facebook-id', $settings[0]['value']);
update_option('share-message', $settings[1]['value']);
update_option('video-size', $settings[2]['value']);
if($settings[2]['value'] == 'custom') {
update_option('video-width', $settings[3]['value']);
update_option('video-height', $settings[4]['value']);
}
else {
delete_option('video-height');
delete_option('video-width');
}
}
private function _noFacebookId(){
$facebookId = get_option('facebook-id');
if(empty($facebookId) || !$facebookId )
return true;
else
return false;
}
function adminNotice() {
echo '<div class="updated">
<p>You have successfully installed WordPress Video Lock Plugin.
Please take a minute to add your facebook API key and get started</p>
</div>
';
}
private function file( $name ) {
if( strpos($name, '/') !== 0 ) {
$name = '/' . $name;
}
return plugins_url() . '/videolock' . $name;
}
private function prefix( $string ) {
return VideoLock::PLUGIN_PREFIX . $string;
}
private function callback($method) {
return array($this, $method);
}
public function run() {
if( self::$running ) {
throw new Exception("The Youtube Locker already running!");
}
//get the plugin script name for install/uninstall hooks
$pluginFile = dirname(__FILE__) . '/videolock.php';
//installation / dezinstalation hooks
register_activation_hook( $pluginFile, $this->callback('install') );
register_deactivation_hook( $pluginFile,$this->callback('uninstall') );
//short codes
add_shortcode( 'youtubelocker', $this->callback('shortcode') );
add_shortcode( 'videolock', $this->callback('shortcode') );
//filters
add_filter('plugin_action_links', $this->callback('actionLinks'), 10, 2 );
//add ajax callback
add_action('wp_ajax_nopriv_video_share',$this->callback('share') );
add_action('wp_ajax_video_share', $this->callback('shareLogged') );
add_action('wp_ajax_videolock_save_settings', $this->callback('saveSettings') );
add_action('wp_ajax_videolock_share_stats', $this->callback('shareStats'));
add_action('admin_enqueue_scripts', $this->callback('queueAdminScripts') );
add_action('admin_menu', $this->callback('createAdminMenu') );
if($this->_noFacebookId()) {
add_action('admin_notices', $this->callback('adminNotice') );
}
add_action('init', $this->callback('init'), 0);
self::$running = true;
}
}
But somehow it's not working as expected. When user first share the video it works like charm but it makes error when the same user share another. it doesnt open the sharer.php it opens a fb dialog box and load for infinity time. I hope you guys can help me to solve that. FYI after the completation of the plugin the plugin will be freeware in wp.org