#StackBounty: #php #javascript #theme-customizer #settings WordPress customizer: load controls in a custom div

Bounty: 100

I have a custom div (holder for extra settings) which I need to load some specific controls from a specific section in there. I can get the controls in JavaScript but I can’t generate the necessary HTML as WordPress do in sections.

wp.customize.section( 'custom_div_1' ).controls();

It gives an array of controls but how to generate the HTML like Site title or Tagline controls in default WordPress section.

This custom div will toggle by the left button Open extra settings.

Screenshot for easier understanding:screenshot

Any help is appreciated.


Get this bounty!!!

#StackBounty: #javascript #functional-programming Using partial application to compose functions

Bounty: 50

I have an application that will provide notifications to clients. It has two configurations:

Default: A single web api instance that notifies the appropriate subscribers

Alternative: Under high load, there will be multiple web api instances. To coordinate messages between instances, I will leverage a redis backplane. When an api instance receives a message, it sends it to the redis backplane, which then pushes it back down to all api instances.

I have a config.useRedis option that should control whether Redis should be used. To get things working, I created some pretty monolithic code:

//Channels will reference the channel name - which is our device id - and an array
//of websockets that are interested in that device
let channels = {};
let redisSubscribers = [];

// Send a message to the appropriate websocket clients listening on the right channel
// As we check the channel, we'll do a little housekeeping as well
const broadcast = (data) => {
  const message = JSON.parse(data);
  const deviceId = message.deviceId;

  if (Object.keys(channels).some(key => +key === deviceId)) {
    //Perform a cleanup of any closed sockets
    channels[deviceId] = channels[deviceId].filter(socket => socket.readyState === 1);

    channels[deviceId].forEach(ws => ws.send(data));

    //If the channel is empty, nuke the channel and close the redis subscription
    //if appropriate
    if (channels[deviceId].length === 0) {
      delete channels[deviceId];

      if (config.useRedis) {
        const subscriber = redisSubscribers.find(sub => +sub.deviceId === deviceId);
        if(subscriber) {
          subscriber.quit();
          redisSubscribers = redisSubscribers.filter(sub => sub !== subscriber);
        }
      }
    }
  }
}

...    

wss.on('connection', (ws) => {
  console.log('socket established...')
  const querystring = url.parse(ws.upgradeReq.url, true).query;
  const deviceId = querystring.deviceId;

  if (!Object.keys(channels).includes(deviceId)) {
    channels[deviceId] = [ws];

    if(config.useRedis) {
      //Init redis subscriber
      ...
    }
  }
  else {
    channels[deviceId].push(ws);
  }

  ws.on('message', (data) => {
    if(config.useRedis) {
      redisPublisher.publish(deviceId, data);
    }
    else {
      const message = JSON.parse(data);
      broadcast(message);
    }
  });
});

I’d like to compose the behaviour instead, which would provide more flexibility in future in case I want to move to something else besides Redis.

So, if Redis is enabled for the app, in the broadcast function, I want to enhance the function with additional logic. In the connection handler, I want to init a Redis subscriber to receive messages from the backplane. In the message handler, I want to replace the default publishing logic with the custom Redis logic.

Note: The following has not been tested, I just threw some code together to demonstrate the course. Consider it pseudo-code 🙂

websocketserver.js

const websocketServer = () => {
  let channels = {};
  const broadcast = (function(data) {
    return function(enhancement) {
      if (Object.keys(channels).some(key => +key === deviceId)) {
        //Perform a cleanup of any closed sockets
        channels[deviceId] = channels[deviceId].filter(socket => socket.readyState === 1);

        channels[deviceId].forEach(ws => ws.send(data));

        //If the channel is empty, nuke the channel
        if (channels[deviceId].length === 0) {
          delete channels[deviceId];
        }

        // If any "enhancement" should be applied, execute the passed in function
        if(typeof enhancement === 'function') {
          enhancement(deviceId)
        }
      }
    }
  })

  const onConnection = () => {
    return function(enhancedSubscribe, enhancedPublish) {
      console.log('socket established...')
      const querystring = url.parse(ws.upgradeReq.url, true).query;
      const deviceId = querystring.deviceId;

      if (!Object.keys(channels).includes(deviceId)) {
        channels[deviceId] = [ws];

        if(typeof === 'enhancedSubscribe') {
          enhancedSubscribe(deviceId)
        }
      }
      else {
        channels[deviceId].push(ws);
      }

      ws.on('message', (enhancedPublish) => {
        if(typeof enhancedPublish === 'function'){
          enhancedPublish(data);
        }
        else {
          const message = JSON.parse(data);
          broadcast(message);
        }
      }
    }
  };

  return {
    broadcast,
    onConnection,
    onMessage
  }
}

redisServer.js

const redisServer = () => {
  let redisSubscribers = [];

  const removeSubscriber = () => {
    const subscriber = redisSubscribers.find(sub => +sub.deviceId === deviceId);
    if(subscriber) {
      subscriber.quit();
      redisSubscribers = redisSubscribers.filter(sub => sub !== subscriber);
    }
  }

  const enhancedSubscribe = (deviceId, broadcast) => {
    //Init redis subscriber
    ...
  }

  const enhancedPublish = (deviceId, data) => {
    redisPublisher.publish(deviceId, data);
  }

  return {
    removeSubscriber,
    enhancedSubscribe,
    enhancedPublish
  }
}

I attempt to compose the behaviour I want like this:

serverFactory.js

const server = () => {

  const broadcast = (data) => {
    let webSocketBroadcast = websocketServer.broadcast(data);
    if (config.useRedis) {
      return webSocketBroadcast();
    }
    else{
      return webSocketBroadcast(redisServer.enchanceBroadcast);
    }
  }

  const onConnection = (ws) => {
    let websocketServerOnConnection = websocketServer.onConnection();
    if (config.useRedis) {
      retuen websocketServerOnConnection()
    }
    else
    }
  }

  return {
    broadcast,
    onconnection,
    onMessage
  }
}

So, I am attempting to extend/enhance the websocket behaviour with partial application. Does this make sense? Anything further I can do to improve this or make it more flexible?


Get this bounty!!!

#StackBounty: #javascript #jquery #html #cordova #wcf How to display set access permission & display /hide div based on database va…

Bounty: 50

i want to set access permissions page where setting the permissions to the user to only view selected div’s only for ex:

There are 5 checkboxes in admin page and 5 div’s in user page if check 3 div user has to get 3 div only i am mapping userlocation & client location & username for setting access permissions and how to display / hide the div in user page based on the checkbox selection or database values?

There is user login separately and admin login separately . Her admin will disable certain features for certain users. using wcf rest and sql server as backend


Get this bounty!!!

#StackBounty: #javascript #jquery #html #css #google-maps Google Maps in jQuery Accordion works in jsFiddle, but maps do not load on my…

Bounty: 50

I am trying to simply make an expanding list of Google Maps which allow you to locate an item. Here I have a static HTML page where you can click records and they will expand to show you a Google Map. The map, however, only comes through as grey until you resize the page.

Here is the page with the problem (the extension says php, but it doesn’t actually have any): https://yt074.addons.la/tmp/track/list.php

I’m already calling google.maps.event.trigger(maps[i], 'resize'); within the code (as you can see by viewing source), and I have tried jQuery(window).trigger('resize');, window.dispatchEvent(new Event('resize')); and a few others to simulate a resizing of the window, but to no avail.

Here is a jsFiddle with the code from above literally copy/pasted into the fiddle and it works: https://jsfiddle.net/myingling/Lkdmp1zo/

Or here is a shorter version on my server which is not working: https://yt074.addons.la/tmp/track/fiddle.php

What am I missing on my server? Server is ubuntu running nginx on an AWS EC2 cluster, but once the code is client-side I don’t understand why that would matter (but better safe to explain).


Get this bounty!!!

#StackBounty: #javascript #security #node.js #express.js Custom CSRF protection in Express / Node

Bounty: 50

Please review my code rather than telling me to use a trusted NPM package like csurf.

What are some potential weaknesses with the following implementation?

'use strict'

const   express = require('express'),
        router = express.Router(),
        crypt = require('../services/crypt')


router.use((req, res, next) => {
    if (req.session.csrfToken === undefined) {
        req.session.csrfToken = crypt.randHex(64) // this uses Crypto.randomBytes(); gives a hex of length 64
        // alt: res.locals.csrfToken = crypt.hash('sha256', req.session.csrfToken + req.headers.host) // also using Crypto
    }

    res.locals.csrfToken = req.session.csrfToken
}

module.exports = router

I put the res.locals.csrfToken in all forms with method="post", and this middleware is always used:

'use strict'

const   express = require('express'),
        router = express.Router()


router.post('*', (req, res, next) => {
    if (req.session.csrfToken !== req.body.csrfToken) {
    // alt: if (crypt.hash('sha256', req.session.csrfToken + req.headers.host) !== req.body.csrfToken) {
        let err = new Error('Invalid CSRF Token!')
        err.status = 403

        return next(err)
    }

    return next()
})

module.exports = router

I am using HTTPS, and my express-session options look something like this:

{
    name: 'sessid',
    resave: false,
    saveUninitialized: false,
    secret: 'djt84nq7y4tnvwosufvgsudih3rve783vdk'
}

Will the alternative (alt) implementation help any?


Get this bounty!!!

#StackBounty: #javascript #c# #jquery #.net #winforms JQuery click() on anchor tag not firing from an injected script inside WebBrowser…

Bounty: 50

I am developing a web bot using WinForms WebBrowser control. Everything is working fine except for the second click() call in following code:

function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();             //<-- This is working
        var x = $('#s_at_m_4-menu li')[5];
        var saveLink = $(x).find('a')[0];
        if (saveLink != null){
            saveLink.click();           //<-- This is not working

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}

saveLink is not null. I know this because I placed an alert() call inside the condition.

Updated code with suggested solutions

function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();
        var x = $('#s_at_m_4-menu li').eq(5);
        var saveLink = x.find('a').eq(0);
        if (saveLink != null) {
            alert(saveLink.html());
            saveLink.click();

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}

But still the same problem. ‘alert()’ is working fine but html() is showing inner text instead of HTML of the anchor.

HTML Code

<li data-caption="Save Record                [Ctrl+S]" class="sbui-appletmenu-item  ui-menu-item" role="presentation">
<a href="javascript:void(0)" aria-disabled="false" class="ui-corner-all" id="ui-id-254" tabindex="-1" role="menuitem">Save Record                [Ctrl+S]</a>
</li>

ID of the anchor tag is dynamically generated.

Also, click() is triggering when the same code is executed from Google Chrome Console. So, could it be the issue with the WebBrowser control?


Get this bounty!!!

#StackBounty: #javascript #angularjs #facebook #.htaccess #facebook-opengraph Can I get AngularJS to use different controllers for Face…

Bounty: 50

I have an AngularJS application that is served up using http-server

I want my the meta-tags (og:title, og:description, og:image) to be populated dynamically for Facebook and other scrapers (like Slack) to post rich-links on social media sites. However, it is tricky because those scrapers do their scraping of the original HTML page before angular dynamically inserts the proper values. So the scrapers see the placeholder values.

One solution to this problem is described here. Basically: feed the scraper-bots static HTML with desired og fields already populated. I would like to do that. But unlike that author, I’m not using apache. In http-server there is no .htaccess file that I’m aware of.m

I use UI-Router and $state-provider to handle the URLs provided to my application like this:

  $stateProvider.state('splash',
      {
          url: '/',
          templateUrl: 'html/splash.html',
          controller: 'SplashCtrl',
          data: {
              meta: {
                'title': 'My Title',
                'description': 'My Description'
              }
          }
      }
  );

Is there some way I can create a state such that scraper-bots will be sent to a different controller than normal human users using a web-browser? How?


Get this bounty!!!

#StackBounty: #2013 #javascript #development #aspx #sputility Does SPUtility.js support adding and removing choices from a drop-down fi…

Bounty: 50

I am working on a sharepoint server 2013. and inside my built-in create.aspx list form i added the following javascript code:-

var selectobject = document.getElementById("Approver_90afaad9-2b54-46fb-8ac1-7374e4efa11e_$DropDownChoice");

for (var i=selectobject.options.length-1; i>=0; i--)
    {

  selectobject.remove(i);
    }

now as shown in the code i am selecting a drop-down list based on its id, then i am removing its choices.

now i want to modify my javascript to use the SPUtility.js library to reference the columns using their internal names, rather than referencing them using their markup id. but i am not sure if SPUtility.js will support or provide the features to remove choices from my drop-down list as i am current doing inside my pure javascript code?

so if i replace this:-

var selectobject = document.getElementById("Approver_90afaad9-2b54-46fb-8ac1-7374e4efa11e_$DropDownChoice");

with SPUtility.js syntax:-

var selectobject = SPUtility.GetSPFieldByInternalName('Approver');

will i still be able to remove the choices??


Get this bounty!!!

#StackBounty: #javascript #c# #deobfuscation #jint Jint+JSfuck – 'Index was outside the bounds of the array'

Bounty: 50

I’m trying to run the following code in jint:

Jint.Engine engine = new Jint.Engine();
var result = engine.SetValue("data", data).Execute("(/\n(.+)/.exec(eval(data.replace(/\s+/, "").slice(0, -2)))[1]);").GetCompletionValue();

Which, when unescaped, is executing the following javascript:

(/n(.+)/.exec(eval(data.replace(/s+/, "").slice(0, -2)))[1]);

the data variable corresponds to a JSfuck string, similar to this: https://pastebin.com/vmGAebW5

The problem is that I always get a ‘Index was outside the bounds of the array’ exception, even though the javascript works fine when run in a browser. Any ideas as to what is causing the issue?


Get this bounty!!!

#StackBounty: #javascript #reactjs #webpack #mocha #sinon How Do I Stub webpack's require.ensure?

Bounty: 100

I use webpack‘s code splitting feature (require.ensure) to reduce the initial bundle size of my React application by loading components that are not visible on page load from a separate bundle that is loaded asynchronously.

This works perfectly, but I have trouble writing a unit test for it.

My test setup is based on Mocha, Chai and Sinon.

Here is the relevant excerpt from the code I have tried so far:

describe('When I render the component', () => {
    let component,
        mySandbox;
    beforeEach(() => {
        mySandbox = sandbox.create();
        mySandbox.stub(require, 'ensure');
        component = mount(<PageHeader />);
    });
    describe('the rendered component', () =>
        it('contains the SideNav component', () =>
            component.find(SideNav).should.have.length(1)
        )
    );
    afterEach(() => mySandbox.restore());
});

When running the test, I get this error message:

“before each” hook for “contains the SideNav component”: Cannot stub non-existent own property ensure

This happens because require.ensure is a method that only exists in a webpack bundle, but I’m not bundling my tests with webpack, nor do I want to, because it would create more overhead and presumably longer test execution times.

So my question is:

Is there a way to stub webpack’s require.ensure with Sinon without running the tests through webpack?


Get this bounty!!!