8 – Export current gutenberg content for page entered in the visual editor as JSON

I’m using Gutenberg and various custom content types like blog post, person, article, etc. I want it so when a user creates an article it automatically fills the page with a preset set of blocks with placeholder data, or data that came from custom fields for that content type.

I do see that there’s a page template section https://www.drupal.org/docs/8/modules/gutenberg/page-templates that you can set for each content type. But instead of manually writing the JSON for the template I want to be able to take the content I’ve already entered and export it to JSON so I can paste it into that field.

Is it possible to export content from the Gutenberg visual editor to JSON so I can use it as a template for content types?

active directory – Abort “Current” Windows Shutdown

So I’m currently doing a school project where I need to develop a script and apply it to a GPO. What the script does is that once the user clicks on Restart/Shutdown/Sign Out it will be prompt asking if the user has work files to save or not. If yes it will cancel the shutdown and allow them to save, if not it will go ahead and delete the local profile.

The issue is that once I press the Shutdown in my VM, the script asks if I want to save the work files, I click on yes, but actually doesn’t cancel the shutdown because it says Unable to abort the system shutdown because no shutdown was in progress and then afterwards it shutdowns the computer entirely and doesn’t allow me to save the work files.

I’ve already selected the option to Run PowerShell Script script last but even changing to first it still gives me the same outcome.

I’ve initially written this script: https://pastebin.com/V7B8U34Y However, I found out this: https://docs.microsoft.com/en-us/windows/win32/shutdown/logging-off but I’m unable to understand how it works and I’ve been googling for examples and found out that needs to be written in C# which I never developed apps in C#

I hope anyone can help me with this.

Thanks

unity – Find the current player instance from multiple scripts

This type of thing is often implemented using some form of the Singleton pattern. Here’s one version, fairly similar to what you’re doing now, just without the redundant double-search for the object, then the component, when all you really wanted was the component:

public class Player: MonoBehaviour {

     static Player _instance;
     public static Player instance {
         get {
             if(_instance == null) {
                 _instance = FindObjectOfType<Player>();    
                 UnityEngine.Assertions.Assert.IsNotNull(_instance, "Failed to find player component.");
             }

             return _instance;
         }
     }
}

Now other scripts can just ask for the current instance like this:

_player = Player.instance;

…and the singleton will look it up for them. It returns a cached copy quickly if it’s been asked before, and only does the slow search the first time it’s asked, or after the player’s been destroyed and re-created.

You can also skip the search entirely and have your player “report” itself on load:

void Awake() { _instance = this; }

…but this can cause timing issues if you have other scripts that need to reference the player in their own Awake methods that happen to run before the player got a chance to do so. If you can safely defer all references to the player until Start or Update though, this is an option.

(As an aside, some folks find they use this pattern so much that they implement it in a Singleton<T> : MonoBehaviour where T: Singleton<T>, using the curiously recurring template pattern, so they can quickly add it to any class by declaring it as Player : Singleton<Player>. This can help if you’re worried about the amount of boilerplate this adds to every type you want to look up this way.)

You’ll find folks are often critical of the singleton pattern for good reasons, though the risk of making the data global doesn’t really apply here – as your code shows, access to the player object was already available globally.

So in this case, the main risk this method introduces is that it limits you to a single player at a time. If you ever want to have multiplayer with multiple instances of the Player class active in the scene at a time, this method only lets you find the first one, and so you have some heavy refactoring to do if you’ve got dozens of scripts that all find “the” player this way.

That’s no worse than your current code, and it’s acceptable for many Unity games. And it’s still solvable. You can replace your instance property with a public static GetPlayer(int playerID) function, or a GetClosestPlayer(), etc. Then systematically replace each occurrence of Player.instance with the appropriate alternative. It’s work, but not an insurmountable obstacle.

batch file – Run script as admin but get the current user

I’m trying to make a script that keeps track of login/logout times of all thin-client users and writes them to a text file on the server. I will set up a task in Task Scheduler that runs a batch file which writes to a text file every time a user logs in/out. To write to a file at C:/ The script must be run as admin. This can be accomplished by selecting “Run with highest privileges” in task scheduler, and making sure it’s run under an admin account.

However, I believe that when I use the %USERPROFILE% command, it will return the admin’s username, not that of whoever just logged in/out. Is there a way to run the script with admin rights, but have some command to get the user that just logged in/out, triggering the task?

2013 – Append current page URL as redirect to new item link

I am using SP2013 on premise. I have 3 lists: 1. Projects 2. Requirements 3. Issues. Lists 2 & 3 have been added to List 1 DispForm.aspx and a lookup column and query string filter links them so that when a Project is selected a lookup column ID connects/selects only corresponding Requirements and Issues all on the same page. Problem is that when I select the New Item link for Lists 2 or 3 on said page the ID is not included in the url and therefore I cannot do a query string on to pre-fill the Project ID Lookup value. So I need to some how append part of the current page url “…/Lists/Project%20Details/DispForm.aspx?ID=1″ (without the &source) and append to the current DispForm.aspx (without the &Rootfolder) as the &Source=”…/Lists/Project%20Details/DispForm.aspx?ID=1” but can’t be hardcoded, has to be able to query the ID variable from the current URL. Any suggestions or ideas? I had a solution if I used a Document Set as the Project list but Document Sets proved to be unworkable in other areas so I am using 3 regular lists instead.

8 – How can I allow the current user to only see their own page?

_permission only allows to give access to the route to the users who have that permission; it doesn’t allow to give access basing on more complex conditions, as in the case of this question. As described in Custom route access checking, the route definition should be similar to the following one.

task_notify.user_page.tasks:
  path: '/user/{user}/tasks'
  defaults:
    _controller: 'Drupaltask_notifyControllerTaskNotifyUserController::tasks'
    _title: 'Tasks list'
  requirements:
    _custom_access:  'Drupaltask_notifyControllerTaskNotifyUserController::taskAccess'
    user: d+

The TaskNotifyUserController class would need to contain at least the following code (and other methods you need from that controller, including tasks()).

class TaskNotifyUserController extends ControllerBase {

  /**
   * Checks access for the users task page.
   *
   * @param DrupaluserUserInterface $user
   *   The user being viewed.
   * @param DrupalCoreSessionAccountInterface $account
   *   The account viewing the page.
   *
   * @return DrupalCoreAccessAccessResultInterface
   *   The access result.
   */
  public function taskAccess(UserInterface $user, AccountInterface $account) {
  public function taskAccess(UserInterface $user) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user()->id() == $account->id())
      ->cachePerUser();
  }

}

If then the access to the route should be allowed also to users with a specific permission (for example, the permission to administer users), the taskAccess() code would be similar to the following one.

  /**
   * Checks access for the users task page.
   *
  /**
   * Checks access for the tasks tab.
   *
   * @param DrupaluserUserInterface $user
   *   The user being viewed.
   * @param DrupalCoreSessionAccountInterface $account
   *   The account viewing the page.
   *
   * @return DrupalCoreAccessAccessResultInterface
   *   The access result.
   */
  public function taskAccess(UserInterface $user, AccountInterface $account) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user->id() == $account->id())
      ->orIf(AccessResult::allowedIfHasPermission($account, 'administer users'))
      ->cachePerUser();
  }

Don’t forget to import the class used from the controller, adding the following lines at the top of the controller file.

use DrupalCoreAccessAccessResult;
use DrupalCoreSessionAccountInterface;
use DrupaluserUserInterface;

If the controller class uses other classes from different namespaces, similar lines must be added for each class.

I took the code used from Drupal core for the Tracker module as example. The Tracker module shows its tracker page on /activity/{user} using a controller to render it. See TrackerController.php.

  /**
   * Checks access for the users recent content tracker page.
   *
   * @param DrupaluserUserInterface $user
   *   The user being viewed.
   * @param DrupalCoreSessionAccountInterface $account
   *   The account viewing the page.
   *
   * @return DrupalCoreAccessAccessResult
   *   The access result.
   */
  public function checkAccess(UserInterface $user, AccountInterface $account) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user
      ->id() == $account->id())->cachePerUser();
  }

The custom access callback is defined in tracker.routing.yml.

tracker.users_recent_content:
  path: '/activity/{user}'
  defaults:
    _controller: 'DrupaltrackerControllerTrackerController::buildContent'
    _title: 'My recent content'
  requirements:
    _permission: 'access content'
    _custom_access: 'DrupaltrackerControllerTrackerController::checkAccess'
    user: d+

postgresql – How to prevent implicit casting from bytea to text during the current connection in postgres?

for example if there are non-ASCII bytes it cannot work smoothly

Why would you think so? bytea is coerced to either hex (default) or escape format when assigned to a text column. Non-ASCII characters are encoded automatically. Should work “smoothly” at all times – except that you don’t want to allow it.

How do I make (implicit) casts from bytea to text throw an exception only within the current connection?

… I can add a preceding SQL statement before every statement, that’s no problem.

Solution with custom cast

Currently (all versions incl. Postgres 13) the cast from bytea to text has no explicit entry in the system catalog pg_cast. It is provided by basic input/output functions of the respective types. This behavior can be overruled with an explicit entry, created with CREATE CAST.

You need to be the owner of the involved types, so this basically means you have to be superuser install it.

Create this casting function once per database:

CREATE FUNCTION public.text(bytea, int, bool) 
  RETURNS text
  LANGUAGE plpgsql STABLE STRICT PARALLEL SAFE AS
$func$
BEGIN
   IF $3 THEN           -- true if the cast is an explicit cast, false otherwise.
     -- no infinite loop because we do the cast manually
     -- honors current setting for bytea_output, hence function not IMMUTABLE
      RETURN textin(byteaout($1));
   ELSE
      RAISE EXCEPTION 'Assignment cast from bytea to text forbidden by custom cast rules in this database!';
      RETURN textin(byteaout($1));  -- we should *never* get here!
   END IF;
END
$func$;

To allow creating / dropping the special cast to unprivileged roles, add wrapper functions. Do this as superuser (or as dedicated daemon role):

CREATE FUNCTION public.f_create_cast_bytea2text() 
  RETURNS void
  LANGUAGE sql SECURITY DEFINER AS
'CREATE CAST (bytea AS text) WITH FUNCTION public.text(bytea, int, bool) AS ASSIGNMENT;';

CREATE FUNCTION public.f_drop_cast_bytea2text() 
  RETURNS void
  LANGUAGE sql SECURITY DEFINER AS
'DROP CAST IF EXISTS (bytea AS text);';

Now you can do what you asked for:

BEGIN;
SELECT public.f_create_cast_bytea2text();  -- optionally activate your casting rule

INSERT INTO tbl(txt_col)
VALUES ('00'::bytea::text, 'local bytea_output: hex');    -- explicit cast still works!

INSERT INTO tbl(txt_col)
VALUES ('00'::bytea); -- but assignment cast forbidden! -> ERROR

SELECT public.f_drop_cast_bytea2text();  -- deactivate your casting rule
END;

db<>fiddle here — second half does not execute due to missing privileges.

Extended test case

Test table:

CREATE TABLE test(id int, txt_col text, note text);
INSERT INTO test(id, txt_col, note) VALUES
  (-1, 'foo', 'plain text input')
, ( 0, '00'::bytea, 'default bytea_output: ' || current_setting('bytea_output'));

No exception raised:

BEGIN;
SELECT public.f_create_cast_bytea2text();

SET LOCAL bytea_output = 'hex';
INSERT INTO test(id, txt_col, note)
VALUES (1, '00'::bytea::text, 'local bytea_output: hex');    -- explicit cast still works

SET LOCAL bytea_output = 'escape';
INSERT INTO test(id, txt_col, note)
VALUES (2, '00'::bytea::text, 'local bytea_output: escape'); -- explicit cast still works

SELECT public.f_drop_cast_bytea2text();
END;

Also no exception:

BEGIN;
SELECT public.f_drop_cast_bytea2text();

SELECT '00'::bytea || text 'foo'; -- implicit cast still works

SELECT public.f_drop_cast_bytea2text();
END;

Exception raised:

BEGIN;
SELECT public.f_create_cast_bytea2text();

INSERT INTO test(id, txt_col, note)
VALUES (3, '00'::bytea, 'must fail!'); -- assignment cast forbidden!

SELECT public.f_drop_cast_bytea2text();
END;