8 – Restrict translation and editing of node to one language

I found this in Workbench Access issue queue:
https://www.drupal.org/project/workbench_access/issues/2982941#comment-12670744

It seems as if I need to deactivate the translate *bundle* *node* permissions and create a hole bunch of new *translate *bundle* *node* *language* permissions on my own. In my case we have 15 node types and 6 languages. That would result in 90 new permissions. That is overwhelming.

I’m trying to restrict the access to creating and editing of nodes in the Drupal admin section to only one language for a user. I didn’t find a module which provides for this feature. Is there any module that does this?

I then tried to create my own module. I came up with this solution

File: custom_i18n_access.module

<?php

use DrupalnodeNodeInterface;
use DrupalCoreSessionAccountInterface;
use DrupalCoreAccessAccessResult;


/**
 * Implements hook_node_access().
 *
 * Prevent editor role to edit and/or delete fr/en nodes. Quick and dirty.
 */
function custom_i18n_access_node_access(NodeInterface $node, $op, AccountInterface $account)
{

    $roles = $account->getRoles();

    if (in_array('administrator', $roles)) {
        return AccessResult::neutral();
    }

    if ($op !== 'update' && $op !== 'delete') {
        return AccessResult::neutral();
    }

    // Access should be restricted only if this permission is set
    if (!$account->hasPermission('custom_i18n_access_restrict')) {
        return AccessResult::neutral();
    }
    
    $current_language = Drupal::languageManager()->getCurrentLanguage();
    $lang             = $current_language->getId();

    if ($account->hasPermission("custom_i18n_access_{$lang}_allow")) {
        return AccessResult::neutral();
    }
    return AccessResult::forbidden();
}

File: custom_i18n_access.permissions.yml

permission_callbacks:
  - Drupalcustom_i18n_accessPermissions::permissions

File: src/Permissions.php

<?php

namespace Drupalcustom_i18n_access;

class Permissions {
    public function permissions() {
        $languages = Drupal::languageManager()->getLanguages();

        $permissions("custom_i18n_access_restrict") = (
            'title' => t("Restrict language access"),
            'description' => 'Restrict the edit access of nodes',
        );

        foreach($languages as $lang) {
            $permissions("custom_i18n_access_{$lang->getId()}_allow") = (
                'title' => t("Allow to edit @lang content", ('@lang' => $lang->getName())),
            );
        }

        return $permissions;
    }
}  

This custom module successfully restricts the editing and deleting of existing content to only the language I specified in the permissions. But it does not prevent new translations of the content into other languages.

As I see it, the HOOK_node_access hook is not called for every language when on the translations subtask page. How can I achieve this? Is there a different hook for that? I didn’t find any help online.

closure properties – How to show that language L is NOT context-free?

True or false: To show that a language L is not context-free, one can alternatively show that the union between L and a known context-free language is not context-free.

I know that you can prove closure under context-free languages using union, but does the above work, too? Any help you can provide would be greatly appreciated!

event subscriber – Age verification does not redirect to intended language

I have a multi-lingual site and found an age verification module which am trying to tweak.
If I select the English option, the age gate redirects to the global site as intended. However, if I choose a different language, the site redirects back to the age-gate page.

The submitForm method looks like this:

public function submitForm(array &$form, FormStateInterface $form_state) {

  $age = $this->checkAge($form_state);
  if ($age < 18) {
    setcookie('age_gate_fail', 1, strtotime( '+1 days' ), '/');
    $welcome = newSymfonyComponentHttpFoundationRedirectResponse('https://google.com');
    $welcome->send();

  } else {

    // Add TRUE to session age_verified.
    $session = Drupal::request()->getSession();
    $session->set('age_verified', 1);

    setcookie('age_gate_ok', 1, strtotime( '+1 days' ), '/');
    setcookie('age_gate_country', $form_state->getValue("country"), strtotime( '+1 days' ), '/');
    setcookie('day', $form_state->getValue("day"), strtotime( '+1 days' ), '/');
    setcookie('month', $form_state->getValue("month"), strtotime( '+1 days' ), '/');
    setcookie('year', $form_state->getValue("year"), strtotime( '+1 days' ), '/');

    if(Settings::get('local_env')) {

      // Add a redirect to requested page. Using $form_state built in redirects.
      $redirect = $session->get('age_verification_path');
      if (!empty($redirect)) {
        $form_state->setRedirect($redirect);
        $form_state->setRedirect("/{$form_state->getValue("language")}");
      }

      $form_state->setRedirect('<front>');

    } else {

      if($form_state->getValue("language") == 'en') {
        $form_state->setRedirect('<front>');
      } else {
        $host = Drupal::request()->getHost();
        $welcome = newSymfonyComponentHttpFoundationRedirectResponse("http://$host/{$form_state->getValue("language")}");
        $welcome->send();
      }
    }
  }
}

The module comes with the EventSubscriber and the content inside is as follows:

<?php

/**
*
* Contains Drupalage_verificationEventSubscriberpathGate.
*/

// Declare the namespace for our own event subscriber.
namespace Drupalage_verificationEventSubscriber;

use SymfonyComponentHttpFoundation;
use SymfonyComponentHttpFoundationRedirectResponse;
use SymfonyComponentHttpKernelKernelEvents;
use SymfonyComponentHttpKernelEventFilterResponseEvent;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use DrupalCorePathPathMatcherInterface;
use DrupalCoreSessionAccountInterface;
use DrupalCoreRoutingTrustedRedirectResponse;


/**
* Event Subscriber PathGate.
*/
class PathGate implements EventSubscriberInterface {
/**
   * The path matcher.
   *
   * @var DrupalCorePathPathMatcherInterface
   */
  protected $pathMatcher;

  /**
   * The current user.
   *
   * @var DrupalCoreSessionAccountInterface
   */
  protected $currentUser;

  /**
   * Constructs a new Redirect404Subscriber.
   *
   * @param DrupalCorePathPathMatcherInterface $path_matcher
   *   The path matcher service.
   * @param DrupalCoreSessionAccountInterface $current_user
   *   Current user.
   */
  public function __construct(PathMatcherInterface $path_matcher, AccountInterface $current_user) {
    $this->pathMatcher = $path_matcher;
    $this->currentUser = $current_user;
  }

  /**
   * Code that should be triggered on event specified.
  */
  public function onRespond(FilterResponseEvent $event) {
    // The RESPONSE event occurs once a response was created for replying to a request.
    // For example you could override or add extra HTTP headers in here.
    $response = $event->getResponse();

    $session = Drupal::request()->getSession();

    $age_verified = $session->get('age_verified');

    // If we have a valid session.
    if ( $age_verified == TRUE ) {
            return;
    }
    if (isset($_COOKIE('age_gate_fail'))) {
      $welcome = newSymfonyComponentHttpFoundationRedirectResponse('https://google.com');
      $welcome->send();
    }

    // Make sure front page module is not run when using cli (drush).
    // Make sure front page module does not run when installing Drupal either.
    if (PHP_SAPI === 'cli' || drupal_installation_attempted()) {
      return;
    }

    // Don't run when site is in maintenance mode.
    if (Drupal::state()->get('system.maintenance_mode')) {
      return;
    }

    // Ignore non index.php requests (like cron).
    if (!empty($_SERVER('SCRIPT_FILENAME')) && realpath(DRUPAL_ROOT . '/index.php') != realpath($_SERVER('SCRIPT_FILENAME'))) {
      return;
    }

    // Get saved settings and other needed objects.
    $config = Drupal::config('age_verification.settings');

    // Now we need to explode the age_verification_user_agents field to separate
    // lines.
    $user_agents = explode("n", $config->get('age_verification_user_agents'));
    $http_user_agent = Drupal::request()->server->get('HTTP_USER_AGENT');

    // For each one of the lines we want to trim white space and empty lines.
    foreach ($user_agents as $key => $user_agent) {
      // If a user has string from $user_agent.
      if (empty($user_agent)) {
        unset($lines($key));
      }
      // To be sure we match proper string, we need to trim it.
      $user_agent = trim($user_agent);

      if ($http_user_agent == $user_agent) {
        return;
      }
    }

    // Send to proper page if logged in.
    $skip_urls_config = $config->get('age_verification_urls_to_skip');

    $skip_urls() = '/admin';
    $skip_urls() = '/admin/*';
    $skip_urls() = '/age-verification';
    $skip_urls() = '/user/login';
    $skip_urls() = '/admin/content';

    if (!Drupal::currentUser()->isAnonymous()) {
        $skip_urls() = '/*';
    }

    // Append the urls to skips with some hardcoded urls.
    $skipPaths = $skip_urls_config . "rn" . implode("rn", $skip_urls);

    $request_path = Drupal::service('path.current')->getPath();

    // Check if the paths don't match then redirect to the age verification form.
    $match = Drupal::service('path.matcher')->matchPath($request_path, $skipPaths);
    $is_front = Drupal::service('path.matcher')->isFrontPage();

    // If not the front page then append the requested path alias as a destination parameter.
    if ($is_front == FALSE) {
      $current_uri = Drupal::request()->getRequestUri();
      $destination = '?destination=' . $current_uri;
          
    } else {
      $destination = '';
    }

    // If the requested path is not restricted.
    if ($match == TRUE) {
      return;
    }
    // Redirect to the /age-verification with the destination.
    elseif ($match == FALSE) {

      $redirect = new RedirectResponse('/age-verification' . $destination);
      $event->setResponse($redirect);
    }

  }

  /**
     * {@inheritdoc}
     */
  public static function getSubscribedEvents() {

    $events(KernelEvents::RESPONSE)() = ('onRespond');
    return $events;

  }

}

How do I fix the redirect to take me to any language I want

I will provide you with five professional courses to learn English language with high quality for $10

I will provide you with five professional courses to learn English language with high quality

English is one of the easiest languages to learn, isn’t it? Get ready for your IELTS or TOEFL with these five courses.

What you’ll learn

  • By studying these courses you will attain the standard of English needed to

    express yourself and your ideas clearly.
  • This will benefit you in your current workplace, in finding new jobs and in all

    areas of future study.
  • When you have completed Everyday English, you will be ideally placed to

    progress to Business English or IELTS course.
  • English Grammar Test is available

Description

Nowadays in the competitive job market, it is necessary to speak English. However English is not only the most useful language in the world. It is also one of the easiest languages to learn. If you want a good job in business, technology, or science, then you must start learning English. And… with a native speaker, you will also gain a bit of British accent. Each lesson of these courses begins with a set of clearly stated objectives and an explanation of its place in the the overall program of study. There are 5-courses self-assessment tests and activities to measure your progress within each lesson.  So, join the courses and brush up your English before taking any English test. Topics Covered  Spelling Sentence structure and construction Infinitives and Gerund Tenses Verbs Comprehension and composition Everyday Expressions

The relevant courses are:
1-TEFL Course Teach English Online As A Foreign Language

2-The Complete Punctuation Course English Writing – Grammar

3-English Grammar tenses & structures

4-Learn Fluent English – For Students & Business Professionals

5-English Speaking People’s Appearance and Character

.

How to interpret this context free language?

$S to aAA$

$A to aS mid bS mid a$

Trivial thing:

starting and ending with a

Atleast 3 a’s are definitely present

(These are very layman observations…but seriously I am unable to figure out what exactly this language is all about. …)
My attempt:

What I am able to generate

1)aaa

2)aAA

a bS A

a ba AA A

a ba ***

This suggests after b there should be atleast 1 a

*(Coz those *** have all

  1. a’s

or

  1. if bS used then again a ‘ba**’

Or

  1. if aS used length also increases by atleast 3.)*

I know this is not a good analysis..and so I am not expecting any answer but would definitely expect some comments about some intuition or idea..plz any help would be much regarded..

(Although answers are always welcome 😉 )

How to deal with metaclasses in strong-typed language : is it ok to mix classes and metaclasses?

I’m working on a programming language design ans I’m struggling with how I should type the concept of Class.

Let me show you some code to illustrate my problem :

class MyClass
{

}

function doSomething(item : MyClass)
{
    return ...
}

a = new MyClass
doSomething(a)

As you can see, this function takes one parameter whose type is MyClass.

Now, I also need the classes to work as first class citizens so that classes themselves could be taken as function parameters or returned.

Keeping the same logic, we can introduce a Class class, like so :

class MyClass
{

}

function doSomethingOnClass(class : Class)
{
    return ...
}

doSomethingOnClass(MyClass)

Here, the class parameter should be a class, not an instance.

What bothers me is the semantic of the Class class. Since Class is the type of all classes, it is a metaclass. We also need to assume that the type of the Class class is Class itself.

But, we some rigor and formalism, is it ok to treat classes and metaclasses the same way since they represent different levels of conceptualisation ?

The same questions could be extended to any other language element that could be treated as first class citizens (class properties …)

How to set C++ language standard for VS2019 in an Unreal project?

I am trying to a simple thing, just like that, in a header file;

#include <filesystem>
#include <iostream>
 
namespace fs = std::filesystem;
 

And IntelliSense goes:
namespace std has no member filesystem.

Okay no worries, it’s an easy fix.
Just set the C++ language standard in the propery pages…

Well, it turns out it isn’t, it’s not an option in Unreal VS project. Tried typing in search bar, View -> Property pages, but no luck.

Okay let’s try doing the whole thing in a console project first.

Same message from IntelliSense as before.

Ok, no worries, I found this.

I found my settings under: Project > projectname Properties

And voila, the console app works.

Let’s try it in the Unreal project.

Well, well… My options are limited here.

myueoptions

I had a look around in the project settings as well:

projectsettings

How do I get this filesystem header work with my project?

How can Kneser-Ney Smoothing be integrated into a neural language model?

I found a paper titled Multimodal representation: Kneser-Ney Smoothing/Skip-Gram based neural language model. I am curious about how the Kneser-Ney Smoothing technique can be integrated into a feed-forward neural language model with one linear hidden layer and a softmax activation. What is the purpose of the Kneser-Ney in such a neural network, and how can it be used for learning the conditional probability for the next word?