On button click save a flag to database in mediawiki 1.3 - mediawiki

I am a fresher in mediawiki. I was trying to implement Manual:Tag extensions/Example (https://www.mediawiki.org/wiki/Manual:Tag_extensions/Example). But the example is based on mediawiki version < 1.3. I have a submit button. I want to save the current user name and a flag (say 1) to a database table if the submit button is clicked. but I am getting
Uncaught SyntaxError: Unexpected identifier (at load.php?lang=en&modules=ext.Example.welcome%7Cjquery&skin=vector&version=h3cy2:1:383).
Can I anyone suggest how to resolve the issue
My hook
class PollHooks implements
\MediaWiki\Hook\ParserFirstCallInitHook
{
Public function onParserFirstCallInit( $parser ) {
$parser->setHook( 'btn', [ self::class, 'pollRender' ] );
//$parser->setHook( 'poll', [self::class, 'pollRender' ] );
}
public static function pollRender( $data, $attribs, $parser, $frame ) {
$ret = '<table class="wtable">';
$ret .= '<tr>';
$ret .= '<td align="center" colspan=2><input id="btn002" type="button" value="Submit"></td>';
$ret .= '</tr>';
$ret .= '</table>';
return $ret;
}
My index.js
( function () {
$("#btn001").click
(
function() {
alert("Button clicked " + mw.user.getName() + ".");
console.log("Button clicked.");
$var user = mw.user.getName();
$flag = 1;
$.get(
mw.util.wikiScript(),
{
action: 'ajax',
rsargs: [user, flag],
rs: 'MediaWiki\\Extension\\Example\\SubmitApi'
}
);
}
);
}() );
SubmitApi.php
use ApiBase;
use Wikimedia\ParamValidator\ParamValidator;
class SubmitApi extends ApiBase {
public function execute() {
/* … */
global $wgUser;
$dbw = wfGetDB( DB_REPLICA );
// Insert vote
$insertQuery = $dbw->insert(
'polldb',
array(
'poll_user' => $user,
'poll_flag' => $flag
)
);
$dbw->commit();
}
public function getAllowedParams() {
return [
'level' => [
ParamValidator::PARAM_TYPE => 'integer',
ParamValidator::PARAM_REQUIRED => true,
]
];
}
}
?>

index.js:
$var user = mw.user.getName();
Remove the $ from $var.

Related

How do I download a generated csv in magento 2.4.5

My files so far are:
system.xml
<field id="generate_csv" translate="label" type="button" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Generate Categories CSV</label>
<frontend_model>Vendor\Module\Block\Adminhtml\System\Config\Button</frontend_model>
</field>
button.php
<?php
namespace [Vendor]\[Module]\Block\Adminhtml\System\Config;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Button extends Field
{
protected $_template = 'Vendor_Module::system/config/button.phtml';
public function __construct(
Context $context,
array $data = []
){
parent::__construct($context, $data);
}
public function render(AbstractElement $element)
{
$element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
return parent::render($element);
}
protected function _getElementHtml(AbstractElement $element)
{
return $this->_toHtml();
}
public function getAjaxUrl()
{
return $this->getUrl('[router]/Export/CategoryExport');
}
public function getButtonHtml()
{
$button = $this->getLayout()->createBlock(
'Magento\Backend\Block\Widget\Button'
)->setData(
[
'id' => 'generate_csv',
'label' => __('Generate CSV')
]
);
return $button->toHtml();
}
}
button.phtml
<script>
require([
'jquery',
'prototype'
], function ($) {
$('#generate_csv').click(function () {
var params = {};
new Ajax.Request('<?php echo $block->getAjaxUrl() ?>', {
parameters: params,
loaderArea: false,
asynchronous: true,
onCreate: function () {
$('#custom_button_response_message').text('');
},
onSuccess: function (transport) {
var resultText = '';
if (transport.status > 200) {
resultText = transport.statusText;
} else {
var response = JSON.parse(transport.responseText);
resultText = response.message
}
$('#generate_csv_response_message').text(resultText);
}
});
});
});
</script>
<?php echo $block->getButtonHtml(); ?>
<p>
<span id="generate_csv_response_message"></span>
</p>
controller
<?php
namespace [Vendor]\[Module]\Controller\Adminhtml\Export;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Catalog\Model\CategoryFactory;
class CategoryExport extends Action
{
protected $resultJsonFactory;
/**
* #param Context $context
* #param JsonFactory $resultJsonFactory
*/
public function __construct(
Context $context,
JsonFactory $resultJsonFactory,
Filesystem $filesystem,
DirectoryList $directoryList,
CollectionFactory $categoryCollectionFactory,
CategoryFactory $categoryFactory
){
$this->resultJsonFactory = $resultJsonFactory;
$this->filesystem = $filesystem;
$this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
$this->categoryCollectionFactory = $categoryCollectionFactory;
$this->categoryFactory = $categoryFactory;
parent::__construct($context);
}
/**
* #return Json
*/
public function execute()
{
$message = 'Success';
$data[] = [
'id' => __('Entity ID'),
'name' => __('Name'),
'level' => __('Level')
];
$categoryCollection = $this->categoryCollectionFactory->create();
$categoryCollection->addAttributeToSelect('*');
$filepath = 'export/customerlist.csv';
$this->directory->create('export');
$stream = $this->directory->openFile($filepath, 'w+');
$stream->lock();
$header = ['Id', 'Name', 'Level'];
$stream->writeCsv($header);
//$categoryArray = array();
foreach ($categoryCollection as $category) {
$data = [];
$data[] = $category->getId();
$data[] = $category->getName();
$data[] = $category->getLevel();
$stream->writeCsv($data);
}
/** #var Json $result */
$result = $this->resultJsonFactory->create();
return $result->setData(['message' => $message]);
}
}
This creates a csv file in var/export directory but I cannot download it
Can anyone help explain how to modify the code so that it will automatically create and down the csv.
I have tried following various examples on the web but none of them have worked.
Please help me out

Wordpress: How do I resolve Notice: Undefined offset: 0 in /wp-includes/capabilities.php on line 1145

I've looked at previous examples of this problem but I can't find a solution for what is causing this notice based on what I've seen from other people. This appears when I am adding a new post only.
1145 is:
$post = get_post( $args[0] );
I'm not getting any other kind of error so I'm not sure where in my code this is causing the problem.
Any help on this?
This is the code:
//show metabox in post editing page
add_action('add_meta_boxes', 'kk_add_metabox' );
//save metabox data
add_action('save_post', 'kk_save_metabox' );
//register widgets
add_action('widgets_init', 'kk_widget_init');
function kk_add_metabox() {
add_meta_box('kk_youtube', 'YouTube Video Link','kk_youtube_handler', 'post');
}
/**
* metabox handler
*/
function kk_youtube_handler($post)
{
$youtube_link = esc_attr( get_post_meta( $post->ID, 'kk_youtube', true ) );
echo '<label for="kk_youtube">YouTube Video Link</label><input type="text" id="kk_youtube" name="kk_youtube" value="' . $youtube_link . '" />';
}
/**
* save metadata
*/
function kk_save_metabox($post_id) {
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
//check if user can edit post
if( !current_user_can( 'edit_post' ) ) {
return;
}
if( isset($_POST['kk_youtube'] )) {
update_post_meta($post_id, 'kk_youtube', esc_url($_POST['kk_youtube']));
}
}
/**
* register widget
*/
function kk_widget_init() {
register_widget('KK_Widget');
}
/**
* Class KK_Widget widget class
*/
class KK_Widget extends WP_Widget
{
function __construct()
{
$widget_options = array(
'classname' => 'kk_class', // For CSS class name
'description' => 'Show a YouTube video from post metadata'
);
$this->WP_Widget('kk_id', 'YouTube Video', $widget_options);
}
/**
* Show widget form in Appearance/Widgets
*/
function form($instance)
{
$defaults = array(
'title' => 'YouTube Video'
);
$instance = wp_parse_args((array)$instance, $defaults);
var_dump($instance);
$title = esc_attr($instance['title']);
echo '<p>Title <input type="text" class="widefat" name="' . $this->get_field_name('title') . '" value="' . $title . '" /></p>';
}
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
return $instance;
}
/**
* Show widget in post/page
*/
function widget($args, $instance)
{
global $before_widget;
global $after_widget;
global $before_title;
global $after_title;
extract( $args );
$title = apply_filters('widget_title', $instance['title']);
//show only if single post
if(is_single()) {
echo $before_widget;
echo $before_title.$title.$after_title;
//get post metadata
$kk_youtube = esc_url(get_post_meta(get_the_ID(), 'kk_youtube', true));
//print widget content
echo '<iframe width="200" height="200" frameborder="0" allowfullscreen src="http://www.youtube.com/embed/' . $this->get_yt_videoid($kk_youtube) . '"></iframe>';
echo $after_widget;
}
}
function get_yt_videoid($url)
{
parse_str(parse_url($url, PHP_URL_QUERY), $my_array_of_vars);
return $my_array_of_vars['v'];
}
}
I found the solution here https://wordpress.org/support/topic/patch-notice-undefined-offset-0-in-capabilitiesphp-on-line-1102
May seem different issue but I could fix the issue changing:
if ( ! current_user_can( 'edit_post' ) ) return;
to
if ( ! current_user_can( 'edit_posts' ) ) return;
In other scenary
if you have a custom taxonomy, you must be sure that 'assign_term' capability on 'capabilities' args is related to 'edit_posts'
'assign_terms' => 'edit_posts',
or
'assign_terms' => 'edit_mycustomposttypes',
(note the 's' at end)
example:
$capabilities = array(
'manage_terms' => 'manage_mytaxs',
'edit_terms' => 'manage_mytaxs',
'delete_terms' => 'manage_mytaxs',
**'assign_terms' => 'edit_mycustomposttypes',**
);
$args = array(
'show_ui' => true,
'show_admin_column' => true,
**'capabilities' => $capabilities,**
);
register_taxonomy( 'mytax', 'mycustomposttype', $args );
This line:
if( !current_user_can( 'edit_post' ) ) {
Should be:
if( !current_user_can( 'edit_post', $post_id ) ) {

fat models and thin controllers in codeigniter

this is a user.php controller
public function verifyLogin() {
if (isset($_POST["email"])) {
$e = $this->input->post("email");
$p = $this->input->post("pass");
$this->form_validation->set_rules("email", "email", "required|valid_email|xss_clean");
$this->form_validation->set_rules("pass", "password", "required|xss_clean");
if ($this->form_validation->run()) {
$data = array(
'select' => '*',
'table' => 'users',
'where' => "email = '$e' AND activated = '1'"
);
$checklogin = $this->query2->selectData($data);
if ($checklogin === FALSE) {
echo "quering userInfo fails. email is wrong or activation not done";
exit();
} else {
foreach ($checklogin as $row) {
$dbid = $row->id;
$dbusername = $row->username;
$dbpassword = $row->password;
$dbemail = $row->email;
if ($p === $dbpassword) {
$login_data = array(
'name' => $dbusername,
'email' => $dbemail,
'password' => $dbpassword,
'id' => $dbid,
'expire' => '86500',
'secure' => TRUE,
'logged_in' => TRUE
);
$this->input->set_cookie($login_data);
$this->session->set_userdata($login_data);
if ($this->session->userdata("logged_in")) {
$time = time();
$now = unix_to_human($time, TRUE, 'us');
$updateLogin = $this->query1->updateLogin($e, $now);
if ($updateLogin) {
echo "success";
} else {
echo 'update failed';
}
} else {
echo "session failed";
}
}else{
echo 'password incorrect';
}
}
}
} else {
echo "form validation fails";
}
} else {
$this->load->view('header');
$this->load->view('login');
$this->load->view('modal');
$this->load->view('footer');
}
}
this is model.php
public function selectData($data){
if(isset($data['direction'])){
$dir = $data['direction'];
}else{
$dir = "ASC";
}
if(isset($data['offset'])){
$off = $data['offset'];
}else{
$off = '0';
}
if(isset($data['select']) && isset($data['table'])){
$this->db->select($data['select'])->from($data['table']);
}
if(isset($data['where'])){
$this->db->where($data['where']);
}
if(isset($data['order_by_name'])){
$this->db->order_by($data['order_by_name'], $dir);
}
if(isset($data['limit'])){
$this->db->limit($data['limit'], $off);
}
$query = $this->db->get();
if($query){
$d = $query->result();
return $d;
}else{
return FALSE;
}
}
is this a good way of quering database?
i am new to mvc and i am reading everywhere about "fat models and this controllers"
what can be done to make it a good mvc architecture?
its only acceptable to echo out from the controller when you are developing:
if ($checklogin === FALSE) {
echo "quering userInfo fails.
if checking login is false then either show a view or go to a new method like
if ($checklogin === FALSE) {
$this->showLoginFailed($errorMessage) ;
the check login code in the controller is a great example of something that could be refactored to a model. then if you need to check login from another controller its much easier. putting the form validation code in a model would be another choice. often times when you are validating form code you are also inserting/updating to a database table -- so having all those details together in a model can make things easier long term.
"fat model" does not mean one method in a model that does a hundred things. it means the controller says -- did this customer form validate and insert to the database? yes or no? 3 lines of code.
the model has the code that is looking into the "fat" details of the form, validation, database, etc etc. say 50 or more lines compared to the 3 in the controller. but the methods in the model should still be clean: small and specific.

Laravel error:: Illegal string offset 'category_name'

I'm trying to create an admin side form. Here i'm trying to select data from the database. Also i want to display it. But for some reason it's not working. Here's my controller code,
public function save()
{
if (Input::has('save'))
{
$rules = array('category_name' => 'required|min:1|max:50', 'parent_category' => 'required');
$input = Input::all();
$messages = array('category_name.required' =>'Please enter the category name.', 'category_name.min' => 'Category name must be more than 4 characters', 'category_name.max' =>'Category name must not be more than 15 characters!!!', 'parent_category.required' => 'Please Select Parent Category.',);
$validator = Validator::make($input, $rules, $messages);
if ($validator->fails())
{
return Redirect::to('admin/category/add')->withErrors($validator)->withInput($input);
}
else
{
$insert_db = CategoryModel::insert($input);
$selected_category = CategoryModel::select($input['category_name']);
}
}
}
and my CategoryModel.php is following.
public static function insert($values)
{
$insert = DB::table('add_category')->insert(array('category_name'=>$values['category_name'], 'parent_category'=>$values['parent_category']));
if(isset($insert))
{
echo 'inserted successfully';
}
else
{
echo 'Failed';
}
}
public static function select($values)
{
$insert = DB::table('add_category')->where('category_name' . '=' . $values['category_name']);
}

query function in cake php

I am writing code in php to basically 'map' data from a mySQL database to another database. I am using the code as follows:
$results = $this->query("select PT_FS_DATA_ID from PATIENT_FLOWSHEET_DATA where
DT_LAST_UPDATED_TIME = (select top 1 DT_LAST_UPDATED_TIME from PATIENT_FLOWSHEET_DATA
order by DT_LAST_UPDATED TIME desc) group by PT_FS_DATA_ID;");
however, I am getting an error:
syntax error, unexpected T_VARIABLE, expecting T_FUNCTION
Everywhere I look this seems to be the correct syntax. Is there something I'm missing here?
I tried putting the controller in there as well $this->controllerName->query, but that didn't work either.
Full Code:
class CaExtraFlowsheetFields extends CaBase {
public $name = 'CaExtraFlowsheetFields';
/*
NOTE: This is to take all the fields in flowsheet and
maps their id's.
*/
//public $useTable = 'ANSWER_ENTRY';
public $useTable = 'PATIENT_FLOWSHEET_DATA';
public $primaryKey = 'PT_FS_DATA_ID';
protected function getPrimaryKeyValue(
$hospital_id,
$patient_id,
$admission_id = null
) {
return $patient_id;
}
//*CHANGE BEGIN*
$results = $this->query("select PT_FS_DATA_ID from PATIENT_FLOWSHEET_DATA where
DT_LAST_UPDATED_TIME = (select top 1 DT_LAST_UPDATED_TIME from PATIENT_FLOWSHEET_DATA
order by DT_LAST_UPDATED TIME desc) group by PT_FS_DATA_ID;");
protected $filedMethodMappings = array(
'Method_GO' => array(
CaBase::KEY_MAPPING_LOGIC_COMPLEXITY => CaBase::LEVEL2_COMPLEXITY,
CaBase::KEY_FIELD_LOGIC_NAME => 'wsMethod_GO',
);
//########################################################################//
//Note[]>Block[] //
//>Method that calls LookUpField for every field in flowsheet // //
//########################################################################//
public function wsMethod_GO ($params) {
foreach($results as $value){
$questionName = ''.$value;
$msg_prefix = $this->name . "::" . __FUNCTION__ . ": ". "arrivez-vouz" ;
$ret = $this->wsLookUpField($params,$questionName,$msg_prefix);
return $ret;
}
unset($value);
}
//########################################################################//
public function wsLookUpField($params,$questionName,$msg_prefix){
$arrayValues=array();
try{
$hospital_id = $params[Constants::KEY_HOSPITAL_ID];
$patient_id = $params[Constants::KEY_PATIENT_ID];
$admission_id = $params[Constants::KEY_ADMISSION_ID];
$msg_prefix = $this->name . "::" . __FUNCTION__ . ": ". "attendez-vouz: l'hopital= ".$hospital_id.
" patient= ".$patient_id." admission= ".$admission_id;
//shows info about given question name
$msg_prefix = "*!*!*!*Show me ---> ".$questionName." : ".$answer_entry_id.
" = aic: " .$answer_id_check;
$ret = array();
//now with needed fields, grab the A_NAME:
$params = array(
'conditions' => array(
$this->name . '.PID' => $patient_id,
$this->name . '.PT_FS_DATA_ID' => $questionName,
),
'order' => array(
$this->name . '.' . $this->primaryKey . ' DESC'
),
'fields' => array(
$this->name . '.FS_VALUE_TEXT',
)
);
$rs = $this->find('first', $params);
/* check to make sure $rs has received an answer from the query
and check to make sure this answer is a part of the most recent
database entries for this note */
if (false != $rs) {
try {
$msg = $msg_prefix . "Data obtained successfully."."<br>".$result;
$result = $rs;
$ret = WsResponse::getResponse_Success($msg, $result);
} catch (Exception $e) {
$msg = $msg_prefix . "Exception occurred.";
$ret = WsResponse::getResponse_Error($msg);
}
/*answer was not part of most recent database entries, meaning no
answer was given for this particular question the last time this
particular note was filled out. Message is given accordingly.*/
} else {
$msg = $msg_prefix . "/No answer given.";
$ret = WsResponse::getResponse_Error($msg);
}
} catch (Exception $e) {
$msg = $msg_prefix . "Exception occurred.";
$ret = WsResponse::getResponse_Error($msg);
}
return $ret;
}
Here is what you are doing:
class ABC {
$result = 'whatever';
}
You can't declare a variable there!
Code needs to be inside a method/function...
class ABC
{
public function wsMethod_GO ($params)
{
$result = 'whatever';
}
}