WF AQ

Knowledge base

4 Gennaio 2019
di admin@admin
Commenti disabilitati su Installazione Entrust ACL per Laravel

Installazione Entrust ACL per Laravel

Fonte: https://github.com/Zizaco/entrust

Codice sorgente: entrust-master

N.B.: installare prima Laravel con relativa procedura e il sistema di autenticazione nativo (https://laravel.com/docs/5.7/authentication).

__________________________________________________

 

Entrust is a succinct and flexible way to add Role-based Permissions to Laravel 5.

If you are looking for the Laravel 4 version, take a look Branch 1.0. It contains the latest entrust version for Laravel 4.

Contents

Installation

  1. In order to install Laravel 5 Entrust, just add the following to your composer.json. Then run composer update:
"zizaco/entrust": "5.2.x-dev"
  1. Open your config/app.php and add the following to the providers array:
Zizaco\Entrust\EntrustServiceProvider::class,
  1. In the same config/app.php and add the following to the aliases array:
'Entrust'   => Zizaco\Entrust\EntrustFacade::class,
  1. Run the command below to publish the package config file config/entrust.php:
php artisan vendor:publish
  1. Open your config/auth.php and add the following to it:
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => Namespace\Of\Your\User\Model\User::class,
        'table' => 'users',
    ],
],
  1. If you want to use Middleware (requires Laravel 5.1 or later) you also need to add the following:
    'role' => \Zizaco\Entrust\Middleware\EntrustRole::class,
    'permission' => \Zizaco\Entrust\Middleware\EntrustPermission::class,
    'ability' => \Zizaco\Entrust\Middleware\EntrustAbility::class,

to routeMiddleware array in app/Http/Kernel.php.

Configuration

Set the property values in the config/auth.php. These values will be used by entrust to refer to the correct user table and model.

To further customize table names and model namespaces, edit the config/entrust.php.

User relation to roles

Now generate the Entrust migration:

php artisan entrust:migration

It will generate the <timestamp>_entrust_setup_tables.php migration. You may now run it with the artisan migrate command:

php artisan migrate

After the migration, four new tables will be present:

  • roles — stores role records
  • permissions — stores permission records
  • role_user — stores many-to-many relations between roles and users
  • permission_role — stores many-to-many relations between roles and permissions

Models

Role

Create a Role model inside app/models/Role.php using the following example:

<?php namespace App;

use Zizaco\Entrust\EntrustRole;

class Role extends EntrustRole
{
}

The Role model has three main attributes:

  • name — Unique name for the Role, used for looking up role information in the application layer. For example: “admin”, “owner”, “employee”.
  • display_name — Human readable name for the Role. Not necessarily unique and optional. For example: “User Administrator”, “Project Owner”, “Widget Co. Employee”.
  • description — A more detailed explanation of what the Role does. Also optional.

Both display_name and description are optional; their fields are nullable in the database.

Permission

Create a Permission model inside app/models/Permission.php using the following example:

<?php namespace App;

use Zizaco\Entrust\EntrustPermission;

class Permission extends EntrustPermission
{
}

The Permission model has the same three attributes as the Role:

  • name — Unique name for the permission, used for looking up permission information in the application layer. For example: “create-post”, “edit-user”, “post-payment”, “mailing-list-subscribe”.
  • display_name — Human readable name for the permission. Not necessarily unique and optional. For example “Create Posts”, “Edit Users”, “Post Payments”, “Subscribe to mailing list”.
  • description — A more detailed explanation of the Permission.

In general, it may be helpful to think of the last two attributes in the form of a sentence: “The permission display_name allows a user to description.”

User

Next, use the EntrustUserTrait trait in your existing User model. For example:

<?php

use Zizaco\Entrust\Traits\EntrustUserTrait;

class User extends Eloquent
{
    use EntrustUserTrait; // add this trait to your user model

    ...
}

This will enable the relation with Role and add the following methods roles()hasRole($name)withRole($name)can($permission), and ability($roles, $permissions, $options) within your User model.

Don’t forget to dump composer autoload

composer dump-autoload

And you are ready to go.

Soft Deleting

The default migration takes advantage of onDelete('cascade') clauses within the pivot tables to remove relations when a parent record is deleted. If for some reason you cannot use cascading deletes in your database, the EntrustRole and EntrustPermission classes, and the HasRole trait include event listeners to manually delete records in relevant pivot tables. In the interest of not accidentally deleting data, the event listeners will not delete pivot data if the model uses soft deleting. However, due to limitations in Laravel’s event listeners, there is no way to distinguish between a call to delete() versus a call to forceDelete(). For this reason, before you force delete a model, you must manually delete any of the relationship data(unless your pivot tables uses cascading deletes). For example:

$role = Role::findOrFail(1); // Pull back a given role

// Regular Delete
$role->delete(); // This will work no matter what

// Force Delete
$role->users()->sync([]); // Delete relationship data
$role->perms()->sync([]); // Delete relationship data

$role->forceDelete(); // Now force delete will work regardless of whether the pivot table has cascading delete

Usage

Concepts

Let’s start by creating the following Roles and Permissions:

$owner = new Role();
$owner->name         = 'owner';
$owner->display_name = 'Project Owner'; // optional
$owner->description  = 'User is the owner of a given project'; // optional
$owner->save();

$admin = new Role();
$admin->name         = 'admin';
$admin->display_name = 'User Administrator'; // optional
$admin->description  = 'User is allowed to manage and edit other users'; // optional
$admin->save();

Next, with both roles created let’s assign them to the users. Thanks to the HasRole trait this is as easy as:

$user = User::where('username', '=', 'michele')->first();

// role attach alias
$user->attachRole($admin); // parameter can be an Role object, array, or id

// or eloquent's original technique
$user->roles()->attach($admin->id); // id only

Now we just need to add permissions to those Roles:

$createPost = new Permission();
$createPost->name         = 'create-post';
$createPost->display_name = 'Create Posts'; // optional
// Allow a user to...
$createPost->description  = 'create new blog posts'; // optional
$createPost->save();

$editUser = new Permission();
$editUser->name         = 'edit-user';
$editUser->display_name = 'Edit Users'; // optional
// Allow a user to...
$editUser->description  = 'edit existing users'; // optional
$editUser->save();

$admin->attachPermission($createPost);
// equivalent to $admin->perms()->sync(array($createPost->id));

$owner->attachPermissions(array($createPost, $editUser));
// equivalent to $owner->perms()->sync(array($createPost->id, $editUser->id));

Checking for Roles & Permissions

Now we can check for roles and permissions simply by doing:

$user->hasRole('owner');   // false
$user->hasRole('admin');   // true
$user->can('edit-user');   // false
$user->can('create-post'); // true

Both hasRole() and can() can receive an array of roles & permissions to check:

$user->hasRole(['owner', 'admin']);       // true
$user->can(['edit-user', 'create-post']); // true

By default, if any of the roles or permissions are present for a user then the method will return true. Passing true as a second parameter instructs the method to require all of the items:

$user->hasRole(['owner', 'admin']);             // true
$user->hasRole(['owner', 'admin'], true);       // false, user does not have admin role
$user->can(['edit-user', 'create-post']);       // true
$user->can(['edit-user', 'create-post'], true); // false, user does not have edit-user permission

You can have as many Roles as you want for each User and vice versa.

The Entrust class has shortcuts to both can() and hasRole() for the currently logged in user:

Entrust::hasRole('role-name');
Entrust::can('permission-name');

// is identical to

Auth::user()->hasRole('role-name');
Auth::user()->can('permission-name');

You can also use placeholders (wildcards) to check any matching permission by doing:

// match any admin permission
$user->can("admin.*"); // true

// match any permission about users
$user->can("*_users"); // true

To filter users according a specific role, you may use withRole() scope, for example to retrieve all admins:

$admins = User::withRole('admin')->get();
// or maybe with a relationsship
$company->users()->withRole('admin')->get();

User ability

More advanced checking can be done using the awesome ability function. It takes in three parameters (roles, permissions, options):

  • roles is a set of roles to check.
  • permissions is a set of permissions to check.

Either of the roles or permissions variable can be a comma separated string or array:

$user->ability(array('admin', 'owner'), array('create-post', 'edit-user'));

// or

$user->ability('admin,owner', 'create-post,edit-user');

This will check whether the user has any of the provided roles and permissions. In this case it will return true since the user is an admin and has the create-post permission.

The third parameter is an options array:

$options = array(
    'validate_all' => true | false (Default: false),
    'return_type'  => boolean | array | both (Default: boolean)
);
  • validate_all is a boolean flag to set whether to check all the values for true, or to return true if at least one role or permission is matched.
  • return_type specifies whether to return a boolean, array of checked values, or both in an array.

Here is an example output:

$options = array(
    'validate_all' => true,
    'return_type' => 'both'
);

list($validate, $allValidations) = $user->ability(
    array('admin', 'owner'),
    array('create-post', 'edit-user'),
    $options
);

var_dump($validate);
// bool(false)

var_dump($allValidations);
// array(4) {
//     ['role'] => bool(true)
//     ['role_2'] => bool(false)
//     ['create-post'] => bool(true)
//     ['edit-user'] => bool(false)
// }

The Entrust class has a shortcut to ability() for the currently logged in user:

Entrust::ability('admin,owner', 'create-post,edit-user');

// is identical to

Auth::user()->ability('admin,owner', 'create-post,edit-user');

Blade templates

Three directives are available for use within your Blade templates. What you give as the directive arguments will be directly passed to the corresponding Entrust function.

@role('admin')
    <p>This is visible to users with the admin role. Gets translated to 
    \Entrust::role('admin')</p>
@endrole

@permission('manage-admins')
    <p>This is visible to users with the given permissions. Gets translated to 
    \Entrust::can('manage-admins'). The @can directive is already taken by core 
    laravel authorization package, hence the @permission directive instead.</p>
@endpermission

@ability('admin,owner', 'create-post,edit-user')
    <p>This is visible to users with the given abilities. Gets translated to 
    \Entrust::ability('admin,owner', 'create-post,edit-user')</p>
@endability

Middleware

You can use a middleware to filter routes and route groups by permission or role

Route::group(['prefix' => 'admin', 'middleware' => ['role:admin']], function() {
    Route::get('/', 'AdminController@welcome');
    Route::get('/manage', ['middleware' => ['permission:manage-admins'], 'uses' => 'AdminController@manageAdmins']);
});

It is possible to use pipe symbol as OR operator:

'middleware' => ['role:admin|root']

To emulate AND functionality just use multiple instances of middleware

'middleware' => ['role:owner', 'role:writer']

For more complex situations use ability middleware which accepts 3 parameters: roles, permissions, validate_all

'middleware' => ['ability:admin|owner,create-post|edit-user,true']

Short syntax route filter

To filter a route by permission or role you can call the following in your app/Http/routes.php:

// only users with roles that have the 'manage_posts' permission will be able to access any route within admin/post
Entrust::routeNeedsPermission('admin/post*', 'create-post');

// only owners will have access to routes within admin/advanced
Entrust::routeNeedsRole('admin/advanced*', 'owner');

// optionally the second parameter can be an array of permissions or roles
// user would need to match all roles or permissions for that route
Entrust::routeNeedsPermission('admin/post*', array('create-post', 'edit-comment'));
Entrust::routeNeedsRole('admin/advanced*', array('owner','writer'));

Both of these methods accept a third parameter. If the third parameter is null then the return of a prohibited access will be App::abort(403), otherwise the third parameter will be returned. So you can use it like:

Entrust::routeNeedsRole('admin/advanced*', 'owner', Redirect::to('/home'));

Furthermore both of these methods accept a fourth parameter. It defaults to true and checks all roles/permissions given. If you set it to false, the function will only fail if all roles/permissions fail for that user. Useful for admin applications where you want to allow access for multiple groups.

// if a user has 'create-post', 'edit-comment', or both they will have access
Entrust::routeNeedsPermission('admin/post*', array('create-post', 'edit-comment'), null, false);

// if a user is a member of 'owner', 'writer', or both they will have access
Entrust::routeNeedsRole('admin/advanced*', array('owner','writer'), null, false);

// if a user is a member of 'owner', 'writer', or both, or user has 'create-post', 'edit-comment' they will have access
// if the 4th parameter is true then the user must be a member of Role and must have Permission
Entrust::routeNeedsRoleOrPermission(
    'admin/advanced*',
    array('owner', 'writer'),
    array('create-post', 'edit-comment'),
    null,
    false
);

Route filter

Entrust roles/permissions can be used in filters by simply using the can and hasRole methods from within the Facade:

Route::filter('manage_posts', function()
{
    // check the current user
    if (!Entrust::can('create-post')) {
        return Redirect::to('admin');
    }
});

// only users with roles that have the 'manage_posts' permission will be able to access any admin/post route
Route::when('admin/post*', 'manage_posts');

Using a filter to check for a role:

Route::filter('owner_role', function()
{
    // check the current user
    if (!Entrust::hasRole('Owner')) {
        App::abort(403);
    }
});

// only owners will have access to routes within admin/advanced
Route::when('admin/advanced*', 'owner_role');

As you can see Entrust::hasRole() and Entrust::can() checks if the user is logged in, and then if he or she has the role or permission. If the user is not logged the return will also be false.

Troubleshooting

If you encounter an error when doing the migration that looks like:

SQLSTATE[HY000]: General error: 1005 Can't create table 'laravelbootstrapstarter.#sql-42c_f8' (errno: 150)
    (SQL: alter table `role_user` add constraint role_user_user_id_foreign foreign key (`user_id`)
    references `users` (`id`)) (Bindings: array ())

Then it’s likely that the id column in your user table does not match the user_id column in role_user. Make sure both are INT(10).

When trying to use the EntrustUserTrait methods, you encounter the error which looks like

Class name must be a valid object or a string

then probably you don’t have published Entrust assets or something went wrong when you did it. First of all check that you have the entrust.php file in your config directory. If you don’t, then try php artisan vendor:publish and, if it does not appear, manually copy the /vendor/zizaco/entrust/src/config/config.php file in your config directory and rename it entrust.php.

If your app uses a custom namespace then you’ll need to tell entrust where your permission and role models are, you can do this by editing the config file in config/entrust.php

'role' => 'Custom\Namespace\Role'
'permission' => 'Custom\Namespace\permission'

License

Entrust is free software distributed under the terms of the MIT license.

Contribution guidelines

Support follows PSR-1 and PSR-4 PHP coding standards, and semantic versioning.

Please report any issue you find in the issues page.
Pull requests are welcome.

 

_______________________________________________

 

N.B.: nel caso in cui l’installazione della libreria restituisca un errore seguire questa procedura:

Go to the file (vendor-> zizaco-> entrust-> src-> commands-> MigrationCommand.php and change the “fire” method to “handle” and after the command “php artisan entrust: migration” will be generated Migration and just run the “php artisan migrate” command that the tables will be generated in your database.

 

6 Dicembre 2018
di admin@admin
Commenti disabilitati su How to enable gzip compression for nginx on Plesk server

How to enable gzip compression for nginx on Plesk server

  1. Connect to the server using SSH.
  2. Create a text file using the following command:

    # touch /etc/nginx/conf.d/gzip.conf

  3. Open the file in any text editor, for example, using vi:

    # vi /etc/nginx/conf.d/gzip.conf

  4. Insert the following content in it:

    gzip on;
    gzip_disable “MSIE [1-6]\\.(?!.*SV1)”;
    gzip_proxied any;
    gzip_comp_level 5;
    gzip_types text/plain text/css application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript image/x-icon image/bmp image/svg+xml;
    gzip_vary on;

    Note: This is an example. It is possible to add other file types in gzip_types section, e.g. application/javascript, application/js, etc. The full list of available types can be viewed on a server directly in /etc/nginx/mime.types file

  5. Test the configuration and fix errors (if any):

    # nginx -t

  6. Reload nginx configuration:

    # service nginx reload

  7. To check if gzip compression enabled use the command below. When gzip enabled you will see in the output ‘Content-Encoding: gzip’:

    # curl -s -H “Accept-Encoding: gzip” -I http://domain.tld | grep Content-Encoding
    Content-Encoding: gzip

25 Settembre 2018
di admin@admin
Commenti disabilitati su Creating Unique Title Slugs with Laravel

Creating Unique Title Slugs with Laravel

When storing content in the database a typical pattern for retrieving it is to create a unique “slug” based on the title. This gives users and search engines a human-friendly way to access it through the URL.

For example, a typical URL might look like, site.com/post/1. The id in the URL gives no hints at what the content is about and is not user-friendly. Slugs, on the other hand, are designed to turn this into site.com/post/my-awesome-article

Creating slugs from an existing string is easy in Laravel as it includes a helper for just this use case:

$title = str_slug('My Awesome Title', '-');

The results of this would be a lower-cased string with a dash (-) separator between the words:

my-awesome-title

While this is a huge help it doesn’t account for situations where you have two pieces of content with the same title.

Laravel slug class

Let’s build a small utility class to handle creating unique slugs based on existing data so we can ensure that no two are the same.

For reference here is the full class:

<?php
namespace App\Services;
use App\Post;
class Slug
{
/**
* @param $title
* @param int $id
* @return string
* @throws \Exception
*/
public function createSlug($title, $id = 0)
{
// Normalize the title
$slug = str_slug($title);
// Get any that could possibly be related.
// This cuts the queries down by doing it once.
$allSlugs = $this->getRelatedSlugs($slug, $id);
// If we haven’t used it before then we are all good.
if (! $allSlugs->contains(‘slug’, $slug)){
return $slug;
}
// Just append numbers like a savage until we find not used.
for ($i = 1; $i <= 10; $i++) {
$newSlug = $slug.’-‘.$i;
if (! $allSlugs->contains(‘slug’, $newSlug)) {
return $newSlug;
}
}
throw new \Exception(‘Can not create a unique slug’);
}
protected function getRelatedSlugs($slug, $id = 0)
{
return Post::select(‘slug’)->where(‘slug’, ‘like’, $slug.’%’)
->where(‘id’, ‘<>’, $id)
->get();
}
}

What this does is give you a createSlug method that can be used in creating and editing by passing the existing record id.

Here is an example of generating for both:

// On create
$post->slug = $slug->createSlug($request->title);
// On update
if ($post->slug != $request->slug) {
 $post->slug = $slug->createSlug($request->slug, $id);
}

The Slug class itself is pretty simple. createSlug calls getRelatedSlugs which performs a single query selecting all the records that could possibly be a duplicate. Then uses the Laravel Collections class to see if it’s already used:

if (! $allSlugs->contains('slug', $slug)){
 return $slug;
}

If it still has a duplicate then it appends a number to the end and performs another check for uniqueness:

for ($i = 1; $i <= 10; $i++) {
    $newSlug = $slug.’-’.$i;
    if (! $allSlugs->contains(‘slug’, $newSlug)) {
        return $newSlug;
    }
}

Finally, if all the numbers are exhausted it just bails out by throwing an Exception.

By utilizing Laravel’s existing helpers and Collections generating unique title slugs is easy. With this implemented all that would be required next is a custom route and a query to pull out a single post by its slug:

Route::get('/post/{slug}', function(){
    $post = \App\Post::where('slug', $slug)->firstOrFail(); 
});

6 Settembre 2018
di admin@admin
Commenti disabilitati su Linux grep command

Linux grep command

The grep command syntax

The syntax is as follows:

grep 'word' filename 
grep 'word' file1 file2 file3
grep 'string1 string2' filename
cat otherfile | grep 'something'
command | grep 'something'
command option1 | grep 'data'
grep --color 'data' fileName

How do I use grep to search a file?

Search /etc/passwd file for boo user, enter:
$ grep boo /etc/passwd
Sample outputs:

foo:x:1000:1000:foo,,,:/home/foo:/bin/ksh

You can force grep to ignore word case i.e match boo, Boo, BOO and all other combination with the -i option:
$ grep -i "boo" /etc/passwd

How to use grep recursively

You can search recursively i.e. read all files under each directory for a string “192.168.1.5”
$ grep -r "192.168.1.5" /etc/
OR
$ grep -R "192.168.1.5" /etc/
Sample outputs:

/etc/ppp/options:# ms-wins 192.168.1.50
/etc/ppp/options:# ms-wins 192.168.1.51
/etc/NetworkManager/system-connections/Wired connection 1:addresses1=192.168.1.5;24;192.168.1.2;

You will see result for 192.168.1.5 on a separate line preceded by the name of the file (such as /etc/ppp/options) in which it was found. The inclusion of the file names in the output data can be suppressed by using the -h option as follows:
$ grep -h -R "192.168.1.5" /etc/
OR
$ grep -hR "192.168.1.5" /etc/
Sample outputs:

# ms-wins 192.168.1.50
# ms-wins 192.168.1.51
addresses1=192.168.1.5;24;192.168.1.2;

How to use grep to search words only

When you search for boo, grep will match fooboo, boo123, barfoo35 and more. You can force the grep command to select only those lines containing matches that form whole words i.e. match only boo word:
$ grep -w "boo" file

How to use grep to search 2 different words

Use the egrep command as follows:
$ egrep -w 'word1|word2' /path/to/file

How can I count line when words has been matched

The grep can report the number of times that the pattern has been matched for each file using -c (count) option:
$ grep -c 'word' /path/to/file
Pass the -n option to precede each line of output with the number of the line in the text file from which it was obtained:
$ grep -n 'root' /etc/passwd
Sample outputs:

1:root:x:0:0:root:/root:/bin/bash
1042:rootdoor:x:0:0:rootdoor:/home/rootdoor:/bin/csh
3319:initrootapp:x:0:0:initrootapp:/home/initroot:/bin/ksh

Force grep invert match

You can use -v option to print inverts the match; that is, it matches only those lines that do not contain the given word. For example print all line that do not contain the word bar:
$ grep -v bar /path/to/file

UNIX / Linux pipes and grep command

grep command often used with shell pipes. In this example, show the name of the hard disk devices:
# dmesg | egrep '(s|h)d[a-z]'
Display cpu model name:
# cat /proc/cpuinfo | grep -i 'Model'
However, above command can be also used as follows without shell pipe:
# grep -i 'Model' /proc/cpuinfo
Sample outputs:

model		: 30
model name	: Intel(R) Core(TM) i7 CPU       Q 820  @ 1.73GHz
model		: 30
model name	: Intel(R) Core(TM) i7 CPU       Q 820  @ 1.73GHz

How do I list just the names of matching files?

Use the -l option to list file name whose contents mention main():
$ grep -l 'main' *.c
Finally, you can force grep to display output in colors, enter:
$ grep --color vivek /etc/passwd

10 Luglio 2018
di admin@admin
Commenti disabilitati su Upgrade Mysql da 5.1 a 5.5 e quindi da 5.5 a 5.6/5.7 o MariaDB 5.5 to 10.0/10.1/10.2 in Plesk Linux

Upgrade Mysql da 5.1 a 5.5 e quindi da 5.5 a 5.6/5.7 o MariaDB 5.5 to 10.0/10.1/10.2 in Plesk Linux

N.B.: l’upgrade diretto da 5.1 a 5.6/5.7 può danneggiare il sistema. Procedere quindi prima con l’upgrade da 5.1 a 5.5 e successivamente a 5.6/5.7 

Versioni supportate:

Plesk Onyx for Linux:

  • MySQL 5.1–5.7
  • MySQL community edition 5.5, 5.6, 5.7

 

How to upgrade MySQL from 5.1 to 5.5 on Plesk for Linux

Plesk Installer gets packages from base repositories of an operating system installed.

If MySQL 5.5 is not listed in the base repository, it is not available in Plesk Installer.

In that case, in order to upgrade MySQL version to 5.5, it is needed to configure a third-party repository.

Note: PHP package can also be upgraded during this procedure. Oracle MySQL yum repository is supported only by Plesk Onyx. Also, it is required to have an SSH connection to the server with administrative privileges.

For CentOS/RHEL/CloudLinux systems Atomic repository can be used:

  1. Install the Atomicorp repository:

    # wget -q -O – http://www.atomicorp.com/installers/atomic | sh

  2. Upgrade MySQL:

    # yum upgrade mysql

  3. Restart the MySQL service:

    # service mysqld restart

  4. Upgrade MySQL databases:

    # mysql_upgrade -uadmin -p`cat /etc/psa/.psa.shadow`

  5. In case the message below appears, refer to the KB article Error during yum upgrade: Packages excluded due to repository protections:

    # yum upgrade mysql
    ….
    881 packages excluded due to repository protections
    No Packages marked for Update

 

 

How to upgrade MySQL 5.5 to 5.6/5.7 or MariaDB 5.5 to 10.0/10.1/10.2 on Linux

https://support.plesk.com/hc/en-us/articles/213403429-How-to-upgrade-MySQL-5-5-to-5-6#centos7

 

For CentOS 6:

      1. Stop the MySQL service:

        # service mysqld stop

      2. Create a backup of databases:

        # cp -a /var/lib/mysql /var/lib/mysql_backup

      3. Disable Atomic repository, if it is enabled:

        # vi /etc/yum.repos.d/atomic.repo
        enabled = 0

      4. Install the MySQL-community repository:

        # yum install http://dev.mysql.com/get/mysql57-community-release-el6-7.noarch.rpm

      5. Select a MySQL version:

        # vi /etc/yum.repos.d/mysql-community.repo
        [mysql56-community]
        enabled=0
        [mysql57-community]
        enabled=1

      6. Install MySQL packages:

        # yum update mysql

        If update of mysql package ends with Nothing to do message, make sure that mysql* packages are not added to excludes in yum.conf file and remove it if it is in the list:

        # cat /etc/yum.conf | grep exclude
        exclude=php-common php-cli php mysql* httpd* mod_ssl*

      7. Type y if this message appears:

        warning: rpmts_HdrFromFdno: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
        Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
        Importing GPG key 0x5072E1F5:
        Userid : MySQL Release Engineering <mysql-build@oss.oracle.com>
        Package: mysql57-community-release-el6-7.noarch (@/mysql57-community-release-el6-7.noarch)
        From : /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
        Is this ok [y/N]:

      8. Start the MySQL service:

        # service mysqld start

        If the service does not start, check the following article: MySQL fails to start: mysql.user table is damaged.

      9. Upgrade MySQL databases:

        # MYSQL_PWD=`cat /etc/psa/.psa.shadow` mysql_upgrade -uadmin

      10. Restart mysql service:

        # service mysqld restart

 

For CentOS 7:

CentOS 7 is shipped with MariaDB. MariaDB 10.x version is a drop-in replacement for MySQL 5.5-5.7.

      1. Create a backup of all databases with the following command:

        # MYSQL_PWD=`cat /etc/psa/.psa.shadow` mysqldump -u admin –all-databases –routines –triggers > /tmp/all-databases.sql

      2. Stop the MariaDB service:

        # service mariadb stop

      3. Remove additional packages like mariadb-bench:

        # rpm -e mariadb-bench

      4. Copy a databases directory in a separate folder like this (for backup purposes also):

        # cp -a /var/lib/mysql/ /var/lib/mysql_backup

      5. Configure MariaDB repository: open the Setting MariaDB repositories page, select OS distro, release and MariaDB version to see the configuration that should be added to /etc/yum.repos.d/MariaDB.repo file. Example for MariaDB10.1:

        [mariadb]
        name = MariaDB
        baseurl = http://yum.mariadb.org/10.1/centos7-amd64
        gpgkey = https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
        gpgcheck = 1

      6. Perform an upgrade with:

        # yum install mariadb

      7. Start the MariaDB service:

        # service mariadb start

      8. Upgrade MySQL databases:

        # MYSQL_PWD=`cat /etc/psa/.psa.shadow` mysql_upgrade -uadmin

      9. Restart mysql service:

        # service mariadb restart

      10. Execute this command to update the package version inside Plesk:

        # plesk sbin packagemng -sdf

        Note: After an upgrade to 10.1 version, there may appear ‘mysql’ init script. It can be removed:

        # rm /etc/init.d/mysql
        # systemctl daemon-reload

7 Dicembre 2017
di admin@admin
Commenti disabilitati su CenotOS: add an user to sudoers for use of sudo

CenotOS: add an user to sudoers for use of sudo

If theres an username user (for example an ftp user) we can use it as sudo user.

On CentOS, the user in “wheel” group had sudoers capacity.

sudo usermod -aG wheel username

28 Novembre 2017
di admin@admin
Commenti disabilitati su Moving WordPress

Moving WordPress

Fonte: https://codex.wordpress.org/Moving_WordPress


 

Moving to a New Server

If you are moving WordPress from one server to another, begin by backing up your WordPress directory, images, plugins, and other files on your site as well as the database. See WordPress Backups and Backing Up Your Database.

Keeping Your Domain Name and URLs

Moving your domain without changing the Home and Site URLs of your WordPress site is very simple, and in most cases can be done by moving the files.

  • If database and URL remain the same, you can move by just copying your files and database.
  • If database name or user changes, edit wp-config.php to have the correct values.
  • If you want to test before you switch, you must temporarily change “siteurl” and “home” in the database table “wp_options” (through phpMyAdmin or similar).
  • If you had any kind of rewrites (permalinks) setup you must disable .htaccess and reconfigure permalinks when it goes live.

Changing Your Domain Name and URLs

Moving a website and changing your domain name or URLs (i.e. from http://example.com/site to http://example.com, or http://example.com to http://example.net) requires the following steps – in sequence.

  1. Download your existing site files.
  2. Export your database – go in to MySQL and export the database.
  3. Move the backed up files and database into a new folder – somewhere safe – this is your site backup.
  4. Log in to the site you want to move and go to Settings > General, then change the URLs. (ie from http://example.com/ to http://example.net ) – save the settings and expect to see a 404 page.
  5. Download your site files again.
  6. Export the database again.
  7. Edit wp-config.php with the new server’s MySQL database name, user and password.
  8. Upload the files.
  9. Import the database on the new server.

When your domain name or URLs change there are additional concerns. The files and database can be moved, however references to the old domain name or location will remain in the database, and that can cause issues with links or theme display.

If you do a search and replace on your entire database to change the URLs, you can cause issues with data serialization, due to the fact that some themes and widgets store values with the length of your URL marked. When this changes, things break. To avoid that serialization issue, you have four options:

  1. Use the Velvet Blues Update URLs plugin if you can access your WP Admin Dashboard.
  2. Use the Better Search Replace plugin if you can access your WP Admin Dashboard.
  3. Use WP-CLI’s search-replace if your hosting provider (or you) have installed WP-CLI.
  4. Use the Search and Replace for WordPress Databases Script to safely change all instances on your old domain or path to your new one. (** only use this option if you are comfortable with database administration ** )

Note: Search and Replace from Interconnectit is a 3rd party script

Moving Directories On Your Existing Server

Moving the WordPress files from one location on your server to another – i.e. changing its URL – requires some special care. If you want to move WordPress to its own folder, but have it run from the root of your domain, please read Giving WordPress Its Own Directory for detailed instructions.

Here are the step-by-step instructions to move your WordPress site to a new location on the same server:

  1. Create the new location using one of these two options:
    1. If you will be moving your WordPress core files to a new directory, create the new directory.
    2. If you want to move WordPress to your root directory, make sure all index.php.htaccess, and other files that might be copied over are backed up and/or moved, and that the root directory is ready for the new WordPress files.
  2. Log in to your site.
  3. Go to the Administration > Settings > General screen.
  4. In the box for WordPress Address (URL): change the address to the new location of your main WordPress core files.
  5. In the box for Site Address (URL): change the address to the new location, which should match the WordPress (your public site) address.
  6. Click Save Changes.
  7. (Do not try to open/view your site now!)
  8. Move your WordPress core files to the new location. This includes the files found within the original directory, such ashttp://example.com/wordpress, and all the sub-directories, to the new location.
  9. Now, try to open your site by going to yourdomain.com/wp-admin. Note, you may need to go to yourdomain.com/wp-login.php
  10. If you are using Permalinks, go to the Administration > Settings > Permalinks screen and update your Permalink structure to your .htaccess file, which should be in the same directory as the main index.php file.
  11. Existing image/media links uploaded media will refer to the old folder and must be updated with the new location. You can do this with the Velvet Blues Update URLs or Better Search Replace plugins, WP-CLI’s search-replace if your hosting provider (or you) have installed WP-CLI, manually in your SQL database, or by using the 3rd party database updating tool Search and Replace Databases Script * Note: this script is best used by experienced developers.
  12. In some cases your permissions may have changed, depending on your ISP. Watch for any files with “0000” permissions and change them back to “0644”.
  13. If your theme supports menus, links to your home page may still have the old subdirectory embedded in them. Go to Appearance > Menus and update them.
  14. Sometimes you would need to restart your server, otherwise your server may give out an error. (happens in MAMP software (Mac)).

It is important that you set the URI locations BEFORE you move the files.

If You Forget to Change the Locations

If you accidentally moved the files before you changed the URIs: you have two options.

  1. Suppose the files were originally in /path/to/old/ and you moved them to /path/to/new before changing the URIs. The way to fix this would be to make /path/to/old/ a symlink (for Windows users, “symlink” is equivalent to “shortcut”) to /path/to/new/, i.e. ln -s /path/to/new /path/to/old and then follow the steps above as normal. Afterwards, delete the symlink if you want.
  2. If you forget to change the WordPress Address and Blog Address, you will be unable to change it using the wordpress interface. However, you can fix it if you have access to the database. Go to the database of your site and find the wp_options table. This table stores all the options that you can set in the interface. The WordPress Address and Blog Address are stored as siteurl and home (the option_name field). All you have to do is change the option_value field to the correct URL for the records with option_name=’siteurl‘ or option_name=’home‘.

If You Have Accidentally Changed your WordPress Site URL

Suppose you accidentally changed the URIs where you cannot move the files (but can still access the login page, through a redirection or something).

wp-login.php can be used to (re-)set the URIs. Find this line:

require( dirname(__FILE__) . '/wp-load.php' );

and insert the following lines below:

//FIXME: do comment/remove these hack lines. (once the database is updated)
update_option('siteurl', 'http://your.domain.name/the/path' );
update_option('home', 'http://your.domain.name/the/path' );

You’re done. Test your site to make sure that it works right. If the change involves a new address for your site, make sure you let people know the new address, and consider adding some redirection instructions in your .htaccess file to guide visitors to the new location.

Changing The Site URL also provides the details of this process.

If Your WordPress Site Has a Customized upload_path Value

It’s possible, but unlikely, that the upload_path option value may be set on some very old WordPress sites, or on sites where the designer needed to customize this path. In this case, you should verify that the path is still valid after the move, and adjust it as it needed. If an absolute rather than a relative path was used, the path may be incorrect for use on the new server. An incorrect upload path will result in problems with media uploads and possible filesystem errors when WordPress attempts to create upload directories on the wrong path. (See ticket ticket #41947.)

The upload_path option cannot be modified on the WordPress admin settings screen, it must be edited in the options table in the database.

Normally, the upload_path value may be blank and WordPress will use the default path. If the value is not blank and contains a value other than the default upload location, you may need to do further research to determine how to handle uploads on the site after the move.

Managing Your Old Site

Shutting It Down

  1. Download a copy of the main wordpress files from your OLD site to your hard drive and edit wp-config.php to suit the new server.
  2. Go back to your OLD site and go to Administration > Settings > General and change the URL (both of them) to that of your new site.
  3. Login on your server, go to phpMyAdmin, export as file, and save your database (but keep the old one just in case). Now, upload this new database and the copy of the wordpress core files with the edited wp-config.php to your new server. That’s it!

Keeping it Running

Caution: Make sure you have a backup of your old site’s WordPress database before proceeding!

Part A – Activating Your New Site

  1. Download your entire WordPress installation to your hard drive. Name the folder appropriately to indicate that this is your OLD site’s installation.
  2. Download your database.
  3. Go back to your OLD site and go to options and change the url (both of them) to that of your new site.
  4. Again, download your entire WordPress installation to your hard drive. Name the folder appropriately to indicate that this is your NEW site’s installation.
  5. Download your database once again (but keep the old one). Upload this database to your new server. It will be easiest if you use the same database name and you create a user with the same login credentials on your new server as on your old server.
  6. If you used a different database name and/or user (see previous step), edit wp-config.php in your NEW site’s installation folder appropriately.
  7. Upload the NEW site’s installation folder to your new site. Presto, your NEW site should be working!

Part B – Restoring Your Old Site

  1. On the original server, delete your OLD site’s database (remember, you should have a copy on your local computer that you made at the very beginning).
  2. Upload your OLD site’s installation folder to your original server, overwriting the files that are currently there (you may also delete the installation folder on the server and simply re-upload the OLD site’s files).
  3. Upload your OLD site’s database from your local computer to the server. That should do it!

Another procedure for making copies of posts, comments, pages, categories and custom field (post status, data, permalinks, ping status, etc.) easy to follow:

  1. Install a new WordPress site
  2. Go on old site Administration Screen. Here, in Manage > Export select “all” in menu Restrict Author.
  3. Click on Download Export File
  4. In new site go on Manage > Import, choose WordPress item.
  5. In the page that will be shown, select the file just exported. Click on Upload file and Import
  6. It will appear a page. In Assign Authors, assign the author to users that already exist or create new ones.
  7. Click on Submit
  8. At the end, click on Have fun

Note: using this method, if there are some articles in the new site (like Hello World, Info Page, etc.), these will not be erased. Articles are only added. Using the former procedure, the articles in new site will be deleted.

Moving WordPress Multisite

Multisite is somewhat more complicated to move, as the database itself has multiple references to the server name as well as the folder locations. If you’re simply moving to a new server with the same domain name, you can copy the files and database over, exactly as you would a traditional install.

If, instead, you are changing domains, then the best way to move Multisite is to move the files, edit the .htaccess and wp-config.php (change DOMAIN_CURRENT_SITE and, if the folder name containing Multisite changed, PATH_CURRENT_SITE), and then manually edit the database. Search for all instances of your domain name, and change them as needed. This step cannot yet be easily automated. It’s safe to search/replace any of the wp_x_posts tables, however do not attempt blanket search/replace without the Search and Replace for WordPress Databases script (aka the interconnectit script).

If you’re moving Multisite from one folder to another, you will need to make sure you edit the wp_blogs entries to change the folder name correctly. You should manually review both wp_site and wp_blogs regardless, to ensure all sites were changed correctly.

Also, manually review all the wp_x_options tables and look for three fields and edit them as needed:

  • home
  • siteurl
  • fileupload_url

If you are moving from subdomains to subfolders, or vice-versa, remember to adjust the .htaccess file and the value for SUBDOMAIN_INSTALL in your wp-config.php file accordingly.