Synchronizes all controllers and existing actions to the database

@param boolean/String $prefix
@param boolean/String $plugin
@param array $permission_ids
@return array $permission_ids
354089
public function synchronize( $prefix = false, $plugin = false, array $permission_ids = [] )
    {
        $classname = '';
        if( !$plugin ) {
            $path = App::path('Controller/'.$prefix)[0];
        } else if( $plugin && is_string($prefix) ) {
            $path = App::path('Controller/' . $prefix, $plugin)[0];
            $classname = $plugin . '.';
        }

        $type_prefix = ( $prefix === '/' || is_bool($prefix) ) ? '' : '/'.$prefix;
        $Permission = TableRegistry::get('Permission');
        $files = scandir($path);
        $this->all_files = array_merge($this->all_files, $files);
        foreach($files as $file) {

            if(in_array($file, $this->_sync_ignore_list['*']) ||
                ( isset($this->_sync_ignore_list[$prefix]) && in_array($file, $this->_sync_ignore_list[$prefix]) )
            ) continue;

            if( is_dir($path.$file) ) {
                if( $prefix || !$plugin )
                    $permission_ids = $this->synchronize($file, $plugin, $permission_ids);
                else if( $plugin )
                    $permission_ids = $this->synchronize('/', $file, $permission_ids);
                continue;
            }

            $controller_name = str_replace('Controller', '', explode('.', $file)[0]);
            $class_name = App::classname($classname.$controller_name, 'Controller'.$type_prefix, 'Controller');
            if( empty($class_name) ) continue;
            $class = new ReflectionClass($class_name);
            $all_actions = $class->getMethods(ReflectionMethod::IS_PUBLIC);

            foreach($all_actions as $action) {
                $permission_prefix = '';
                if( $plugin )
                    $permission_prefix .= $plugin.'.';
                if( $prefix )
                    $permission_prefix .= $prefix;

                $class = new ReflectionClass($action->class);
                $file_name = explode('/',$class->getFileName());
                $file_name = end($file_name);
                if( in_array($file_name, $this->_sync_ignore_list['*']) || ($action->class != $class_name && !in_array($file_name, $this->all_files)) ||
                    in_array($action->name, $this->_sync_ignore_list['*']['*']) ||
                    ( isset($this->_sync_ignore_list['*'][$controller_name]) && in_array($action->name, $this->_sync_ignore_list['*'][$controller_name]) ) ||
                    ( isset($this->_sync_ignore_list[$permission_prefix]['*']) && in_array($action->name, $this->_sync_ignore_list[$permission_prefix]['*']) ) ||
                    ( isset($this->_sync_ignore_list[$permission_prefix][$controller_name]) && in_array($action->name, $this->_sync_ignore_list[$permission_prefix][$controller_name]) )
                ) continue;

                $unique_string = $this->getUniqueString($controller_name, $action->name, $prefix, $plugin);
                $permission_id = $Permission->find()
                    ->select(['id'])
                    ->where(['unique_string' => $unique_string])
                    ->first();

                if (is_null($permission_id)) {
                    $new_permission = $Permission->newEntity();
                    $new_permission->action = $action->name;
                    $new_permission->controller = $controller_name;
                    $new_permission->prefix = $permission_prefix;
                    $new_permission->unique_string = $unique_string;

                    if ($Permission->save($new_permission))
                        array_push($permission_ids, $new_permission->id);

                } else {
                    array_push($permission_ids, $permission_id->id);
                }
            }
        }

        if( !$plugin && !$prefix ) {
            foreach( $this->_plugins as $plugin )
                $permission_ids = $this->synchronize('/', $plugin, $permission_ids);

            $Permission->deleteAll(['id NOT IN'=>$permission_ids]);
        }

        return $permission_ids;
    }
1013858
public function buildAllowed($role, $explicit_permissions = [])
    {
        $paths = [];

        $controllers = [];
        foreach (glob($this->alias->get('@app') . '/Areas/*/Controllers/*Controller.php') as $item) {
            $controller = str_replace($this->alias->get('@app'), $this->alias->get('@ns.app'), $item);
            $controllers[] = str_replace('/', '\\', substr($controller, 0, -4));
        }

        foreach (glob($this->alias->get('@app') . '/Controllers/*Controller.php') as $item) {
            $controllers[] = $this->alias->get('@ns.app') . '\\Controllers\\' . basename($item, '.php');
        }

        foreach ($controllers as $controller) {
            /** @var  \ManaPHP\Rest\Controller $controllerInstance */
            $controllerInstance = new $controller();
            $acl = $controllerInstance->getAcl();

            foreach (get_class_methods($controller) as $method) {
                if (preg_match('#^(.*)Action$#', $method, $match)) {
                    $action = $match[1];
                    $path = $this->generatePath($controller, $action);
                    if ($this->isAclAllow($acl, $role, $action)) {
                        $paths[] = $path;
                    } elseif (in_array($path, $explicit_permissions, true)) {
                        $paths[] = $path;
                    } elseif (isset($acl[$action]) && $acl[$action][0] === '@') {
                        $real_path = $this->generatePath($controller, substr($acl[$action], 1));
                        if (in_array($real_path, $explicit_permissions, true)) {
                            $paths[] = $path;
                        }
                    }
                }
            }
        }

        return $paths;
    }
44390
public function canExtended($resource_id, $method_code, $action, $module_id = null) : bool {
		// rearrange controllers
		if (!isset(self::$cached_controllers_by_ids)) {
			self::$cached_controllers_by_ids = [];
			foreach (self::$cached_controllers as $k => $v) {
				self::$cached_controllers_by_ids[$v['id']] = $k;
			}
		}
		// if we got a string
		if (is_string($resource_id)) {
			$resource_id = self::$cached_controllers[$resource_id]['id'] ?? null;
		}
		// if resource is not present we return false
		if (empty(self::$cached_controllers_by_ids[$resource_id])) return false;
		// missing features
		if (!empty(self::$cached_controllers[self::$cached_controllers_by_ids[$resource_id]]['missing_features'])) return false;
		// super admin
		if (\User::get('super_admin')) return true;
		// load all actions from datasource
		if (is_null(self::$cached_actions) && !\Object\Error\Base::$flag_database_tenant_not_found) {
			self::$cached_actions = \Object\ACL\Resources::getStatic('actions', 'primary');
		}
		if (is_string($action)) $action = self::$cached_actions[$action]['id'];
		// see if we have permission overrides
		$permissions = \User::get('permissions');
		if (!empty($permissions)) {
			// process permissions
			$all_actions = $permissions[$resource_id]['AllActions'][-1] ?? [];
			$actual_action = $permissions[$resource_id][$method_code][$action] ?? [];
			$temp = array_merge_hard($all_actions, $actual_action);
			if (!empty($temp)) {
				if (!empty($module_id)) {
					$temp = $temp[$module_id] ?? null;
				} else { // find any active permision
					$temp2 = $temp;
					$temp = null;
					foreach ($temp2 as $k => $v) {
						if ($v === 0) {
							$temp = 0;
							break;
						}
					}
				}
			}
			if ($temp === 0) {
				return true;
			} else if ($temp === 1) {
				return false;
			}
		}
		// load user roles
		$roles = \User::roles();
		// authorized controllers have full access
		if (empty(self::$cached_controllers[self::$cached_controllers_by_ids[$resource_id]]['acl_permission']) && !empty(self::$cached_controllers[self::$cached_controllers_by_ids[$resource_id]]['acl_authorized'])) {
			// if user is logged in
			if (\User::authorized()) return true;
		}
		// go through roles
		foreach ($roles as $v) {
			$temp = $this->processRole($v, $resource_id, $method_code, $action, $module_id);
			if ($temp === 1) {
				return true;
			} else if ($temp === 2) {
				return false;
			}
		}
		// go through teams
		foreach (\User::teams() as $v) {
			$temp = $this->processTeam($v, $resource_id, $method_code, $action, $module_id);
			if ($temp === 1) {
				return true;
			} else if ($temp === 2) {
				return false;
			}
		}
		return false;
	}
519961
private static function get_active_plugins( $blog_id = 0 ) {
            self::require_plugin_essentials();

            $active_plugin            = array();
            $all_plugins              = fs_get_plugins();
            $active_plugins_basenames = self::get_active_plugins_basenames( $blog_id );

            foreach ( $active_plugins_basenames as $plugin_basename ) {
                $active_plugin[ $plugin_basename ] = $all_plugins[ $plugin_basename ];
            }

            return $active_plugin;
        }
1335849
protected function getPermissionNoBypassChecks($permissions, array $context, array $typeKeys): array
    {
        if (is_array($permissions) && array_key_exists('NO_BYPASS', $permissions)) {
            return $this->getPermissionChecks($permissions['NO_BYPASS'], $context, $typeKeys);
        }

        return [];
    }
638724
function _get_license_by_id( $id, $sync_licenses = true ) {
            $this->_logger->entrance();

            if ( ! FS_Plugin_License::is_valid_id( $id ) ) {
                return false;
            }

            /**
             * When running from the network level admin and opted-in from the network,
             * check if the license exists in the network user licenses collection.
             *
             * @author Vova Feldman (@svovaf)
             * @since  2.0.0
             */
            if ( fs_is_network_admin() &&
                 $this->is_network_registered() &&
                 ( ! is_object( $this->_user ) || $this->_storage->network_user_id != $this->_user->id )
            ) {
                $licenses = $this->get_user_licenses( $this->_storage->network_user_id );

                foreach ( $licenses as $license ) {
                    if ( $id == $license->id ) {
                        return $license;
                    }
                }
            }

            if ( ! $this->has_any_license() && $sync_licenses ) {
                $this->_sync_licenses( $id );
            }

            if ( is_array( $this->_licenses ) ) {
                foreach ( $this->_licenses as $license ) {
                    if ( $id == $license->id ) {
                        return $license;
                    }
                }
            }

            return false;
        }
142467
private function _saveRolePermissions($request, $role)
    {
        $permissionIds = [];

        if (count($request->get('permissions')) > 0) {
            foreach ($request->get('permissions') as $key => $value) {
                if ($value != 1) {
                    continue;
                }
                $permissions = explode(',', $key);
                foreach ($permissions as $permissionName) {
                    if (null === ($permissionModel = Permission::getPermissionByName($permissionName))) {
                        $permissionModel = Permission::create(['name' => $permissionName]);
                    }
                    $permissionIds[] = $permissionModel->id;
                }
            }
        }
        $ids = array_unique($permissionIds);
        $role->permissions()->sync($ids);
    }
1240187
public function isPermissionAssigned($permissionId, $roleIds)
    {
        $qb = $this->createQueryBuilder('rolePermission');

        $result = $qb
            ->select('rolePermission.id')
            ->where(
                $qb->expr()->andX(
                    $qb->expr()->eq('rolePermission.permissionId', $permissionId),
                    $qb->expr()->in('rolePermission.roleId', $roleIds)
                )
            )
            ->setMaxResults(1)
            ->getQuery()
            ->getArrayResult();

        return count($result) > 0;
    }
107208
function(plugins) {
		var p = this._plugins;
		([]).concat(plugins).forEach(function(plugin) {
			if (p.indexOf(plugin) === -1) {
				p.push(plugin);
			}
		});

		this._cacheId++;
	}
71511
private function buildSystemPermissions($id): void
    {
        foreach ($this->configs as $config) {
            foreach ($config->getOperations() as $operation) {
                $field = PermissionUtils::getMapAction(null);
                $this->cache[$id][$config->getType()][$field][$operation] = true;
            }

            foreach ($config->getFields() as $fieldConfig) {
                foreach ($fieldConfig->getOperations() as $operation) {
                    $this->cache[$id][$config->getType()][$fieldConfig->getField()][$operation] = true;
                }
            }
        }
    }
1197851
public function rolePermissionAdd(Role $role, Permission $permission)
    {
        if (!$role->role_id or !$permission->permission_id) {
            throw new ValidationError("Invalid Role/Permission state");
        }
        $query = "
            INSERT INTO
                auth_role_permissions (role_id, permission_id, added_on)
            VALUES
                (:role_id, :permission_id, " . $this->sql_time_func . ")
        ";
        $cur = $this->db->prepare($query);
        $cur->bindParam(":role_id", $role->role_id, PDO::PARAM_INT);
        $cur->bindParam(":permission_id", $permission->permission_id, PDO::PARAM_INT);
        $this->db->beginTransaction();
        try {
            $cur->execute();
            $this->db->commit();
        } catch (PDOException $db_err) {
            $this->db->rollBack();
            if ($this->logger) {
                $this->logger->error("Failed to add permission to role", ['exception' => $db_err]);
            }
            return false;
        }
        return true;
    }
215045
public function syncPermissions($permissions)
    {
        $mappedPermissions = [];

        foreach ($permissions as $permission) {
            $mappedPermissions[] = Helper::getIdFor($permission, 'permission');
        }

        $changes = $this->permissions()->sync($mappedPermissions);
        $this->flushCache();
        $this->fireLaratrustEvent("permission.synced", [$this, $changes]);

        return $this;
    }
165374
protected function dispatch($permissions, $type = NULL, $context = NULL) {
    if(is_bool($permissions)) {
      return $this->dispatchBoolean($permissions, $type, $context);
    }

    if(is_string($permissions)) {
      return $this->dispatchString($permissions, $type, $context);
    }

    if(is_array($permissions)) {
      return $this->dispatchArray($permissions, $type, $context);
    }

    throw new InvalidArgumentTypeException("A permission must either be a boolean, a string or an array. Evaluated permissions: " . print_r($permissions, TRUE));
  }
601202
public function syncPermissions($permissions = [], $team = null, $detaching = true)
    {
        return $this->syncModels('permissions', $permissions, $team, $detaching);
    }
770478
private function getPermissionActions()
    {
        $actions = [];

        /**
         * @var $route \Symfony\Component\Routing\Route
         */
        foreach ($this->get('router')->getRouteCollection()->all() as $name => $route) {
            if ($route->hasOption('require_admin_permission')) {
                list(, $action) = explode('.', $route->getOption('require_admin_permission'));
                $actions[$action] = [
                    'id'   => $action,
                    'name' => $action
                ];
            }
        }

        ksort($actions);

        return array_values($actions);
    }
614793
public function createInstances(array $plugin_ids, array $configurations = []) {
    $instances = [];

    foreach ($plugin_ids as $plugin_id) {
      $configuration = isset($configurations[$plugin_id]) ? $configurations[$plugin_id] : [];
      $instances[$plugin_id] = static::createInstance($plugin_id, $configuration);
    }

    return $instances;
  }
1001815
public function registerPermissions(PluginPermissionsEvent $event)
    {
        $event->registerPermissions($this->translator->trans('plugin.ingest.permissions.label'), array(
            'plugin_ingest_settings' => $this->translator->trans('plugin.ingest.permissions.settings')
        ));
    }