code
stringlengths
31
1.39M
docstring
stringlengths
23
16.8k
func_name
stringlengths
1
126
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
166
url
stringlengths
50
220
license
stringclasses
7 values
protected function throttleKey(Request $request) { return Str::transliterate(Str::lower($request->input($this->username())).'|'.$request->ip()); }
Get the throttle key for the given request. @param \Illuminate\Http\Request $request @return string
throttleKey
php
laravel/ui
auth-backend/ThrottlesLogins.php
https://github.com/laravel/ui/blob/master/auth-backend/ThrottlesLogins.php
MIT
public function maxAttempts() { return property_exists($this, 'maxAttempts') ? $this->maxAttempts : 5; }
Get the maximum number of attempts to allow. @return int
maxAttempts
php
laravel/ui
auth-backend/ThrottlesLogins.php
https://github.com/laravel/ui/blob/master/auth-backend/ThrottlesLogins.php
MIT
public function decayMinutes() { return property_exists($this, 'decayMinutes') ? $this->decayMinutes : 1; }
Get the number of minutes to throttle for. @return int
decayMinutes
php
laravel/ui
auth-backend/ThrottlesLogins.php
https://github.com/laravel/ui/blob/master/auth-backend/ThrottlesLogins.php
MIT
public function show(Request $request) { return $request->user()->hasVerifiedEmail() ? redirect($this->redirectPath()) : view('auth.verify'); }
Show the email verification notice. @param \Illuminate\Http\Request $request @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
show
php
laravel/ui
auth-backend/VerifiesEmails.php
https://github.com/laravel/ui/blob/master/auth-backend/VerifiesEmails.php
MIT
public function verify(Request $request) { if (! hash_equals((string) $request->route('id'), (string) $request->user()->getKey())) { throw new AuthorizationException; } if (! hash_equals((string) $request->route('hash'), sha1($request->user()->getEmailForVerification()))) { throw new AuthorizationException; } if ($request->user()->hasVerifiedEmail()) { return $request->wantsJson() ? new JsonResponse([], 204) : redirect($this->redirectPath()); } if ($request->user()->markEmailAsVerified()) { event(new Verified($request->user())); } if ($response = $this->verified($request)) { return $response; } return $request->wantsJson() ? new JsonResponse([], 204) : redirect($this->redirectPath())->with('verified', true); }
Mark the authenticated user's email address as verified. @param \Illuminate\Http\Request $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse @throws \Illuminate\Auth\Access\AuthorizationException
verify
php
laravel/ui
auth-backend/VerifiesEmails.php
https://github.com/laravel/ui/blob/master/auth-backend/VerifiesEmails.php
MIT
protected function verified(Request $request) { // }
The user has been verified. @param \Illuminate\Http\Request $request @return mixed
verified
php
laravel/ui
auth-backend/VerifiesEmails.php
https://github.com/laravel/ui/blob/master/auth-backend/VerifiesEmails.php
MIT
public function resend(Request $request) { if ($request->user()->hasVerifiedEmail()) { return $request->wantsJson() ? new JsonResponse([], 204) : redirect($this->redirectPath()); } $request->user()->sendEmailVerificationNotification(); return $request->wantsJson() ? new JsonResponse([], 202) : back()->with('resent', true); }
Resend the email verification notification. @param \Illuminate\Http\Request $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
resend
php
laravel/ui
auth-backend/VerifiesEmails.php
https://github.com/laravel/ui/blob/master/auth-backend/VerifiesEmails.php
MIT
public function handle() { if (static::hasMacro($this->argument('type'))) { return call_user_func(static::$macros[$this->argument('type')], $this); } if (! in_array($this->argument('type'), ['bootstrap'])) { throw new InvalidArgumentException('Invalid preset.'); } $this->ensureDirectoriesExist(); $this->exportViews(); if (! $this->option('views')) { $this->exportBackend(); } $this->components->info('Authentication scaffolding generated successfully.'); }
Execute the console command. @return void @throws \InvalidArgumentException
handle
php
laravel/ui
src/AuthCommand.php
https://github.com/laravel/ui/blob/master/src/AuthCommand.php
MIT
protected function ensureDirectoriesExist() { if (! is_dir($directory = $this->getViewPath('layouts'))) { mkdir($directory, 0755, true); } if (! is_dir($directory = $this->getViewPath('auth/passwords'))) { mkdir($directory, 0755, true); } }
Create the directories for the files. @return void
ensureDirectoriesExist
php
laravel/ui
src/AuthCommand.php
https://github.com/laravel/ui/blob/master/src/AuthCommand.php
MIT
protected function exportViews() { foreach ($this->views as $key => $value) { if (file_exists($view = $this->getViewPath($value)) && ! $this->option('force')) { if (! $this->components->confirm("The [$value] view already exists. Do you want to replace it?")) { continue; } } copy( __DIR__.'/Auth/'.$this->argument('type').'-stubs/'.$key, $view ); } }
Export the authentication views. @return void
exportViews
php
laravel/ui
src/AuthCommand.php
https://github.com/laravel/ui/blob/master/src/AuthCommand.php
MIT
protected function exportBackend() { $this->callSilent('ui:controllers'); $controller = app_path('Http/Controllers/HomeController.php'); if (file_exists($controller) && ! $this->option('force')) { if ($this->components->confirm("The [HomeController.php] file already exists. Do you want to replace it?", true)) { file_put_contents($controller, $this->compileStub('controllers/HomeController')); } } else { file_put_contents($controller, $this->compileStub('controllers/HomeController')); } $baseController = app_path('Http/Controllers/Controller.php'); if (file_exists($baseController) && ! $this->option('force')) { if ($this->components->confirm("The [Controller.php] file already exists. Do you want to replace it?", true)) { file_put_contents($baseController, $this->compileStub('controllers/Controller')); } } else { file_put_contents($baseController, $this->compileStub('controllers/Controller')); } if (! file_exists(database_path('migrations/0001_01_01_000000_create_users_table.php'))) { copy( __DIR__.'/../stubs/migrations/2014_10_12_100000_create_password_resets_table.php', base_path('database/migrations/2014_10_12_100000_create_password_resets_table.php') ); } file_put_contents( base_path('routes/web.php'), file_get_contents(__DIR__.'/Auth/stubs/routes.stub'), FILE_APPEND ); }
Export the authentication backend. @return void
exportBackend
php
laravel/ui
src/AuthCommand.php
https://github.com/laravel/ui/blob/master/src/AuthCommand.php
MIT
protected function compileStub($stub) { return str_replace( '{{namespace}}', $this->laravel->getNamespace(), file_get_contents(__DIR__.'/Auth/stubs/'.$stub.'.stub') ); }
Compiles the given stub. @param string $stub @return string
compileStub
php
laravel/ui
src/AuthCommand.php
https://github.com/laravel/ui/blob/master/src/AuthCommand.php
MIT
protected function getViewPath($path) { return implode(DIRECTORY_SEPARATOR, [ config('view.paths')[0] ?? resource_path('views'), $path, ]); }
Get full view path relative to the application's configured view path. @param string $path @return string
getViewPath
php
laravel/ui
src/AuthCommand.php
https://github.com/laravel/ui/blob/master/src/AuthCommand.php
MIT
public function auth() { return function ($options = []) { $namespace = class_exists($this->prependGroupNamespace('Auth\LoginController')) ? null : 'App\Http\Controllers'; $this->group(['namespace' => $namespace], function() use($options) { // Login Routes... if ($options['login'] ?? true) { $this->get('login', 'Auth\LoginController@showLoginForm')->name('login'); $this->post('login', 'Auth\LoginController@login'); } // Logout Routes... if ($options['logout'] ?? true) { $this->post('logout', 'Auth\LoginController@logout')->name('logout'); } // Registration Routes... if ($options['register'] ?? true) { $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register'); $this->post('register', 'Auth\RegisterController@register'); } // Password Reset Routes... if ($options['reset'] ?? true) { $this->resetPassword(); } // Password Confirmation Routes... if ($options['confirm'] ?? class_exists($this->prependGroupNamespace('Auth\ConfirmPasswordController'))) { $this->confirmPassword(); } // Email Verification Routes... if ($options['verify'] ?? false) { $this->emailVerification(); } }); }; }
Register the typical authentication routes for an application. @param array $options @return callable
auth
php
laravel/ui
src/AuthRouteMethods.php
https://github.com/laravel/ui/blob/master/src/AuthRouteMethods.php
MIT
public function resetPassword() { return function () { $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request'); $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email'); $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset'); $this->post('password/reset', 'Auth\ResetPasswordController@reset')->name('password.update'); }; }
Register the typical reset password routes for an application. @return callable
resetPassword
php
laravel/ui
src/AuthRouteMethods.php
https://github.com/laravel/ui/blob/master/src/AuthRouteMethods.php
MIT
public function confirmPassword() { return function () { $this->get('password/confirm', 'Auth\ConfirmPasswordController@showConfirmForm')->name('password.confirm'); $this->post('password/confirm', 'Auth\ConfirmPasswordController@confirm'); }; }
Register the typical confirm password routes for an application. @return callable
confirmPassword
php
laravel/ui
src/AuthRouteMethods.php
https://github.com/laravel/ui/blob/master/src/AuthRouteMethods.php
MIT
public function emailVerification() { return function () { $this->get('email/verify', 'Auth\VerificationController@show')->name('verification.notice'); $this->get('email/verify/{id}/{hash}', 'Auth\VerificationController@verify')->name('verification.verify'); $this->post('email/resend', 'Auth\VerificationController@resend')->name('verification.resend'); }; }
Register the typical email verification routes for an application. @return callable
emailVerification
php
laravel/ui
src/AuthRouteMethods.php
https://github.com/laravel/ui/blob/master/src/AuthRouteMethods.php
MIT
public function handle() { if (! is_dir($directory = app_path('Http/Controllers/Auth'))) { mkdir($directory, 0755, true); } $filesystem = new Filesystem; collect($filesystem->allFiles(__DIR__.'/../stubs/Auth')) ->each(function (SplFileInfo $file) use ($filesystem) { $filesystem->copy( $file->getPathname(), app_path('Http/Controllers/Auth/'.Str::replaceLast('.stub', '.php', $file->getFilename())) ); }); $this->components->info('Authentication scaffolding generated successfully.'); }
Execute the console command. @return void
handle
php
laravel/ui
src/ControllersCommand.php
https://github.com/laravel/ui/blob/master/src/ControllersCommand.php
MIT
public function handle() { if (static::hasMacro($this->argument('type'))) { return call_user_func(static::$macros[$this->argument('type')], $this); } if (! in_array($this->argument('type'), ['bootstrap', 'vue', 'react'])) { throw new InvalidArgumentException('Invalid preset.'); } if ($this->option('auth')) { $this->call('ui:auth'); } $this->{$this->argument('type')}(); }
Execute the console command. @return void @throws \InvalidArgumentException
handle
php
laravel/ui
src/UiCommand.php
https://github.com/laravel/ui/blob/master/src/UiCommand.php
MIT
protected function bootstrap() { Presets\Bootstrap::install(); $this->components->info('Bootstrap scaffolding installed successfully.'); $this->components->warn('Please run [npm install && npm run dev] to compile your fresh scaffolding.'); }
Install the "bootstrap" preset. @return void
bootstrap
php
laravel/ui
src/UiCommand.php
https://github.com/laravel/ui/blob/master/src/UiCommand.php
MIT
protected function vue() { Presets\Bootstrap::install(); Presets\Vue::install(); $this->components->info('Vue scaffolding installed successfully.'); $this->components->warn('Please run [npm install && npm run dev] to compile your fresh scaffolding.'); }
Install the "vue" preset. @return void
vue
php
laravel/ui
src/UiCommand.php
https://github.com/laravel/ui/blob/master/src/UiCommand.php
MIT
protected function react() { Presets\Bootstrap::install(); Presets\React::install(); $this->components->info('React scaffolding installed successfully.'); $this->components->warn('Please run [npm install && npm run dev] to compile your fresh scaffolding.'); }
Install the "react" preset. @return void
react
php
laravel/ui
src/UiCommand.php
https://github.com/laravel/ui/blob/master/src/UiCommand.php
MIT
public function register() { if ($this->app->runningInConsole()) { $this->commands([ AuthCommand::class, ControllersCommand::class, UiCommand::class, ]); } }
Register the package services. @return void
register
php
laravel/ui
src/UiServiceProvider.php
https://github.com/laravel/ui/blob/master/src/UiServiceProvider.php
MIT
public function boot() { Route::mixin(new AuthRouteMethods); }
Bootstrap any application services. @return void
boot
php
laravel/ui
src/UiServiceProvider.php
https://github.com/laravel/ui/blob/master/src/UiServiceProvider.php
MIT
protected static function updatePackageArray(array $packages) { return [ 'bootstrap' => '^5.2.3', '@popperjs/core' => '^2.11.6', 'sass' => '^1.56.1', ] + $packages; }
Update the given package array. @param array $packages @return array
updatePackageArray
php
laravel/ui
src/Presets/Bootstrap.php
https://github.com/laravel/ui/blob/master/src/Presets/Bootstrap.php
MIT
protected static function updateViteConfiguration() { copy(__DIR__.'/bootstrap-stubs/vite.config.js', base_path('vite.config.js')); }
Update the Vite configuration. @return void
updateViteConfiguration
php
laravel/ui
src/Presets/Bootstrap.php
https://github.com/laravel/ui/blob/master/src/Presets/Bootstrap.php
MIT
protected static function updateSass() { (new Filesystem)->ensureDirectoryExists(resource_path('sass')); copy(__DIR__.'/bootstrap-stubs/_variables.scss', resource_path('sass/_variables.scss')); copy(__DIR__.'/bootstrap-stubs/app.scss', resource_path('sass/app.scss')); }
Update the Sass files for the application. @return void
updateSass
php
laravel/ui
src/Presets/Bootstrap.php
https://github.com/laravel/ui/blob/master/src/Presets/Bootstrap.php
MIT
protected static function updateBootstrapping() { copy(__DIR__.'/bootstrap-stubs/bootstrap.js', resource_path('js/bootstrap.js')); }
Update the bootstrapping files. @return void
updateBootstrapping
php
laravel/ui
src/Presets/Bootstrap.php
https://github.com/laravel/ui/blob/master/src/Presets/Bootstrap.php
MIT
protected static function ensureComponentDirectoryExists() { $filesystem = new Filesystem; if (! $filesystem->isDirectory($directory = resource_path('js/components'))) { $filesystem->makeDirectory($directory, 0755, true); } }
Ensure the component directories we need exist. @return void
ensureComponentDirectoryExists
php
laravel/ui
src/Presets/Preset.php
https://github.com/laravel/ui/blob/master/src/Presets/Preset.php
MIT
protected static function updatePackages($dev = true) { if (! file_exists(base_path('package.json'))) { return; } $configurationKey = $dev ? 'devDependencies' : 'dependencies'; $packages = json_decode(file_get_contents(base_path('package.json')), true); $packages[$configurationKey] = static::updatePackageArray( array_key_exists($configurationKey, $packages) ? $packages[$configurationKey] : [], $configurationKey ); ksort($packages[$configurationKey]); file_put_contents( base_path('package.json'), json_encode($packages, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT).PHP_EOL ); }
Update the "package.json" file. @param bool $dev @return void
updatePackages
php
laravel/ui
src/Presets/Preset.php
https://github.com/laravel/ui/blob/master/src/Presets/Preset.php
MIT
protected static function removeNodeModules() { tap(new Filesystem, function ($files) { $files->deleteDirectory(base_path('node_modules')); $files->delete(base_path('yarn.lock')); }); }
Remove the installed Node modules. @return void
removeNodeModules
php
laravel/ui
src/Presets/Preset.php
https://github.com/laravel/ui/blob/master/src/Presets/Preset.php
MIT
protected static function updatePackageArray(array $packages) { return [ '@vitejs/plugin-react' => '^4.2.0', 'react' => '^18.2.0', 'react-dom' => '^18.2.0', ] + Arr::except($packages, [ '@vitejs/plugin-vue', 'vue' ]); }
Update the given package array. @param array $packages @return array
updatePackageArray
php
laravel/ui
src/Presets/React.php
https://github.com/laravel/ui/blob/master/src/Presets/React.php
MIT
protected static function updateViteConfiguration() { copy(__DIR__.'/react-stubs/vite.config.js', base_path('vite.config.js')); }
Update the Vite configuration. @return void
updateViteConfiguration
php
laravel/ui
src/Presets/React.php
https://github.com/laravel/ui/blob/master/src/Presets/React.php
MIT
protected static function updateComponent() { (new Filesystem)->delete( resource_path('js/components/ExampleComponent.vue') ); copy( __DIR__.'/react-stubs/Example.jsx', resource_path('js/components/Example.jsx') ); }
Update the example component. @return void
updateComponent
php
laravel/ui
src/Presets/React.php
https://github.com/laravel/ui/blob/master/src/Presets/React.php
MIT
protected static function updateBootstrapping() { copy(__DIR__.'/react-stubs/app.js', resource_path('js/app.js')); }
Update the bootstrapping files. @return void
updateBootstrapping
php
laravel/ui
src/Presets/React.php
https://github.com/laravel/ui/blob/master/src/Presets/React.php
MIT
protected static function addViteReactRefreshDirective() { $view = static::getViewPath('layouts/app.blade.php'); if (! file_exists($view)) { return; } file_put_contents( $view, str_replace('@vite(', '@viteReactRefresh'.PHP_EOL.' @vite(', file_get_contents($view)) ); }
Add Vite's React Refresh Runtime @return void
addViteReactRefreshDirective
php
laravel/ui
src/Presets/React.php
https://github.com/laravel/ui/blob/master/src/Presets/React.php
MIT
protected static function getViewPath($path) { return implode(DIRECTORY_SEPARATOR, [ config('view.paths')[0] ?? resource_path('views'), $path, ]); }
Get full view path relative to the application's configured view path. @param string $path @return string
getViewPath
php
laravel/ui
src/Presets/React.php
https://github.com/laravel/ui/blob/master/src/Presets/React.php
MIT
protected static function updatePackageArray(array $packages) { return [ '@vitejs/plugin-vue' => '^5.2.1', 'vue' => '^3.5.13', ] + Arr::except($packages, [ '@vitejs/plugin-react', 'react', 'react-dom', ]); }
Update the given package array. @param array $packages @return array
updatePackageArray
php
laravel/ui
src/Presets/Vue.php
https://github.com/laravel/ui/blob/master/src/Presets/Vue.php
MIT
protected static function updateViteConfiguration() { copy(__DIR__.'/vue-stubs/vite.config.js', base_path('vite.config.js')); }
Update the Vite configuration. @return void
updateViteConfiguration
php
laravel/ui
src/Presets/Vue.php
https://github.com/laravel/ui/blob/master/src/Presets/Vue.php
MIT
protected static function updateComponent() { (new Filesystem)->delete( resource_path('js/components/Example.js') ); copy( __DIR__.'/vue-stubs/ExampleComponent.vue', resource_path('js/components/ExampleComponent.vue') ); }
Update the example component. @return void
updateComponent
php
laravel/ui
src/Presets/Vue.php
https://github.com/laravel/ui/blob/master/src/Presets/Vue.php
MIT
protected static function updateBootstrapping() { copy(__DIR__.'/vue-stubs/app.js', resource_path('js/app.js')); }
Update the bootstrapping files. @return void
updateBootstrapping
php
laravel/ui
src/Presets/Vue.php
https://github.com/laravel/ui/blob/master/src/Presets/Vue.php
MIT
protected function handleRequestUsing(Request $request, callable $callback) { return new TestResponse( (new Pipeline($this->app)) ->send($request) ->through([ \Illuminate\Session\Middleware\StartSession::class, ]) ->then($callback) ); }
Handle Request using the following pipeline. @param \Illuminate\Http\Request $request @param callable $callback @return \Illuminate\Testing\TestResponse
handleRequestUsing
php
laravel/ui
tests/AuthBackend/AuthenticatesUsersTest.php
https://github.com/laravel/ui/blob/master/tests/AuthBackend/AuthenticatesUsersTest.php
MIT
protected function validator(array $data) { return Validator::make($data, [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'password' => ['required', 'string', 'min:8', 'confirmed'], ]); }
Get a validator for an incoming registration request. @param array $data @return \Illuminate\Contracts\Validation\Validator
validator
php
laravel/ui
tests/AuthBackend/RegistersUsersTest.php
https://github.com/laravel/ui/blob/master/tests/AuthBackend/RegistersUsersTest.php
MIT
protected function create(array $data) { $user = (new User())->forceFill([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); $user->save(); return $user; }
Create a new user instance after a valid registration. @param array $data @return \App\Models\User
create
php
laravel/ui
tests/AuthBackend/RegistersUsersTest.php
https://github.com/laravel/ui/blob/master/tests/AuthBackend/RegistersUsersTest.php
MIT
protected function handleRequestUsing(Request $request, callable $callback) { return new TestResponse( (new Pipeline($this->app)) ->send($request) ->through([ \Illuminate\Session\Middleware\StartSession::class, ]) ->then($callback) ); }
Handle Request using the following pipeline. @param \Illuminate\Http\Request $request @param callable $callback @return \Illuminate\Testing\TestResponse
handleRequestUsing
php
laravel/ui
tests/AuthBackend/RegistersUsersTest.php
https://github.com/laravel/ui/blob/master/tests/AuthBackend/RegistersUsersTest.php
MIT
public function __construct(string $table, string $properties, string $modelNamespace) { $this->table = $table; $this->properties = $properties; $this->modelNamespace = $modelNamespace; $this->_init(); }
ModelGenerator constructor. @param string $table @param string $properties @param string $modelNamespace
__construct
php
awais-vteams/laravel-crud-generator
src/ModelGenerator.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/ModelGenerator.php
MIT
public function getEloquentRelations(): array { return [$this->functions, $this->properties]; }
Get all the eloquent relations. @return array
getEloquentRelations
php
awais-vteams/laravel-crud-generator
src/ModelGenerator.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/ModelGenerator.php
MIT
private function _getTableRelations(): array { return [ ...$this->getBelongsTo(), ...$this->getOtherRelations(), ]; }
Get all relations from Table. @return array
_getTableRelations
php
awais-vteams/laravel-crud-generator
src/ModelGenerator.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/ModelGenerator.php
MIT
protected function extractTableName(string $foreignTable): string { $dotPosition = strpos($foreignTable, '.'); if ($dotPosition !== false) { return substr($foreignTable, $dotPosition + 1); // Extract table name only } return $foreignTable; // No dot found, return the original name }
Extract the table name from a fully qualified table name (e.g., database.table). @param string $foreignTable @return string
extractTableName
php
awais-vteams/laravel-crud-generator
src/ModelGenerator.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/ModelGenerator.php
MIT
public function handle() { $this->info('Running Crud Generator ...'); $this->table = $this->getNameInput(); // If table not exist in DB return if (! $this->tableExists()) { $this->error("`$this->table` table not exist"); return false; } // Build the class name from table name $this->name = $this->_buildClassName(); // Generate the crud $this->buildOptions() ->buildController() ->buildModel() ->buildViews() ->writeRoute(); $this->info('Created Successfully.'); return true; }
Execute the console command. @throws FileNotFoundException
handle
php
awais-vteams/laravel-crud-generator
src/Commands/CrudGenerator.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/CrudGenerator.php
MIT
protected function buildController(): static { if ($this->options['stack'] == 'livewire') { $this->buildLivewire(); return $this; } $controllerPath = $this->options['stack'] == 'api' ? $this->_getApiControllerPath($this->name) : $this->_getControllerPath($this->name); if ($this->files->exists($controllerPath) && $this->ask('Already exist Controller. Do you want overwrite (y/n)?', 'y') == 'n') { return $this; } $this->info('Creating Controller ...'); $replace = $this->buildReplacements(); $stubFolder = match ($this->options['stack']) { 'api' => 'api/', default => '' }; $controllerTemplate = str_replace( array_keys($replace), array_values($replace), $this->getStub($stubFolder.'Controller') ); $this->write($controllerPath, $controllerTemplate); if ($this->options['stack'] == 'api') { $resourcePath = $this->_getResourcePath($this->name); $resourceTemplate = str_replace( array_keys($replace), array_values($replace), $this->getStub($stubFolder.'Resource') ); $this->write($resourcePath, $resourceTemplate); } return $this; }
Build the Controller Class and save in app/Http/Controllers. @return $this @throws FileNotFoundException
buildController
php
awais-vteams/laravel-crud-generator
src/Commands/CrudGenerator.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/CrudGenerator.php
MIT
protected function buildViews(): static { if ($this->options['stack'] == 'api') { return $this; } $this->info('Creating Views ...'); $tableHead = "\n"; $tableBody = "\n"; $viewRows = "\n"; $form = "\n"; foreach ($this->getFilteredColumns() as $column) { $title = Str::title(str_replace('_', ' ', $column)); $tableHead .= $this->getHead($title); $tableBody .= $this->getBody($column); $viewRows .= $this->getField($title, $column, 'view-field'); $form .= $this->getField($title, $column); } $replace = array_merge($this->buildReplacements(), [ '{{tableHeader}}' => $tableHead, '{{tableBody}}' => $tableBody, '{{viewRows}}' => $viewRows, '{{form}}' => $form, ]); $this->buildLayout(); foreach (['index', 'create', 'edit', 'form', 'show'] as $view) { $path = match ($this->options['stack']) { 'livewire' => $this->isLaravel12() ? "views/{$this->options['stack']}/12/$view" : "views/{$this->options['stack']}/default/$view", default => "views/{$this->options['stack']}/$view" }; $viewTemplate = str_replace( array_keys($replace), array_values($replace), $this->getStub($path) ); $this->write($this->_getViewPath($view), $viewTemplate); } return $this; }
@return $this @throws FileNotFoundException @throws Exception
buildViews
php
awais-vteams/laravel-crud-generator
src/Commands/CrudGenerator.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/CrudGenerator.php
MIT
private function _buildClassName(): string { return Str::studly(Str::singular($this->table)); }
Make the class name from table name. @return string
_buildClassName
php
awais-vteams/laravel-crud-generator
src/Commands/CrudGenerator.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/CrudGenerator.php
MIT
public function __construct(Filesystem $files) { parent::__construct(); $this->files = $files; $this->unwantedColumns = config('crud.model.unwantedColumns', $this->unwantedColumns); $this->modelNamespace = config('crud.model.namespace', $this->modelNamespace); $this->controllerNamespace = config('crud.controller.namespace', $this->controllerNamespace); $this->apiControllerNamespace = config('crud.controller.apiNamespace', $this->apiControllerNamespace); $this->resourceNamespace = config('crud.resources.namespace', $this->resourceNamespace); $this->livewireNamespace = config('crud.livewire.namespace', $this->livewireNamespace); $this->requestNamespace = config('crud.request.namespace', $this->requestNamespace); $this->layout = config('crud.layout', $this->layout); }
Create a new controller creator command instance. @param Filesystem $files @return void
__construct
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
protected function makeDirectory(string $path): string { if (! $this->files->isDirectory(dirname($path))) { $this->files->makeDirectory(dirname($path), 0777, true, true); } return $path; }
Build the directory if necessary. @param string $path @return string
makeDirectory
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
protected function write(string $path, string $content): void { $this->makeDirectory($path); $this->files->put($path, $content); }
Write the file/Class. @param string $path @param string $content
write
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
protected function getStub(string $type, bool $content = true): string { $stub_path = config('crud.stub_path', 'default'); if (blank($stub_path) || $stub_path == 'default') { $stub_path = __DIR__.'/../stubs/'; } $path = Str::finish($stub_path, '/')."$type.stub"; if (! $content) { return $path; } return $this->files->get($path); }
Get the stub file. @param string $type @param boolean $content @return string @throws FileNotFoundException
getStub
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
private function _getNamespacePath(string $namespace): string { $str = Str::start(Str::finish(Str::after($namespace, 'App'), '\\'), '\\'); return str_replace('\\', '/', $str); }
Get the path from namespace. @param string $namespace @return string
_getNamespacePath
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
private function _getLayoutPath(): string { return $this->makeDirectory(resource_path("/views/layouts/app.blade.php")); }
Get the default layout path. @return string
_getLayoutPath
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
protected function getField(string $title, string $column, string $type = 'form-field'): string { $replace = array_merge($this->buildReplacements(), [ '{{title}}' => $title, '{{column}}' => $column, '{{column_snake}}' => Str::snake($column), ]); $path = match ($this->options['stack']) { 'livewire' => $this->isLaravel12() ? "views/{$this->options['stack']}/12/$type" : "views/{$this->options['stack']}/default/$type", default => "views/{$this->options['stack']}/$type" }; return str_replace( array_keys($replace), array_values($replace), $this->getStub($path) ); }
Build the form fields for form. @param string $title @param string $column @param string $type @return string @throws FileNotFoundException
getField
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
protected function buildLayout(): void { if ($this->layout === false) { return; } if (view()->exists($this->layout) || view()->exists('components.'.$this->layout)) { return; } $this->info('Creating Layout ...'); $uiPackage = match ($this->options['stack']) { 'tailwind', 'react', 'vue' => 'laravel/breeze', 'livewire' => $this->isLaravel12() ? 'laravel/livewire-starter-kit' : 'laravel/breeze', default => 'laravel/ui' }; if (! $this->requireComposerPackages([$uiPackage], true)) { throw new Exception("Unable to install $uiPackage. Please install it manually"); } $uiCommand = match ($this->options['stack']) { 'tailwind' => 'php artisan breeze:install blade', 'livewire' => 'php artisan breeze:install livewire', 'react' => 'php artisan breeze:install react', 'vue' => 'php artisan breeze:install vue', default => 'php artisan ui bootstrap --auth' }; // Do not run command for v12.* if ($this->isLaravel12()) { return; } $this->runCommands([$uiCommand]); }
Make layout if not exists. @throws Exception
buildLayout
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
protected function getColumns(): ?array { if (empty($this->tableColumns)) { $this->tableColumns = Schema::getColumns($this->table); } return $this->tableColumns; }
Get the DB Table columns. @return array|null
getColumns
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
protected function modelReplacements(): array { $properties = '*'; $livewireFormProperties = ''; $livewireFormSetValues = ''; $rulesArray = []; $softDeletesNamespace = $softDeletes = ''; $modelName = Str::camel($this->name); foreach ($this->getColumns() as $column) { $properties .= "\n * @property \${$column['name']}"; if (! in_array($column['name'], $this->unwantedColumns)) { $livewireFormProperties .= "\n public \${$column['name']} = '';"; $livewireFormSetValues .= "\n \$this->{$column['name']} = \$this->{$modelName}Model->{$column['name']};"; } if (! $column['nullable']) { $rulesArray[$column['name']] = ['required']; } if ($column['type_name'] == 'bool') { $rulesArray[$column['name']][] = 'boolean'; } if ($column['type_name'] == 'uuid') { $rulesArray[$column['name']][] = 'uuid'; } if ($column['type_name'] == 'text' || $column['type_name'] == 'varchar') { $rulesArray[$column['name']][] = 'string'; } if ($column['name'] == 'deleted_at') { $softDeletesNamespace = "use Illuminate\Database\Eloquent\SoftDeletes;\n"; $softDeletes = "use SoftDeletes;\n"; } } $rules = function () use ($rulesArray) { $rules = ''; // Exclude the unwanted rulesArray $rulesArray = Arr::except($rulesArray, $this->unwantedColumns); // Make rulesArray foreach ($rulesArray as $col => $rule) { $rules .= "\n\t\t\t'$col' => '".implode('|', $rule)."',"; } return $rules; }; $fillable = function () { $filterColumns = $this->getFilteredColumns(); // Add quotes to the unwanted columns for fillable array_walk($filterColumns, function (&$value) { $value = "'".$value."'"; }); // CSV format return implode(', ', $filterColumns); }; $properties .= "\n *"; [$relations, $properties] = (new ModelGenerator($this->table, $properties, $this->modelNamespace))->getEloquentRelations(); return [ '{{fillable}}' => $fillable(), '{{rules}}' => $rules(), '{{relations}}' => $relations, '{{properties}}' => $properties, '{{softDeletesNamespace}}' => $softDeletesNamespace, '{{softDeletes}}' => $softDeletes, '{{livewireFormProperties}}' => $livewireFormProperties, '{{livewireFormSetValues}}' => $livewireFormSetValues, ]; }
Make model attributes/replacements. @return array
modelReplacements
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
protected function getNameInput(): string { return trim($this->argument('name')); }
Get the desired class name from the input. @return string
getNameInput
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
protected function getArguments(): array { return [ ['name', InputArgument::REQUIRED, 'The name of the table'], ]; }
Get the console command arguments. @return array
getArguments
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
protected function requireComposerPackages(array $packages, bool $asDev = false): bool { $command = array_merge( ['composer', 'require'], $packages, $asDev ? ['--dev'] : [], ); return (new Process($command, base_path(), ['COMPOSER_MEMORY_LIMIT' => '-1'])) ->setTimeout(null) ->run(function ($type, $output) { $this->output->write($output); }) === 0; }
Installs the given Composer Packages into the application. @param array $packages @param bool $asDev @return bool
requireComposerPackages
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
protected function runCommands(array $commands): void { $process = Process::fromShellCommandline(implode(' && ', $commands), null, null, null, null); if ('\\' !== DIRECTORY_SEPARATOR && file_exists('/dev/tty') && is_readable('/dev/tty')) { try { $process->setTty(true); } catch (RuntimeException $e) { $this->output->writeln(' <bg=yellow;fg=black> WARN </> '.$e->getMessage().PHP_EOL); } } $process->run(function ($type, $line) { $this->output->write(' '.$line); }); }
Run the given commands. @param array $commands @return void
runCommands
php
awais-vteams/laravel-crud-generator
src/Commands/GeneratorCommand.php
https://github.com/awais-vteams/laravel-crud-generator/blob/master/src/Commands/GeneratorCommand.php
MIT
public function isAdmin( $id='') { if(!$this->User->adminCheck($id, 'update')) { $this->set('admin', true); return true; } else { $this->set('admin', false); return false; } }
Set class var admin to true if the user id is admin. @param integer $id
isAdmin
php
Datawalke/Coordino
app/app_controller.php
https://github.com/Datawalke/Coordino/blob/master/app/app_controller.php
MIT
public function __validatePost($data, $redirectUrl) { $this->Post->set($data); $this->User->set($data); $errors = array(); if(!$this->Post->validates() || !$this->User->validates()) { $data['Post']['content'] = $this->Markdownify->parseString($data['Post']['content']); $validationErrors = array_merge($this->Post->invalidFields(), $this->User->invalidFields()); $errors = array( 'errors' => $validationErrors, 'data' => $data ); $this->Session->write(array('errors' => $errors)); $this->redirect($redirectUrl); } }
Validates the Post data. Since Posts need to validate for both logged in and non logged in accounts a separate validation technique was needed. @param string $data @param string $redirectUrl @return void
__validatePost
php
Datawalke/Coordino
app/controllers/posts_controller.php
https://github.com/Datawalke/Coordino/blob/master/app/controllers/posts_controller.php
MIT
public function __postSave($type, $userId, $data, $relatedId = null) { /** * Add in required Post data */ $this->data['Post']['type'] = $type; $this->data['Post']['user_id'] = $userId; $this->data['Post']['timestamp'] = time(); if($type == 'question') { $this->data['Post']['url_title'] = $this->Post->niceUrl($this->data['Post']['title']); } if($type == 'answer') { $this->data['Post']['related_id'] = $relatedId; } $this->data['Post']['public_key'] = uniqid(); if(!empty($this->data['Post']['tags'])) { $this->Post->Behaviors->attach('Tag', array('table_label' => 'tags', 'tags_label' => 'tag', 'separator' => ', ')); } /** * Filter out any nasty XSS */ Configure::write('debug', 0); $this->data['Post']['content'] = str_replace('<code>', '<code class="prettyprint">', $this->data['Post']['content']); $this->data['Post']['content'] = @$this->Htmlfilter->filter($this->data['Post']['content']); /** * Spam Protection */ $flags = 0; $content = strip_tags($this->data['Post']['content']); // Get links in the content $links = preg_match_all("#(^|[\n ])(?:(?:http|ftp|irc)s?:\/\/|www.)(?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,4}(?:[-a-zA-Z0-9._\/&=+%?;\#]+)#is", $content, $matches); $links = $matches[0]; $totalLinks = count($links); $length = strlen($content); // How many links are in the body // +2 if less than 2, -1 per link if over 2 if ($totalLinks > 2) { $flags = $flags + $totalLinks; } else { $flags = $flags - 1; } // How long is the body // +2 if more then 20 chars and no links, -1 if less then 20 if ($length >= 20 && $totalLinks <= 0) { $flags = $flags - 1; } else if ($length >= 20 && $totalLinks == 1) { ++$flags; } else if ($length < 20) { $flags = $flags + 2; } // Keyword search $blacklistKeywords = $this->Setting->find('first', array('conditions' => array('name' => 'blacklist'))); $blacklistKeywords = unserialize($blacklistKeywords['Setting']['description']); foreach ($blacklistKeywords as $keyword) { if (stripos($content, $keyword) !== false) { $flags = $flags + substr_count(strtolower($content), $keyword); } } $blacklistWords = array('.html', '.info', '?', '&', '.de', '.pl', '.cn'); foreach ($links as $link) { foreach ($blacklistWords as $word) { if (stripos($link, $word) !== false) { ++$flags; } } foreach ($blacklistKeywords as $keyword) { if (stripos($link, $keyword) !== false) { ++$flags; } } if (strlen($link) >= 30) { ++$flags; } } // Body starts with... // -10 flags $firstWord = substr($content, 0, stripos($content, ' ')); $firstDisallow = array_merge($blacklistKeywords, array('interesting', 'cool', 'sorry')); if (in_array(strtolower($firstWord), $firstDisallow)) { $flags = $flags + 10; } $manyTimes = $this->Post->find('count', array( 'conditions' => array('Post.content' => $this->data['Post']['content']) )); // Random character match // -1 point per 5 consecutive consonants $consonants = preg_match_all('/[^aAeEiIoOuU\s]{5,}+/i', $content, $matches); $totalConsonants = count($matches[0]); if ($totalConsonants > 0) { $flags = $flags + $totalConsonants; } $flags = $flags + $manyTimes; $this->data['Post']['flags'] = $flags; if($flags >= $this->Setting->getValue('flag_display_limit')) { $this->data['Post']['tags'] = ''; } /** * Save the Data */ if($this->Post->save($this->data)) { if($type == 'question') { $this->History->record('asked', $this->Post->id, $this->Auth->user('id')); }elseif($type == 'answer') { $this->History->record('answered', $this->Post->id, $this->Auth->user('id')); } $user_info = $this->User->find('first', array('conditions' => array('id' => $userId))); if($type == 'question') { $this->User->save(array('id' => $userId, 'question_count' => $user_info['User']['question_count'] + 1)); }elseif($type == 'answer') { $this->User->save(array('id' => $userId, 'answer_count' => $user_info['User']['answer_count'] + 1)); } $post = $this->data['Post']; /** * Hack to normalize data. * Note this should be added to the Tag Behavior at some point. * This was but in because the behavior would delete the relations as soon as they put them in. */ $this->Post->Behaviors->detach('Tag'); $tags = array( 'id' => $this->Post->id, 'tags' => '' ); $this->Post->save($tags); return $post; } else { return false; } }
Saves the Post data for a user @param string $type Either question or answer @param string $userId the ID of the user posting @param string $data $this->data @return array $post The saved Post data.
__postSave
php
Datawalke/Coordino
app/controllers/posts_controller.php
https://github.com/Datawalke/Coordino/blob/master/app/controllers/posts_controller.php
MIT
public function __userSave($data) { $data['User']['public_key'] = uniqid(); $data['User']['password'] = $this->Auth->password(uniqid('p')); $data['User']['joined'] = time(); $data['User']['url_title'] = $this->Post->niceUrl($data['User']['username']); /** * Set up cookie data incase they leave the site and the session ends and they have not registered yet */ $this->Cookie->write(array('User' => $data['User'])); /** * Save the data */ $this->User->save($data); $data['User']['id'] = $this->User->id; return $data; }
Saves the user data and creates a new user account for them. @param string $data @return void @todo this should be moved to the model at some point
__userSave
php
Datawalke/Coordino
app/controllers/posts_controller.php
https://github.com/Datawalke/Coordino/blob/master/app/controllers/posts_controller.php
MIT
public function view($public_key) { /** * Set the Post model to recursive 2 so we can pull back the User's information with each comment. */ $this->Post->recursive = 2; /** * Change to contains. Limit to just question and comment data, no answers. */ $this->Post->unbindModel( array('hasMany' => array('Answer')) ); $question = $this->Post->findByPublicKey($public_key); /* * Look up the flag limit. */ $flag_check = $this->Setting->find( 'first', array( 'conditions' => array( 'name' => 'flag_display_limit' ), 'fields' => array('value'), 'recursive' => -1 ) ); /** * Check to see if the post is spam or not. * If so redirect. */ if($question['Post']['flags'] >= $flag_check['Setting']['value'] && $this->Setting->repCheck($this->Auth->user('id'), 'rep_edit')) { $this->Session->setFlash(__('The question you are trying to view no longer exists.',true), 'error'); $this->redirect('/'); } /** * Even though Post can return an array of answers through associations * we cannot order or sort this data as we need to */ $this->Answer->recursive = 3; $answers = $this->Answer->find('all', array( 'conditions' => array( 'Answer.related_id' => $question['Post']['id'], 'Answer.flags <' => $flag_check['Setting']['value'] ), 'order' => 'Answer.status DESC' )); if(!empty($question)) { $views = array( 'id' => $question['Post']['id'], 'views' => $question['Post']['views'] + 1 ); $this->Post->save($views); } if($this->Auth->user('id') && !$this->Setting->repCheck($this->Auth->user('id'), 'rep_edit')) { $this->set('rep_rights', 'yeah!'); } $this->set('title_for_layout', $question['Post']['title']); $this->set('question', $question); $this->set('answers', $answers); }
Allowes the user to view a question. If a user tries to view a Post that is a answer type they will be redirected. @param string $public_key @return void
view
php
Datawalke/Coordino
app/controllers/posts_controller.php
https://github.com/Datawalke/Coordino/blob/master/app/controllers/posts_controller.php
MIT
public function remoteLogin($name, $email, $timestamp, $hash) { $serverHash = md5($name . $email . $timestamp . $this->Setting->getValue('remote_auth_key')); if($serverHash != $hash) { $this->Session->setFlash('Invalid name, email, timestamp, or authentication key. Please check your conditions and try again.', 'error'); $this->redirect('/'); } if((time() - $timestamp) > 1800) { $this->Session->setFlash('The provided timestamp is too old. Please try again.', 'error'); $this->redirect('/'); } $account = $this->User->findByEmail($email); if(!empty($account)) { $this->Auth->login($account); } else { $data['User']['username'] = $name; $data['User']['email'] = $email; $data['User']['registered'] = 1; $this->Auth->login($this->__userSave($data)); } $this->redirect('/'); }
Logs in the user via a remote method. @param string $name @param string $email @param string $hash md5($name . $email . $api_key) @return void
remoteLogin
php
Datawalke/Coordino
app/controllers/users_controller.php
https://github.com/Datawalke/Coordino/blob/master/app/controllers/users_controller.php
MIT
public function __construct() { /** * Import the Markdownify vendor files. */ App::import('Vendor', 'htmlfilter/htmlfilter'); $this->htmlFilter = new HtmlFilter; }
Import the HTML Filter vendor files and instantiate the object.
__construct
php
Datawalke/Coordino
app/controllers/components/htmlfilter.php
https://github.com/Datawalke/Coordino/blob/master/app/controllers/components/htmlfilter.php
MIT
public function __construct() { /** * Import the Markdownify vendor files. */ App::import('Vendor', 'markdown/markdown'); }
Import the Markdownify vendor files and instantiate the object.
__construct
php
Datawalke/Coordino
app/controllers/components/markdown.php
https://github.com/Datawalke/Coordino/blob/master/app/controllers/components/markdown.php
MIT
public function parseString($textInput) { return Markdown($textInput); }
parse a Text string @param string $textInput @return string markdown formatted
parseString
php
Datawalke/Coordino
app/controllers/components/markdown.php
https://github.com/Datawalke/Coordino/blob/master/app/controllers/components/markdown.php
MIT
public function __construct() { /** * Import the Markdownify vendor files. */ App::import('Vendor', 'markdownify/markdownify'); /** * instantiate the Mardownify object. */ $this->markdownify = new Markdownify; }
Import the Markdownify vendor files and instantiate the object.
__construct
php
Datawalke/Coordino
app/controllers/components/markdownify.php
https://github.com/Datawalke/Coordino/blob/master/app/controllers/components/markdownify.php
MIT
public function parseString($htmlInput) { return $this->markdownify->parseString($htmlInput); }
parse a HTML string @param string $html @return string markdown formatted
parseString
php
Datawalke/Coordino
app/controllers/components/markdownify.php
https://github.com/Datawalke/Coordino/blob/master/app/controllers/components/markdownify.php
MIT
function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array()){ if ($privkey == null || $privkey == ''){ die ("To use reCAPTCHA you must get an API key from <a href='http://recaptcha.net/api/getkey'>http://recaptcha.net/api/getkey</a>"); } if ($remoteip == null || $remoteip == ''){ die ("For security reasons, you must pass the remote ip to reCAPTCHA"); } //discard spam submissions if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) { $this->is_valid = false; $this->error = 'incorrect-captcha-sol'; return 0; } $response = $this->_recaptcha_http_post(Configure::read('Recaptcha.verifyServer'), "/verify", array ( 'privatekey' => $privkey, 'remoteip' => $remoteip, 'challenge' => $challenge, 'response' => $response ) + $extra_params ); $answers = explode ("\n", $response [1]); if (trim ($answers [0]) == 'true') { $this->is_valid = true; return 1; }else{ $this->is_valid = false; $this->error = $answers [1]; return 0; } }
Calls an HTTP POST function to verify if the user's guess was correct @param string $privkey @param string $remoteip @param string $challenge @param string $response @param array $extra_params an array of extra variables to post to the server @return ReCaptchaResponse
recaptcha_check_answer
php
Datawalke/Coordino
app/controllers/components/recaptcha.php
https://github.com/Datawalke/Coordino/blob/master/app/controllers/components/recaptcha.php
MIT
function _recaptcha_qsencode ($data) { $req = ""; foreach ( $data as $key => $value ) $req .= $key . '=' . urlencode( stripslashes($value) ) . '&'; // Cut the last '&' $req=substr($req,0,strlen($req)-1); return $req; }
Encodes the given data into a query string format @param $data - array of string elements to be encoded @return string - encoded request
_recaptcha_qsencode
php
Datawalke/Coordino
app/controllers/components/recaptcha.php
https://github.com/Datawalke/Coordino/blob/master/app/controllers/components/recaptcha.php
MIT
function setup(&$Model, $settings = array()) { if (!empty($settings) && is_array($settings)) { $this->settings = array_merge($this->settings, $settings); } if (!empty($this->settings['blacklist_keys']) && is_array($this->settings['blacklist_keys'])) { $this->blacklistKeywords = array_merge($this->blacklistKeywords, $this->settings['blacklist_keys']); } if (!empty($this->settings['blacklist_words']) && is_array($this->settings['blacklist_words'])) { $this->blacklistWords = array_merge($this->blacklistWords, $this->settings['blacklist_words']); } }
Startup hook from the model @param object $Model @param array $settings @return void
setup
php
Datawalke/Coordino
app/models/behaviors/commentia.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/commentia.php
MIT
function afterSave(&$Model, $created) { if ($created) { $data = $Model->data[$Model->name]; $flags = 0; if (!empty($data)) { // Get links in the content $links = preg_match_all("#(^|[\n ])(?:(?:http|ftp|irc)s?:\/\/|www.)(?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,4}(?:[-a-zA-Z0-9._\/&=+%?;\#]+)#is", $data[$this->settings['column_content']], $matches); $links = $matches[0]; $totalLinks = count($links); $length = strlen($data[$this->settings['column_content']]); // How many links are in the body // +2 if less than 2, -1 per link if over 2 if ($totalLinks > 2) { $flags = $flags - $totalLinks; } else { $flags = $flags + 2; } // How long is the body // +2 if more then 20 chars and no links, -1 if less then 20 if ($length >= 20 && $totalLinks <= 0) { $flags = $flags + 2; } else if ($length >= 20 && $totalLinks == 1) { ++$flags; } else if ($length < 20) { --$flags; } // Number of previous comments from email // +1 per approved, -1 per spam $comments = $Model->find('all', array( 'fields' => array($Model->alias .'.id', $Model->alias .'.status'), 'conditions' => array($Model->alias .'.'. $this->settings['column_email'] => $data[$this->settings['column_email']]), 'recursive' => -1, 'contain' => false )); if (!empty($comments)) { foreach ($comments as $comment) { if ($comment[$Model->alias]['status'] == 'spam') { --$flags; } if ($comment[$Model->alias]['status'] == 'approved') { ++$flags; } } } // Keyword search // -1 per blacklisted keyword foreach ($this->blacklistKeywords as $keyword) { if (stripos($data[$this->settings['column_content']], $keyword) !== false) { --$flags; } } // URLs that have certain words or characters in them // -1 per blacklisted word // URL length // -1 if more then 30 chars foreach ($links as $link) { foreach ($this->blacklistWords as $word) { if (stripos($link, $word) !== false) { --$flags; } } foreach ($this->blacklistKeywords as $keyword) { if (stripos($link, $keyword) !== false) { --$flags; } } if (strlen($link) >= 30) { --$flags; } } // Body starts with... // -10 flags $firstWord = substr($data[$this->settings['column_content']], 0, stripos($data[$this->settings['column_content']], ' ')); $firstDisallow = array_merge($this->blacklistKeywords, array('interesting', 'cool', 'sorry')); if (in_array(strtolower($firstWord), $firstDisallow)) { $flags = $flags - 10; } // Author name has http:// in it // -2 flags if (stripos($data[$this->settings['column_author']], 'http://') !== false) { $flags = $flags - 2; } // Body used in previous comment // -1 per exact comment $previousComments = $Model->find('count', array( 'conditions' => array($Model->alias .'.'. $this->settings['column_content'] => $data[$this->settings['column_content']]), 'recursive' => -1, 'contain' => false )); if ($previousComments > 0) { $flags = $flags - $previousComments; } // Random character match // -1 point per 5 consecutive consonants $consonants = preg_match_all('/[^aAeEiIoOuU\s]{5,}+/i', $data[$this->settings['column_content']], $matches); $totalConsonants = count($matches[0]); if ($totalConsonants > 0) { $flags = $flags - $totalConsonants; } // Finalize and save if ($flags >= 1) { $status = 'approved'; } else if ($flags == 0) { $status = 'pending'; } else if ($flags <= $this->settings['deletion']) { $status = 'delete'; } else { $status = 'spam'; } if ($status == 'delete') { $Model->delete($Model->id, false); } else { $update = array(); $update['status'] = $status; $update['flags'] = $flags; $save = array('status'); if ($this->settings['save_flags'] === true) { $save[] = 'flags'; } $Model->id = $Model->id; $Model->save($update, false, $save); if ($this->settings['send_email'] === true) { $this->notify($data, $update); } } } return $flags; } }
Runs before a save and marks the content as spam or regular comment @param object $Model @param boolean $created @return mixed
afterSave
php
Datawalke/Coordino
app/models/behaviors/commentia.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/commentia.php
MIT
function notify($data, $stats) { if (!empty($this->settings['parent_model']) && !empty($this->settings['article_link']) && !empty($this->settings['notify_email'])) { App::import('Component', 'Email'); $Email = new EmailComponent(); $Entry = ucfirst(strtolower($this->settings['parent_model'])); // Get parent entry/blog $entry = ClassRegistry::init($Entry)->find('first', array( 'fields' => array($Entry .'.id', $Entry .'.title'), 'conditions' => array($Entry .'.id' => $data[$this->settings['column_foreign_id']]) )); // Config $entryLink = str_replace(':id', $entry[$Entry]['id'], $this->settings['article_link']); $entryTitle = $entry[$Entry]['title']; // Build message $message = "A new comment has been posted for: ". $entryLink ."\n\n"; $message .= 'Name: '. $data[$this->settings['column_author']] .' <'. $data[$this->settings['column_email']] .">\n"; $message .= 'Status: '. ucfirst($stats['status']) .' ('. $stats['flags'] ." flags)\n"; $message .= "Message:\n\n". $data[$this->settings['column_content']]; // Send email $Email->to = $this->settings['notify_email']; $Email->from = $data[$this->settings['column_author']] .' <'. $data[$this->settings['column_email']] .'>'; $Email->subject = 'Comment Approval: '. $entryTitle; $Email->send($message); } }
Sends out an email notifying you of a new comment @param array $data @param array $stats @return void
notify
php
Datawalke/Coordino
app/models/behaviors/commentia.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/commentia.php
MIT
public function setup(&$Model, $config = null) { if (is_array($config)) { $this->settings[$Model->alias] = array_merge($this->defaults, $config); } else { $this->settings[$Model->alias] = $this->defaults; } $this->createShadowModel($Model); $Model->Behaviors->attach('Containable'); }
Configure the behavior through the Model::actsAs property @param object $Model @param array $config
setup
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function createRevision(&$Model) { if (! $Model->id) { trigger_error('RevisionBehavior: Model::id must be set', E_USER_WARNING); return null; } if (!$Model->ShadowModel) { trigger_error('RevisionBehavior: ShadowModel doesnt exist.', E_USER_WARNING); return false; } $habtm = array(); $all_habtm = $Model->getAssociated('hasAndBelongsToMany'); foreach ($all_habtm as $assocAlias) { if (isset($Model->ShadowModel->_schema[$assocAlias])) { $habtm[] = $assocAlias; } } $data = $Model->find('first', array( 'conditions'=>array($Model->alias.'.'.$Model->primaryKey => $Model->id), 'contain' => $habtm )); $Model->ShadowModel->create($data); $Model->ShadowModel->set('version_created', date('Y-m-d H:i:s')); foreach ($habtm as $assocAlias) { $foreign_keys = Set::extract($data,'/'.$assocAlias.'/'.$Model->{$assocAlias}->primaryKey); $Model->ShadowModel->set($assocAlias, implode(',',$foreign_keys)); } return $Model->ShadowModel->save(); }
Manually create a revision of the current record of Model->id @example $this->Post->id = 5; $this->Post->createRevision(); @param object $Model @return boolean success
createRevision
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function diff(&$Model, $from_version_id = null, $to_version_id = null, $options = array()) { if (! $Model->id) { trigger_error('RevisionBehavior: Model::id must be set', E_USER_WARNING); return null; } if (!$Model->ShadowModel) { trigger_error('RevisionBehavior: ShadowModel doesnt exist.', E_USER_WARNING); return null; } if (isset($options['conditions'])) { $conditions = am($options['conditions'],array($Model->primaryKey => $Model->id)); } else { $conditions = array( $Model->primaryKey => $Model->id); } if (is_numeric($from_version_id) || is_numeric($to_version_id)) { if (is_numeric($from_version_id) && is_numeric($to_version_id)) { $conditions['version_id'] = array($from_version_id,$to_version_id); if ($Model->ShadowModel->find('count',array('conditions'=>$conditions)) < 2) { return false; } } else { if (is_numeric($from_version_id)) { $conditions['version_id'] = $from_version_id; } else { $conditions['version_id'] = $to_version_id; } if ($Model->ShadowModel->find('count',array('conditions'=>$conditions)) < 1) { return false; } } } $conditions = array($Model->primaryKey => $Model->id); if (is_numeric($from_version_id)) { $conditions['version_id >='] = $from_version_id; } if (is_numeric($to_version_id)) { $conditions['version_id <='] = $to_version_id; } $options['conditions'] = $conditions; $all = $this->revisions($Model,$options,true); if (sizeof($all) == 0) { return null; } $unified = array(); $keys = array_keys($all[0][$Model->alias]); foreach ($keys as $field) { $all_values = Set::extract($all,'/'.$Model->alias.'/'.$field); $all_values = array_reverse(array_unique(array_reverse($all_values,true)),true); if (sizeof($all_values) == 1) { $unified[$field] = reset($all_values); } else { $unified[$field] = $all_values; } } return array($Model->alias => $unified); }
Returns an array that maps to the Model, only with multiple values for fields that has been changed @example $this->Post->id = 4; $changes = $this->Post->diff(); @example $this->Post->id = 4; $my_changes = $this->Post->diff(null,nul,array('conditions'=>array('user_id'=>4))); @example $this->Post->id = 4; $difference = $this->Post->diff(45,192); @param Object $Model @param int $from_version_id @param int $to_version_id @param array $options @return array
diff
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function newest(&$Model, $options = array()) { if (! $Model->id) { trigger_error('RevisionBehavior: Model::id must be set', E_USER_WARNING); return null; } if (!$Model->ShadowModel) { trigger_error('RevisionBehavior: ShadowModel doesnt exist.', E_USER_WARNING); return null; } if (isset($options['conditions'])) { $options['conditions'] = am($options['conditions'],array($Model->alias.'.'.$Model->primaryKey => $Model->id)); } else { $options['conditions'] = array( $Model->alias.'.'.$Model->primaryKey => $Model->id); } return $Model->ShadowModel->find('first',$options); }
Finds the newest revision, including the current one. Use with caution, the live model may be different depending on the usage of ignore fields. @example $this->Post->id = 6; $newest_revision = $this->Post->newest(); @param object $Model @param array $options @return array
newest
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function previous(&$Model, $options = array()) { if (! $Model->id) { trigger_error('RevisionBehavior: Model::id must be set', E_USER_WARNING); return null; } if (!$Model->ShadowModel) { trigger_error('RevisionBehavior: ShadowModel doesnt exist.', E_USER_WARNING); return false; } $options['limit'] = 1; $options['page'] = 2; if (isset($options['conditions'])) { $options['conditions'] = am($options['conditions'],array($Model->primaryKey => $Model->id)); } else { $options['conditions'] = array( $Model->primaryKey => $Model->id); } $revisions = $Model->ShadowModel->find('all',$options); if (!$revisions) { return null; } return $revisions[0]; }
Find the second newest revisions, including the current one. @example $this->Post->id = 6; $undo_revision = $this->Post->previous(); @param object $Model @param array $options @return array
previous
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function revertAll(&$Model, $options = array()) { if (!$Model->ShadowModel) { trigger_error('RevisionBehavior: ShadowModel doesnt exist.', E_USER_WARNING); return false; } if (empty($options) || !isset($options['date'])) { return FALSE; } if (!isset($options['conditions'])) { $options['conditions'] = array(); } // leave model rows out side of condtions alone // leave model rows not edited since date alone $all = $Model->find('all',array('conditions'=>$options['conditions'],'fields'=>$Model->primaryKey)); $allIds = Set::extract($all,'/'.$Model->alias.'/'.$Model->primaryKey); $cond = $options['conditions']; $cond['version_created <'] = $options['date']; $created_before_date = $Model->ShadowModel->find('all',array( 'order' => $Model->primaryKey, 'conditions' => $cond, 'fields' => array('version_id',$Model->primaryKey) )); $created_before_dateIds = Set::extract($created_before_date,'/'.$Model->alias.'/'.$Model->primaryKey); $deleteIds = array_diff($allIds,$created_before_dateIds); // delete all Model rows where there are only version_created later than date $Model->deleteAll(array($Model->alias.'.'.$Model->primaryKey => $deleteIds),false,true); unset($cond['version_created <']); $cond['version_created >='] = $options['date']; $created_after_date = $Model->ShadowModel->find('all',array( 'order' => $Model->primaryKey, 'conditions' => $cond, 'fields' => array('version_id',$Model->primaryKey) )); $created_after_dateIds = Set::extract($created_after_date,'/'.$Model->alias.'/'.$Model->primaryKey); $updateIds = array_diff($created_after_dateIds,$deleteIds); $revertSuccess = true; // update model rows that have version_created earlier than date to latest before date foreach ($updateIds as $mid) { $Model->id = $mid; if ( ! $Model->revertToDate($options['date']) ) { $revertSuccess = false; } } return $revertSuccess; }
Revert all rows matching conditions to given date. Model rows outside condition or not edited will not be affected. Edits since date will be reverted and rows created since date deleted. @param object $Model @param array $options 'conditions','date' @return boolean success
revertAll
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function revertTo(&$Model, $version_id) { if (! $Model->id) { trigger_error('RevisionBehavior: Model::id must be set', E_USER_WARNING); return null; } if (!$Model->ShadowModel) { trigger_error('RevisionBehavior: ShadowModel doesnt exist.', E_USER_WARNING); return false; } $data = $Model->ShadowModel->find('first',array('conditions'=>array('version_id'=>$version_id))); if ($data == false) { return false; } foreach ($Model->getAssociated('hasAndBelongsToMany') as $assocAlias) { if (isset($Model->ShadowModel->_schema[$assocAlias])) { $data[$assocAlias][$assocAlias] = explode(',',$data[$Model->alias][$assocAlias]); } } return $Model->save($data); }
Revert current Model->id to the given revision id Will return false if version id is invalid or save fails @example $this->Post->id = 3; $this->Post->revertTo(12); @param object $Model @param int $version_id @return boolean
revertTo
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function revertToDate(&$Model, $datetime, $cascade = false, $force_delete = false) { if (! $Model->id) { trigger_error('RevisionBehavior: Model::id must be set', E_USER_WARNING); return null; } if ($cascade) { $associated = array_merge($Model->hasMany, $Model->hasOne); foreach ($associated as $assoc => $data) { $ids = array(); $cascade = false; /* Check if association has dependent children */ $depassoc = array_merge($Model->$assoc->hasMany, $Model->$assoc->hasOne); foreach ($depassoc as $dep) { if ($dep['dependent']) { $cascade = true; } } /* Query live data for children */ $children = $Model->$assoc->find('list', array('conditions'=>array($data['foreignKey']=>$Model->id),'recursive'=>-1)); if (!empty($children)) { $ids = array_keys($children); } /* Query shadow table for deleted children */ $revision_children = $Model->$assoc->ShadowModel->find('all', array( 'fields'=>array('DISTINCT '.$Model->primaryKey), 'conditions'=>array( $data['foreignKey']=>$Model->id, 'NOT' => array( $Model->primaryKey => $ids ) ), )); if (!empty($revision_children)) { $ids = am($ids,Set::extract($revision_children,'/'.$assoc.'/'.$Model->$assoc->primaryKey)); } /* Revert all children */ foreach ($ids as $id) { $Model->$assoc->id = $id; $Model->$assoc->revertToDate($datetime, $cascade, $force_delete); } } } if (empty($Model->ShadowModel)) { return true; } $data = $Model->ShadowModel->find('first',array( 'conditions'=>array( $Model->primaryKey => $Model->id, 'version_created <='=>$datetime ), 'order'=>'version_created ASC, version_id ASC' )); /* If no previous version was found and revertToDate() was called with force_delete, then delete the live data, else leave it alone */ if ($data == false) { if ($force_delete) { $Model->logableAction['Revision'] = 'revertToDate('.$datetime.') delete'; return $Model->delete($Model->id); } return true; } $habtm = array(); foreach ($Model->getAssociated('hasAndBelongsToMany') as $assocAlias) { if (isset($Model->ShadowModel->_schema[$assocAlias])) { $habtm[] = $assocAlias; } } $liveData = $Model->find('first', array( 'contain'=> $habtm, 'conditions'=>array($Model->alias.'.'.$Model->primaryKey => $Model->id))); $Model->logableAction['Revision'] = 'revertToDate('.$datetime.') add'; if ($liveData) { $Model->logableAction['Revision'] = 'revertToDate('.$datetime.') edit'; foreach ($Model->getAssociated('hasAndBelongsToMany') as $assocAlias) { if (isset($Model->ShadowModel->_schema[$assocAlias])) { $ids = Set::extract($liveData,'/'.$assocAlias.'/'.$Model->$assocAlias->primaryKey); if (empty($ids) || is_string($ids)) { $liveData[$Model->alias][$assocAlias] = ''; } else { $liveData[$Model->alias][$assocAlias] = implode(',',$ids); } $data[$assocAlias][$assocAlias] = explode(',',$data[$Model->alias][$assocAlias]); } unset($liveData[$assocAlias]); } $changeDetected = false; foreach ($liveData[$Model->alias] as $key => $value) { if ( isset($data[$Model->alias][$key])) { $old_value = $data[$Model->alias][$key]; } else { $old_value = ''; } if ($value != $old_value ) { $changeDetected = true; } } if (!$changeDetected) { return true; } } $auto = $this->settings[$Model->alias]['auto']; $this->settings[$Model->alias]['auto'] = false; $Model->ShadowModel->create($data,true); $Model->ShadowModel->set('version_created', date('Y-m-d H:i:s')); $Model->ShadowModel->save(); $Model->version_id = $Model->ShadowModel->id; $success = $Model->save($data); $this->settings[$Model->alias]['auto'] = $auto; return $success; }
Revert to the oldest revision after the given datedate. Will cascade to hasOne and hasMany associeted models if $cascade is true. Will return false if no change is made on the main model @example $this->Post->id = 3; $this->Post->revertToDate(date('Y-m-d H:i:s',strtotime('Yesterday'))); @example $this->Post->id = 4; $this->Post->revertToDate('2008-09-01',true); @param object $Model @param string $datetime @param boolean $cascade @param boolean $force_delete @return boolean
revertToDate
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function revisions(&$Model, $options = array(), $include_current = false) { if (! $Model->id) { trigger_error('RevisionBehavior: Model::id must be set', E_USER_WARNING); return null; } if (!$Model->ShadowModel) { trigger_error('RevisionBehavior: ShadowModel doesnt exist.', E_USER_WARNING); return null; } if (isset($options['conditions'])) { $options['conditions'] = am($options['conditions'],array($Model->alias.'.'.$Model->primaryKey => $Model->id)); } else { $options['conditions'] = array($Model->alias.'.'.$Model->primaryKey => $Model->id); } if ( $include_current == false ) { $current = $this->newest($Model, array('fields'=>array($Model->alias.'.version_id',$Model->primaryKey))); $options['conditions'][$Model->alias.'.version_id !='] = $current[$Model->alias]['version_id']; } return $Model->ShadowModel->find('all',$options); }
Returns a comeplete list of revisions for the current Model->id. The options array may include Model::find parameters to narrow down result Alias for shadow('all',array('conditions'=>array($Model->primaryKey => $Model->id))); @example $this->Post->id = 4; $history = $this->Post->revisions(); @example $this->Post->id = 4; $today = $this->Post->revisions(array('conditions'=>array('version_create >'=>'2008-12-10'))); @param object $Model @param array $options @param boolean $include_current If true will include last saved (live) data @return array
revisions
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function undelete(&$Model) { if (! $Model->id) { trigger_error('RevisionBehavior: Model::id must be set', E_USER_WARNING); return null; } if (!$Model->ShadowModel) { trigger_error('RevisionBehavior: ShadowModel doesnt exist.', E_USER_WARNING); return false; } if ($Model->find('count',array( 'conditions'=>array($Model->primaryKey=>$Model->id), 'recursive'=>-1)) > 0) { return false; } $data = $this->newest($Model); if (!$data) { return false; } $beforeUndeleteSuccess = true; if (method_exists($Model,'beforeUndelete')) { $beforeUndeleteSuccess = $Model->beforeUndelete(); } if (!$beforeUndeleteSuccess) { return false; } $model_id = $data[$Model->alias][$Model->primaryKey]; unset($data[$Model->alias][$Model->ShadowModel->primaryKey]); $Model->create($data,true); $auto_setting = $this->settings[$Model->alias]['auto']; $this->settings[$Model->alias]['auto'] = false; $save_success = $Model->save(); $this->settings[$Model->alias]['auto'] = $auto_setting; if (!$save_success) { return false; } $Model->updateAll( array($Model->primaryKey => $model_id), array($Model->primaryKey => $Model->id) ); $Model->id = $model_id; $Model->createRevision(); $afterUndeleteSuccess = true; if (method_exists($Model,'afterUndelete')) { $afterUndeleteSuccess = $Model->afterUndelete(); } return $afterUndeleteSuccess; }
Undoes an delete by saving the last revision to the Model Will return false if this Model->id exist in the live table. Calls Model::beforeUndelete and Model::afterUndelete @example $this->Post->id = 7; $this->Post->undelete(); @param object $Model @return boolean
undelete
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function undo(&$Model) { if (! $Model->id) { trigger_error('RevisionBehavior: Model::id must be set', E_USER_WARNING); return null; } if (!$Model->ShadowModel) { trigger_error('RevisionBehavior: ShadowModel doesnt exist.', E_USER_WARNING); return false; } $data = $this->previous($Model); if ($data == false) { $Model->logableAction['Revision'] = 'undo add'; $Model->delete($Model->id); return false; } foreach ($Model->getAssociated('hasAndBelongsToMany') as $assocAlias) { if (isset($Model->ShadowModel->_schema[$assocAlias])) { $data[$assocAlias][$assocAlias] = explode(',',$data[$Model->alias][$assocAlias]); } } $Model->logableAction['Revision'] = 'undo changes'; return $Model->save($data); }
Update to previous revision @example $this->Post->id = 2; $this->Post->undo(); @param object $Model @return boolean
undo
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function updateRevisions(&$Model, $idlist = array()) { if (!$Model->ShadowModel) { trigger_error('RevisionBehavior: ShadowModel doesnt exist.', E_USER_WARNING); return null; } foreach ($idlist as $id ) { $Model->id = $id; $Model->createRevision(); } }
Calls create revision for all rows matching primary key list of $idlist @example $this->Model->updateRevisions(array(1,2,3)); @param object $Model @param array $idlist
updateRevisions
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function afterDelete(&$Model) { if ($this->settings[$Model->alias]['auto'] === false) { return true; } if (!$Model->ShadowModel) { return true; } if (isset($this->deleteUpdates[$Model->alias]) && !empty($this->deleteUpdates[$Model->alias])) { foreach ($this->deleteUpdates[$Model->alias] as $assocAlias => $assocIds) { $Model->{$assocAlias}->updateRevisions($assocIds); } unset($this->deleteUpdates[$Model->alias]); } }
Causes revision for habtm associated models if that model does version control on their relationship. BeforeDelete identifies the related models that will need to do the revision update in afterDelete. Uses @param unknown_type $Model
afterDelete
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function beforeDelete(&$Model) { if ($this->settings[$Model->alias]['auto'] === false) { return true; } if (!$Model->ShadowModel) { return true; } foreach ($Model->hasAndBelongsToMany as $assocAlias => $a) { if (isset($Model->{$assocAlias}->ShadowModel->_schema[$Model->alias])) { $joins = $Model->{$a['with']}->find('all',array( 'recursive' => -1, 'conditions' => array( $a['foreignKey'] => $Model->id ) )); $this->deleteUpdates[$Model->alias][$assocAlias] = Set::extract($joins,'/'.$a['with'].'/'.$a['associationForeignKey']); } } return true; }
Causes revision for habtm associated models if that model does version control on their relationship. BeforeDelete identifies the related models that will need to do the revision update in afterDelete. @param object $Model @return boolean
beforeDelete
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
public function beforeSave(&$Model) { if ($this->settings[$Model->alias]['auto'] === false) { return true; } if (!$Model->ShadowModel) { return true; } $Model->ShadowModel->create(); if (!isset($Model->data[$Model->alias][$Model->primaryKey]) && !$Model->id) { return true; } $habtm = array(); foreach ($Model->getAssociated('hasAndBelongsToMany') as $assocAlias) { if (isset($Model->ShadowModel->_schema[$assocAlias])) { $habtm[] = $assocAlias; } } $this->oldData[$Model->alias] = $Model->find('first', array( 'contain'=> $habtm, 'conditions'=>array($Model->alias.'.'.$Model->primaryKey => $Model->id))); return true; }
Revision uses the beforeSave callback to remember the old data for comparison in afterSave @param object $Model @return boolean
beforeSave
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
private function createShadowModel(&$Model) { if (is_null($this->settings[$Model->alias]['useDbConfig'])) { $dbConfig = $Model->useDbConfig; } else { $dbConfig = $this->settings[$Model->alias]['useDbConfig']; } $db = & ConnectionManager::getDataSource($dbConfig); if ($Model->useTable) { $shadow_table = $Model->useTable; } else { $shadow_table = Inflector::tableize($Model->name); } $shadow_table = $shadow_table . $this->revision_suffix; $prefix = $Model->tablePrefix ? $Model->tablePrefix : $db->config['prefix']; $full_table_name = $prefix . $shadow_table; $existing_tables = $db->listSources(); if (!in_array($full_table_name, $existing_tables)) { $Model->ShadowModel = false; return false; } $useShadowModel = $this->settings[$Model->alias]['model']; if (is_string($useShadowModel) && App::import('model',$useShadowModel)) { $Model->ShadowModel = new $useShadowModel(false, $shadow_table, $dbConfig); } else { $Model->ShadowModel = new Model(false, $shadow_table, $dbConfig); } if ($Model->tablePrefix) { $Model->ShadowModel->tablePrefix = $Model->tablePrefix; } $Model->ShadowModel->alias = $Model->alias; $Model->ShadowModel->primaryKey = 'version_id'; $Model->ShadowModel->order = 'version_created DESC, version_id DESC'; return true; }
Returns a generic model that maps to the current $Model's shadow table. @param object $Model @return boolean
createShadowModel
php
Datawalke/Coordino
app/models/behaviors/revision.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/revision.php
MIT
function setup(&$model, $settings = array()) { $default = array( 'table_label' => 'tags', 'tag_label' => 'tag', 'separator' => ','); if (!isset($this->settings[$model->name])) { $this->settings[$model->name] = $default; } $this->settings[$model->name] = array_merge($this->settings[$model->name], ife(is_array($settings), $settings, array())); }
Initiate behaviour for the model using specified settings. @param object $model Model using the behaviour @param array $settings Settings to override for model. @access public
setup
php
Datawalke/Coordino
app/models/behaviors/tag.php
https://github.com/Datawalke/Coordino/blob/master/app/models/behaviors/tag.php
MIT