Protect Crud functions of controller.

@return string
7083
protected function protectMethods()
    {
        $request = $this->request;

        // available methods for resources.
        $resources = $this->crud['resources'];

        // protection methods being passed in a route.
        $methods = $this->getAction('protect_methods');

        // get method being called on controller.
        $caller = $this->parseMethod();

        // determine if we use resource or restful http method to protect crud.
        $called = in_array($caller, $resources) ? $caller : $request->method();

        // if controller is a resource or closure
        // and does not have methods like
        // UserController@index but only
        // UserController we use crud restful.
        $methods = is_array($methods) ? $methods :
            (in_array($caller, $resources) ?
                $this->crud['resource'] : $this->crud['restful']);

        // determine crud method we're trying to protect
        $crud = $this->filterMethods($methods, function ($k, $v) use ($called) {
            return in_array($called, $v);
        });

        // crud method is read, view, delete etc
        // match it against our permissions
        // view.user or delete.user
        // multiple keys like create,store?
        // use OR operator and join keys with alias.
        $permission = implode('|', array_map(function ($e) {
            return $e . '.' . $this->parseAlias();
        }, array_keys($crud)));

        return ! $this->forbiddenRoute() && $request->user()->can($permission);
    }
869419
final private function __setDataFromMethods()
    {
        // Get all public methods from class
        $this->methods = $this->class->getMethods(\ReflectionMethod::IS_PUBLIC);

        // Remove __contruct, __init, __finalize and this class methods from $this->methods
        $this->methods = array_filter($this->methods, function ($method) {
            return
                $method->class !== 'Sober\Controller\Controller' &&
                $method->name !== '__construct' &&
                $method->name !== '__before' &&
                $method->name !== '__after';
        });

        // Get all public static methods from class
        $this->staticMethods = $this->class->getMethods(\ReflectionMethod::IS_STATIC);

        // Remove $this->staticMethods from $this->methods using array_diff
        $this->dataMethods = array_diff($this->methods, $this->staticMethods);

        // Filter the remaining data methods
        $this->dataMethods = array_filter($this->dataMethods, function ($method) {
            return $method = $method->name;
        });

        // For each method convert method name to snake case and add to data[key => value]
        foreach ($this->dataMethods as $method) {
            // Convert method name to snake case
            $var = Utils::convertToSnakeCase($method->name);

            // Add var method name to data[]
            $this->data[$var] = $this->{$method->name}();
        }
    }
360215
protected function crudConfigOverride()
    {
        // Override crud restful from config.
        if ( ($restful = config('acl.crud.restful')) != null ) {
            $this->crud['restful'] = $restful;
        }

        // Override crud resource from config.
        if ( ($resource = config('acl.crud.resource')) != null ) {
            $this->crud['resource'] = $resource;
        }
    }
57592
public function onBeforeInit()
    {
        $disallowed_controllers = [
            DevelopmentAdmin::class,
            DevBuildController::class,
            DatabaseAdmin::class
        ];

        // Don't run this during dev/build or dev/tasks
        if (!in_array(get_class($this->owner), $disallowed_controllers)) {
            // Set global local based on Site Config
            $config = SiteConfig::current_site_config();
            i18n::set_locale($config->SiteLocale);

            // Now find and set the desired currency symbol
            $number_format = new NumberFormatter($config->SiteLocale, NumberFormatter::CURRENCY);
            $symbol = $number_format->getSymbol(NumberFormatter::CURRENCY_SYMBOL);
            DBCurrency::config()->currency_symbol = $symbol;
        }
    }
587356
protected function _handlers()
    {
        $gmstrtotime = function ($value) {
            $TZ = date_default_timezone_get();
            if ($TZ === 'UTC') {
                return strtotime($value);
            }
            date_default_timezone_set('UTC');
            $time = strtotime($value);
            date_default_timezone_set($TZ);
            return $time;
        };

        return [
            'array' => [
                'object' => function($value, $column) {
                    return $value->to('array', $column);
                },
                'string' => function($value, $column) {
                    return (string) $value;
                },
                'integer' => function($value, $column) {
                    return (int) $value;
                },
                'float' => function($value, $column) {
                    return (float) $value;
                },
                'date' => function($value, $column) {
                    return $this->convert('array', 'datetime', $value, ['format' => 'Y-m-d']);
                },
                'datetime' => function($value, $column) use ($gmstrtotime) {
                    $column += ['format' => 'Y-m-d H:i:s'];
                    $format = $column['format'];
                    if ($value instanceof DateTime) {
                        return $value->format($format);
                    }
                    return gmdate($format, is_numeric($value) ? $value : $gmstrtotime($value));
                },
                'boolean' => function($value, $column) {
                    return $value;
                },
                'null' => function($value, $column) {
                    return;
                },
                'json' => function($value, $column) {
                    return is_array($value) ? $value : $value->to('array', $column);
                }
            ],
            'cast' => [
                'object' => function($value, $column, $options) {
                    return is_array($value) ? new Document([
                        'schema' => $options['schema'] ?? null,
                        'basePath' => $options['basePath'] ?? null,
                        'data' => $value
                    ]) : $value;
                },
                'string' => function($value, $column, $options) {
                    return (string) $value;
                },
                'integer' => function($value, $column, $options) {
                    return (integer) $value;
                },
                'float'   => function($value, $column, $options) {
                    return (float) $value;
                },
                'decimal' => function($value, $column, $options) {
                    $column += ['precision' => 2, 'decimal' => '.', 'separator' => ''];
                    return number_format($value, $column['precision'], $column['decimal'], $column['separator']);
                },
                'boolean' => function($value, $column, $options) {
                    return !!$value;
                },
                'date'    => function($value, $column, $options) {
                    return $this->convert('cast', 'datetime', $value, ['format' => 'Y-m-d'], $options);
                },
                'datetime'    => function($value, $column, $options) use ($gmstrtotime) {
                    $column += ['format' => 'Y-m-d H:i:s'];
                    if ($value instanceof DateTime) {
                        return $value;
                    }
                    $timestamp = is_numeric($value) ? $value : $gmstrtotime($value);
                    if ($timestamp < 0 || $timestamp === false) {
                        return;
                    }
                    return DateTime::createFromFormat("!{$column['format']}", gmdate($column['format'], $timestamp), new DateTimeZone('UTC'));
                },
                'null'    => function($value, $column, $options) {
                    return null;
                },
                'json' => function($value, $column, $options) {
                    return is_string($value) ? json_decode($value, true) : $value;
                }
            ]
        ];
    }
242029
function run()
    {
        $res = $this->resolve();

        $ctrl = isset($res['controller']) && $res['controller'] !== null ? $res['controller'] : $this->defaultController;
        $action = isset($res['action']) && $res['action'] !== null ? $res['action'] : $this->defaultAction;

        //Name format to Controller namespace
        $tmp = explode('\\', str_replace('/', '\\', $ctrl));
        $ctrl = '\\Controller';
        foreach($tmp as $tmp1){
            $ctrl .= '\\'.ucfirst($tmp1);
        }

        //instantiate the controller
        $controller = new $ctrl(['params' => $res['params'], 'request' => $this->request]);

        $this->params = $res['params'];

        if (method_exists($controller, $action))
            return $controller->$action();
        else
            return $controller->{static::$defaultAction}();
    }
1120480
protected function getTaskClass()
    {
        $info = "Generate controller '{$this->getControllerName()}'...";
        $class = CreateController::class;
        if (null !== $this->getEntityName()) {
            $info = "Generate CRUD controller '{$this->getControllerName()}'...";
            $class = CreateCrudController::class;
        }
        $this->output->writeln("<info>{$info}</info>");
        return $class;
    }
198788
public function actionSave()
    {
        $user_id = \Yii::$app->request->post('user_id');
        $menu_ids = \Yii::$app->request->post('menu_ids');
        $username = \Yii::$app->request->post('username');
        $nickname = \Yii::$app->request->post('nickname');
        $source_password = \Yii::$app->request->post('source_password');
        $group_ids = (array)\Yii::$app->request->post('group_ids');
        $is_group_access = \Yii::$app->request->post('is_group_access');
        $is_user_access = \Yii::$app->request->post('is_user_access');
        $is_system = \Yii::$app->request->post('is_system');
        $note = \Yii::$app->request->post('note');
        $status = \Yii::$app->request->post('status');

        $groupIdsStr = '';
        if ($group_ids) {
            $groupIdsStr = join(',', array_filter($group_ids, function ($groupId) {
                return DpAdminGroup::getByGroupId($groupId);
            }));
        }

        $saveData = [
            'username' => $username,
            'nickname' => $nickname,
            'source_password' => $source_password,
            'group_ids' => $groupIdsStr,
            'is_group_access' => $is_group_access,
            'is_user_access' => $is_user_access,
            'is_system' => $is_system,
            'note' => $note,
            'status' => $status,
        ];
        if ($user_id) {
            $obj = DpAdminUser::find()
                ->where([
                    'user_id' => $user_id
                ])
                ->one();
            if (!$obj) {
                return $this->renderError('保存失败，记录不存在！');
            }
        } else {
            $obj = new DpAdminUser();
        }
        $obj->setAttributes($saveData);
        if (!$obj->save()) {
            foreach ($obj->getErrors() as $error) {
                foreach ($error as $message) {
                    return [
                        'success' => false,
                        'msg' => $message,
                    ];
                }
            }
        }
        // 用户关联的菜单权限更新
        DpAdminUserMenuRelation::deleteByUserId($obj->user_id);
        if ($menu_ids) {
            $menuIdArr = array_filter(StringHelper::explode($menu_ids, ',', true, true), function ($menuId) {
                return DpAdminMenu::getByMenuId($menuId);
            });
            if ($menuIdArr) {
                foreach ($menuIdArr as $menuId) {
                    $linkObj = new DpAdminUserMenuRelation();
                    $linkObj->setAttributes([
                        'user_id' => $obj->user_id,
                        'menu_id' => $menuId,
                    ]);
                    $linkObj->save();
                }
            }
        }

        return $this->renderSuccess('保存成功');
    }
952631
public function getModelNameHtmlAttribute()
    {
        $class = Decoy::controllerForModel($this->model);

        // There is not a controller for the model
        if (!$class || !class_exists($class)) {
            return sprintf('<b><a href="%s">%s</a></b>',
            $this->filterUrl(['model' => $this->model]),
            preg_replace('#(?<!\ )[A-Z]#', ' $0', $this->model));
        }

        // There is a corresponding controller class
        $controller = new $class;
        return sprintf('<b class="js-tooltip" title="%s"><a href="%s">%s</a></b>',
            htmlentities($controller->description()),
            $this->filterUrl(['model' => $this->model]),
            Str::singular($controller->title()));
    }
1003380
public function generateController()
    {
        if (!$content = $this->getControllerContent()) {
            return '';
        }

        $path = app_path('Http/Controllers/'.implode('/', $this->sectionSegmentsStudly).'Controller.php');

        if (is_file($path)) {
            return '';
        }

        $this->createMissingDirs($path);

        return file_put_contents($path, $content) !== false ? $path : '';
    }
904870
public function getGuarded()
    {
        $guarded_create = !$this->exists ? $this->getAttributesFromSchema('guarded-create', false, true) : [];
        $guarded_update = $this->exists ? $this->getAttributesFromSchema('guarded-update', false, true) : [];
        $guarded = $this->getAttributesFromSchema('guarded', false, true);

        return array_merge($guarded_create, $guarded_update, $guarded);
    }
510198
protected function prepareValuesToSave()
    {
        $values = parent::prepareValuesToSave();
        if ($this->changePassword) {
            $password = null;
            foreach ($this->formProperties as $key => $property) {
                if ($property['uri'] == GenerisRdf::PROPERTY_USER_PASSWORD && isset($this->formProperties[$key]['formValue'])) {
                    $password = $this->formProperties[$key]['formValue'];
                    break;
                }
            }

            $values[GenerisRdf::PROPERTY_USER_PASSWORD] = core_kernel_users_Service::getPasswordHash()->encrypt($password);
        }

        return $values;
    }
143711
public function actionDisable()
    {
        $maintenance = Yii::$app->maintenanceMode;

        if ($maintenance->getIsEnabled(true) && $maintenance->disable()) {
            $this->stdout("Maintenance mode disabled successfully.\n", Console::FG_GREEN);
            return Controller::EXIT_CODE_NORMAL;
        } else {
            $this->stdout("Maintenance mode already disabled.\n", Console::FG_RED);
            return Controller::EXIT_CODE_ERROR;
        }
    }
656678
public function getRequestData() {
        $data = $this->Controller->request->data;

        if ($data) {
            foreach ($data as $model => $fields) {
                foreach ($fields as $key => $value) {
                    if (
                        (mb_substr($key, -5) === '_null') ||
                        (mb_substr($key, -11) === '_type_ahead') ||
                        in_array($key, array('redirect_to', 'log_comment', 'report_action'))
                    ) {
                        unset($data[$model][$key]);
                    }
                }
            }
        }

        return $data;
    }
1302328
public function index()
    {
        $userGroupPermission = $this->UserGroupPermission->newEntity();
        
        $controllers = $this->Acl->getControllers();
        $groups = $users = [];
        
        if( !empty($controllers['user']) ) {
            $Users = TableRegistry::get($controllers['user']);
            $users = $Users->find()->select(['id','email'])->toArray();
        }
        if( !empty($controllers['group']) ) {
            $groups = TableRegistry::get($controllers['group']);
            $groups = $groups->find()->select(['id','name'])->toArray();
        }

        $permission = $this->UserGroupPermission->Permission->find()->select(['id','unique_string'])
            ->order(['unique_string'=>'DESC'])->toArray();
        $this->set(compact('userGroupPermission', 'permission', 'users', 'groups'));
        $this->set('_serialize', ['userGroupPermission']);
    }
276564
protected function renderTrustedPropertiesField()
    {
        $formFieldNames = $this->viewHelperVariableContainer->get(\Neos\FluidAdaptor\ViewHelpers\FormViewHelper::class, 'formFieldNames');
        $requestHash = $this->mvcPropertyMappingConfigurationService->generateTrustedPropertiesToken($formFieldNames, $this->getFieldNamePrefix());
        return '<input type="hidden" name="' . $this->prefixFieldName('__trustedProperties') . '" value="' . htmlspecialchars($requestHash) . '" />' . chr(10);
    }
672757
public function toData()
    {
        if ($this->action === self::TYPE_READ) {
            return [
                'fields' => 'whitelisted_domains',
            ];
        }

        if ($this->action === self::TYPE_DELETE) {
            return [
                'fields' => [
                    'whitelisted_domains',
                ],
            ];
        }

        return [
            'whitelisted_domains' => $this->domains,
        ];
    }