Merge pull request #679 from stefantalen/feature/PSR-2

[WIP] Updating code to match PSR standards
This commit is contained in:
Samuel Georges 2014-10-19 10:25:15 +11:00
commit b30d85df2d
223 changed files with 4097 additions and 2785 deletions

View File

@ -2,132 +2,132 @@
return array(
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => true,
'debug' => true,
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => 'http://localhost',
'url' => 'http://localhost',
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => 'CHANGE_ME!!!',
'key' => 'CHANGE_ME!!!',
'cipher' => MCRYPT_RIJNDAEL_128,
'cipher' => MCRYPT_RIJNDAEL_128,
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => array_merge(include(base_path().'/modules/system/providers.php'), array(
'providers' => array_merge(include(base_path().'/modules/system/providers.php'), array(
// 'Illuminate\Html\HtmlServiceProvider', // Example
// 'Illuminate\Html\HtmlServiceProvider', // Example
'System\ServiceProvider',
)),
'System\ServiceProvider',
)),
/*
|--------------------------------------------------------------------------
| Service Provider Manifest
|--------------------------------------------------------------------------
|
| The service provider manifest is used by Laravel to lazy load service
| providers which are not needed for each request, as well to keep a
| list of all of the services. Here, you may set its storage spot.
|
*/
/*
|--------------------------------------------------------------------------
| Service Provider Manifest
|--------------------------------------------------------------------------
|
| The service provider manifest is used by Laravel to lazy load service
| providers which are not needed for each request, as well to keep a
| list of all of the services. Here, you may set its storage spot.
|
*/
'manifest' => storage_path().'/meta',
'manifest' => storage_path().'/meta',
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => array_merge(include(base_path().'/modules/system/aliases.php'), array(
'aliases' => array_merge(include(base_path().'/modules/system/aliases.php'), array(
// 'Str' => 'Illuminate\Support\Str', // Example
// 'Str' => 'Illuminate\Support\Str', // Example
)),
)),
);

View File

@ -2,88 +2,88 @@
return array(
/*
|--------------------------------------------------------------------------
| Default Cache Driver
|--------------------------------------------------------------------------
|
| This option controls the default cache "driver" that will be used when
| using the Caching library. Of course, you may use other drivers any
| time you wish. This is the default when another is not specified.
|
| Supported: "file", "database", "apc", "memcached", "redis", "array"
|
*/
/*
|--------------------------------------------------------------------------
| Default Cache Driver
|--------------------------------------------------------------------------
|
| This option controls the default cache "driver" that will be used when
| using the Caching library. Of course, you may use other drivers any
| time you wish. This is the default when another is not specified.
|
| Supported: "file", "database", "apc", "memcached", "redis", "array"
|
*/
'driver' => 'file',
'driver' => 'file',
/*
|--------------------------------------------------------------------------
| File Cache Location
|--------------------------------------------------------------------------
|
| When using the "file" cache driver, we need a location where the cache
| files may be stored. A sensible default has been specified, but you
| are free to change it to any other place on disk that you desire.
|
*/
/*
|--------------------------------------------------------------------------
| File Cache Location
|--------------------------------------------------------------------------
|
| When using the "file" cache driver, we need a location where the cache
| files may be stored. A sensible default has been specified, but you
| are free to change it to any other place on disk that you desire.
|
*/
'path' => storage_path().'/cache',
'path' => storage_path().'/cache',
/*
|--------------------------------------------------------------------------
| Database Cache Connection
|--------------------------------------------------------------------------
|
| When using the "database" cache driver you may specify the connection
| that should be used to store the cached items. When this option is
| null the default database connection will be utilized for cache.
|
*/
/*
|--------------------------------------------------------------------------
| Database Cache Connection
|--------------------------------------------------------------------------
|
| When using the "database" cache driver you may specify the connection
| that should be used to store the cached items. When this option is
| null the default database connection will be utilized for cache.
|
*/
'connection' => null,
'connection' => null,
/*
|--------------------------------------------------------------------------
| Database Cache Table
|--------------------------------------------------------------------------
|
| When using the "database" cache driver we need to know the table that
| should be used to store the cached items. A default table name has
| been provided but you're free to change it however you deem fit.
|
*/
/*
|--------------------------------------------------------------------------
| Database Cache Table
|--------------------------------------------------------------------------
|
| When using the "database" cache driver we need to know the table that
| should be used to store the cached items. A default table name has
| been provided but you're free to change it however you deem fit.
|
*/
'table' => 'cache',
'table' => 'cache',
/*
|--------------------------------------------------------------------------
| Memcached Servers
|--------------------------------------------------------------------------
|
| Now you may specify an array of your Memcached servers that should be
| used when utilizing the Memcached cache driver. All of the servers
| should contain a value for "host", "port", and "weight" options.
|
*/
/*
|--------------------------------------------------------------------------
| Memcached Servers
|--------------------------------------------------------------------------
|
| Now you may specify an array of your Memcached servers that should be
| used when utilizing the Memcached cache driver. All of the servers
| should contain a value for "host", "port", and "weight" options.
|
*/
'memcached' => array(
'memcached' => array(
array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 100),
array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 100),
),
),
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing a RAM based store such as APC or Memcached, there might
| be other applications utilizing the same cache. So, we'll specify a
| value to get prefixed to all our keys so we can avoid collisions.
|
*/
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing a RAM based store such as APC or Memcached, there might
| be other applications utilizing the same cache. So, we'll specify a
| value to get prefixed to all our keys so we can avoid collisions.
|
*/
'prefix' => 'laravel',
'prefix' => 'laravel',
);

View File

@ -2,126 +2,126 @@
return array(
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/
/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/
'fetch' => PDO::FETCH_CLASS,
'fetch' => PDO::FETCH_CLASS,
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => 'mysql',
'default' => 'mysql',
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => array(
'connections' => array(
'sqlite' => array(
'driver' => 'sqlite',
'database' => 'database/production.sqlite',
'prefix' => '',
),
'sqlite' => array(
'driver' => 'sqlite',
'database' => 'database/production.sqlite',
'prefix' => '',
),
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'port' => '',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'port' => '',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'pgsql' => array(
'driver' => 'pgsql',
'host' => 'localhost',
'port' => '',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
),
'pgsql' => array(
'driver' => 'pgsql',
'host' => 'localhost',
'port' => '',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
),
'sqlsrv' => array(
'driver' => 'sqlsrv',
'host' => 'localhost',
'port' => '',
'database' => 'database',
'username' => 'root',
'password' => '',
'prefix' => '',
),
'sqlsrv' => array(
'driver' => 'sqlsrv',
'host' => 'localhost',
'port' => '',
'database' => 'database',
'username' => 'root',
'password' => '',
'prefix' => '',
),
),
),
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk have not actually be run in the databases.
|
*/
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk have not actually be run in the databases.
|
*/
'migrations' => 'migrations',
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => array(
'redis' => array(
'cluster' => true,
'cluster' => true,
'default' => array(
'host' => '127.0.0.1',
'port' => 6379,
'database' => 0,
),
'default' => array(
'host' => '127.0.0.1',
'port' => 6379,
'database' => 0,
),
),
),
);

View File

@ -2,123 +2,123 @@
return array(
/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "mail", "sendmail"
|
*/
/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "mail", "sendmail"
|
*/
'driver' => 'smtp',
'driver' => 'smtp',
/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Postmark mail service, which will provide reliable delivery.
|
*/
/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Postmark mail service, which will provide reliable delivery.
|
*/
'host' => 'smtp.mailgun.org',
'host' => 'smtp.mailgun.org',
/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to delivery e-mails to
| users of your application. Like the host we have set this value to
| stay compatible with the Postmark e-mail application by default.
|
*/
/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to delivery e-mails to
| users of your application. Like the host we have set this value to
| stay compatible with the Postmark e-mail application by default.
|
*/
'port' => 587,
'port' => 587,
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => array('address' => 'noreply@site.com', 'name' => 'October'),
'from' => array('address' => 'noreply@site.com', 'name' => 'October'),
/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/
/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/
'encryption' => 'tls',
'encryption' => 'tls',
/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/
/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/
'username' => null,
'username' => null,
/*
|--------------------------------------------------------------------------
| SMTP Server Password
|--------------------------------------------------------------------------
|
| Here you may set the password required by your SMTP server to send out
| messages from your application. This will be given to the server on
| connection so that the application will be able to send messages.
|
*/
/*
|--------------------------------------------------------------------------
| SMTP Server Password
|--------------------------------------------------------------------------
|
| Here you may set the password required by your SMTP server to send out
| messages from your application. This will be given to the server on
| connection so that the application will be able to send messages.
|
*/
'password' => null,
'password' => null,
/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/
/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/
'sendmail' => '/usr/sbin/sendmail -bs',
'sendmail' => '/usr/sbin/sendmail -bs',
/*
|--------------------------------------------------------------------------
| Mail "Pretend"
|--------------------------------------------------------------------------
|
| When this option is enabled, e-mail will not actually be sent over the
| web and will instead be written to your application's logs files so
| you may inspect the message. This is great for local development.
|
*/
/*
|--------------------------------------------------------------------------
| Mail "Pretend"
|--------------------------------------------------------------------------
|
| When this option is enabled, e-mail will not actually be sent over the
| web and will instead be written to your application's logs files so
| you may inspect the message. This is great for local development.
|
*/
'pretend' => false,
'pretend' => false,
);

View File

@ -2,126 +2,126 @@
return array(
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "native", "cookie", "database", "apc",
| "memcached", "redis", "array"
|
*/
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "native", "cookie", "database", "apc",
| "memcached", "redis", "array"
|
*/
'driver' => 'native',
'driver' => 'native',
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle for it is expired. If you want them
| to immediately expire when the browser closes, set it to zero.
|
*/
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle for it is expired. If you want them
| to immediately expire when the browser closes, set it to zero.
|
*/
'lifetime' => 120,
'lifetime' => 120,
'expire_on_close' => false,
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path().'/sessions',
'files' => storage_path().'/sessions',
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the database
| connection that should be used to manage your sessions. This should
| correspond to a connection in your "database" configuration file.
|
*/
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the database
| connection that should be used to manage your sessions. This should
| correspond to a connection in your "database" configuration file.
|
*/
'connection' => null,
'connection' => null,
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => array(2, 100),
'lottery' => array(2, 100),
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => 'october_session',
'cookie' => 'october_session',
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => null,
'domain' => null,
);

View File

@ -2,30 +2,30 @@
return array(
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => array(__DIR__.'/../views'),
'paths' => array(__DIR__.'/../views'),
/*
|--------------------------------------------------------------------------
| Pagination View
|--------------------------------------------------------------------------
|
| This view will be used to render the pagination link output, and can
| be easily customized here to show any view you like. A clean view
| compatible with Twitter's Bootstrap is given to you by default.
|
*/
/*
|--------------------------------------------------------------------------
| Pagination View
|--------------------------------------------------------------------------
|
| This view will be used to render the pagination link output, and can
| be easily customized here to show any view you like. A clean view
| compatible with Twitter's Bootstrap is given to you by default.
|
*/
'pagination' => 'pagination::slider-3',
'pagination' => 'pagination::slider-3',
);

View File

@ -11,15 +11,13 @@
|
*/
App::before(function($request)
{
//
App::before(function ($request) {
//
});
App::after(function($request, $response)
{
//
App::after(function ($request, $response) {
//
});
/*
@ -33,15 +31,13 @@ App::after(function($request, $response)
|
*/
Route::filter('auth', function()
{
// if (Auth::guest()) return Redirect::guest('login');
Route::filter('auth', function () {
// if (Auth::guest()) return Redirect::guest('login');
});
Route::filter('auth.basic', function()
{
// return Auth::basic();
Route::filter('auth.basic', function () {
// return Auth::basic();
});
/*
@ -55,9 +51,8 @@ Route::filter('auth.basic', function()
|
*/
Route::filter('guest', function()
{
// if (Auth::check()) return Redirect::to('/');
Route::filter('guest', function () {
// if (Auth::check()) return Redirect::to('/');
});
/*
@ -71,10 +66,8 @@ Route::filter('guest', function()
|
*/
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
Route::filter('csrf', function () {
if (Session::token() != Input::get('_token')) {
throw new Illuminate\Session\TokenMismatchException;
}
});

View File

@ -10,4 +10,3 @@
| the console gets access to each of the command object instances.
|
*/

View File

@ -46,8 +46,7 @@ Log::useFiles(storage_path().'/logs/system.log');
|
*/
App::error(function(Exception $exception, $code)
{
App::error(function (Exception $exception, $code) {
/*
* October uses a custom error handler, see
* System\Classes\ErrorHandler::handleException
@ -65,8 +64,7 @@ App::error(function(Exception $exception, $code)
|
*/
App::down(function()
{
App::down(function () {
return Response::make("Be right back!", 503);
});

View File

@ -27,9 +27,8 @@ require __DIR__.'/../vendor/autoload.php';
|
*/
if (file_exists($compiled = __DIR__.'/compiled.php'))
{
require $compiled;
if (file_exists($compiled = __DIR__.'/compiled.php')) {
require $compiled;
}
/*
@ -69,5 +68,3 @@ October\Rain\Support\ClassLoader::addDirectories(array(__DIR__.'/../modules', __
*/
Illuminate\Support\ClassLoader::register();

View File

@ -2,56 +2,56 @@
return array(
/*
|--------------------------------------------------------------------------
| Application Path
|--------------------------------------------------------------------------
|
| Here we just defined the path to the application directory. Most likely
| you will never need to change this value as the default setup should
| work perfectly fine for the vast majority of all our applications.
|
*/
/*
|--------------------------------------------------------------------------
| Application Path
|--------------------------------------------------------------------------
|
| Here we just defined the path to the application directory. Most likely
| you will never need to change this value as the default setup should
| work perfectly fine for the vast majority of all our applications.
|
*/
'app' => __DIR__.'/../app',
'app' => __DIR__.'/../app',
/*
|--------------------------------------------------------------------------
| Public Path
|--------------------------------------------------------------------------
|
| The public path contains the assets for your web application, such as
| your JavaScript and CSS files, and also contains the primary entry
| point for web requests into these applications from the outside.
|
*/
/*
|--------------------------------------------------------------------------
| Public Path
|--------------------------------------------------------------------------
|
| The public path contains the assets for your web application, such as
| your JavaScript and CSS files, and also contains the primary entry
| point for web requests into these applications from the outside.
|
*/
'public' => __DIR__.'/..',
'public' => __DIR__.'/..',
/*
|--------------------------------------------------------------------------
| Base Path
|--------------------------------------------------------------------------
|
| The base path is the root of the Laravel installation. Most likely you
| will not need to change this value. But, if for some wild reason it
| is necessary you will do so here, just proceed with some caution.
|
*/
/*
|--------------------------------------------------------------------------
| Base Path
|--------------------------------------------------------------------------
|
| The base path is the root of the Laravel installation. Most likely you
| will not need to change this value. But, if for some wild reason it
| is necessary you will do so here, just proceed with some caution.
|
*/
'base' => __DIR__.'/..',
'base' => __DIR__.'/..',
/*
|--------------------------------------------------------------------------
| Storage Path
|--------------------------------------------------------------------------
|
| The storage path is used by Laravel to store cached Blade views, logs
| and other pieces of information. You may modify the path here when
| you want to change the location of this directory for your apps.
|
*/
/*
|--------------------------------------------------------------------------
| Storage Path
|--------------------------------------------------------------------------
|
| The storage path is used by Laravel to store cached Blade views, logs
| and other pieces of information. You may modify the path here when
| you want to change the location of this directory for your apps.
|
*/
'storage' => __DIR__.'/../app/storage',
'storage' => __DIR__.'/../app/storage',
);

View File

@ -24,8 +24,8 @@ $app = new Illuminate\Foundation\Application;
|
*/
$env = $app->detectEnvironment(function(){
return isset($_SERVER['CMS_ENV']) ? $_SERVER['CMS_ENV'] : 'production';
$env = $app->detectEnvironment(function () {
return isset($_SERVER['CMS_ENV']) ? $_SERVER['CMS_ENV'] : 'production';
});
/*
@ -63,13 +63,13 @@ require $framework.'/Illuminate/Foundation/start.php';
*/
if (!isset($unitTesting) || !$unitTesting) {
header('Cache-Control: no-store, private, no-cache, must-revalidate'); // HTTP/1.1
header('Cache-Control: pre-check=0, post-check=0, max-age=0, max-stale = 0', false); // HTTP/1.1
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Expires: 0', false);
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Pragma: no-cache');
header('Cache-Control: no-store, private, no-cache, must-revalidate'); // HTTP/1.1
header('Cache-Control: pre-check=0, post-check=0, max-age=0, max-stale = 0', false); // HTTP/1.1
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Expires: 0', false);
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
header('Pragma: no-cache');
}
/*

View File

@ -24,7 +24,7 @@ class ServiceProvider extends ModuleServiceProvider
/*
* Register widgets
*/
WidgetManager::instance()->registerFormWidgets(function($manager){
WidgetManager::instance()->registerFormWidgets(function ($manager) {
$manager->registerFormWidget('Backend\FormWidgets\CodeEditor', [
'label' => 'Code editor',
'code' => 'codeeditor'
@ -62,7 +62,7 @@ class ServiceProvider extends ModuleServiceProvider
/*
* Register navigation
*/
BackendMenu::registerCallback(function($manager) {
BackendMenu::registerCallback(function ($manager) {
$manager->registerMenuItems('October.Backend', [
'dashboard' => [
'label' => 'backend::lang.dashboard.menu_label',
@ -77,7 +77,7 @@ class ServiceProvider extends ModuleServiceProvider
/*
* Register settings
*/
SettingsManager::instance()->registerCallback(function($manager){
SettingsManager::instance()->registerCallback(function ($manager) {
$manager->registerSettingItems('October.Backend', [
'branding' => [
'label' => 'backend::lang.branding.menu_label',
@ -130,17 +130,23 @@ class ServiceProvider extends ModuleServiceProvider
/*
* Register permissions
*/
BackendAuth::registerCallback(function($manager) {
BackendAuth::registerCallback(function ($manager) {
$manager->registerPermissions('October.Backend', [
'backend.access_dashboard' => ['label' => 'system::lang.permissions.view_the_dashboard', 'tab' => 'System'],
'backend.manage_users' => ['label' => 'system::lang.permissions.manage_other_administrators', 'tab' => 'System'],
'backend.access_dashboard' => [
'label' => 'system::lang.permissions.view_the_dashboard',
'tab' => 'System'
],
'backend.manage_users' => [
'label' => 'system::lang.permissions.manage_other_administrators',
'tab' => 'System'
],
]);
});
/*
* Register mail templates
*/
MailTemplate::registerCallback(function($template){
MailTemplate::registerCallback(function ($template) {
$template->registerMailTemplates([
'backend::mail.invite' => 'Invitation for newly created administrators.',
'backend::mail.restore' => 'Password reset instructions for backend-end administrators.',
@ -157,5 +163,4 @@ class ServiceProvider extends ModuleServiceProvider
{
parent::boot('backend');
}
}

View File

@ -84,19 +84,19 @@ class FormController extends ControllerBehavior
*/
$this->formWidget = $this->makeWidget('Backend\Widgets\Form', $config);
$this->formWidget->bindEvent('form.extendFieldsBefore', function() {
$this->formWidget->bindEvent('form.extendFieldsBefore', function () {
$this->controller->formExtendFieldsBefore($this->formWidget);
});
$this->formWidget->bindEvent('form.extendFields', function() {
$this->formWidget->bindEvent('form.extendFields', function () {
$this->controller->formExtendFields($this->formWidget);
});
$this->formWidget->bindEvent('form.beforeRefresh', function($saveData) {
$this->formWidget->bindEvent('form.beforeRefresh', function ($saveData) {
return $this->controller->formExtendRefreshData($this->formWidget, $saveData);
});
$this->formWidget->bindEvent('form.refresh', function($result) {
$this->formWidget->bindEvent('form.refresh', function ($result) {
return $this->controller->formExtendRefreshResults($this->formWidget, $result);
});
@ -105,8 +105,9 @@ class FormController extends ControllerBehavior
/*
* Detected Relation controller behavior
*/
if ($this->controller->isClassExtendedWith('Backend.Behaviors.RelationController'))
if ($this->controller->isClassExtendedWith('Backend.Behaviors.RelationController')) {
$this->controller->initRelation($model);
}
$this->prepareVars($model);
}
@ -133,12 +134,14 @@ class FormController extends ControllerBehavior
{
try {
$this->context = strlen($context) ? $context : $this->getConfig('create[context]', 'create');
$this->controller->pageTitle = $this->controller->pageTitle ?: $this->getLang('create[title]', 'backend::lang.form.create_title');
$this->controller->pageTitle = $this->controller->pageTitle ?: $this->getLang(
'create[title]',
'backend::lang.form.create_title'
);
$model = $this->controller->formCreateModelObject();
$this->initForm($model);
}
catch (Exception $ex) {
$this->controller->vars['formModel'] = $model;
} catch (Exception $ex) {
$this->controller->handleError($ex);
}
}
@ -166,8 +169,9 @@ class FormController extends ControllerBehavior
Flash::success($this->getLang('create[flashSave]', 'backend::lang.form.create_success'));
if ($redirect = $this->makeRedirect('create', $model))
if ($redirect = $this->makeRedirect('create', $model)) {
return $redirect;
}
}
//
@ -184,12 +188,15 @@ class FormController extends ControllerBehavior
{
try {
$this->context = strlen($context) ? $context : $this->getConfig('update[context]', 'update');
$this->controller->pageTitle = $this->controller->pageTitle ?: $this->getLang('update[title]', 'backend::lang.form.update_title');
$this->controller->pageTitle = $this->controller->pageTitle ?: $this->getLang(
'update[title]',
'backend::lang.form.update_title'
);
$model = $this->controller->formFindModelObject($recordId);
$this->initForm($model);
}
catch (Exception $ex) {
$this->controller->vars['formModel'] = $model;
} catch (Exception $ex) {
$this->controller->handleError($ex);
}
}
@ -218,8 +225,9 @@ class FormController extends ControllerBehavior
Flash::success($this->getLang('update[flashSave]', 'backend::lang.form.update_success'));
if ($redirect = $this->makeRedirect('update', $model))
if ($redirect = $this->makeRedirect('update', $model)) {
return $redirect;
}
}
/**
@ -239,8 +247,9 @@ class FormController extends ControllerBehavior
Flash::success($this->getLang('update[flashDelete]', 'backend::lang.form.delete_success'));
if ($redirect = $this->makeRedirect('delete', $model))
if ($redirect = $this->makeRedirect('delete', $model)) {
return $redirect;
}
}
//
@ -257,12 +266,15 @@ class FormController extends ControllerBehavior
{
try {
$this->context = strlen($context) ? $context : $this->getConfig('preview[context]', 'preview');
$this->controller->pageTitle = $this->controller->pageTitle ?: $this->getLang('preview[title]', 'backend::lang.form.preview_title');
$this->controller->pageTitle = $this->controller->pageTitle ?: $this->getLang(
'preview[title]',
'backend::lang.form.preview_title'
);
$model = $this->controller->formFindModelObject($recordId);
$this->initForm($model);
}
catch (Exception $ex) {
$this->controller->vars['formModel'] = $model;
} catch (Exception $ex) {
$this->controller->handleError($ex);
}
}
@ -278,8 +290,9 @@ class FormController extends ControllerBehavior
*/
public function formRender($options = [])
{
if (!$this->formWidget)
if (!$this->formWidget) {
throw new ApplicationException(Lang::get('backend::lang.form.behavior_not_ready'));
}
return $this->formWidget->render($options);
}
@ -315,14 +328,17 @@ class FormController extends ControllerBehavior
public function makeRedirect($context = null, $model = null)
{
$redirectUrl = null;
if (post('close') && !ends_with($context, '-close'))
if (post('close') && !ends_with($context, '-close')) {
$context .= '-close';
}
if (post('redirect', true))
if (post('redirect', true)) {
$redirectUrl = Backend::url($this->getRedirectUrl($context));
}
if ($model && $redirectUrl)
if ($model && $redirectUrl) {
$redirectUrl = RouterHelper::parseValues($model, array_keys($model->getAttributes()), $redirectUrl);
}
return ($redirectUrl) ? Redirect::to($redirectUrl) : null;
}
@ -344,8 +360,9 @@ class FormController extends ControllerBehavior
'preview' => $this->getConfig('preview[redirect]', ''),
];
if (!isset($redirects[$context]))
if (!isset($redirects[$context])) {
return $redirects['default'];
}
return $redirects[$context];
}
@ -452,43 +469,57 @@ class FormController extends ControllerBehavior
* Called before the creation or updating form is saved.
* @param Model
*/
public function formBeforeSave($model) {}
public function formBeforeSave($model)
{
}
/**
* Called after the creation or updating form is saved.
* @param Model
*/
public function formAfterSave($model) {}
public function formAfterSave($model)
{
}
/**
* Called before the creation form is saved.
* @param Model
*/
public function formBeforeCreate($model) {}
public function formBeforeCreate($model)
{
}
/**
* Called after the creation form is saved.
* @param Model
*/
public function formAfterCreate($model) {}
public function formAfterCreate($model)
{
}
/**
* Called before the updating form is saved.
* @param Model
*/
public function formBeforeUpdate($model) {}
public function formBeforeUpdate($model)
{
}
/**
* Called after the updating form is saved.
* @param Model
*/
public function formAfterUpdate($model) {}
public function formAfterUpdate($model)
{
}
/**
* Called after the form model is deleted.
* @param Model
*/
public function formAfterDelete($model) {}
public function formAfterDelete($model)
{
}
/**
@ -536,14 +567,18 @@ class FormController extends ControllerBehavior
* @param Backend\Widgets\Form $host The hosting form widget
* @return void
*/
public function formExtendFieldsBefore($host) {}
public function formExtendFieldsBefore($host)
{
}
/**
* Called after the form fields are defined.
* @param Backend\Widgets\Form $host The hosting form widget
* @return void
*/
public function formExtendFields($host) {}
public function formExtendFields($host)
{
}
/**
* Called before the form is refreshed, should return an array of additional save data.
@ -551,7 +586,9 @@ class FormController extends ControllerBehavior
* @param array $saveData Current save data
* @return array
*/
public function formExtendRefreshData($host, $saveData) {}
public function formExtendRefreshData($host, $saveData)
{
}
/**
* Called after the form is refreshed, should return an array of additional result parameters.
@ -559,7 +596,9 @@ class FormController extends ControllerBehavior
* @param array $result Current result parameters.
* @return array
*/
public function formExtendRefreshResults($host, $result) {}
public function formExtendRefreshResults($host, $result)
{
}
/**
* Extend supplied model used by create and update actions, the model can
@ -578,7 +617,9 @@ class FormController extends ControllerBehavior
* @param October\Rain\Database\Builder $query
* @return void
*/
public function formExtendQuery($query) {}
public function formExtendQuery($query)
{
}
/**
* Static helper for extending form fields.
@ -588,8 +629,10 @@ class FormController extends ControllerBehavior
public static function extendFormFields($callback)
{
$calledClass = self::getCalledExtensionClass();
Event::listen('backend.form.extendFields', function($widget) use ($calledClass, $callback) {
if (!is_a($widget->getController(), $calledClass)) return;
Event::listen('backend.form.extendFields', function ($widget) use ($calledClass, $callback) {
if (!is_a($widget->getController(), $calledClass)) {
return;
}
$callback($widget, $widget->model, $widget->getContext());
});
}
@ -615,15 +658,21 @@ class FormController extends ControllerBehavior
{
$this->modelsToSave[] = $model;
if (!is_array($saveData))
if (!is_array($saveData)) {
return;
}
$singularTypes = ['belongsTo', 'hasOne', 'morphOne'];
foreach ($saveData as $attribute => $value) {
if (is_array($value) && $model->hasRelation($attribute) && in_array($model->getRelationType($attribute), $singularTypes))
if (
is_array($value) &&
$model->hasRelation($attribute) &&
in_array($model->getRelationType($attribute), $singularTypes)
) {
$this->setModelAttributes($model->{$attribute}, $value);
else
} else {
$model->{$attribute} = $value;
}
}
}
}

View File

@ -68,8 +68,7 @@ class ListController extends ControllerBehavior
if (is_array($controller->listConfig)) {
$this->listDefinitions = $controller->listConfig;
$this->primaryDefinition = key($this->listDefinitions);
}
else {
} else {
$this->listDefinitions = ['list' => $controller->listConfig];
$this->primaryDefinition = 'list';
}
@ -99,8 +98,9 @@ class ListController extends ControllerBehavior
*/
public function makeList($definition = null)
{
if (!$definition || !isset($this->listDefinitions[$definition]))
if (!$definition || !isset($this->listDefinitions[$definition])) {
$definition = $this->primaryDefinition;
}
$listConfig = $this->makeConfig($this->listDefinitions[$definition], $this->requiredConfig);
@ -117,39 +117,59 @@ class ListController extends ControllerBehavior
$columnConfig = $this->makeConfig($listConfig->list);
$columnConfig->model = $model;
$columnConfig->alias = $definition;
if (isset($listConfig->recordUrl)) $columnConfig->recordUrl = $listConfig->recordUrl;
if (isset($listConfig->recordOnClick)) $columnConfig->recordOnClick = $listConfig->recordOnClick;
if (isset($listConfig->recordsPerPage)) $columnConfig->recordsPerPage = $listConfig->recordsPerPage;
if (isset($listConfig->noRecordsMessage)) $columnConfig->noRecordsMessage = $listConfig->noRecordsMessage;
if (isset($listConfig->defaultSort)) $columnConfig->defaultSort = $listConfig->defaultSort;
if (isset($listConfig->showSorting)) $columnConfig->showSorting = $listConfig->showSorting;
if (isset($listConfig->showSetup)) $columnConfig->showSetup = $listConfig->showSetup;
if (isset($listConfig->showCheckboxes)) $columnConfig->showCheckboxes = $listConfig->showCheckboxes;
if (isset($listConfig->showTree)) $columnConfig->showTree = $listConfig->showTree;
if (isset($listConfig->treeExpanded)) $columnConfig->treeExpanded = $listConfig->treeExpanded;
if (isset($listConfig->recordUrl)) {
$columnConfig->recordUrl = $listConfig->recordUrl;
}
if (isset($listConfig->recordOnClick)) {
$columnConfig->recordOnClick = $listConfig->recordOnClick;
}
if (isset($listConfig->recordsPerPage)) {
$columnConfig->recordsPerPage = $listConfig->recordsPerPage;
}
if (isset($listConfig->noRecordsMessage)) {
$columnConfig->noRecordsMessage = $listConfig->noRecordsMessage;
}
if (isset($listConfig->defaultSort)) {
$columnConfig->defaultSort = $listConfig->defaultSort;
}
if (isset($listConfig->showSorting)) {
$columnConfig->showSorting = $listConfig->showSorting;
}
if (isset($listConfig->showSetup)) {
$columnConfig->showSetup = $listConfig->showSetup;
}
if (isset($listConfig->showCheckboxes)) {
$columnConfig->showCheckboxes = $listConfig->showCheckboxes;
}
if (isset($listConfig->showTree)) {
$columnConfig->showTree = $listConfig->showTree;
}
if (isset($listConfig->treeExpanded)) {
$columnConfig->treeExpanded = $listConfig->treeExpanded;
}
$widget = $this->makeWidget('Backend\Widgets\Lists', $columnConfig);
$widget->bindToController();
/*
* Extensibility helpers
*/
$widget->bindEvent('list.extendQueryBefore', function($query) use ($definition) {
$widget->bindEvent('list.extendQueryBefore', function ($query) use ($definition) {
$this->controller->listExtendQueryBefore($query, $definition);
});
$widget->bindEvent('list.extendQuery', function($query) use ($definition) {
$widget->bindEvent('list.extendQuery', function ($query) use ($definition) {
$this->controller->listExtendQuery($query, $definition);
});
$widget->bindEvent('list.injectRowClass', function($record) use ($definition) {
$widget->bindEvent('list.injectRowClass', function ($record) use ($definition) {
return $this->controller->listInjectRowClass($record, $definition);
});
$widget->bindEvent('list.overrideColumnValue', function($record, $column, $value) use ($definition) {
$widget->bindEvent('list.overrideColumnValue', function ($record, $column, $value) use ($definition) {
return $this->controller->listOverrideColumnValue($record, $column->columnName, $definition);
});
$widget->bindEvent('list.overrideHeaderValue', function($column, $value) use ($definition) {
$widget->bindEvent('list.overrideHeaderValue', function ($column, $value) use ($definition) {
return $this->controller->listOverrideHeaderValue($column->columnName, $definition);
});
@ -167,7 +187,7 @@ class ListController extends ControllerBehavior
* Link the Search Widget to the List Widget
*/
if ($searchWidget = $toolbarWidget->getSearchWidget()) {
$searchWidget->bindEvent('search.submit', function() use ($widget, $searchWidget) {
$searchWidget->bindEvent('search.submit', function () use ($widget, $searchWidget) {
$widget->setSearchTerm($searchWidget->getActiveTerm());
return $widget->onRefresh();
});
@ -193,7 +213,7 @@ class ListController extends ControllerBehavior
/*
* Filter the list when the scopes are changed
*/
$filterWidget->bindEvent('filter.update', function() use ($widget, $filterWidget){
$filterWidget->bindEvent('filter.update', function () use ($widget, $filterWidget) {
$widget->addFilter([$filterWidget, 'applyAllScopesToQuery']);
return $widget->onRefresh();
});
@ -213,7 +233,10 @@ class ListController extends ControllerBehavior
*/
public function index()
{
$this->controller->pageTitle = $this->controller->pageTitle ?: trans($this->getConfig('title', 'backend::lang.list.default_title'));
$this->controller->pageTitle = $this->controller->pageTitle ?: trans($this->getConfig(
'title',
'backend::lang.list.default_title'
));
$this->controller->bodyClass = 'slim-container';
$this->makeLists();
}
@ -225,19 +248,23 @@ class ListController extends ControllerBehavior
*/
public function listRender($definition = null)
{
if (!count($this->listWidgets))
if (!count($this->listWidgets)) {
throw new SystemException(Lang::get('backend::lang.list.behavior_not_ready'));
}
if (!$definition || !isset($this->listDefinitions[$definition]))
if (!$definition || !isset($this->listDefinitions[$definition])) {
$definition = $this->primaryDefinition;
}
$collection = [];
if (isset($this->toolbarWidgets[$definition]))
if (isset($this->toolbarWidgets[$definition])) {
$collection[] = $this->toolbarWidgets[$definition]->render();
}
if (isset($this->filterWidgets[$definition]))
if (isset($this->filterWidgets[$definition])) {
$collection[] = $this->filterWidgets[$definition]->render();
}
$collection[] = $this->listWidgets[$definition]->render();
@ -251,11 +278,13 @@ class ListController extends ControllerBehavior
*/
public function listRefresh($definition = null)
{
if (!count($this->listWidgets))
if (!count($this->listWidgets)) {
$this->makeLists();
}
if (!$definition || !isset($this->listDefinitions[$definition]))
if (!$definition || !isset($this->listDefinitions[$definition])) {
$definition = $this->primaryDefinition;
}
return $this->listWidgets[$definition]->onRefresh();
}
@ -266,8 +295,9 @@ class ListController extends ControllerBehavior
*/
public function listGetWidget($definition = null)
{
if (!$definition)
if (!$definition) {
$definition = $this->primaryDefinition;
}
return array_get($this->listWidgets, $definition);
}
@ -291,14 +321,18 @@ class ListController extends ControllerBehavior
* before the default query is processed.
* @param October\Rain\Database\Builder $query
*/
public function listExtendQueryBefore($query, $definition = null) {}
public function listExtendQueryBefore($query, $definition = null)
{
}
/**
* Controller override: Extend the query used for populating the list
* after the default query is processed.
* @param October\Rain\Database\Builder $query
*/
public function listExtendQuery($query, $definition = null) {}
public function listExtendQuery($query, $definition = null)
{
}
/**
* Returns a CSS class name for a list row (<tr class="...">).
@ -306,7 +340,9 @@ class ListController extends ControllerBehavior
* @param string $definition List definition (optional)
* @return string HTML view
*/
public function listInjectRowClass($record, $definition = null) {}
public function listInjectRowClass($record, $definition = null)
{
}
/**
* Replace a table column value (<td>...</td>)
@ -315,7 +351,9 @@ class ListController extends ControllerBehavior
* @param string $definition List definition (optional)
* @return string HTML view
*/
public function listOverrideColumnValue($record, $columnName, $definition = null) {}
public function listOverrideColumnValue($record, $columnName, $definition = null)
{
}
/**
* Replace the entire table header contents (<th>...</th>) with custom HTML
@ -323,7 +361,9 @@ class ListController extends ControllerBehavior
* @param string $definition List definition (optional)
* @return string HTML view
*/
public function listOverrideHeaderValue($columnName, $definition = null) {}
public function listOverrideHeaderValue($columnName, $definition = null)
{
}
/**
* Static helper for extending form fields.
@ -333,10 +373,11 @@ class ListController extends ControllerBehavior
public static function extendListColumns($callback)
{
$calledClass = self::getCalledExtensionClass();
Event::listen('backend.list.extendColumns', function($widget) use ($calledClass, $callback) {
if (!is_a($widget->getController(), $calledClass)) return;
Event::listen('backend.list.extendColumns', function ($widget) use ($calledClass, $callback) {
if (!is_a($widget->getController(), $calledClass)) {
return;
}
$callback($widget, $widget->model);
});
}
}

View File

@ -158,24 +158,35 @@ class RelationController extends ControllerBehavior
*/
public function initRelation($model, $field = null)
{
if ($field == null)
if ($field == null) {
$field = post(self::PARAM_FIELD);
}
$this->config = $this->originalConfig;
$this->model = $model;
$this->field = $field;
if ($field == null)
if ($field == null) {
return;
}
if (!$this->model)
throw new ApplicationException(Lang::get('backend::lang.relation.missing_model', ['class'=>get_class($this->controller)]));
if (!$this->model) {
throw new ApplicationException(Lang::get(
'backend::lang.relation.missing_model',
['class'=>get_class($this->controller)]
));
}
if (!$this->model instanceof Model)
throw new ApplicationException(Lang::get('backend::lang.model.invalid_class', ['model'=>get_class($this->model), 'class'=>get_class($this->controller)]));
if (!$this->model instanceof Model) {
throw new ApplicationException(Lang::get(
'backend::lang.model.invalid_class',
['model'=>get_class($this->model), 'class'=>get_class($this->controller)]
));
}
if (!$this->getConfig($field))
if (!$this->getConfig($field)) {
throw new ApplicationException(Lang::get('backend::lang.relation.missing_definition', compact('field')));
}
$this->alias = camel_case('relation ' . $field);
$this->config = $this->makeConfig($this->getConfig($field), $this->requiredRelationProperties);
@ -196,27 +207,31 @@ class RelationController extends ControllerBehavior
/*
* Toolbar widget
*/
if ($this->toolbarWidget = $this->makeToolbarWidget())
if ($this->toolbarWidget = $this->makeToolbarWidget()) {
$this->toolbarWidget->bindToController();
}
/*
* View widget
*/
if ($this->viewWidget = $this->makeViewWidget())
if ($this->viewWidget = $this->makeViewWidget()) {
$this->viewWidget->bindToController();
}
/*
* Manage widget
*/
if ($this->manageWidget = $this->makeManageWidget())
if ($this->manageWidget = $this->makeManageWidget()) {
$this->manageWidget->bindToController();
}
/*
* Pivot widget
*/
if ($this->manageMode == 'pivot') {
if ($this->pivotWidget = $this->makePivotWidget())
if ($this->pivotWidget = $this->makePivotWidget()) {
$this->pivotWidget->bindToController();
}
}
}
@ -268,15 +283,18 @@ class RelationController extends ControllerBehavior
{
$field = $this->validateField($field);
if (is_string($options)) $options = ['sessionKey' => $options];
if (is_string($options)) {
$options = ['sessionKey' => $options];
}
$this->prepareVars();
/*
* Session key
*/
if (isset($options['sessionKey']))
if (isset($options['sessionKey'])) {
$this->sessionKey = $options['sessionKey'];
}
/*
* Determine the partial to use based on the supplied section option
@ -334,11 +352,13 @@ class RelationController extends ControllerBehavior
{
$field = $field ?: post(self::PARAM_FIELD);
if ($field && $field != $this->field)
if ($field && $field != $this->field) {
$this->initRelation($this->model, $field);
}
if (!$field && !$this->field)
if (!$field && !$this->field) {
throw new ApplicationException(Lang::get('backend::lang.relation.missing_definition', compact('field')));
}
return $field ?: $this->field;
}
@ -368,8 +388,9 @@ class RelationController extends ControllerBehavior
*/
protected function beforeAjax()
{
if ($this->initialized)
if ($this->initialized) {
return;
}
$this->controller->pageAction();
$this->validateField();
@ -386,8 +407,9 @@ class RelationController extends ControllerBehavior
public function relationMakePartial($partial, $params = [])
{
$contents = $this->controller->makePartial('relation_'.$partial, $params + $this->vars, false);
if (!$contents)
if (!$contents) {
$contents = $this->makePartial($partial, $params);
}
return $contents;
}
@ -400,11 +422,13 @@ class RelationController extends ControllerBehavior
public function relationGetId($suffix = null)
{
$id = class_basename($this);
if ($this->field)
if ($this->field) {
$id .= '-' . $this->field;
}
if ($suffix !== null)
if ($suffix !== null) {
$id .= '-' . $suffix;
}
return $this->controller->getId($id);
}
@ -420,8 +444,9 @@ class RelationController extends ControllerBehavior
->getBaseQuery()
->select($foreignKeyName);
if ($checkIds !== null && is_array($checkIds) && count($checkIds))
if ($checkIds !== null && is_array($checkIds) && count($checkIds)) {
$results = $results->whereIn($foreignKeyName, $checkIds);
}
return $results->lists($foreignKeyName);
}
@ -434,8 +459,9 @@ class RelationController extends ControllerBehavior
{
$this->beforeAjax();
if ($this->manageMode == 'pivot' && $this->manageId)
if ($this->manageMode == 'pivot' && $this->manageId) {
return $this->onRelationManagePivotForm();
}
// The form should not share its session key with the parent
$this->vars['newSessionKey'] = str_random(40);
@ -480,8 +506,9 @@ class RelationController extends ControllerBehavior
if (($checkedIds = post('checked')) && is_array($checkedIds)) {
foreach ($checkedIds as $relationId) {
if (!$obj = $this->relationObject->find($relationId))
if (!$obj = $this->relationObject->find($relationId)) {
continue;
}
$obj->delete();
}
@ -497,8 +524,9 @@ class RelationController extends ControllerBehavior
{
$this->beforeAjax();
if ($this->viewMode != 'multi')
if ($this->viewMode != 'multi') {
throw new ApplicationException(Lang::get('backend::lang.relation.invalid_action_single'));
}
if (($checkedIds = post('checked')) && is_array($checkedIds)) {
/*
@ -511,10 +539,11 @@ class RelationController extends ControllerBehavior
$models = $this->relationModel->whereIn($foreignKeyName, $checkedIds)->get();
foreach ($models as $model) {
if ($this->model->exists)
if ($this->model->exists) {
$this->relationObject->add($model);
else
} else {
$this->relationObject->add($model, $this->relationGetSessionKey());
}
}
}
@ -528,8 +557,9 @@ class RelationController extends ControllerBehavior
{
$this->beforeAjax();
if ($this->viewMode != 'multi')
if ($this->viewMode != 'multi') {
throw new ApplicationException(Lang::get('backend::lang.relation.invalid_action_single'));
}
if (($checkedIds = post('checked')) && is_array($checkedIds)) {
$this->relationObject->detach($checkedIds);
@ -560,8 +590,9 @@ class RelationController extends ControllerBehavior
$foreignKeyName = $this->relationModel->getKeyName();
$existing = $this->relationObject->where($foreignKeyName, $foreignId)->count();
if (!$existing)
if (!$existing) {
$this->relationObject->add($foreignModel, null, $saveData);
}
return ['#'.$this->relationGetId('view') => $this->relationRenderView()];
}
@ -593,8 +624,9 @@ class RelationController extends ControllerBehavior
protected function makeToolbarWidget()
{
if ($this->readOnly)
if ($this->readOnly) {
return;
}
$defaultConfig = [
'buttons' => '@/modules/backend/behaviors/relationcontroller/partials/_toolbar.htm',
@ -631,18 +663,23 @@ class RelationController extends ControllerBehavior
$config->recordsPerPage = $this->getConfig('view[recordsPerPage]');
if (!$this->readOnly) {
$config->recordOnClick = sprintf("$.oc.relationBehavior.clickManageListRecord(:id, '%s', '%s')", $this->field, $this->relationGetSessionKey());
$config->recordOnClick = sprintf(
"$.oc.relationBehavior.clickManageListRecord(:id, '%s', '%s')",
$this->field,
$this->relationGetSessionKey()
);
$config->showCheckboxes = true;
}
if ($emptyMessage = $this->getConfig('emptyMessage'))
if ($emptyMessage = $this->getConfig('emptyMessage')) {
$config->noRecordsMessage = $emptyMessage;
}
/*
* Constrain the query by the relationship and deferred items
*/
$widget = $this->makeWidget('Backend\Widgets\Lists', $config);
$widget->bindEvent('list.extendQuery', function($query) {
$widget->bindEvent('list.extendQuery', function ($query) {
$this->relationObject->setQuery($query);
if ($this->model->exists) {
$this->relationObject->addConstraints();
@ -657,7 +694,7 @@ class RelationController extends ControllerBehavior
*/
if ($this->toolbarWidget && $this->getConfig('view[showSearch]')) {
if ($searchWidget = $this->toolbarWidget->getSearchWidget()) {
$searchWidget->bindEvent('search.submit', function() use ($widget, $searchWidget) {
$searchWidget->bindEvent('search.submit', function () use ($widget, $searchWidget) {
$widget->setSearchTerm($searchWidget->getActiveTerm());
return $widget->onRefresh();
});
@ -665,11 +702,10 @@ class RelationController extends ControllerBehavior
$searchWidget->setActiveTerm(null);
}
}
}
/*
* Single (belongs to, has one)
*/
elseif ($this->viewMode == 'single') {
} elseif ($this->viewMode == 'single') {
$config = $this->makeConfig($this->config->form);
$config->model = $this->relationModel;
$config->arrayName = class_basename($this->relationModel);
@ -693,13 +729,16 @@ class RelationController extends ControllerBehavior
$config->model = $this->relationModel;
$config->alias = $this->alias . 'ManagePivotList';
$config->showSetup = false;
$config->recordOnClick = sprintf("$.oc.relationBehavior.clickManagePivotListRecord(:id, '%s', '%s')", $this->field, $this->relationGetSessionKey());
$config->recordOnClick = sprintf(
"$.oc.relationBehavior.clickManagePivotListRecord(:id, '%s', '%s')",
$this->field,
$this->relationGetSessionKey()
);
$widget = $this->makeWidget('Backend\Widgets\Lists', $config);
}
/*
* List
*/
elseif ($this->manageMode == 'list' && isset($this->config->list)) {
} elseif ($this->manageMode == 'list' && isset($this->config->list)) {
$config = $this->makeConfig($this->config->list);
$config->model = $this->relationModel;
$config->alias = $this->alias . 'ManageList';
@ -716,19 +755,17 @@ class RelationController extends ControllerBehavior
if ($this->getConfig('manage[showSearch]')) {
$this->searchWidget = $this->makeSearchWidget();
$this->searchWidget->bindToController();
$this->searchWidget->bindEvent('search.submit', function() use ($widget) {
$this->searchWidget->bindEvent('search.submit', function () use ($widget) {
$widget->setSearchTerm($this->searchWidget->getActiveTerm());
return $widget->onRefresh();
});
$this->searchWidget->setActiveTerm(null);
}
}
/*
* Form
*/
elseif ($this->manageMode == 'form' && isset($this->config->form)) {
} elseif ($this->manageMode == 'form' && isset($this->config->form)) {
$config = $this->makeConfig($this->config->form);
$config->model = $this->relationModel;
$config->arrayName = class_basename($this->relationModel);
@ -750,14 +787,15 @@ class RelationController extends ControllerBehavior
$widget = $this->makeWidget('Backend\Widgets\Form', $config);
}
if (!$widget)
if (!$widget) {
return null;
}
/*
* Exclude existing relationships
*/
if ($this->manageMode == 'pivot' || $this->manageMode == 'list') {
$widget->bindEvent('list.extendQuery', function($query) {
$widget->bindEvent('list.extendQuery', function ($query) {
/*
* Where not in the current list of related records
@ -806,16 +844,18 @@ class RelationController extends ControllerBehavior
*/
public function relationGetSessionKey($force = false)
{
if ($this->sessionKey && !$force)
if ($this->sessionKey && !$force) {
return $this->sessionKey;
}
if (post('_relation_session_key'))
if (post('_relation_session_key')) {
return $this->sessionKey = post('_relation_session_key');
}
if (post('_session_key'))
if (post('_session_key')) {
return $this->sessionKey = post('_session_key');
}
return $this->sessionKey = FormHelper::getSessionKey();
}
}

View File

@ -35,8 +35,9 @@ class UserPreferencesModel extends SettingsModel
*/
public function instance()
{
if (isset(self::$instances[$this->recordCode]))
if (isset(self::$instances[$this->recordCode])) {
return self::$instances[$this->recordCode];
}
if (!$item = $this->getSettingsRecord()) {
$this->model->initSettingsData();
@ -81,8 +82,9 @@ class UserPreferencesModel extends SettingsModel
$this->model->namespace = $namespace;
$this->model->user_id = $preferences->userContext->id;
if ($this->fieldValues)
if ($this->fieldValues) {
$this->model->value = $this->fieldValues;
}
}
/**
@ -94,8 +96,9 @@ class UserPreferencesModel extends SettingsModel
/*
* Let the core columns through
*/
if ($key == 'namespace' || $key == 'group')
if ($key == 'namespace' || $key == 'group') {
return true;
}
return parent::isKeyAllowed($key);
}

View File

@ -80,9 +80,9 @@ class AuthManager extends RainAuthManager
*/
public function registerPermissions($owner, array $definitions)
{
foreach ($definitions as $code=>$definition) {
foreach ($definitions as $code => $definition) {
$permission = (object)array_merge(self::$permissionDefaults, array_merge($definition, [
'code' => $code,
'code' => $code,
'owner' => $owner
]));
@ -96,8 +96,9 @@ class AuthManager extends RainAuthManager
*/
public function listPermissions()
{
if ($this->permissionCache !== false)
if ($this->permissionCache !== false) {
return $this->permissionCache;
}
/*
* Load module items
@ -113,8 +114,9 @@ class AuthManager extends RainAuthManager
foreach ($plugins as $id => $plugin) {
$items = $plugin->registerPermissions();
if (!is_array($items))
if (!is_array($items)) {
continue;
}
$this->registerPermissions($id, $items);
}
@ -122,14 +124,14 @@ class AuthManager extends RainAuthManager
/*
* Sort permission items
*/
usort($this->permissions, function($a, $b) {
if ($a->order == $b->order)
usort($this->permissions, function ($a, $b) {
if ($a->order == $b->order) {
return 0;
}
return $a->order > $b->order ? 1 : -1;
});
return $this->permissionCache = $this->permissions;
}
}

View File

@ -46,8 +46,9 @@ class BackendController extends ControllerBase
self::$action = $action = isset($params[2]) ? $this->parseAction($params[2]) : 'index';
self::$params = $controllerParams = array_slice($params, 3);
$controllerClass = '\\'.$module.'\Controllers\\'.$controller;
if ($controllerObj = $this->findController($controllerClass, $action, '/modules'))
if ($controllerObj = $this->findController($controllerClass, $action, '/modules')) {
return $controllerObj->run($action, $controllerParams);
}
/*
* Look for a Plugin controller
@ -58,8 +59,13 @@ class BackendController extends ControllerBase
self::$action = $action = isset($params[3]) ? $this->parseAction($params[3]) : 'index';
self::$params = $controllerParams = array_slice($params, 4);
$controllerClass = '\\'.$author.'\\'.$plugin.'\Controllers\\'.$controller;
if ($controllerObj = $this->findController($controllerClass, $action, Config::get('cms.pluginsDir', '/plugins')))
if ($controllerObj = $this->findController(
$controllerClass,
$action,
Config::get('cms.pluginsDir', '/plugins')
)) {
return $controllerObj->run($action, $controllerParams);
}
}
/*
@ -83,17 +89,20 @@ class BackendController extends ControllerBase
if (!class_exists($controller)) {
$controller = Str::normalizeClassName($controller);
$controllerFile = PATH_BASE.$dirPrefix.strtolower(str_replace('\\', '/', $controller)) . '.php';
if ($controllerFile = File::existsInsensitive($controllerFile))
if ($controllerFile = File::existsInsensitive($controllerFile)) {
include_once($controllerFile);
}
}
if (!class_exists($controller))
if (!class_exists($controller)) {
return false;
}
$controllerObj = App::make($controller);
if ($controllerObj->actionExists($action))
if ($controllerObj->actionExists($action)) {
return $controllerObj;
}
return false;
}
@ -105,8 +114,9 @@ class BackendController extends ControllerBase
*/
protected function parseAction($actionName)
{
if (strpos($actionName, '-') !== false)
if (strpos($actionName, '-') !== false) {
return camel_case($actionName);
}
return $actionName;
}

View File

@ -40,11 +40,11 @@ class BackendHelper
$backendUri = Config::get('cms.backendUri');
$baseUrl = Request::getBaseUrl();
if ($path === null)
if ($path === null) {
return $baseUrl . '/' . $backendUri;
}
$path = RouterHelper::normalizeUrl($path);
return $baseUrl . '/' . $backendUri . $path;
}
}

View File

@ -94,7 +94,15 @@ class Controller extends Extendable
/**
* @var array Default methods which cannot be called as actions.
*/
public $hiddenActions = ['run', 'actionExists', 'pageAction', 'getId', 'setStatusCode', 'handleError', 'makeHintPartial'];
public $hiddenActions = [
'run',
'actionExists',
'pageAction',
'getId',
'setStatusCode',
'handleError',
'makeHintPartial'
];
/**
* @var array Controller specified methods which cannot be called as actions.
@ -170,8 +178,9 @@ class Controller extends Extendable
}
// Check his access groups against the page definition
if ($this->requiredPermissions && !$this->user->hasAnyAccess($this->requiredPermissions))
if ($this->requiredPermissions && !$this->user->hasAnyAccess($this->requiredPermissions)) {
return Response::make(View::make('backend::access_denied'), 403);
}
}
/*
@ -179,8 +188,7 @@ class Controller extends Extendable
*/
if (Session::has('locale')) {
App::setLocale(Session::get('locale'));
}
elseif ($this->user && $locale = BackendPreferences::get('locale')) {
} elseif ($this->user && $locale = BackendPreferences::get('locale')) {
Session::put('locale', $locale);
App::setLocale($locale);
}
@ -188,22 +196,29 @@ class Controller extends Extendable
/*
* Execute AJAX event
*/
if ($ajaxResponse = $this->execAjaxHandlers())
if ($ajaxResponse = $this->execAjaxHandlers()) {
return $ajaxResponse;
}
/*
* Execute postback handler
*/
if (($handler = post('_handler')) && ($handlerResponse = $this->runAjaxHandler($handler)) && $handlerResponse !== true)
if (
($handler = post('_handler')) &&
($handlerResponse = $this->runAjaxHandler($handler)) &&
$handlerResponse !== true
) {
return $handlerResponse;
}
/*
* Execute page action
*/
$result = $this->execPageAction($action, $params);
if (!is_string($result))
if (!is_string($result)) {
return $result;
}
return Response::make($result, $this->statusCode);
}
@ -218,12 +233,14 @@ class Controller extends Extendable
*/
public function actionExists($name, $internal = false)
{
if (!strlen($name) || substr($name, 0, 1) == '_' || !$this->methodExists($name))
if (!strlen($name) || substr($name, 0, 1) == '_' || !$this->methodExists($name)) {
return false;
}
foreach ($this->hiddenActions as $method) {
if (strtolower($name) == strtolower($method))
if (strtolower($name) == strtolower($method)) {
return false;
}
}
$ownMethod = method_exists($this, $name);
@ -231,15 +248,18 @@ class Controller extends Extendable
if ($ownMethod) {
$methodInfo = new \ReflectionMethod($this, $name);
$public = $methodInfo->isPublic();
if ($public)
if ($public) {
return true;
}
}
if ($internal && (($ownMethod && $methodInfo->isProtected()) || !$ownMethod))
if ($internal && (($ownMethod && $methodInfo->isProtected()) || !$ownMethod)) {
return true;
}
if (!$ownMethod)
if (!$ownMethod) {
return true;
}
return false;
}
@ -250,8 +270,9 @@ class Controller extends Extendable
*/
public function pageAction()
{
if (!$this->action)
if (!$this->action) {
return;
}
$this->suppressView = true;
$this->execPageAction($this->action, $this->params);
@ -267,22 +288,30 @@ class Controller extends Extendable
{
$result = null;
if (!$this->actionExists($actionName))
throw new SystemException(sprintf("Action %s is not found in the controller %s", $actionName, get_class($this)));
if (!$this->actionExists($actionName)) {
throw new SystemException(sprintf(
"Action %s is not found in the controller %s",
$actionName,
get_class($this)
));
}
// Execute the action
$result = call_user_func_array([$this, $actionName], $parameters);
if ($result instanceof RedirectResponse)
if ($result instanceof RedirectResponse) {
return $result;
}
// No page title
if (!$this->pageTitle)
if (!$this->pageTitle) {
$this->pageTitle = 'backend::lang.page.untitled';
}
// Load the view
if (!$this->suppressView && is_null($result))
if (!$this->suppressView && is_null($result)) {
return $this->makeView($actionName);
}
return $this->makeViewContent($result);
}
@ -298,8 +327,9 @@ class Controller extends Extendable
/*
* Validate the handler name
*/
if (!preg_match('/^(?:\w+\:{2})?on[A-Z]{1}[\w+]*$/', $handler))
if (!preg_match('/^(?:\w+\:{2})?on[A-Z]{1}[\w+]*$/', $handler)) {
throw new SystemException(Lang::get('cms::lang.ajax_handler.invalid_name', ['name'=>$handler]));
}
/*
* Validate the handler partial list
@ -309,11 +339,14 @@ class Controller extends Extendable
// @todo Do we need to validate backend partials?
// foreach ($partialList as $partial) {
// if (!preg_match('/^(?:\w+\:{2}|@)?[a-z0-9\_\-\.\/]+$/i', $partial))
// throw new SystemException(Lang::get('cms::lang.partial.invalid_name', ['name'=>$partial]));
// if (!preg_match('/^(?:\w+\:{2}|@)?[a-z0-9\_\-\.\/]+$/i', $partial)) {
// throw new SystemException(Lang::get(
// 'cms::lang.partial.invalid_name',
// ['name' => $partial]
// ));
// }
// }
}
else {
} else {
$partialList = [];
}
@ -322,23 +355,26 @@ class Controller extends Extendable
/*
* Execute the handler
*/
if (!$result = $this->runAjaxHandler($handler))
if (!$result = $this->runAjaxHandler($handler)) {
throw new ApplicationException(Lang::get('cms::lang.ajax_handler.not_found', ['name'=>$handler]));
}
/*
* If the handler returned an array, we should add it to output for rendering.
* If it is a string, add it to the array with the key "result".
*/
if (is_array($result))
if (is_array($result)) {
$responseContents = array_merge($responseContents, $result);
elseif (is_string($result))
} elseif (is_string($result)) {
$responseContents['result'] = $result;
}
/*
* Render partials and return the response as array that will be converted to JSON automatically.
*/
foreach ($partialList as $partial)
foreach ($partialList as $partial) {
$responseContents[$partial] = $this->makePartial($partial);
}
/*
* If the handler returned a redirect, process it so framework.js knows to redirect
@ -346,11 +382,10 @@ class Controller extends Extendable
*/
if ($result instanceof RedirectResponse) {
$responseContents['X_OCTOBER_REDIRECT'] = $result->getTargetUrl();
}
/*
* No redirect is used, look for any flash messages
*/
else if (Flash::check()) {
} elseif (Flash::check()) {
$responseContents['#layout-flash-messages'] = $this->makeLayoutPartial('flash_messages');
}
@ -362,8 +397,7 @@ class Controller extends Extendable
}
return Response::make()->setContent($responseContents);
}
catch (ValidationException $ex) {
} catch (ValidationException $ex) {
/*
* Handle validation error gracefully
*/
@ -372,15 +406,18 @@ class Controller extends Extendable
$responseContents['#layout-flash-messages'] = $this->makeLayoutPartial('flash_messages');
$responseContents['X_OCTOBER_ERROR_FIELDS'] = $ex->getFields();
return Response::make($responseContents, 406);
}
catch (MassAssignmentException $ex) {
return Response::make(Lang::get('backend::lang.model.mass_assignment_failed', ['attribute' => $ex->getMessage()]), 500);
}
catch (ApplicationException $ex) {
} catch (MassAssignmentException $ex) {
return Response::make(
Lang::get('backend::lang.model.mass_assignment_failed', ['attribute' => $ex->getMessage()]),
500
);
} catch (ApplicationException $ex) {
return Response::make($ex->getMessage(), 500);
}
catch (Exception $ex) {
return Response::make(sprintf('"%s" on line %s of %s', $ex->getMessage(), $ex->getLine(), $ex->getFile()), 500);
} catch (Exception $ex) {
return Response::make(
sprintf('"%s" on line %s of %s', $ex->getMessage(), $ex->getLine(), $ex->getFile()),
500
);
}
}
@ -405,20 +442,21 @@ class Controller extends Extendable
*/
$this->pageAction();
if ($this->fatalError)
if ($this->fatalError) {
throw new SystemException($this->fatalError);
}
if (!isset($this->widget->{$widgetName}))
if (!isset($this->widget->{$widgetName})) {
throw new SystemException(Lang::get('backend::lang.widget.not_bound', ['name'=>$widgetName]));
}
if (($widget = $this->widget->{$widgetName}) && method_exists($widget, $handlerName)) {
$result = call_user_func_array([$widget, $handlerName], $this->params);
return ($result) ?: true;
}
}
else {
} else {
/*
* Process page specific handler (index_onSomething)
* Process page specific handler (index_onSomething) {
*/
$pageHandler = $this->action . '_' . $handler;
@ -428,7 +466,7 @@ class Controller extends Extendable
}
/*
* Process page global handler (onSomething)
* Process page global handler (onSomething) {
*/
if ($this->methodExists($handler)) {
$result = call_user_func_array([$this, $handler], $this->params);
@ -458,8 +496,9 @@ class Controller extends Extendable
public function getId($suffix = null)
{
$id = class_basename(get_called_class()) . '-' . $this->action;
if ($suffix !== null)
if ($suffix !== null) {
$id .= '-' . $suffix;
}
return $id;
}
@ -497,8 +536,9 @@ class Controller extends Extendable
*/
public function makeHintPartial($name, $partial = null, array $params = [])
{
if (!$partial)
if (!$partial) {
$partial = $name;
}
return $this->makeLayoutPartial('hint', [
'hintName' => $name,
@ -514,8 +554,9 @@ class Controller extends Extendable
*/
public function onHideBackendHint()
{
if (!$name = post('name'))
if (!$name = post('name')) {
throw new ApplicationException('Missing a hint name.');
}
$preferences = UserPreferences::forUser();
$hiddenHints = $preferences->get('backend::hints.hidden', []);
@ -534,5 +575,4 @@ class Controller extends Extendable
$hiddenHints = UserPreferences::forUser()->get('backend::hints.hidden', []);
return array_key_exists($name, $hiddenHints);
}
}

View File

@ -45,7 +45,10 @@ class ControllerBehavior extends ExtensionBase
// Option A: (@todo Determine which is faster by benchmark)
// $relativePath = strtolower(str_replace('\\', '/', get_called_class()));
// $this->viewPath = $this->configPath = ['modules/' . $relativePath . '/partials', 'plugins/' . $relativePath . '/partials'];
// $this->viewPath = $this->configPath = [
// 'modules/' . $relativePath . '/partials',
// 'plugins/' . $relativePath . '/partials'
// ];
// $this->assetPath = ['modules/' . $relativePath . '/assets', 'plugins/' . $relativePath . '/assets'];
// Option B:
@ -93,8 +96,9 @@ class ControllerBehavior extends ExtensionBase
* First part will be the field name, pop it off
*/
$fieldName = array_shift($keyParts);
if (!isset($this->config->{$fieldName}))
if (!isset($this->config->{$fieldName})) {
return $default;
}
$result = $this->config->{$fieldName};
@ -102,8 +106,9 @@ class ControllerBehavior extends ExtensionBase
* Loop the remaining key parts and build a result
*/
foreach ($keyParts as $key) {
if (!array_key_exists($key, $result))
if (!array_key_exists($key, $result)) {
return $default;
}
$result = $result[$key];
}
@ -121,8 +126,9 @@ class ControllerBehavior extends ExtensionBase
*/
protected function hideAction($methodName)
{
if (!is_array($methodName))
if (!is_array($methodName)) {
$methodName = [$methodName];
}
$this->controller->hiddenActions = array_merge($this->controller->hiddenActions, $methodName);
}

View File

@ -113,18 +113,39 @@ class FilterScope
*/
protected function evalConfig($config)
{
if (isset($config['options'])) $this->options($config['options']);
if (isset($config['context'])) $this->context = $config['context'];
if (isset($config['default'])) $this->defaults = $config['default'];
if (isset($config['conditions'])) $this->conditions = $config['conditions'];
if (isset($config['scope'])) $this->scope = $config['scope'];
if (isset($config['cssClass'])) $this->cssClass = $config['cssClass'];
if (isset($config['nameFrom'])) $this->nameFrom = $config['nameFrom'];
if (isset($config['descriptionFrom'])) $this->descriptionFrom = $config['descriptionFrom'];
if (isset($config['options'])) {
$this->options($config['options']);
}
if (isset($config['context'])) {
$this->context = $config['context'];
}
if (isset($config['default'])) {
$this->defaults = $config['default'];
}
if (isset($config['conditions'])) {
$this->conditions = $config['conditions'];
}
if (isset($config['scope'])) {
$this->scope = $config['scope'];
}
if (isset($config['cssClass'])) {
$this->cssClass = $config['cssClass'];
}
if (isset($config['nameFrom'])) {
$this->nameFrom = $config['nameFrom'];
}
if (isset($config['descriptionFrom'])) {
$this->descriptionFrom = $config['descriptionFrom'];
}
/* @todo Remove line if year >= 2015 */ if (isset($config['nameColumn'])) $this->nameFrom = $config['nameColumn'];
// @todo Remove line if year >= 2015
if (isset($config['nameColumn'])) {
$this->nameFrom = $config['nameColumn'];
}
if (array_key_exists('disabled', $config)) $this->disabled = $config['disabled'];
if (array_key_exists('disabled', $config)) {
$this->disabled = $config['disabled'];
}
return $config;
}
@ -136,13 +157,14 @@ class FilterScope
$id = 'scope';
$id .= '-'.$this->scopeName;
if ($suffix)
if ($suffix) {
$id .= '-'.$suffix;
}
if ($this->idPrefix)
if ($this->idPrefix) {
$id = $this->idPrefix . '-' . $id;
}
return Str::evalHtmlId($id);
}
}

View File

@ -193,15 +193,13 @@ class FormField
if ($value === null) {
if (is_array($this->options)) {
return $this->options;
}
elseif (is_callable($this->options)) {
} elseif (is_callable($this->options)) {
$callable = $this->options;
return $callable();
}
return [];
}
else {
} else {
$this->options = $value;
}
@ -233,28 +231,67 @@ class FormField
*/
protected function evalConfig($config)
{
if (isset($config['options'])) $this->options($config['options']);
if (isset($config['span'])) $this->span($config['span']);
if (isset($config['context'])) $this->context = $config['context'];
if (isset($config['size'])) $this->size($config['size']);
if (isset($config['tab'])) $this->tab($config['tab']);
if (isset($config['commentAbove'])) $this->comment($config['commentAbove'], 'above');
if (isset($config['comment'])) $this->comment($config['comment']);
if (isset($config['placeholder'])) $this->placeholder = $config['placeholder'];
if (isset($config['default'])) $this->defaults = $config['default'];
if (isset($config['cssClass'])) $this->cssClass = $config['cssClass'];
if (isset($config['attributes'])) $this->attributes($config['attributes']);
if (isset($config['containerAttributes'])) $this->attributes($config['containerAttributes'], 'container');
if (isset($config['depends'])) $this->depends = $config['depends'];
if (isset($config['path'])) $this->path = $config['path'];
if (isset($config['options'])) {
$this->options($config['options']);
}
if (isset($config['span'])) {
$this->span($config['span']);
}
if (isset($config['context'])) {
$this->context = $config['context'];
}
if (isset($config['size'])) {
$this->size($config['size']);
}
if (isset($config['tab'])) {
$this->tab($config['tab']);
}
if (isset($config['commentAbove'])) {
$this->comment($config['commentAbove'], 'above');
}
if (isset($config['comment'])) {
$this->comment($config['comment']);
}
if (isset($config['placeholder'])) {
$this->placeholder = $config['placeholder'];
}
if (isset($config['default'])) {
$this->defaults = $config['default'];
}
if (isset($config['cssClass'])) {
$this->cssClass = $config['cssClass'];
}
if (isset($config['attributes'])) {
$this->attributes($config['attributes']);
}
if (isset($config['containerAttributes'])) {
$this->attributes($config['containerAttributes'], 'container');
}
if (isset($config['depends'])) {
$this->depends = $config['depends'];
}
if (isset($config['path'])) {
$this->path = $config['path'];
}
if (array_key_exists('required', $config)) $this->required = $config['required'];
if (array_key_exists('disabled', $config)) $this->disabled = $config['disabled'];
if (array_key_exists('hidden', $config)) $this->hidden = $config['hidden'];
if (array_key_exists('stretch', $config)) $this->stretch = $config['stretch'];
if (array_key_exists('required', $config)) {
$this->required = $config['required'];
}
if (array_key_exists('disabled', $config)) {
$this->disabled = $config['disabled'];
}
if (array_key_exists('hidden', $config)) {
$this->hidden = $config['hidden'];
}
if (array_key_exists('stretch', $config)) {
$this->stretch = $config['stretch'];
}
if (isset($config['valueFrom'])) $this->valueFrom = $config['valueFrom'];
else $this->valueFrom = $this->fieldName;
if (isset($config['valueFrom'])) {
$this->valueFrom = $config['valueFrom'];
} else {
$this->valueFrom = $this->fieldName;
}
return $config;
}
@ -284,8 +321,9 @@ class FormField
*/
public function attributes($items, $position = 'field')
{
if (!is_array($items))
if (!is_array($items)) {
return;
}
$multiArray = array_filter($items, 'is_array');
if (!$multiArray) {
@ -316,13 +354,15 @@ class FormField
*/
public function getName($arrayName = null)
{
if ($arrayName === null)
if ($arrayName === null) {
$arrayName = $this->arrayName;
}
if ($arrayName)
if ($arrayName) {
return $arrayName.'['.implode('][', Str::evalHtmlArray($this->fieldName)).']';
else
} else {
return $this->fieldName;
}
}
/**
@ -331,16 +371,19 @@ class FormField
public function getId($suffix = null)
{
$id = 'field';
if ($this->arrayName)
if ($this->arrayName) {
$id .= '-'.$this->arrayName;
}
$id .= '-'.$this->fieldName;
if ($suffix)
if ($suffix) {
$id .= '-'.$suffix;
}
if ($this->idPrefix)
if ($this->idPrefix) {
$id = $this->idPrefix . '-' . $id;
}
return Str::evalHtmlId($id);
}

View File

@ -61,16 +61,23 @@ abstract class FormWidgetBase extends WidgetBase
$this->valueFrom = $formField->valueFrom;
$this->model = $model;
/* @todo Remove line if year >= 2015 */ $this->columnName = $formField->valueFrom;
// @todo Remove line if year >= 2015
$this->columnName = $formField->valueFrom;
if (isset($configuration->sessionKey)) $this->sessionKey = $configuration->sessionKey;
if (isset($configuration->previewMode)) $this->previewMode = $configuration->previewMode;
if (isset($configuration->sessionKey)) {
$this->sessionKey = $configuration->sessionKey;
}
if (isset($configuration->previewMode)) {
$this->previewMode = $configuration->previewMode;
}
/*
* Form fields originally passed their configuration via the options index.
* This step should be removed if year >= 2015.
*/
if (isset($configuration->options)) $configuration = array_merge($configuration->options, (array)$configuration);
if (isset($configuration->options)) {
$configuration = array_merge($configuration->options, (array)$configuration);
}
parent::__construct($controller, $configuration);
}
@ -125,5 +132,4 @@ abstract class FormWidgetBase extends WidgetBase
return [$model, $last];
}
}

View File

@ -108,19 +108,39 @@ class ListColumn
*/
protected function evalConfig($config)
{
if (isset($config['cssClass'])) $this->cssClass = $config['cssClass'];
if (isset($config['searchable'])) $this->searchable = $config['searchable'];
if (isset($config['sortable'])) $this->sortable = $config['sortable'];
if (isset($config['invisible'])) $this->invisible = $config['invisible'];
if (isset($config['valueFrom'])) $this->valueFrom = $config['valueFrom'];
if (isset($config['select'])) $this->sqlSelect = $config['select'];
if (isset($config['relation'])) $this->relation = $config['relation'];
if (isset($config['format'])) $this->format = $config['format'];
if (isset($config['path'])) $this->path = $config['path'];
if (isset($config['cssClass'])) {
$this->cssClass = $config['cssClass'];
}
if (isset($config['searchable'])) {
$this->searchable = $config['searchable'];
}
if (isset($config['sortable'])) {
$this->sortable = $config['sortable'];
}
if (isset($config['invisible'])) {
$this->invisible = $config['invisible'];
}
if (isset($config['valueFrom'])) {
$this->valueFrom = $config['valueFrom'];
}
if (isset($config['select'])) {
$this->sqlSelect = $config['select'];
}
if (isset($config['relation'])) {
$this->relation = $config['relation'];
}
if (isset($config['format'])) {
$this->format = $config['format'];
}
if (isset($config['path'])) {
$this->path = $config['path'];
}
/* @todo Remove line if year >= 2015 */ if (isset($config['nameFrom'])) $this->valueFrom = $config['nameFrom'];
// @todo Remove lines if year >= 2015
if (isset($config['nameFrom'])) {
$this->valueFrom = $config['nameFrom'];
}
return $config;
}
}

View File

@ -83,8 +83,9 @@ class NavigationManager
foreach ($plugins as $id => $plugin) {
$items = $plugin->registerNavigation();
if (!is_array($items))
if (!is_array($items)) {
continue;
}
$this->registerMenuItems($id, $items);
}
@ -97,9 +98,10 @@ class NavigationManager
/*
* Sort menu items
*/
usort($this->items, function($a, $b) {
if ($a->order == $b->order)
usort($this->items, function ($a, $b) {
if ($a->order == $b->order) {
return 0;
}
return $a->order > $b->order ? 1 : -1;
});
@ -111,8 +113,9 @@ class NavigationManager
$this->items = $this->filterItemPermissions($user, $this->items);
foreach ($this->items as $item) {
if (!$item->sideMenu || !count($item->sideMenu))
if (!$item->sideMenu || !count($item->sideMenu)) {
continue;
}
$item->sideMenu = $this->filterItemPermissions($user, $item->sideMenu);
}
@ -161,8 +164,9 @@ class NavigationManager
*/
public function registerMenuItems($owner, array $definitions)
{
if (!$this->items)
if (!$this->items) {
$this->items = [];
}
foreach ($definitions as $code => $definition) {
$item = (object) array_merge(self::$mainItemDefaults, array_merge($definition, [
@ -192,8 +196,9 @@ class NavigationManager
*/
public function addMainMenuItems($owner, array $definitions)
{
foreach ($definitions as $code => $definition)
foreach ($definitions as $code => $definition) {
$this->addMainMenuItem($owner, $code, $definition);
}
}
/**
@ -207,8 +212,9 @@ class NavigationManager
$sideMenu = isset($definition['sideMenu']) ? $definition['sideMenu'] : null;
$itemKey = $this->makeItemKey($owner, $code);
if (isset($this->items[$itemKey]))
if (isset($this->items[$itemKey])) {
$definition = array_merge((array) $this->items[$itemKey], $definition);
}
$item = (object) array_merge(self::$mainItemDefaults, array_merge($definition, [
'code' => $code,
@ -217,8 +223,9 @@ class NavigationManager
$this->items[$itemKey] = $item;
if ($sideMenu !== null)
if ($sideMenu !== null) {
$this->addSideMenuItems($sideMenu);
}
}
/**
@ -229,8 +236,9 @@ class NavigationManager
*/
public function addSideMenuItems($owner, $code, array $definitions)
{
foreach ($definitions as $sideCode => $definition)
foreach ($definitions as $sideCode => $definition) {
$this->addSideMenuItem($owner, $code, $sideCode, $definition);
}
}
/**
@ -243,12 +251,14 @@ class NavigationManager
public function addSideMenuItem($owner, $code, $sideCode, array $definition)
{
$itemKey = $this->makeItemKey($owner, $code);
if (!isset($this->items[$itemKey]))
if (!isset($this->items[$itemKey])) {
return false;
}
$mainItem = $this->items[$itemKey];
if (isset($mainItem->sideMenu[$sideCode]))
if (isset($mainItem->sideMenu[$sideCode])) {
$definition = array_merge((array) $mainItem->sideMenu[$sideCode], $definition);
}
$item = (object) array_merge(self::$sideItemDefaults, $definition);
$this->items[$itemKey]->sideMenu[$sideCode] = $item;
@ -260,8 +270,9 @@ class NavigationManager
*/
public function listMainMenuItems()
{
if ($this->items === null)
if ($this->items === null) {
$this->loadItems();
}
return $this->items;
}
@ -281,14 +292,16 @@ class NavigationManager
}
}
if (!$activeItem)
if (!$activeItem) {
return [];
}
$items = $activeItem->sideMenu;
foreach ($items as $item) {
if ($item->counter !== null && is_callable($item->counter))
if ($item->counter !== null && is_callable($item->counter)) {
$item->counter = call_user_func($item->counter, $item);
}
}
return $items;
@ -369,8 +382,9 @@ class NavigationManager
public function getActiveMainMenuItem()
{
foreach ($this->listMainMenuItems() as $item) {
if ($this->isMainMenuItemActive($item))
if ($this->isMainMenuItemActive($item)) {
return $item;
}
}
return null;
@ -399,7 +413,9 @@ class NavigationManager
}
/**
* Returns the side navigation partial for a specific main menu previously registered with the registerContextSidenavPartial() method.
* Returns the side navigation partial for a specific main menu previously registered
* with the registerContextSidenavPartial() method.
*
* @param string $owner Specifies the navigation owner in the format Vendor/Module.
* @param string $mainMenuItemCode Specifies the main menu item code.
* @return mixed Returns the partial name or null.
@ -421,9 +437,10 @@ class NavigationManager
*/
protected function filterItemPermissions($user, array $items)
{
$items = array_filter($items, function($item) use ($user) {
if (!$item->permissions || !count($item->permissions))
$items = array_filter($items, function ($item) use ($user) {
if (!$item->permissions || !count($item->permissions)) {
return true;
}
return $user->hasAnyAccess($item->permissions);
});

View File

@ -79,8 +79,7 @@ abstract class Skin
return $isPublic
? $this->publicSkinPath . $path
: $this->skinPath . $path;
}
else {
} else {
return $isPublic
? $this->defaultPublicSkinPath . $path
: $this->defaultSkinPath . $path;
@ -101,8 +100,9 @@ abstract class Skin
*/
public static function getActive()
{
if (self::$skinCache !== null)
if (self::$skinCache !== null) {
return self::$skinCache;
}
$skinClass = Config::get('cms.backendSkin');
$skinObject = new $skinClass();

View File

@ -52,7 +52,10 @@ abstract class WidgetBase
// Option A: (@todo Determine which is faster by benchmark)
// $relativePath = strtolower(str_replace('\\', '/', get_called_class()));
// $this->viewPath = $this->configPath = ['modules/' . $relativePath . '/partials', 'plugins/' . $relativePath . '/partials'];
// $this->viewPath = $this->configPath = [
// 'modules/' . $relativePath . '/partials',
// 'plugins/' . $relativePath . '/partials'
// ];
// $this->assetPath = ['modules/' . $relativePath . '/assets', 'plugins/' . $relativePath . '/assets'];
// Option B:
@ -62,16 +65,18 @@ abstract class WidgetBase
/*
* Apply configuration values to a new config object.
*/
if (!$configuration)
if (!$configuration) {
$configuration = [];
}
$this->config = $this->makeConfig($configuration);
/*
* If no alias is set by the configuration.
*/
if (!isset($this->alias))
if (!isset($this->alias)) {
$this->alias = (isset($this->config->alias)) ? $this->config->alias : $this->defaultAlias;
}
/*
* Prepare assets used by this widget.
@ -81,28 +86,35 @@ abstract class WidgetBase
/*
* Initialize the widget.
*/
if (!$this->getConfig('noInit', false))
if (!$this->getConfig('noInit', false)) {
$this->init();
}
}
/**
* Initialize the widget, called by the constructor and free from its parameters.
* @return void
*/
public function init(){}
public function init()
{
}
/**
* Renders the widgets primary contents.
* @return string HTML markup supplied by this widget.
*/
public function render(){}
public function render()
{
}
/**
* Adds widget specific asset files. Use $this->addJs() and $this->addCss()
* to register new assets to include on the page.
* @return void
*/
protected function loadAssets(){}
protected function loadAssets()
{
}
/**
* Binds a widget to the controller for safe use.
@ -110,8 +122,9 @@ abstract class WidgetBase
*/
public function bindToController()
{
if ($this->controller->widget === null)
if ($this->controller->widget === null) {
$this->controller->widget = new \stdClass();
}
$this->controller->widget->{$this->alias} = $this;
}
@ -125,11 +138,13 @@ abstract class WidgetBase
{
$id = class_basename(get_called_class());
if ($this->alias != $this->defaultAlias)
if ($this->alias != $this->defaultAlias) {
$id .= '-' . $this->alias;
}
if ($suffix !== null)
if ($suffix !== null) {
$id .= '-' . $suffix;
}
return Str::evalHtmlId($id);
}
@ -161,8 +176,9 @@ abstract class WidgetBase
* First part will be the field name, pop it off
*/
$fieldName = array_shift($keyParts);
if (!isset($this->config->{$fieldName}))
if (!isset($this->config->{$fieldName})) {
return $default;
}
$result = $this->config->{$fieldName};
@ -170,8 +186,9 @@ abstract class WidgetBase
* Loop the remaining key parts and build a result
*/
foreach ($keyParts as $key) {
if (!array_key_exists($key, $result))
if (!array_key_exists($key, $result)) {
return $default;
}
$result = $result[$key];
}
@ -218,11 +235,13 @@ abstract class WidgetBase
$sessionId = $this->makeSessionId();
$currentStore = [];
if (Session::has($sessionId))
if (Session::has($sessionId)) {
$currentStore = unserialize(Session::get($sessionId));
}
if ($key === null)
if ($key === null) {
return $currentStore;
}
return isset($currentStore[$key]) ? $currentStore[$key] : $default;
}
@ -247,5 +266,4 @@ abstract class WidgetBase
$sessionId = $this->makeSessionId();
Session::forget($sessionId);
}
}

View File

@ -69,8 +69,9 @@ class WidgetManager
/*
* Build configuration
*/
if ($configuration === null)
if ($configuration === null) {
$configuration = [];
}
/*
* Create widget object
@ -110,11 +111,13 @@ class WidgetManager
$plugins = $this->pluginManager->getPlugins();
foreach ($plugins as $plugin) {
if (!is_array($widgets = $plugin->registerFormWidgets()))
if (!is_array($widgets = $plugin->registerFormWidgets())) {
continue;
}
foreach ($widgets as $className => $widgetInfo)
foreach ($widgets as $className => $widgetInfo) {
$this->registerFormWidget($className, $widgetInfo);
}
}
}
@ -131,10 +134,14 @@ class WidgetManager
{
$widgetCode = isset($widgetInfo['code']) ? $widgetInfo['code'] : null;
/* @todo Remove line if year >= 2015 */ if (!$widgetCode) $widgetCode = isset($widgetInfo['alias']) ? $widgetInfo['alias'] : null;
/* @todo Remove line if year >= 2015 */
if (!$widgetCode) {
$widgetCode = isset($widgetInfo['alias']) ? $widgetInfo['alias'] : null;
}
if (!$widgetCode)
if (!$widgetCode) {
$widgetCode = Str::getClassId($className);
}
$this->formWidgets[$className] = $widgetInfo;
$this->formWidgetHints[$widgetCode] = $className;
@ -165,17 +172,20 @@ class WidgetManager
*/
public function resolveFormWidget($name)
{
if ($this->formWidgets === null)
if ($this->formWidgets === null) {
$this->listFormWidgets();
}
$hints = $this->formWidgetHints;
if (isset($hints[$name]))
if (isset($hints[$name])) {
return $hints[$name];
}
$_name = Str::normalizeClassName($name);
if (isset($this->formWidgets[$_name]))
if (isset($this->formWidgets[$_name])) {
return $_name;
}
return $name;
}
@ -206,11 +216,13 @@ class WidgetManager
$plugins = $this->pluginManager->getPlugins();
foreach ($plugins as $plugin) {
if (!is_array($widgets = $plugin->registerReportWidgets()))
if (!is_array($widgets = $plugin->registerReportWidgets())) {
continue;
}
foreach ($widgets as $className => $widgetInfo)
foreach ($widgets as $className => $widgetInfo) {
$this->registerReportWidget($className, $widgetInfo);
}
}
}

View File

@ -37,5 +37,4 @@ class AccessLogs extends Controller
BackendMenu::setContext('October.System', 'system', 'settings');
SettingsManager::setContext('October.Backend', 'access_logs');
}
}

View File

@ -47,12 +47,12 @@ class Auth extends Controller
$this->bodyClass = 'signin';
try {
if (post('postback'))
if (post('postback')) {
return $this->signin_onSubmit();
else
} else {
$this->bodyClass .= ' preload';
}
catch (Exception $ex) {
}
} catch (Exception $ex) {
Flash::error($ex->getMessage());
}
}
@ -65,8 +65,9 @@ class Auth extends Controller
];
$validation = Validator::make(post(), $rules);
if ($validation->fails())
if ($validation->fails()) {
throw new ValidationException($validation);
}
// Authenticate user
$user = BackendAuth::authenticate([
@ -99,10 +100,10 @@ class Auth extends Controller
public function restore()
{
try {
if (post('postback'))
if (post('postback')) {
return $this->restore_onSubmit();
}
catch (Exception $ex) {
}
} catch (Exception $ex) {
Flash::error($ex->getMessage());
}
}
@ -114,8 +115,9 @@ class Auth extends Controller
];
$validation = Validator::make(post(), $rules);
if ($validation->fails())
if ($validation->fails()) {
throw new ValidationException($validation);
}
$user = BackendAuth::findUserByLogin(post('login'));
if (!$user) {
@ -134,8 +136,7 @@ class Auth extends Controller
'link' => $link,
];
Mail::send('backend::mail.restore', $data, function($message) use ($user)
{
Mail::send('backend::mail.restore', $data, function ($message) use ($user) {
$message->to($user->email, $user->full_name)->subject(trans('backend::lang.account.password_reset'));
});
@ -148,13 +149,14 @@ class Auth extends Controller
public function reset($userId = null, $code = null)
{
try {
if (post('postback'))
if (post('postback')) {
return $this->reset_onSubmit();
}
if (!$userId || !$code)
if (!$userId || !$code) {
throw new ApplicationException(trans('backend::lang.account.reset_error'));
}
catch (Exception $ex) {
}
} catch (Exception $ex) {
Flash::error($ex->getMessage());
}
@ -164,25 +166,29 @@ class Auth extends Controller
public function reset_onSubmit()
{
if (!post('id') || !post('code'))
if (!post('id') || !post('code')) {
throw new ApplicationException(trans('backend::lang.account.reset_error'));
}
$rules = [
'password' => 'required|min:2'
];
$validation = Validator::make(post(), $rules);
if ($validation->fails())
if ($validation->fails()) {
throw new ValidationException($validation);
}
$code = post('code');
$user = BackendAuth::findUserById(post('id'));
if (!$user->checkResetPasswordCode($code))
if (!$user->checkResetPasswordCode($code)) {
throw new ApplicationException(trans('backend::lang.account.reset_error'));
}
if (!$user->attemptResetPassword($code, post('password')))
if (!$user->attemptResetPassword($code, post('password'))) {
throw new ApplicationException(trans('backend::lang.account.reset_fail'));
}
$user->clearResetPassword();

View File

@ -45,8 +45,9 @@ class Groups extends Controller
'type' => 'checkbox',
];
if (isset($permission->tab))
if (isset($permission->tab)) {
$fieldConfig['tab'] = $permission->tab;
}
$permissionFields[$fieldName] = $fieldConfig;
}

View File

@ -28,11 +28,36 @@ class Index extends Controller
BackendMenu::setContextOwner('October.Backend');
new ReportContainer($this);
/* @todo Remove line if year >= 2015 */ if (\Schema::hasColumn('backend_users', 'activated')) \Schema::table('backend_users', function($table) { $table->renameColumn('activated', 'is_activated'); });
/* @todo Remove line if year >= 2015 */ if (\Schema::hasColumn('backend_user_throttle', 'suspended')) \Schema::table('backend_user_throttle', function($table) { $table->renameColumn('suspended', 'is_suspended'); });
/* @todo Remove line if year >= 2015 */ if (\Schema::hasColumn('backend_user_throttle', 'banned')) \Schema::table('backend_user_throttle', function($table) { $table->renameColumn('banned', 'is_banned'); });
/* @todo Remove line if year >= 2015 */ if (\Schema::hasColumn('deferred_bindings', 'bind')) \Schema::table('deferred_bindings', function($table) { $table->renameColumn('bind', 'is_bind'); });
/* @todo Remove line if year >= 2015 */ if (\Schema::hasColumn('system_files', 'public')) \Schema::table('system_files', function($table) { $table->renameColumn('public', 'is_public'); });
/* @todo Remove line if year >= 2015 */
if (\Schema::hasColumn('backend_users', 'activated')) {
\Schema::table('backend_users', function ($table) {
$table->renameColumn('activated', 'is_activated');
});
}
/* @todo Remove line if year >= 2015 */
if (\Schema::hasColumn('backend_user_throttle', 'suspended')) {
\Schema::table('backend_user_throttle', function ($table) {
$table->renameColumn('suspended', 'is_suspended');
});
}
/* @todo Remove line if year >= 2015 */
if (\Schema::hasColumn('backend_user_throttle', 'banned')) {
\Schema::table('backend_user_throttle', function ($table) {
$table->renameColumn('banned', 'is_banned');
});
}
/* @todo Remove line if year >= 2015 */
if (\Schema::hasColumn('deferred_bindings', 'bind')) {
\Schema::table('deferred_bindings', function ($table) {
$table->renameColumn('bind', 'is_bind');
});
}
/* @todo Remove line if year >= 2015 */
if (\Schema::hasColumn('system_files', 'public')) {
\Schema::table('system_files', function ($table) {
$table->renameColumn('public', 'is_public');
});
}
}
public function index()

View File

@ -32,8 +32,9 @@ class Users extends Controller
{
parent::__construct();
if ($this->action == 'myaccount')
if ($this->action == 'myaccount') {
$this->requiredPermissions = null;
}
BackendMenu::setContext('October.System', 'system', 'users');
SettingsManager::setContext('October.System', 'administrators');
@ -45,8 +46,9 @@ class Users extends Controller
public function update($recordId, $context = null)
{
// Users cannot edit themselves, only use My Settings
if ($context != 'myaccount' && $recordId == $this->user->id)
if ($context != 'myaccount' && $recordId == $this->user->id) {
return Redirect::to(Backend::url('backend/users/myaccount'));
}
return $this->asExtension('FormController')->update($recordId, $context);
}
@ -74,8 +76,9 @@ class Users extends Controller
*/
$loginChanged = $this->user->login != post('User[login]');
$passwordChanged = strlen(post('User[password]'));
if ($loginChanged || $passwordChanged)
if ($loginChanged || $passwordChanged) {
BackendAuth::login($this->user->reload(), true);
}
return $result;
}
@ -85,8 +88,9 @@ class Users extends Controller
*/
protected function formExtendFields($form)
{
if ($form->getContext() == 'myaccount')
if ($form->getContext() == 'myaccount') {
return;
}
$permissionFields = [];
foreach (BackendAuth::listPermissions() as $permission) {
@ -109,8 +113,9 @@ class Users extends Controller
'span' => 'auto',
];
if (isset($permission->tab))
if (isset($permission->tab)) {
$fieldConfig['tab'] = $permission->tab;
}
$permissionFields[$fieldName] = $fieldConfig;
}

View File

@ -5,11 +5,9 @@ use Illuminate\Database\Migrations\Migration;
class DbBackendUsers extends Migration
{
public function up()
{
Schema::create('backend_users', function(Blueprint $table)
{
Schema::create('backend_users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('first_name')->nullable();
@ -32,5 +30,4 @@ class DbBackendUsers extends Migration
{
Schema::dropIfExists('backend_users');
}
}

View File

@ -5,11 +5,9 @@ use Illuminate\Database\Migrations\Migration;
class DbBackendUserGroups extends Migration
{
public function up()
{
Schema::create('backend_user_groups', function($table)
{
Schema::create('backend_user_groups', function ($table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('name')->unique();
@ -22,5 +20,4 @@ class DbBackendUserGroups extends Migration
{
Schema::dropIfExists('backend_user_groups');
}
}

View File

@ -5,11 +5,9 @@ use Illuminate\Database\Migrations\Migration;
class DbBackendUsersGroups extends Migration
{
public function up()
{
Schema::create('backend_users_groups', function($table)
{
Schema::create('backend_users_groups', function ($table) {
$table->engine = 'InnoDB';
$table->integer('user_id')->unsigned();
$table->integer('user_group_id')->unsigned();
@ -21,5 +19,4 @@ class DbBackendUsersGroups extends Migration
{
Schema::dropIfExists('backend_users_groups');
}
}

View File

@ -5,11 +5,9 @@ use Illuminate\Database\Migrations\Migration;
class DbBackendUserThrottle extends Migration
{
public function up()
{
Schema::create('backend_user_throttle', function($table)
{
Schema::create('backend_user_throttle', function ($table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned();
@ -27,5 +25,4 @@ class DbBackendUserThrottle extends Migration
{
Schema::dropIfExists('backend_user_throttle');
}
}

View File

@ -7,8 +7,7 @@ class DbBackendUserPreferences extends Migration
{
public function up()
{
Schema::create('backend_user_preferences', function($table)
{
Schema::create('backend_user_preferences', function ($table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned();

View File

@ -5,11 +5,9 @@ use Illuminate\Database\Migrations\Migration;
class DbBackendAccessLog extends Migration
{
public function up()
{
Schema::create('backend_access_log', function(Blueprint $table)
{
Schema::create('backend_access_log', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned();
@ -22,5 +20,4 @@ class DbBackendAccessLog extends Migration
{
Schema::dropIfExists('backend_access_log');
}
}

View File

@ -17,5 +17,4 @@ class DatabaseSeeder extends Seeder
$this->call('Backend\Database\Seeds\SeedSetupAdmin');
}
}

View File

@ -15,7 +15,9 @@ class SeedSetupAdmin extends Seeder
public function setDefaults($values)
{
if (!is_array($values)) return;
if (!is_array($values)) {
return;
}
foreach ($values as $attribute => $value) {
static::$$attribute = $value;
}
@ -40,5 +42,4 @@ class SeedSetupAdmin extends Seeder
$user->addGroup($group);
}
}

View File

@ -12,5 +12,8 @@ class Backend extends Facade
*
* @return string
*/
protected static function getFacadeAccessor() { return 'backend.helper'; }
protected static function getFacadeAccessor()
{
return 'backend.helper';
}
}

View File

@ -12,5 +12,8 @@ class BackendAuth extends Facade
*
* @return string
*/
protected static function getFacadeAccessor() { return 'backend.auth'; }
protected static function getFacadeAccessor()
{
return 'backend.auth';
}
}

View File

@ -12,5 +12,8 @@ class BackendMenu extends Facade
*
* @return string
*/
protected static function getFacadeAccessor() { return 'backend.menu'; }
protected static function getFacadeAccessor()
{
return 'backend.menu';
}
}

View File

@ -118,5 +118,4 @@ class CodeEditor extends FormWidgetBase
$this->addJs('vendor/ace/ace.js', 'core');
$this->addJs('js/codeeditor.js', 'core');
}
}

View File

@ -99,16 +99,19 @@ class DataGrid extends FormWidgetBase
{
$methodName = 'get'.studly_case($this->fieldName).'AutocompleteValues';
if (!$this->model->methodExists($methodName) && !$this->model->methodExists('getGridAutocompleteValues'))
if (!$this->model->methodExists($methodName) && !$this->model->methodExists('getGridAutocompleteValues')) {
throw new ApplicationException('Model :model does not contain a method getGridAutocompleteValues()');
}
if ($this->model->methodExists($methodName))
if ($this->model->methodExists($methodName)) {
$result = $this->model->$methodName($field, $value, $data);
else
} else {
$result = $this->model->getGridAutocompleteValues($this->fieldName, $field, $value, $data);
}
if (!is_array($result))
if (!is_array($result)) {
$result = [];
}
return $result;
}
@ -122,16 +125,19 @@ class DataGrid extends FormWidgetBase
{
$methodName = 'get'.studly_case($this->fieldName).'DataSourceValues';
if (!$this->model->methodExists($methodName) && !$this->model->methodExists('getGridDataSourceValues'))
if (!$this->model->methodExists($methodName) && !$this->model->methodExists('getGridDataSourceValues')) {
throw new ApplicationException('Model :model does not contain a method getGridDataSourceValues()');
}
if ($this->model->methodExists($methodName))
if ($this->model->methodExists($methodName)) {
$result = $this->model->$methodName();
else
} else {
$result = $this->model->getGridDataSourceValues($this->fieldName);
}
if (!is_array($result))
if (!is_array($result)) {
$result = [];
}
return $result;
}

View File

@ -60,10 +60,11 @@ class DatePicker extends FormWidgetBase
$value = $this->getLoadData();
if ($this->mode != 'datetime' && $value) {
if (is_string($value))
if (is_string($value)) {
$value = substr($value, 0, 10);
elseif (is_object($value))
} elseif (is_object($value)) {
$value = $value->toDateString();
}
}
$this->vars['value'] = $value ?: '';

View File

@ -39,7 +39,10 @@ class FileUpload extends FormWidgetBase
{
$this->imageHeight = $this->getConfig('imageHeight', 100);
$this->imageWidth = $this->getConfig('imageWidth', 100);
$this->previewNoFilesMessage = $this->getConfig('previewNoFilesMessage', 'backend::lang.form.preview_no_files_message');
$this->previewNoFilesMessage = $this->getConfig(
'previewNoFilesMessage',
'backend::lang.form.preview_no_files_message'
);
$this->checkUploadPostback();
}
@ -87,8 +90,9 @@ class FileUpload extends FormWidgetBase
{
$mode = $this->getConfig('mode', 'image');
if (str_contains($mode, '-'))
if (str_contains($mode, '-')) {
return $mode;
}
$relationType = $this->getRelationType();
$mode .= ($relationType == 'attachMany' || $relationType == 'morphMany') ? '-multi' : '-single';
@ -171,8 +175,7 @@ class FileUpload extends FormWidgetBase
}
throw new SystemException('Unable to find file, it may no longer exist');
}
catch (Exception $ex) {
} catch (Exception $ex) {
return json_encode(['error' => $ex->getMessage()]);
}
}
@ -200,8 +203,9 @@ class FileUpload extends FormWidgetBase
*/
protected function checkUploadPostback()
{
if (!($uniqueId = post('X_OCTOBER_FILEUPLOAD')) || $uniqueId != $this->getId())
if (!($uniqueId = post('X_OCTOBER_FILEUPLOAD')) || $uniqueId != $this->getId()) {
return;
}
try {
$uploadedFile = Input::file('file_data');
@ -209,19 +213,22 @@ class FileUpload extends FormWidgetBase
$isImage = starts_with($this->getDisplayMode(), 'image');
$validationRules = ['max:'.File::getMaxFilesize()];
if ($isImage)
if ($isImage) {
$validationRules[] = 'mimes:jpg,jpeg,bmp,png,gif';
}
$validation = Validator::make(
['file_data' => $uploadedFile],
['file_data' => $validationRules]
);
if ($validation->fails())
if ($validation->fails()) {
throw new ValidationException($validation);
}
if (!$uploadedFile->isValid())
if (!$uploadedFile->isValid()) {
throw new SystemException('File is not valid');
}
$fileRelation = $this->getRelationObject();
@ -235,8 +242,7 @@ class FileUpload extends FormWidgetBase
$file->thumb = $file->getThumb($this->imageWidth, $this->imageHeight, ['mode' => 'crop']);
$result = $file;
}
catch (Exception $ex) {
} catch (Exception $ex) {
$result = json_encode(['error' => $ex->getMessage()]);
}

View File

@ -84,11 +84,21 @@ class RecordFinder extends FormWidgetBase
$this->nameFrom = $this->getConfig('nameFrom', $this->nameFrom);
$this->descriptionFrom = $this->getConfig('descriptionFrom', $this->descriptionFrom);
/* @todo Remove line if year >= 2015 */ if ($this->getConfig('nameColumn')) $this->nameFrom = $this->getConfig('nameColumn');
/* @todo Remove line if year >= 2015 */ if ($this->getConfig('descriptionColumn')) $this->descriptionFrom = $this->getConfig('descriptionColumn');
/* @todo Remove lines if year >= 2015 */
if ($this->getConfig('nameColumn')) {
$this->nameFrom = $this->getConfig('nameColumn');
}
/* @todo Remove lines if year >= 2015 */
if ($this->getConfig('descriptionColumn')) {
$this->descriptionFrom = $this->getConfig('descriptionColumn');
}
if (!$this->model->hasRelation($this->relationName))
throw new SystemException(Lang::get('backend::lang.model.missing_relation', ['class'=>get_class($this->controller), 'relation'=>$this->relationName]));
if (!$this->model->hasRelation($this->relationName)) {
throw new SystemException(Lang::get('backend::lang.model.missing_relation', [
'class' => get_class($this->controller),
'relation' => $this->relationName
]));
}
if (post('recordfinder_flag')) {
$this->listWidget = $this->makeListWidget();
@ -100,7 +110,7 @@ class RecordFinder extends FormWidgetBase
/*
* Link the Search Widget to the List Widget
*/
$this->searchWidget->bindEvent('search.submit', function() {
$this->searchWidget->bindEvent('search.submit', function () {
$this->listWidget->setSearchTerm($this->searchWidget->getActiveTerm());
return $this->listWidget->onRefresh();
});
@ -162,24 +172,27 @@ class RecordFinder extends FormWidgetBase
public function getKeyValue()
{
if (!$this->relationModel)
if (!$this->relationModel) {
return null;
}
return $this->relationModel->{$this->keyFrom};
}
public function getNameValue()
{
if (!$this->relationModel || !$this->nameFrom)
if (!$this->relationModel || !$this->nameFrom) {
return null;
}
return $this->relationModel->{$this->nameFrom};
}
public function getDescriptionValue()
{
if (!$this->relationModel || !$this->descriptionFrom)
if (!$this->relationModel || !$this->descriptionFrom) {
return null;
}
return $this->relationModel->{$this->descriptionFrom};
}

View File

@ -61,11 +61,21 @@ class Relation extends FormWidgetBase
$this->descriptionFrom = $this->getConfig('descriptionFrom', $this->descriptionFrom);
$this->emptyOption = $this->getConfig('emptyOption');
/* @todo Remove line if year >= 2015 */ if ($this->getConfig('nameColumn')) $this->nameFrom = $this->getConfig('nameColumn');
/* @todo Remove line if year >= 2015 */ if ($this->getConfig('descriptionColumn')) $this->descriptionFrom = $this->getConfig('descriptionColumn');
/* @todo Remove lines if year >= 2015 */
if ($this->getConfig('nameColumn')) {
$this->nameFrom = $this->getConfig('nameColumn');
}
/* @todo Remove lines if year >= 2015 */
if ($this->getConfig('descriptionColumn')) {
$this->descriptionFrom = $this->getConfig('descriptionColumn');
}
if (!$this->model->hasRelation($this->relationName))
throw new SystemException(Lang::get('backend::lang.model.missing_relation', ['class'=>get_class($this->controller), 'relation'=>$this->relationName]));
if (!$this->model->hasRelation($this->relationName)) {
throw new SystemException(Lang::get(
'backend::lang.model.missing_relation',
['class'=>get_class($this->controller), 'relation'=>$this->relationName]
));
}
}
/**
@ -90,7 +100,7 @@ class Relation extends FormWidgetBase
*/
protected function makeRenderFormField()
{
return $this->renderFormField = RelationBase::noConstraints(function() {
return $this->renderFormField = RelationBase::noConstraints(function () {
$field = clone $this->formField;
@ -100,8 +110,7 @@ class Relation extends FormWidgetBase
if (in_array($this->relationType, ['belongsToMany', 'morphToMany', 'morphedByMany'])) {
$field->type = 'checkboxlist';
}
else if ($this->relationType == 'belongsTo') {
} elseif ($this->relationType == 'belongsTo') {
$field->type = 'dropdown';
$field->placeholder = $this->emptyOption;
}
@ -117,10 +126,11 @@ class Relation extends FormWidgetBase
$query->getQuery()->getQuery()->joins = [];
$treeTraits = ['October\Rain\Database\Traits\NestedTree', 'October\Rain\Database\Traits\SimpleTree'];
if (count(array_intersect($treeTraits, class_uses($relatedObj))) > 0)
if (count(array_intersect($treeTraits, class_uses($relatedObj))) > 0) {
$field->options = $query->listsNested($this->nameFrom, $relatedObj->getKeyName());
else
} else {
$field->options = $query->lists($this->nameFrom, $relatedObj->getKeyName());
}
return $field;
});
@ -131,11 +141,13 @@ class Relation extends FormWidgetBase
*/
public function getSaveData($value)
{
if (is_string($value) && !strlen($value))
if (is_string($value) && !strlen($value)) {
return null;
}
if (is_array($value) && !count($value))
if (is_array($value) && !count($value)) {
return null;
}
return $value;
}

View File

@ -1,256 +1,256 @@
<?php
return [
'field' => [
'invalid_type' => 'نوع فیلد :type نا معتبر می باشد.',
'options_method_not_exists' => 'کلاس مدل :model باید شامل متد :method() باشد و گزینه های مورد نیاز ":field" را بازگرداند.',
],
'widget' => [
'not_registered' => "کلاس مربوط به ابزارک ':name' به سیستم معرفی نشده است",
'not_bound' => "ابزارکی تعریف شده در کلاس با نام ':name' به هیچ کنترلری ارتباط داده نشده است",
],
'page' => [
'untitled' => "بدون عنوان",
'access_denied' => [
'label' => "شما مجوز دسترسی ندارید",
'help' => "شما مجوز لازم براس دسترسی به این صفحه را ندارید.",
'cms_link' => "بازگشت به مدیریت",
],
],
'partial' => [
'not_found' => "بخشی با نام ':name' یافت نشد.",
],
'account' => [
'sign_out' => 'خروج',
'login' => 'ورود',
'reset' => 'تنظیم مجدد',
'restore' => 'بازگرداندن',
'login_placeholder' => 'ورود',
'password_placeholder' => 'کلمه عبور',
'forgot_password' => "کلمه عبور خود را فراموش کرده اید؟",
'enter_email' => "پست الکترونیکی خود را وارد نمایید",
'enter_login' => "نام کاربری خود را وارد نمایید",
'email_placeholder' => "پست الکترونیکی",
'enter_new_password' => "کلمه عبور جدید را وارد نمایید",
'password_reset' => "بازگرداندن کلمه عبور",
'restore_success' => "یک نامه به پست الکترونیکی شما جهت شروع عملیات بارگرداندن کلمه عبور ارسال شد.",
'restore_error' => "کاربری با نام کاریری ':login' یافت نشد.",
'reset_success' => "کلمه عبور شما بارگردانی شد و شما هم اکنون میتوانید وارد سیستم شوید.",
'reset_error' => "اطلاعات رمز عبور نا معتبر است , لطفا مجددا تلاش نمایید!",
'reset_fail' => "عدم توانایی در بازگرداندن کلمه عبور شما!",
'apply' => 'اعمال کردن',
'cancel' => 'انصراف',
'delete' => 'حذف',
'ok' => 'تایید',
],
'dashboard' => [
'menu_label' => 'میز کار',
'widget_label' => 'ابزارک',
'widget_width' => 'عرض',
'full_width' => 'عرض کامل',
'add_widget' => 'افزودن ابزارک',
'widget_inspector_title' => 'تنظیمات ابزارک',
'widget_inspector_description' => 'پیکر بندی ابزارک گزارشگیری',
'widget_columns_label' => 'عرض :columns',
'widget_columns_description' => 'عرض ابزارک باید عددی مابین 1 تا 10 باشد.',
'widget_columns_error' => 'لطفا عرض ابزارک را عددی مابین 1 تا 10 وارد نمایید.',
'columns' => '{1} ستون|[2,Inf] ستون ها',
'widget_new_row_label' => 'تحمیل سطر جدید',
'widget_new_row_description' => 'افزودن ابزارک در سطر جدید.',
'widget_title_label' => 'عنوان ابزارک',
'widget_title_error' => 'گزینه "عنوان ابزارک" حتما باید وارد شود.',
'status' => [
'widget_title_default' => 'وضعیت سیستم',
'online' => 'online',
'update_available' => '{0} به روز رسانی موجود است!|{1} به روز رسانی موجود است!|[2,Inf] به روز رسانی موجود است!',
]
],
'user' => [
'name' => 'مدیریت',
'menu_label' => 'مدیران',
'menu_description' => 'مدیریت کاربران , گروه ها و دسترسی های مدیران.',
'list_title' => 'مدیریت مدیران',
'new' => 'مدیر جدید',
'login' => "ورود",
'first_name' => "نام",
'last_name' => "نام خانوادگی",
'full_name' => "نام کامل",
'email' => "پست الکترونیکی",
'groups' => "گروه ها",
'groups_comment' => "مختص گروهی که این شخص به آن تعلق دارد.",
'avatar' => "نمایه",
'password' => "کلمه عبور",
'password_confirmation' => "تکرار کلمه عبور",
'superuser' => "کاربر ممتاز",
'superuser_comment' => "اگر میخواهید این شخص به تمام قسمت ها دسترسی داشته باشد این گزینه را فعال نمایید.",
'send_invite' => 'دعوت نامه توسط پست الکترونیکی ارسال شود',
'send_invite_comment' => 'جهت ارسال دعوت نامه به پست الکترونیکی این شخص این گزینه را فعال نمایید',
'delete_confirm' => 'آیا از حذف این مدیر اطمینان دارید؟',
'return' => 'بازگشت به لیست مدیران',
'allow' => 'اجازه دسترسی',
'inherit' => 'ارث بری',
'deny' => 'عدم دسترسی',
'group' => [
'name' => 'گروه',
'name_field' => 'نام',
'menu_label' => 'گروه ها',
'list_title' => 'مدیریت گروه ها',
'new' => 'گروه مدیریت جدید',
'delete_confirm' => 'آیا از حذف این گروه از مدیران اطمینان دارید?',
'return' => 'بازگشت به لیست گروه ها',
],
'preferences' => [
'not_authenticated' => 'هیچ کاربر ثبت شده ای جهت بارگذاری یا ذخیره تنظیمات وجود ندارد.'
]
],
'list' => [
'default_title' => 'لیست',
'search_prompt' => 'جستجو...',
'no_records' => 'چیزی یافت نشد.',
'missing_model' => 'هیچ مدلی برای لیست استفاده شده در کلاس :class تعریف نشده است.',
'missing_column' => 'ستونی برای :columns تعریف نشده است.',
'missing_columns' => 'ستونی برای لیست عریف شده در :class موجود نیست.',
'missing_definition' => "در لیست تعریف شده ستونی برای ':field' موجود نیست.",
'behavior_not_ready' => 'لسیت مقدار دهی اولیه شده است ، لطفا بررسی نمایید که متد makeLists() در کنترلر خود فراخوانی کرده باشید.',
'invalid_column_datetime' => "ستون ':column' از نوع شی تاریخ نمی باشد ، لطفا بررسی نمایید که این ستون در مدل از نوع تاریخ تعریف شده باشد.",
'pagination' => 'نمایش :from تا :to از :total مورد',
'prev_page' => 'صفحه قبل',
'next_page' => 'صفحه بعد',
'loading' => 'در حال بارگذاری...',
'setup_title' => 'راه اندازی لیست',
'setup_help' => 'ستون هایی را که میخواهید مشاهده نمایید را انتخاب نمایید. میتوانید محل قرار گیری ستونها را با جابجا نمودن آنها به .',
'records_per_page' => 'مورد در هر صفحه',
'records_per_page_help' => 'تعداد موارد نمایش داده شده در هر صفحه را انتخاب نمایید. لطفا توجه نمایید نمایش تعداد زیادی از موارد در هر صفحه از کارایی سیستم میکاهد.'
],
'fileupload' => [
'attachment' => 'فایل ضمیمه',
'help' => 'برای فایل ضمیمه عنوان و توضیح مختصری وارد نمایید.',
'title_label' => 'عنوان',
'description_label' => 'توضیحات'
],
'form' => [
'create_title' => ":name جدید",
'update_title' => "ویرایش :name",
'preview_title' => "پیش نمایش :name",
'create_success' => ':name با موفقیت ایجاد شد.',
'update_success' => ':name با موفقیت به روز رسانی شد.',
'delete_success' => ':name با موفقیت حذف شد.',
'missing_id' => "رکورد مشخصه (ID) برای فرم انتخاب نشده است.",
'missing_model' => 'مدلی برای فرن تعریف شده در کلاس :class مشخص نشده است.',
'missing_definition' => "فرم مورد نظر شامل فیلدی برای ':field' نمی باشد.",
'not_found' => 'فرمی با مشخصه :id یافت نشد.',
'create' => 'ایجاد',
'create_and_close' => 'ایجاد و خروج',
'creating' => 'در حال ایجاد...',
'save' => 'ذخیره',
'save_and_close' => 'ذخیره و خروج',
'saving' => 'در حال ذخیره...',
'delete' => 'حذف',
'deleting' => 'در حال حذف...',
'undefined_tab' => 'متفرقه',
'field_off' => 'خاموش',
'field_on' => 'روشن',
'add' => 'افزودن',
'apply' => 'اعمال',
'cancel' => 'انصراف',
'close' => 'خروج',
'ok' => 'تایید',
'or' => 'یا',
'confirm_tab_close' => 'در صورت بستن این پنجره موارد ذخیره نشده از بین خواهند رفت. آیا از حذف شدن این پنجره اطمینان دارید؟',
'behavior_not_ready' => 'فرم مور نظر مقدار دهی اولیه نشده است ، بررسی کنید که متد initForm() در کنترلر فرتخوانی شده باشد.',
'preview_no_files_message' => 'فایل ها ارسال نشدند',
'select' => 'انتخاب',
'select_all' => 'همه',
'select_none' => 'هیچ',
'select_placeholder' => 'لطفا انتخاب نمایید',
'insert_row' => 'افزودن سطر',
'delete_row' => 'حذف سطر',
'concurrency_file_changed_title' => 'فایل تغییر کرد',
'concurrency_file_changed_description' => 'فایلی که شما ویرایش کردید توسط کاربر دیگری تغییر یافته و ذخیره شده است. شما میتوانید فایل را مجددا بارگذاری نمایید و تغییراتی که اعمال کرده اید را از دست بدهید و یا تغییرات اعمال شده توسط آن کاربر را بین برده و فایل را بازنویسی نمایید.',
'reload' => 'بارگذاری مجدد',
],
'relation' => [
'missing_definition' => "در ارتباط مورد نظر فیلد ':field' وجود ندارد.",
'missing_model' => "مدلی برای ارتباط موجود در :class وجود ندارد.",
'invalid_action_single' => "این عمل در ارتباط یک تعرفه نمبتواند اعمال شود.",
'invalid_action_multi' => "این عمل در ارتباط چند طرفه نمیتواند اعمال شود.",
'help' => "بر روی یک گزینه کلیک کنید تا افزوده شود",
'related_data' => "اعلاعات :name مرتبط",
'add' => "افزودن",
'add_selected' => "افرودن انتخاب شده ها",
'add_a_new' => ":name جدید",
'cancel' => "انصراف",
'add_name' => "افزودن :name",
'create' => "ایجاد",
'create_name' => "ایجاد :name",
'update' => "بروز رسانی",
'update_name' => "بروز رسانی :name",
'remove' => "حذف",
'remove_name' => "حذف :name",
'delete' => "حذف",
'delete_name' => "حذف :name",
'delete_confirm' => "آیا اطمینان دارید؟",
],
'model' => [
'name' => "مدل",
'not_found' => "مدل ':class' با مشخصه ی :id یافت نشد",
'missing_id' => "مشخصه ای برای مودل مورد نظر یافت نشد.",
'missing_relation' => "مدل ':class' شامل تعریفی از ':relation'.",
'invalid_class' => "مدل :model استفاده شده در :class معتبر نمی باشد، این مدل باید از کلاس \Model ارث برده باشد.",
'mass_assignment_failed' => "Mass assignment failed for Model attribute ':attribute'.",
],
'warnings' => [
'tips' => 'راهنمایی پیکر بندی سیستم',
'tips_description' => 'مشکلاتی در پیکربندی سیستم وجود دارد، شما باید تنظیمات زیر را بررسی نمایید.',
'permissions' => 'پوشه :name یا یکی از زیر پوشه های آن برای PHP قابل نوشتن نیستند. لطفا تنظیمات این پوشه را تعییر دهید.',
'extension' => 'افزونه PHP با نام :name نصب نشده است. لطفن این افزونه را نصب کرده و فعال نمایید.'
],
'editor' => [
'menu_label' => 'تنظیمات ویرایشگر کد',
'menu_description' => 'سفارشی سازی ویرایشگر کد، مانند اندازه فونت و رنگ بندی آن.',
'font_size' => 'اندازه فونت',
'tab_size' => 'اندازه کاراکتر TAB',
'use_hard_tabs' => 'فاصله گذاری با استفاده از TAB',
'code_folding' => 'بلاک بندی کدها',
'word_wrap' => 'چیدمان کلمات',
'highlight_active_line' => 'مشخص نودن خط فعال',
'show_invisibles' => 'نمایش کاراکتر های مخفی',
'show_gutter' => 'نمایش نشانگر',
'theme' => 'رنگ بندی',
],
'tooltips' => [
'preview_website' => 'پیش نماسش وب سایت'
],
'mysettings' => [
'menu_label' => 'تنظیمات من',
'menu_description' => 'تنظیمات مربوط به حساب کاربری شما',
],
'myaccount' => [
'menu_label' => 'حساب کاربری من',
'menu_description' => 'به روز رسانی اطلاعات حساب کار بری شما مانند نام و کلمه عبور و ... .',
'menu_keywords' => 'ورود امن'
],
'backend_preferences' => [
'menu_label' => 'تنظیمات مدیریت',
'menu_description' => 'تنظیمات مربوط به زبان مربوط به قسمت مدیریت.',
'locale' => 'زبان',
'locale_comment' => 'زبان مورد نظر خود را انتخاب نمایید.',
],
'access_log' => [
'hint' => 'این لیست نشاندهنده ورود کاربران مدیر به سیستم می باشد. موارد برای مدت :days روز نگهداری می شوند.',
'menu_label' => 'ثبت دسترسی ها',
'menu_description' => 'نمایش لیست ورود موفقیت آمیز کاربران مدیر.',
'created_at' => 'زمان و تاریخ',
'login' => 'ورود',
'ip_address' => 'آدرس آی پی',
'first_name' => 'نام',
'last_name' => 'نام خوانوادگی',
'email' => 'پست الکترونیکی',
],
'filter' => [
'all' => 'همه'
],
'layout' => [
'direction' => 'rtl'
]
'field' => [
'invalid_type' => 'نوع فیلد :type نا معتبر می باشد.',
'options_method_not_exists' => 'کلاس مدل :model باید شامل متد :method() باشد و گزینه های مورد نیاز ":field" را بازگرداند.',
],
'widget' => [
'not_registered' => "کلاس مربوط به ابزارک ':name' به سیستم معرفی نشده است",
'not_bound' => "ابزارکی تعریف شده در کلاس با نام ':name' به هیچ کنترلری ارتباط داده نشده است",
],
'page' => [
'untitled' => "بدون عنوان",
'access_denied' => [
'label' => "شما مجوز دسترسی ندارید",
'help' => "شما مجوز لازم براس دسترسی به این صفحه را ندارید.",
'cms_link' => "بازگشت به مدیریت",
],
],
'partial' => [
'not_found' => "بخشی با نام ':name' یافت نشد.",
],
'account' => [
'sign_out' => 'خروج',
'login' => 'ورود',
'reset' => 'تنظیم مجدد',
'restore' => 'بازگرداندن',
'login_placeholder' => 'ورود',
'password_placeholder' => 'کلمه عبور',
'forgot_password' => "کلمه عبور خود را فراموش کرده اید؟",
'enter_email' => "پست الکترونیکی خود را وارد نمایید",
'enter_login' => "نام کاربری خود را وارد نمایید",
'email_placeholder' => "پست الکترونیکی",
'enter_new_password' => "کلمه عبور جدید را وارد نمایید",
'password_reset' => "بازگرداندن کلمه عبور",
'restore_success' => "یک نامه به پست الکترونیکی شما جهت شروع عملیات بارگرداندن کلمه عبور ارسال شد.",
'restore_error' => "کاربری با نام کاریری ':login' یافت نشد.",
'reset_success' => "کلمه عبور شما بارگردانی شد و شما هم اکنون میتوانید وارد سیستم شوید.",
'reset_error' => "اطلاعات رمز عبور نا معتبر است , لطفا مجددا تلاش نمایید!",
'reset_fail' => "عدم توانایی در بازگرداندن کلمه عبور شما!",
'apply' => 'اعمال کردن',
'cancel' => 'انصراف',
'delete' => 'حذف',
'ok' => 'تایید',
],
'dashboard' => [
'menu_label' => 'میز کار',
'widget_label' => 'ابزارک',
'widget_width' => 'عرض',
'full_width' => 'عرض کامل',
'add_widget' => 'افزودن ابزارک',
'widget_inspector_title' => 'تنظیمات ابزارک',
'widget_inspector_description' => 'پیکر بندی ابزارک گزارشگیری',
'widget_columns_label' => 'عرض :columns',
'widget_columns_description' => 'عرض ابزارک باید عددی مابین 1 تا 10 باشد.',
'widget_columns_error' => 'لطفا عرض ابزارک را عددی مابین 1 تا 10 وارد نمایید.',
'columns' => '{1} ستون|[2,Inf] ستون ها',
'widget_new_row_label' => 'تحمیل سطر جدید',
'widget_new_row_description' => 'افزودن ابزارک در سطر جدید.',
'widget_title_label' => 'عنوان ابزارک',
'widget_title_error' => 'گزینه "عنوان ابزارک" حتما باید وارد شود.',
'status' => [
'widget_title_default' => 'وضعیت سیستم',
'online' => 'online',
'update_available' => '{0} به روز رسانی موجود است!|{1} به روز رسانی موجود است!|[2,Inf] به روز رسانی موجود است!',
]
],
'user' => [
'name' => 'مدیریت',
'menu_label' => 'مدیران',
'menu_description' => 'مدیریت کاربران , گروه ها و دسترسی های مدیران.',
'list_title' => 'مدیریت مدیران',
'new' => 'مدیر جدید',
'login' => "ورود",
'first_name' => "نام",
'last_name' => "نام خانوادگی",
'full_name' => "نام کامل",
'email' => "پست الکترونیکی",
'groups' => "گروه ها",
'groups_comment' => "مختص گروهی که این شخص به آن تعلق دارد.",
'avatar' => "نمایه",
'password' => "کلمه عبور",
'password_confirmation' => "تکرار کلمه عبور",
'superuser' => "کاربر ممتاز",
'superuser_comment' => "اگر میخواهید این شخص به تمام قسمت ها دسترسی داشته باشد این گزینه را فعال نمایید.",
'send_invite' => 'دعوت نامه توسط پست الکترونیکی ارسال شود',
'send_invite_comment' => 'جهت ارسال دعوت نامه به پست الکترونیکی این شخص این گزینه را فعال نمایید',
'delete_confirm' => 'آیا از حذف این مدیر اطمینان دارید؟',
'return' => 'بازگشت به لیست مدیران',
'allow' => 'اجازه دسترسی',
'inherit' => 'ارث بری',
'deny' => 'عدم دسترسی',
'group' => [
'name' => 'گروه',
'name_field' => 'نام',
'menu_label' => 'گروه ها',
'list_title' => 'مدیریت گروه ها',
'new' => 'گروه مدیریت جدید',
'delete_confirm' => 'آیا از حذف این گروه از مدیران اطمینان دارید?',
'return' => 'بازگشت به لیست گروه ها',
],
'preferences' => [
'not_authenticated' => 'هیچ کاربر ثبت شده ای جهت بارگذاری یا ذخیره تنظیمات وجود ندارد.'
]
],
'list' => [
'default_title' => 'لیست',
'search_prompt' => 'جستجو...',
'no_records' => 'چیزی یافت نشد.',
'missing_model' => 'هیچ مدلی برای لیست استفاده شده در کلاس :class تعریف نشده است.',
'missing_column' => 'ستونی برای :columns تعریف نشده است.',
'missing_columns' => 'ستونی برای لیست عریف شده در :class موجود نیست.',
'missing_definition' => "در لیست تعریف شده ستونی برای ':field' موجود نیست.",
'behavior_not_ready' => 'لسیت مقدار دهی اولیه شده است ، لطفا بررسی نمایید که متد makeLists() در کنترلر خود فراخوانی کرده باشید.',
'invalid_column_datetime' => "ستون ':column' از نوع شی تاریخ نمی باشد ، لطفا بررسی نمایید که این ستون در مدل از نوع تاریخ تعریف شده باشد.",
'pagination' => 'نمایش :from تا :to از :total مورد',
'prev_page' => 'صفحه قبل',
'next_page' => 'صفحه بعد',
'loading' => 'در حال بارگذاری...',
'setup_title' => 'راه اندازی لیست',
'setup_help' => 'ستون هایی را که میخواهید مشاهده نمایید را انتخاب نمایید. میتوانید محل قرار گیری ستونها را با جابجا نمودن آنها به .',
'records_per_page' => 'مورد در هر صفحه',
'records_per_page_help' => 'تعداد موارد نمایش داده شده در هر صفحه را انتخاب نمایید. لطفا توجه نمایید نمایش تعداد زیادی از موارد در هر صفحه از کارایی سیستم میکاهد.'
],
'fileupload' => [
'attachment' => 'فایل ضمیمه',
'help' => 'برای فایل ضمیمه عنوان و توضیح مختصری وارد نمایید.',
'title_label' => 'عنوان',
'description_label' => 'توضیحات'
],
'form' => [
'create_title' => ":name جدید",
'update_title' => "ویرایش :name",
'preview_title' => "پیش نمایش :name",
'create_success' => ':name با موفقیت ایجاد شد.',
'update_success' => ':name با موفقیت به روز رسانی شد.',
'delete_success' => ':name با موفقیت حذف شد.',
'missing_id' => "رکورد مشخصه (ID) برای فرم انتخاب نشده است.",
'missing_model' => 'مدلی برای فرن تعریف شده در کلاس :class مشخص نشده است.',
'missing_definition' => "فرم مورد نظر شامل فیلدی برای ':field' نمی باشد.",
'not_found' => 'فرمی با مشخصه :id یافت نشد.',
'create' => 'ایجاد',
'create_and_close' => 'ایجاد و خروج',
'creating' => 'در حال ایجاد...',
'save' => 'ذخیره',
'save_and_close' => 'ذخیره و خروج',
'saving' => 'در حال ذخیره...',
'delete' => 'حذف',
'deleting' => 'در حال حذف...',
'undefined_tab' => 'متفرقه',
'field_off' => 'خاموش',
'field_on' => 'روشن',
'add' => 'افزودن',
'apply' => 'اعمال',
'cancel' => 'انصراف',
'close' => 'خروج',
'ok' => 'تایید',
'or' => 'یا',
'confirm_tab_close' => 'در صورت بستن این پنجره موارد ذخیره نشده از بین خواهند رفت. آیا از حذف شدن این پنجره اطمینان دارید؟',
'behavior_not_ready' => 'فرم مور نظر مقدار دهی اولیه نشده است ، بررسی کنید که متد initForm() در کنترلر فرتخوانی شده باشد.',
'preview_no_files_message' => 'فایل ها ارسال نشدند',
'select' => 'انتخاب',
'select_all' => 'همه',
'select_none' => 'هیچ',
'select_placeholder' => 'لطفا انتخاب نمایید',
'insert_row' => 'افزودن سطر',
'delete_row' => 'حذف سطر',
'concurrency-file-changed-title' => 'فایل تغییر کرد',
'concurrency-file-changed-description' => 'فایلی که شما ویرایش کردید توسط کاربر دیگری تغییر یافته و ذخیره شده است. شما میتوانید فایل را مجددا بارگذاری نمایید و تغییراتی که اعمال کرده اید را از دست بدهید و یا تغییرات اعمال شده توسط آن کاربر را بین برده و فایل را بازنویسی نمایید.',
'reload' => 'بارگذاری مجدد',
],
'relation' => [
'missing_definition' => "در ارتباط مورد نظر فیلد ':field' وجود ندارد.",
'missing_model' => "مدلی برای ارتباط موجود در :class وجود ندارد.",
'invalid_action_single' => "این عمل در ارتباط یک تعرفه نمبتواند اعمال شود.",
'invalid_action_multi' => "این عمل در ارتباط چند طرفه نمیتواند اعمال شود.",
'help' => "بر روی یک گزینه کلیک کنید تا افزوده شود",
'related_data' => "اعلاعات :name مرتبط",
'add' => "افزودن",
'add_selected' => "افرودن انتخاب شده ها",
'add_a_new' => ":name جدید",
'cancel' => "انصراف",
'add_name' => "افزودن :name",
'create' => "ایجاد",
'create_name' => "ایجاد :name",
'update' => "بروز رسانی",
'update_name' => "بروز رسانی :name",
'remove' => "حذف",
'remove_name' => "حذف :name",
'delete' => "حذف",
'delete_name' => "حذف :name",
'delete_confirm' => "آیا اطمینان دارید؟",
],
'model' => [
'name' => "مدل",
'not_found' => "مدل ':class' با مشخصه ی :id یافت نشد",
'missing_id' => "مشخصه ای برای مودل مورد نظر یافت نشد.",
'missing_relation' => "مدل ':class' شامل تعریفی از ':relation'.",
'invalid_class' => "مدل :model استفاده شده در :class معتبر نمی باشد، این مدل باید از کلاس \Model ارث برده باشد.",
'mass_assignment_failed' => "Mass assignment failed for Model attribute ':attribute'.",
],
'warnings' => [
'tips' => 'راهنمایی پیکر بندی سیستم',
'tips_description' => 'مشکلاتی در پیکربندی سیستم وجود دارد، شما باید تنظیمات زیر را بررسی نمایید.',
'permissions' => 'پوشه :name یا یکی از زیر پوشه های آن برای PHP قابل نوشتن نیستند. لطفا تنظیمات این پوشه را تعییر دهید.',
'extension' => 'افزونه PHP با نام :name نصب نشده است. لطفن این افزونه را نصب کرده و فعال نمایید.'
],
'editor' => [
'menu_label' => 'تنظیمات ویرایشگر کد',
'menu_description' => 'سفارشی سازی ویرایشگر کد، مانند اندازه فونت و رنگ بندی آن.',
'font_size' => 'اندازه فونت',
'tab_size' => 'اندازه کاراکتر TAB',
'use_hard_tabs' => 'فاصله گذاری با استفاده از TAB',
'code_folding' => 'بلاک بندی کدها',
'word_wrap' => 'چیدمان کلمات',
'highlight_active_line' => 'مشخص نودن خط فعال',
'show_invisibles' => 'نمایش کاراکتر های مخفی',
'show_gutter' => 'نمایش نشانگر',
'theme' => 'رنگ بندی',
],
'tooltips' => [
'preview_website' => 'پیش نماسش وب سایت'
],
'mysettings' => [
'menu_label' => 'تنظیمات من',
'menu_description' => 'تنظیمات مربوط به حساب کاربری شما',
],
'myaccount' => [
'menu_label' => 'حساب کاربری من',
'menu_description' => 'به روز رسانی اطلاعات حساب کار بری شما مانند نام و کلمه عبور و ... .',
'menu_keywords' => 'ورود امن'
],
'backend_preferences' => [
'menu_label' => 'تنظیمات مدیریت',
'menu_description' => 'تنظیمات مربوط به زبان مربوط به قسمت مدیریت.',
'locale' => 'زبان',
'locale_comment' => 'زبان مورد نظر خود را انتخاب نمایید.',
],
'access_log' => [
'hint' => 'این لیست نشاندهنده ورود کاربران مدیر به سیستم می باشد. موارد برای مدت :days روز نگهداری می شوند.',
'menu_label' => 'ثبت دسترسی ها',
'menu_description' => 'نمایش لیست ورود موفقیت آمیز کاربران مدیر.',
'created_at' => 'زمان و تاریخ',
'login' => 'ورود',
'ip_address' => 'آدرس آی پی',
'first_name' => 'نام',
'last_name' => 'نام خوانوادگی',
'email' => 'پست الکترونیکی',
],
'filter' => [
'all' => 'همه'
],
'layout' => [
'direction' => 'rtl'
]
];

View File

@ -37,5 +37,4 @@ class AccessLog extends Model
return $record;
}
}

View File

@ -65,8 +65,9 @@ class BrandSettings extends Model
public static function getLogo()
{
$settings = self::instance();
if (!$settings->logo)
if (!$settings->logo) {
return null;
}
return $settings->logo->getPath();
}
@ -83,10 +84,11 @@ class BrandSettings extends Model
'secondary-color-dark' => self::get('secondary_color_dark', self::SECONDARY_DARK),
]);
$parser->parse(File::get(PATH_BASE.'/modules/backend/models/brandsettings/custom.less').self::get('custom_css'));
$parser->parse(
File::get(PATH_BASE.'/modules/backend/models/brandsettings/custom.less').self::get('custom_css')
);
$css = $parser->getCss();
return $css;
}
}

View File

@ -66,8 +66,9 @@ class User extends UserBase
// return parent::getPersistCode();
// Option B:
if (!$this->persist_code)
if (!$this->persist_code) {
return parent::getPersistCode();
}
return $this->persist_code;
}
@ -77,18 +78,23 @@ class User extends UserBase
*/
public function getAvatarThumb($size = 25, $default = null)
{
if ($this->avatar)
if ($this->avatar) {
return $this->avatar->getThumb($size, $size);
else
return '//www.gravatar.com/avatar/' . md5(strtolower(trim($this->email))) . '?s='.$size.'&d='.urlencode($default);
} else {
return '//www.gravatar.com/avatar/'.
md5(strtolower(trim($this->email))) .
'?s='. $size .
'&d='. urlencode($default);
}
}
public function afterCreate()
{
$this->restorePurgedValues();
if ($this->send_invite)
if ($this->send_invite) {
$this->sendInvitation();
}
}
public function sendInvitation()
@ -100,10 +106,8 @@ class User extends UserBase
'link' => Backend::url('backend'),
];
Mail::send('backend::mail.invite', $data, function($message)
{
Mail::send('backend::mail.invite', $data, function ($message) {
$message->to($this->email, $this->full_name);
});
}
}

View File

@ -31,8 +31,9 @@ class UserPreferences extends PreferencesBase
public function resolveUser($user)
{
$user = BackendAuth::getUser();
if (!$user)
if (!$user) {
throw new SystemException(trans('backend::lang.user.preferences.not_authenticated'));
}
return $user;
}

View File

@ -3,12 +3,12 @@
/*
* Register Backend routes before all user routes.
*/
App::before(function($request) {
App::before(function ($request) {
/*
* Other pages
*/
Route::group(['prefix' => Config::get('cms.backendUri', 'backend')], function() {
Route::group(['prefix' => Config::get('cms.backendUri', 'backend')], function () {
Route::any('{slug}', 'Backend\Classes\BackendController@run')->where('slug', '(.*)?');
});

View File

@ -54,5 +54,4 @@ class Standard extends Skin
{
return [$this->skinPath.'/layouts'];
}
}

View File

@ -26,12 +26,14 @@ trait CollapsableWidget
protected function getGroupStatuses()
{
if ($this->groupStatusCache !== false)
if ($this->groupStatusCache !== false) {
return $this->groupStatusCache;
}
$groups = $this->getSession('groups', []);
if (!is_array($groups))
if (!is_array($groups)) {
return $this->groupStatusCache = [];
}
return $this->groupStatusCache = $groups;
}
@ -47,8 +49,9 @@ trait CollapsableWidget
protected function getGroupStatus($group)
{
$statuses = $this->getGroupStatuses();
if (array_key_exists($group, $statuses))
if (array_key_exists($group, $statuses)) {
return $statuses[$group];
}
return true;
}

View File

@ -17,24 +17,28 @@ trait InspectableContainer
public function onInspectableGetOptions()
{
$property = trim(Request::input('inspectorProperty'));
if (!$property)
if (!$property) {
throw new ApplicationException('The property name is not specified.');
}
$className = trim(Request::input('inspectorClassName'));
if (!$className)
if (!$className) {
throw new ApplicationException('The inspectable class name is not specified.');
}
$traitFound = in_array('System\Traits\PropertyContainer', class_uses_recursive($className));
if (!$traitFound)
if (!$traitFound) {
throw new ApplicationException('The options cannot be loaded for the specified class.');
}
$obj = new $className(null);
$methodName = 'get'.ucfirst($property).'Options';
if (method_exists($obj, $methodName))
if (method_exists($obj, $methodName)) {
$options = $obj->$methodName();
else
} else {
$options = $obj->getPropertyOptions($property);
}
/*
* Convert to array to retain the sort order in JavaScript

View File

@ -33,11 +33,13 @@ trait SearchableWidget
{
foreach ($words as $word) {
$word = trim($word);
if (!strlen($word))
if (!strlen($word)) {
continue;
}
if (Str::contains(Str::lower($text), $word))
if (Str::contains(Str::lower($text), $word)) {
return true;
}
}
return false;

View File

@ -28,12 +28,14 @@ trait SelectableWidget
protected function getSelectedItems()
{
if ($this->selectedItemsCache !== false)
if ($this->selectedItemsCache !== false) {
return $this->selectedItemsCache;
}
$items = $this->getSession('selected', []);
if (!is_array($items))
if (!is_array($items)) {
return $this->selectedItemsCache = [];
}
return $this->selectedItemsCache = $items;
}
@ -54,8 +56,9 @@ trait SelectableWidget
protected function isItemSelected($itemId)
{
$selectedItems = $this->getSelectedItems();
if (!is_array($selectedItems) || !isset($selectedItems[$itemId]))
if (!is_array($selectedItems) || !isset($selectedItems[$itemId])) {
return false;
}
return $selectedItems[$itemId];
}

View File

@ -102,8 +102,9 @@ class Filter extends WidgetBase
{
$this->defineFilterScopes();
if (!$scope = post('scopeName'))
if (!$scope = post('scopeName')) {
return;
}
$scope = $this->getScope($scope);
@ -124,8 +125,9 @@ class Filter extends WidgetBase
*/
$params = func_get_args();
$result = $this->fireEvent('filter.update', [$params]);
if ($result && is_array($result))
if ($result && is_array($result)) {
return Util::arrayMerge($result);
}
}
/**
@ -137,8 +139,9 @@ class Filter extends WidgetBase
$this->defineFilterScopes();
$searchQuery = post('search');
if (!$scopeName = post('scopeName'))
if (!$scopeName = post('scopeName')) {
return;
}
$scope = $this->getScope($scopeName);
$activeKeys = $scope->value ? array_keys($scope->value) : [];
@ -188,8 +191,9 @@ class Filter extends WidgetBase
{
$active = [];
foreach ($availableOptions as $id => $option) {
if (!in_array($id, $activeKeys))
if (!in_array($id, $activeKeys)) {
continue;
}
$active[$id] = $option;
unset($availableOptions[$id]);
@ -204,8 +208,9 @@ class Filter extends WidgetBase
protected function getOptionsFromModel($scope, $searchQuery = null)
{
$model = $this->scopeModels[$scope->scopeName];
if (!$searchQuery)
if (!$searchQuery) {
return $model->all();
}
$searchFields = [$model->getKeyName(), $this->getScopeNameColumn($scope)];
return $model->searchWhere($searchQuery, $searchFields)->get();
@ -216,8 +221,9 @@ class Filter extends WidgetBase
*/
protected function defineFilterScopes()
{
if ($this->scopesDefined)
if ($this->scopesDefined) {
return;
}
/*
* Extensibility
@ -228,8 +234,9 @@ class Filter extends WidgetBase
/*
* All scopes
*/
if (!isset($this->config->scopes) || !is_array($this->config->scopes))
if (!isset($this->config->scopes) || !is_array($this->config->scopes)) {
$this->config->scopes = [];
}
$this->addScopes($this->config->scopes);
@ -256,8 +263,9 @@ class Filter extends WidgetBase
*/
if ($scopeObj->context !== null) {
$context = (is_array($scopeObj->context)) ? $scopeObj->context : [$scopeObj->context];
if (!in_array($this->getContext(), $context))
if (!in_array($this->getContext(), $context)) {
continue;
}
}
/*
@ -318,11 +326,13 @@ class Filter extends WidgetBase
*/
public function applyScopeToQuery($scope, $query)
{
if (is_string($scope))
if (is_string($scope)) {
$scope = $this->getScope($scope);
}
if (!$scope->value)
if (!$scope->value) {
return;
}
$value = is_array($scope->value) ? array_keys($scope->value) : $scope->value;
@ -331,11 +341,10 @@ class Filter extends WidgetBase
*/
if ($scopeConditions = $scope->conditions) {
if (is_array($value)) {
$filtered = implode(',', array_build($value, function($key, $_value){
$filtered = implode(',', array_build($value, function ($key, $_value) {
return [$key, Db::getPdo()->quote($_value)];
}));
}
else {
} else {
$filtered = Db::getPdo()->quote($value);
}
@ -361,8 +370,9 @@ class Filter extends WidgetBase
*/
public function getScopeValue($scope, $default = null)
{
if (is_string($scope))
if (is_string($scope)) {
$scope = $this->getScope($scope);
}
$cacheKey = 'scope-'.$scope->scopeName;
return $this->getSession($cacheKey, $default);
@ -373,8 +383,9 @@ class Filter extends WidgetBase
*/
public function setScopeValue($scope, $value)
{
if (is_string($scope))
if (is_string($scope)) {
$scope = $this->getScope($scope);
}
$cacheKey = 'scope-'.$scope->scopeName;
$this->putSession($cacheKey, $value);
@ -398,8 +409,9 @@ class Filter extends WidgetBase
*/
public function getScope($scope)
{
if (!isset($this->allScopes[$scope]))
if (!isset($this->allScopes[$scope])) {
throw new ApplicationException('No definition for scope ' . $scope);
}
return $this->allScopes[$scope];
}
@ -411,8 +423,9 @@ class Filter extends WidgetBase
*/
public function getScopeNameColumn($scope)
{
if (is_string($scope))
if (is_string($scope)) {
$scope = $this->getScope($scope);
}
return $scope->nameFrom;
}
@ -451,14 +464,16 @@ class Filter extends WidgetBase
protected function optionsFromAjax($options)
{
$processed = [];
if (!is_array($options))
if (!is_array($options)) {
return $processed;
}
foreach ($options as $option) {
if (!$id = array_get($option, 'id')) continue;
if (!$id = array_get($option, 'id')) {
continue;
}
$processed[$id] = array_get($option, 'name');
}
return $processed;
}
}

View File

@ -140,9 +140,15 @@ class Form extends WidgetBase
*/
public function render($options = [])
{
if (isset($options['preview'])) $this->previewMode = $options['preview'];
if (!isset($options['useContainer'])) $options['useContainer'] = true;
if (!isset($options['section'])) $options['section'] = null;
if (isset($options['preview'])) {
$this->previewMode = $options['preview'];
}
if (!isset($options['useContainer'])) {
$options['useContainer'] = true;
}
if (!isset($options['section'])) {
$options['section'] = null;
}
$extraVars = [];
$targetPartial = 'form';
@ -153,10 +159,17 @@ class Form extends WidgetBase
if ($section = $options['section']) {
switch (strtolower($section)) {
case 'outside':
$sectionPartial = 'section_outside-fields';
break;
case 'primary':
$sectionPartial = 'section_primary-tabs';
break;
case 'secondary':
$sectionPartial = 'section_secondary-tabs';
break;
default:
case 'outside': $sectionPartial = 'section_outside-fields'; break;
case 'primary': $sectionPartial = 'section_primary-tabs'; break;
case 'secondary': $sectionPartial = 'section_secondary-tabs'; break;
break;
}
$targetPartial = $sectionPartial;
@ -180,13 +193,19 @@ class Form extends WidgetBase
public function renderField($field, $options = [])
{
if (is_string($field)) {
if (!isset($this->fields[$field]))
throw new ApplicationException(Lang::get('backend::lang.form.missing_definition', compact('field')));
if (!isset($this->fields[$field])) {
throw new ApplicationException(Lang::get(
'backend::lang.form.missing_definition',
compact('field')
));
}
$field = $this->fields[$field];
}
if (!isset($options['useContainer'])) $options['useContainer'] = true;
if (!isset($options['useContainer'])) {
$options['useContainer'] = true;
}
$targetPartial = $options['useContainer'] ? 'field-container' : 'field';
$this->prepareVars();
@ -209,8 +228,12 @@ class Form extends WidgetBase
{
$this->model = $this->getConfig('model');
if (!$this->model)
throw new ApplicationException(Lang::get('backend::lang.form.missing_model', ['class'=>get_class($this->controller)]));
if (!$this->model) {
throw new ApplicationException(Lang::get(
'backend::lang.form.missing_model',
['class'=>get_class($this->controller)]
));
}
$this->data = (object) $this->getConfig('data', $this->model);
@ -236,8 +259,9 @@ class Form extends WidgetBase
*/
public function setFormValues($data = null)
{
if ($data == null)
if ($data == null) {
$data = $this->getSaveData();
}
$this->model->fill($data);
$this->data = (object) array_merge((array) $this->data, (array) $data);
@ -260,9 +284,12 @@ class Form extends WidgetBase
/*
* Extensibility
*/
$eventResults = $this->fireEvent('form.beforeRefresh', [$saveData]) + Event::fire('backend.form.beforeRefresh', [$this, $saveData]);
foreach ($eventResults as $eventResult)
$eventResults = $this->fireEvent('form.beforeRefresh', [$saveData]) +
Event::fire('backend.form.beforeRefresh', [$this, $saveData]);
foreach ($eventResults as $eventResult) {
$saveData = $eventResult + $saveData;
}
/*
* Set the form variables and prepare the widget
@ -276,8 +303,9 @@ class Form extends WidgetBase
if (($updateFields = post('fields')) && is_array($updateFields)) {
foreach ($updateFields as $field) {
if (!isset($this->fields[$field]))
if (!isset($this->fields[$field])) {
continue;
}
$fieldObject = $this->fields[$field];
$result['#' . $fieldObject->getId('group')] = $this->makePartial('field', ['field' => $fieldObject]);
@ -287,15 +315,19 @@ class Form extends WidgetBase
/*
* Update the whole form
*/
if (empty($result))
if (empty($result)) {
$result = ['#'.$this->getId() => $this->makePartial('form')];
}
/*
* Extensibility
*/
$eventResults = $this->fireEvent('form.refresh', [$result]) + Event::fire('backend.form.refresh', [$this, $result]);
foreach ($eventResults as $eventResult)
$eventResults = $this->fireEvent('form.refresh', [$result]) +
Event::fire('backend.form.refresh', [$this, $result]);
foreach ($eventResults as $eventResult) {
$result = $eventResult + $result;
}
return $result;
}
@ -306,8 +338,9 @@ class Form extends WidgetBase
*/
protected function defineFormFields()
{
if ($this->fieldsDefined)
if ($this->fieldsDefined) {
return;
}
/*
* Extensibility
@ -318,24 +351,27 @@ class Form extends WidgetBase
/*
* Outside fields
*/
if (!isset($this->config->fields) || !is_array($this->config->fields))
if (!isset($this->config->fields) || !is_array($this->config->fields)) {
$this->config->fields = [];
}
$this->addFields($this->config->fields);
/*
* Primary Tabs + Fields
*/
if (!isset($this->config->tabs['fields']) || !is_array($this->config->tabs['fields']))
if (!isset($this->config->tabs['fields']) || !is_array($this->config->tabs['fields'])) {
$this->config->tabs['fields'] = [];
}
$this->addFields($this->config->tabs['fields'], 'primary');
/*
* Secondary Tabs + Fields
*/
if (!isset($this->config->secondaryTabs['fields']) || !is_array($this->config->secondaryTabs['fields']))
if (!isset($this->config->secondaryTabs['fields']) || !is_array($this->config->secondaryTabs['fields'])) {
$this->config->secondaryTabs['fields'] = [];
}
$this->addFields($this->config->secondaryTabs['fields'], 'secondary');
@ -350,18 +386,21 @@ class Form extends WidgetBase
*/
$this->processAutoSpan($this->outsideFields);
foreach ($this->primaryTabs as $fields)
foreach ($this->primaryTabs as $fields) {
$this->processAutoSpan($fields);
}
foreach ($this->secondaryTabs as $fields)
foreach ($this->secondaryTabs as $fields) {
$this->processAutoSpan($fields);
}
/*
* Bind all form widgets to controller
*/
foreach ($this->fields as $field) {
if ($field->type != 'widget')
if ($field->type != 'widget') {
continue;
}
$widget = $this->makeFormWidget($field);
$widget->bindToController();
@ -379,10 +418,11 @@ class Form extends WidgetBase
$prevSpan = null;
foreach ($fields as $field) {
if (strtolower($field->span) == 'auto') {
if ($prevSpan == 'left')
if ($prevSpan == 'left') {
$field->span = 'right';
else
} else {
$field->span = 'left';
}
}
$prevSpan = $field->span;
@ -397,12 +437,13 @@ class Form extends WidgetBase
foreach ($fields as $name => $config) {
$defaultTab = Lang::get('backend::lang.form.undefined_tab');
if (!is_array($config))
if (!is_array($config)) {
$tab = $defaultTab;
elseif (!isset($config['tab']))
} elseif (!isset($config['tab'])) {
$tab = $config['tab'] = $defaultTab;
else
} else {
$tab = $config['tab'];
}
$fieldObj = $this->makeFormField($name, $config);
@ -411,8 +452,9 @@ class Form extends WidgetBase
*/
if ($fieldObj->context !== null) {
$context = (is_array($fieldObj->context)) ? $fieldObj->context : [$fieldObj->context];
if (!in_array($this->getContext(), $context))
if (!in_array($this->getContext(), $context)) {
continue;
}
}
$this->fields[$name] = $fieldObj;
@ -428,7 +470,6 @@ class Form extends WidgetBase
$this->outsideFields[$name] = $fieldObj;
break;
}
}
}
@ -451,7 +492,9 @@ class Form extends WidgetBase
list($fieldName, $fieldContext) = $this->getFieldName($name);
$field = new FormField($fieldName, $label);
if ($fieldContext) $field->context = $fieldContext;
if ($fieldContext) {
$field->context = $fieldContext;
}
$field->arrayName = $this->arrayName;
$field->idPrefix = $this->getId();
@ -459,20 +502,22 @@ class Form extends WidgetBase
* Simple field type
*/
if (is_string($config)) {
if ($this->isFormWidget($config) !== false)
if ($this->isFormWidget($config) !== false) {
$field->displayAs('widget', ['widget' => $config]);
else
} else {
$field->displayAs($config);
}
}
/*
* Defined field type
*/
else {
} else {
$fieldType = isset($config['type']) ? $config['type'] : null;
if (!is_string($fieldType) && !is_null($fieldType))
throw new ApplicationException(Lang::get('backend::lang.field.invalid_type', ['type'=>gettype($fieldType)]));
if (!is_string($fieldType) && !is_null($fieldType)) {
throw new ApplicationException(Lang::get(
'backend::lang.field.invalid_type',
['type'=>gettype($fieldType)]
));
}
/*
* Widget with configuration
@ -493,8 +538,9 @@ class Form extends WidgetBase
/*
* Check model if field is required
*/
if (!$field->required && $this->model && method_exists($this->model, 'isAttributeRequired'))
if (!$field->required && $this->model && method_exists($this->model, 'isAttributeRequired')) {
$field->required = $this->model->isAttributeRequired($field->fieldName);
}
/*
* Get field options from model
@ -505,7 +551,7 @@ class Form extends WidgetBase
/*
* Defer the execution of option data collection
*/
$field->options(function() use ($field, $config) {
$field->options(function () use ($field, $config) {
$fieldOptions = (isset($config['options'])) ? $config['options'] : null;
$fieldOptions = $this->getOptionsFromModel($field, $fieldOptions);
return $fieldOptions;
@ -522,19 +568,23 @@ class Form extends WidgetBase
*/
protected function isFormWidget($fieldType)
{
if ($fieldType === null)
if ($fieldType === null) {
return false;
}
if (strpos($fieldType, '\\'))
if (strpos($fieldType, '\\')) {
return true;
}
$widgetClass = $this->widgetManager->resolveFormWidget($fieldType);
if (!class_exists($widgetClass))
if (!class_exists($widgetClass)) {
return false;
}
if (is_subclass_of($widgetClass, 'Backend\Classes\FormWidgetBase'))
if (is_subclass_of($widgetClass, 'Backend\Classes\FormWidgetBase')) {
return true;
}
return false;
}
@ -544,11 +594,13 @@ class Form extends WidgetBase
*/
protected function makeFormWidget($field)
{
if ($field->type != 'widget')
if ($field->type != 'widget') {
return null;
}
if (isset($this->formWidgets[$field->fieldName]))
if (isset($this->formWidgets[$field->fieldName])) {
return $this->formWidgets[$field->fieldName];
}
$widgetConfig = $this->makeConfig($field->config);
$widgetConfig->alias = $this->alias . studly_case(Str::evalHtmlId($field->fieldName));
@ -557,9 +609,10 @@ class Form extends WidgetBase
$widgetName = $widgetConfig->widget;
$widgetClass = $this->widgetManager->resolveFormWidget($widgetName);
if (!class_exists($widgetClass)) {
throw new ApplicationException(Lang::get('backend::lang.widget.not_registered', [
'name' => $widgetClass
]));
throw new ApplicationException(Lang::get(
'backend::lang.widget.not_registered',
['name' => $widgetClass]
));
}
$widget = new $widgetClass($this->controller, $this->model, $field, $widgetConfig);
@ -611,8 +664,9 @@ class Form extends WidgetBase
*/
public function getFieldName($field)
{
if (strpos($field, '@') === false)
if (strpos($field, '@') === false) {
return [$field, null];
}
return explode('@', $field);
}
@ -623,8 +677,12 @@ class Form extends WidgetBase
public function getFieldValue($field)
{
if (is_string($field)) {
if (!isset($this->fields[$field]))
throw new ApplicationException(Lang::get('backend::lang.form.missing_definition', compact('field')));
if (!isset($this->fields[$field])) {
throw new ApplicationException(Lang::get(
'backend::lang.form.missing_definition',
compact('field')
));
}
$field = $this->fields[$field];
}
@ -647,17 +705,20 @@ class Form extends WidgetBase
foreach ($keyParts as $key) {
if ($result instanceof Model && $result->hasRelation($key)) {
if ($key == $lastField)
if ($key == $lastField) {
$result = $result->getRelationValue($key) ?: $defaultValue;
else
} else {
$result = $result->{$key};
}
elseif (is_array($result)) {
if (!array_key_exists($key, $result)) return $defaultValue;
}
} elseif (is_array($result)) {
if (!array_key_exists($key, $result)) {
return $defaultValue;
}
$result = $result[$key];
}
else {
if (!isset($result->{$key})) return $defaultValue;
} else {
if (!isset($result->{$key})) {
return $defaultValue;
}
$result = $result->{$key};
}
@ -674,8 +735,9 @@ class Form extends WidgetBase
*/
public function getFieldDepends($field)
{
if (!$field->depends)
if (!$field->depends) {
return;
}
$depends = is_array($field->depends) ? $field->depends : [$field->depends];
$depends = htmlspecialchars(json_encode($depends), ENT_QUOTES, 'UTF-8');
@ -689,15 +751,17 @@ class Form extends WidgetBase
{
$data = ($this->arrayName) ? post($this->arrayName) : post();
if (!$data)
if (!$data) {
$data = [];
}
/*
* Number fields should be converted to integers
*/
foreach ($this->fields as $field) {
if ($field->type != 'number')
if ($field->type != 'number') {
continue;
}
/*
* Handle HTML array, eg: item[key][another]
@ -719,8 +783,9 @@ class Form extends WidgetBase
: null;
$data[$field] = $widget->getSaveData($widgetValue);
if ($data[$field] === FormWidgetBase::NO_SAVE_DATA)
if ($data[$field] === FormWidgetBase::NO_SAVE_DATA) {
unset($data[$field]);
}
}
/*
@ -728,8 +793,9 @@ class Form extends WidgetBase
*/
$remappedFields = [];
foreach ($this->fields as $field) {
if ($field->fieldName == $field->valueFrom)
if ($field->fieldName == $field->valueFrom) {
continue;
}
/*
* Get the value, remove it from the data collection
@ -773,21 +839,31 @@ class Form extends WidgetBase
*/
if (!is_array($fieldOptions) && !$fieldOptions) {
$methodName = 'get'.studly_case($field->fieldName).'Options';
if (!$this->methodExists($this->model, $methodName) && !$this->methodExists($this->model, 'getDropdownOptions'))
throw new ApplicationException(Lang::get('backend::lang.field.options_method_not_exists', ['model'=>get_class($this->model), 'method'=>$methodName, 'field'=>$field->fieldName]));
if (
!$this->methodExists($this->model, $methodName) &&
!$this->methodExists($this->model, 'getDropdownOptions')
) {
throw new ApplicationException(Lang::get(
'backend::lang.field.options_method_not_exists',
['model'=>get_class($this->model), 'method'=>$methodName, 'field'=>$field->fieldName]
));
}
if ($this->methodExists($this->model, $methodName))
if ($this->methodExists($this->model, $methodName)) {
$fieldOptions = $this->model->$methodName($field->value);
else
} else {
$fieldOptions = $this->model->getDropdownOptions($field->fieldName, $field->value);
}
}
/*
* Field options are an explicit method reference
*/
elseif (is_string($fieldOptions)) {
if (!$this->methodExists($this->model, $fieldOptions))
throw new ApplicationException(Lang::get('backend::lang.field.options_method_not_exists', ['model'=>get_class($this->model), 'method'=>$fieldOptions, 'field'=>$field->fieldName]));
} elseif (is_string($fieldOptions)) {
if (!$this->methodExists($this->model, $fieldOptions)) {
throw new ApplicationException(Lang::get(
'backend::lang.field.options_method_not_exists',
['model'=>get_class($this->model), 'method'=>$fieldOptions, 'field'=>$field->fieldName]
));
}
$fieldOptions = $this->model->$fieldOptions($field->value, $field->fieldName);
}
@ -800,11 +876,13 @@ class Form extends WidgetBase
*/
public function getSessionKey()
{
if ($this->sessionKey)
if ($this->sessionKey) {
return $this->sessionKey;
}
if (post('_session_key'))
if (post('_session_key')) {
return $this->sessionKey = post('_session_key');
}
return $this->sessionKey = FormHelper::getSessionKey();
}
@ -825,10 +903,10 @@ class Form extends WidgetBase
*/
protected function methodExists($object, $method)
{
if (method_exists($object, 'methodExists'))
if (method_exists($object, 'methodExists')) {
return $object->methodExists($method);
}
return method_exists($object, $method);
}
}

View File

@ -117,8 +117,9 @@ class Grid extends WidgetBase
protected function makeToolbarWidget()
{
if ($this->disableToolbar)
if ($this->disableToolbar) {
return;
}
$defaultConfig = [
'buttons' => $this->getViewPath('_toolbar.htm'),
@ -148,8 +149,9 @@ class Grid extends WidgetBase
public function onDataChanged()
{
if (!$this->monitorChanges)
if (!$this->monitorChanges) {
return;
}
/*
* Changes array, each array item will contain:
@ -168,16 +170,19 @@ class Grid extends WidgetBase
public function onDataSource()
{
if (!$this->useDataSource)
if (!$this->useDataSource) {
return;
}
$result = [];
if ($_result = $this->fireEvent('grid.dataSource', [], true))
if ($_result = $this->fireEvent('grid.dataSource', [], true)) {
$result = $_result;
}
if (!is_array($result))
if (!is_array($result)) {
$result = [];
}
return ['result' => $result];
}
@ -188,8 +193,9 @@ class Grid extends WidgetBase
protected function getColumnHeaders()
{
if (!$this->showHeader)
if (!$this->showHeader) {
return false;
}
$headers = [];
foreach ($this->columns as $key => $column) {
@ -214,8 +220,9 @@ class Grid extends WidgetBase
$item = [];
$item['data'] = $key;
if (isset($column['readOnly']))
if (isset($column['readOnly'])) {
$item['readOnly'] = $column['readOnly'];
}
$item = $this->evalColumnType($column, $item);
$definitions[] = $item;
@ -225,8 +232,9 @@ class Grid extends WidgetBase
protected function evalColumnType($column, $item)
{
if (!isset($column['type']))
if (!isset($column['type'])) {
return $item;
}
switch ($column['type']) {
case 'number':
@ -244,8 +252,12 @@ class Grid extends WidgetBase
case 'autocomplete':
$item['type'] = 'autocomplete';
if (isset($column['options'])) $item['source'] = $column['options'];
if (isset($column['strict'])) $item['strict'] = $column['strict'];
if (isset($column['options'])) {
$item['source'] = $column['options'];
}
if (isset($column['strict'])) {
$item['strict'] = $column['strict'];
}
break;
}
@ -266,5 +278,4 @@ class Grid extends WidgetBase
$this->addJs('vendor/handsontable/jquery.handsontable.js', 'core');
$this->addJs('js/datagrid.js', 'core');
}
}

View File

@ -152,7 +152,10 @@ class Lists extends WidgetBase
*/
$this->recordUrl = $this->getConfig('recordUrl', $this->recordUrl);
$this->recordOnClick = $this->getConfig('recordOnClick', $this->recordOnClick);
$this->recordsPerPage = $this->getSession('per_page', $this->getConfig('recordsPerPage', $this->recordsPerPage));
$this->recordsPerPage = $this->getSession(
'per_page',
$this->getConfig('recordsPerPage', $this->recordsPerPage)
);
$this->noRecordsMessage = $this->getConfig('noRecordsMessage', $this->noRecordsMessage);
$this->defaultSort = $this->getConfig('defaultSort', $this->defaultSort);
$this->showSorting = $this->getConfig('showSorting', $this->showSorting);
@ -206,8 +209,7 @@ class Lists extends WidgetBase
$this->vars['pageLast'] = $this->records->getLastPage();
$this->vars['pageFrom'] = $this->records->getFrom();
$this->vars['pageTo'] = $this->records->getTo();
}
else {
} else {
$this->vars['recordTotal'] = $this->records->count();
$this->vars['pageCurrent'] = 1;
}
@ -239,11 +241,19 @@ class Lists extends WidgetBase
{
$this->model = $this->getConfig('model');
if (!$this->model)
throw new ApplicationException(Lang::get('backend::lang.list.missing_model', ['class'=>get_class($this->controller)]));
if (!$this->model) {
throw new ApplicationException(Lang::get(
'backend::lang.list.missing_model',
['class'=>get_class($this->controller)]
));
}
if (!$this->model instanceof Model)
throw new ApplicationException(Lang::get('backend::lang.model.invalid_class', ['model'=>get_class($this->model), 'class'=>get_class($this->controller)]));
if (!$this->model instanceof Model) {
throw new ApplicationException(Lang::get(
'backend::lang.model.invalid_class',
['model'=>get_class($this->model), 'class'=>get_class($this->controller)]
));
}
return $this->model;
}
@ -295,11 +305,10 @@ class Lists extends WidgetBase
: $table . '.' . $column->valueFrom;
$relationSearchable[$column->relation][] = $columnName;
}
/*
* Primary
*/
else {
} else {
$columnName = isset($column->sqlSelect)
? DbDongle::raw($this->parseTableName($column->sqlSelect, $primaryTable))
: $primaryTable . '.' . $column->columnName;
@ -314,11 +323,13 @@ class Lists extends WidgetBase
*/
foreach ($this->getVisibleListColumns() as $column) {
if (!$this->isColumnRelated($column) || (!isset($column->sqlSelect) && !isset($column->valueFrom)))
if (!$this->isColumnRelated($column) || (!isset($column->sqlSelect) && !isset($column->valueFrom))) {
continue;
}
if (isset($column->valueFrom))
if (isset($column->valueFrom)) {
$withs[] = $column->relation;
}
$joins[] = $column->relation;
}
@ -335,7 +346,7 @@ class Lists extends WidgetBase
$columnsToSearch = array_get($relationSearchable, $join, []);
if (count($columnsToSearch) > 0) {
$query->whereHas($join, function($_query) use ($columnsToSearch) {
$query->whereHas($join, function ($_query) use ($columnsToSearch) {
$_query->searchWhere($this->searchTerm, $columnsToSearch);
});
}
@ -353,8 +364,9 @@ class Lists extends WidgetBase
* Custom select queries
*/
foreach ($this->getVisibleListColumns() as $column) {
if (!isset($column->sqlSelect))
if (!isset($column->sqlSelect)) {
continue;
}
$alias = Db::getQueryGrammar()->wrap($column->columnName);
@ -379,11 +391,10 @@ class Lists extends WidgetBase
$joinSql = $countQuery->select($joinSql)->toSql();
$selects[] = Db::raw("(".$joinSql.") as ".$alias);
}
/*
* Primary column
*/
else {
} else {
$sqlSelect = $this->parseTableName($column->sqlSelect, $primaryTable);
$selects[] = DbDongle::raw($sqlSelect . ' as '. $alias);
}
@ -393,7 +404,7 @@ class Lists extends WidgetBase
* Apply a supplied search term for primary columns
*/
if (count($primarySearchable) > 0) {
$query->orWhere(function($innerQuery) use ($primarySearchable) {
$query->orWhere(function ($innerQuery) use ($primarySearchable) {
$innerQuery->searchWhere($this->searchTerm, $primarySearchable);
});
}
@ -402,8 +413,9 @@ class Lists extends WidgetBase
* Apply sorting
*/
if ($sortColumn = $this->getSortColumn()) {
if (($column = array_get($this->columns, $sortColumn)) && $column->sqlSelect)
if (($column = array_get($this->columns, $sortColumn)) && $column->sqlSelect) {
$sortColumn = $column->sqlSelect;
}
$query->orderBy($sortColumn, $this->sortDirection);
}
@ -437,12 +449,12 @@ class Lists extends WidgetBase
{
if ($this->showTree) {
$records = $this->model->getAllRoot();
}
else {
} else {
$model = $this->prepareModel();
$records = ($this->showPagination)
? $model->paginate($this->recordsPerPage)
: $model->get();
}
return $this->records = $records;
@ -455,11 +467,13 @@ class Lists extends WidgetBase
*/
public function getRecordUrl($record)
{
if (isset($this->recordOnClick))
if (isset($this->recordOnClick)) {
return 'javascript:;';
}
if (!isset($this->recordUrl))
if (!isset($this->recordUrl)) {
return null;
}
$columns = array_keys($record->getAttributes());
$url = RouterHelper::parseValues($record, $columns, $this->recordUrl);
@ -473,8 +487,9 @@ class Lists extends WidgetBase
*/
public function getRecordOnClick($record)
{
if (!isset($this->recordOnClick))
if (!isset($this->recordOnClick)) {
return null;
}
$columns = array_keys($record->getAttributes());
$recordOnClick = RouterHelper::parseValues($record, $columns, $this->recordOnClick);
@ -511,27 +526,32 @@ class Lists extends WidgetBase
/*
* Supplied column list
*/
if ($this->columnOverride === null)
if ($this->columnOverride === null) {
$this->columnOverride = $this->getSession('visible', null);
}
if ($this->columnOverride && is_array($this->columnOverride)) {
$invalidColumns = array_diff($this->columnOverride, array_keys($definitions));
if (!count($definitions))
throw new ApplicationException(Lang::get('backend::lang.list.missing_column', ['columns'=>implode(',', $invalidColumns)]));
if (!count($definitions)) {
throw new ApplicationException(Lang::get(
'backend::lang.list.missing_column',
['columns'=>implode(',', $invalidColumns)]
));
}
foreach ($this->columnOverride as $columnName) {
$definitions[$columnName]->invisible = false;
$columns[$columnName] = $definitions[$columnName];
}
}
/*
* Use default column list
*/
else {
} else {
foreach ($definitions as $columnName => $column) {
if ($column->invisible)
if ($column->invisible) {
continue;
}
$columns[$columnName] = $definitions[$columnName];
}
@ -545,8 +565,12 @@ class Lists extends WidgetBase
*/
protected function defineListColumns()
{
if (!isset($this->config->columns) || !is_array($this->config->columns) || !count($this->config->columns))
throw new ApplicationException(Lang::get('backend::lang.list.missing_columns', ['class'=>get_class($this->controller)]));
if (!isset($this->config->columns) || !is_array($this->config->columns) || !count($this->config->columns)) {
throw new ApplicationException(Lang::get(
'backend::lang.list.missing_columns',
['class'=>get_class($this->controller)]
));
}
$this->addColumns($this->config->columns);
@ -591,12 +615,13 @@ class Lists extends WidgetBase
*/
protected function makeListColumn($name, $config)
{
if (is_string($config))
if (is_string($config)) {
$label = $config;
elseif (isset($config['label']))
} elseif (isset($config['label'])) {
$label = $config['label'];
else
} else {
$label = studly_case($name);
}
$columnType = isset($config['type']) ? $config['type'] : null;
@ -614,8 +639,12 @@ class Lists extends WidgetBase
{
$columns = $this->visibleColumns ?: $this->getVisibleListColumns();
$total = count($columns);
if ($this->showCheckboxes) $total++;
if ($this->showSetup) $total++;
if ($this->showCheckboxes) {
$total++;
}
if ($this->showSetup) {
$total++;
}
return $total;
}
@ -629,11 +658,13 @@ class Lists extends WidgetBase
/*
* Extensibility
*/
if ($response = Event::fire('backend.list.overrideHeaderValue', [$this, $column, $value], true))
if ($response = Event::fire('backend.list.overrideHeaderValue', [$this, $column, $value], true)) {
$value = $response;
}
if ($response = $this->fireEvent('list.overrideHeaderValue', [$column, $value], true))
if ($response = $this->fireEvent('list.overrideHeaderValue', [$column, $value], true)) {
$value = $response;
}
return $value;
}
@ -650,38 +681,42 @@ class Lists extends WidgetBase
* Handle taking name from model attribute.
*/
if ($column->valueFrom) {
if (!array_key_exists($columnName, $record->getRelations()))
if (!array_key_exists($columnName, $record->getRelations())) {
$value = null;
elseif ($this->isColumnRelated($column, true))
} elseif ($this->isColumnRelated($column, true)) {
$value = implode(', ', $record->{$columnName}->lists($column->valueFrom));
elseif ($this->isColumnRelated($column))
} elseif ($this->isColumnRelated($column)) {
$value = $record->{$columnName}->{$column->valueFrom};
else
} else {
$value = $record->{$column->valueFrom};
}
}
/*
* Otherwise, if the column is a relation, it will be a custom select,
* so prevent the Model from attempting to load the relation
* if the value is NULL.
*/
else {
if ($record->hasRelation($columnName) && array_key_exists($columnName, $record->attributes))
} else {
if ($record->hasRelation($columnName) && array_key_exists($columnName, $record->attributes)) {
$value = $record->attributes[$columnName];
else
} else {
$value = $record->{$columnName};
}
}
if (method_exists($this, 'eval'. studly_case($column->type) .'TypeValue'))
if (method_exists($this, 'eval'. studly_case($column->type) .'TypeValue')) {
$value = $this->{'eval'. studly_case($column->type) .'TypeValue'}($record, $column, $value);
}
/*
* Extensibility
*/
if ($response = Event::fire('backend.list.overrideColumnValue', [$this, $record, $column, $value], true))
if ($response = Event::fire('backend.list.overrideColumnValue', [$this, $record, $column, $value], true)) {
$value = $response;
}
if ($response = $this->fireEvent('list.overrideColumnValue', [$record, $column, $value], true))
if ($response = $this->fireEvent('list.overrideColumnValue', [$record, $column, $value], true)) {
$value = $response;
}
return $value;
}
@ -698,11 +733,13 @@ class Lists extends WidgetBase
/*
* Extensibility
*/
if ($response = Event::fire('backend.list.injectRowClass', [$this, $record], true))
if ($response = Event::fire('backend.list.injectRowClass', [$this, $record], true)) {
$value = $response;
}
if ($response = $this->fireEvent('list.injectRowClass', [$record], true))
if ($response = $this->fireEvent('list.injectRowClass', [$record], true)) {
$value = $response;
}
return $value;
}
@ -740,13 +777,15 @@ class Lists extends WidgetBase
*/
protected function evalDatetimeTypeValue($record, $column, $value)
{
if ($value === null)
if ($value === null) {
return null;
}
$value = $this->validateDateTimeValue($value, $column);
if ($column->format !== null)
if ($column->format !== null) {
return $value->format($column->format);
}
return $value->toDayDateTimeString();
}
@ -756,13 +795,15 @@ class Lists extends WidgetBase
*/
protected function evalTimeTypeValue($record, $column, $value)
{
if ($value === null)
if ($value === null) {
return null;
}
$value = $this->validateDateTimeValue($value, $column);
if ($column->format === null)
if ($column->format === null) {
$column->format = 'g:i A';
}
return $value->format($column->format);
}
@ -772,13 +813,15 @@ class Lists extends WidgetBase
*/
protected function evalDateTypeValue($record, $column, $value)
{
if ($value === null)
if ($value === null) {
return null;
}
$value = $this->validateDateTimeValue($value, $column);
if ($column->format !== null)
if ($column->format !== null) {
return $value->format($column->format);
}
return $value->toFormattedDateString();
}
@ -788,8 +831,9 @@ class Lists extends WidgetBase
*/
protected function evalTimesinceTypeValue($record, $column, $value)
{
if ($value === null)
if ($value === null) {
return null;
}
$value = $this->validateDateTimeValue($value, $column);
@ -801,11 +845,16 @@ class Lists extends WidgetBase
*/
protected function validateDateTimeValue($value, $column)
{
if ($value instanceof DateTime)
if ($value instanceof DateTime) {
$value = Carbon::instance($value);
}
if (!$value instanceof Carbon)
throw new ApplicationException(Lang::get('backend::lang.list.invalid_column_datetime', ['column' => $column->columnName]));
if (!$value instanceof Carbon) {
throw new ApplicationException(Lang::get(
'backend::lang.list.invalid_column_datetime',
['column' => $column->columnName]
));
}
return $value;
}
@ -832,8 +881,7 @@ class Lists extends WidgetBase
{
if (empty($term)) {
$this->showTree = $this->getConfig('showTree', $this->showTree);
}
else {
} else {
$this->showTree = false;
}
@ -850,8 +898,9 @@ class Lists extends WidgetBase
$searchable = [];
foreach ($columns as $column) {
if (!$column->searchable)
if (!$column->searchable) {
continue;
}
$searchable[] = $column;
}
@ -875,10 +924,11 @@ class Lists extends WidgetBase
*/
$sortOptions = ['column' => $this->getSortColumn(), 'direction' => $this->sortDirection];
if ($column != $sortOptions['column'] || $sortOptions['direction'] == 'asc')
if ($column != $sortOptions['column'] || $sortOptions['direction'] == 'asc') {
$this->sortDirection = $sortOptions['direction'] = 'desc';
else
} else {
$this->sortDirection = $sortOptions['direction'] = 'asc';
}
$this->sortColumn = $sortOptions['column'] = $column;
@ -898,11 +948,13 @@ class Lists extends WidgetBase
*/
protected function getSortColumn()
{
if (!$this->isSortable())
if (!$this->isSortable()) {
return false;
}
if ($this->sortColumn !== null)
if ($this->sortColumn !== null) {
return $this->sortColumn;
}
/*
* User preference
@ -910,18 +962,19 @@ class Lists extends WidgetBase
if ($this->showSorting && ($sortOptions = $this->getSession('sort'))) {
$this->sortColumn = $sortOptions['column'];
$this->sortDirection = $sortOptions['direction'];
}
/*
* Supplied default
*/
else {
} else {
if (is_string($this->defaultSort)) {
$this->sortColumn = $this->defaultSort;
$this->sortDirection = 'desc';
}
elseif (is_array($this->defaultSort) && isset($this->defaultSort['column'])) {
} elseif (is_array($this->defaultSort) && isset($this->defaultSort['column'])) {
$this->sortColumn = $this->defaultSort['column'];
$this->sortDirection = (isset($this->defaultSort['direction'])) ? $this->defaultSort['direction'] : 'desc';
$this->sortDirection = (isset($this->defaultSort['direction'])) ?
$this->defaultSort['direction'] :
'desc';
}
}
@ -942,10 +995,11 @@ class Lists extends WidgetBase
*/
protected function isSortable($column = null)
{
if ($column === null)
if ($column === null) {
return (count($this->getSortableColumns()) > 0);
else
} else {
return array_key_exists($column, $this->getSortableColumns());
}
}
/**
@ -953,15 +1007,17 @@ class Lists extends WidgetBase
*/
protected function getSortableColumns()
{
if ($this->sortableColumns !== null)
if ($this->sortableColumns !== null) {
return $this->sortableColumns;
}
$columns = $this->getColumns();
$sortable = [];
foreach ($columns as $column) {
if (!$column->sortable)
if (!$column->sortable) {
continue;
}
$sortable[$column->columnName] = $column;
}
@ -1005,8 +1061,9 @@ class Lists extends WidgetBase
protected function getSetupPerPageOptions()
{
$perPageOptions = [20, 40, 80, 100, 120];
if (!in_array($this->recordsPerPage, $perPageOptions))
if (!in_array($this->recordsPerPage, $perPageOptions)) {
$perPageOptions[] = $this->recordsPerPage;
}
sort($perPageOptions);
return $perPageOptions;
@ -1038,15 +1095,23 @@ class Lists extends WidgetBase
*/
public function validateTree()
{
if (!$this->showTree) return;
if (!$this->showTree) {
return;
}
$this->showSorting = $this->showPagination = false;
if (!$this->model->methodExists('getChildren'))
throw new ApplicationException('To display list as a tree, the specified model must have a method "getChildren"');
if (!$this->model->methodExists('getChildren')) {
throw new ApplicationException(
'To display list as a tree, the specified model must have a method "getChildren"'
);
}
if (!$this->model->methodExists('getChildCount'))
throw new ApplicationException('To display list as a tree, the specified model must have a method "getChildCount"');
if (!$this->model->methodExists('getChildCount')) {
throw new ApplicationException(
'To display list as a tree, the specified model must have a method "getChildCount"'
);
}
}
/**
@ -1082,14 +1147,20 @@ class Lists extends WidgetBase
*/
protected function isColumnRelated($column, $multi = false)
{
if (!isset($column->relation))
if (!isset($column->relation)) {
return false;
}
if (!$this->model->hasRelation($column->relation))
throw new ApplicationException(Lang::get('backend::lang.model.missing_relation', ['class'=>get_class($this->model), 'relation'=>$column->relation]));
if (!$this->model->hasRelation($column->relation)) {
throw new ApplicationException(Lang::get(
'backend::lang.model.missing_relation',
['class'=>get_class($this->model), 'relation'=>$column->relation]
));
}
if (!$multi)
if (!$multi) {
return true;
}
$relationType = $this->model->getRelationType($column->relation);
@ -1103,5 +1174,4 @@ class Lists extends WidgetBase
'hasManyThrough'
]);
}
}

View File

@ -62,9 +62,10 @@ class ReportContainer extends WidgetBase
if (File::isFile($path)) {
$config = $this->makeConfig($configFile);
foreach ($config as $field=>$value) {
if (property_exists($this, $field))
foreach ($config as $field => $value) {
if (property_exists($this, $field)) {
$this->$field = $value;
}
}
}
}
@ -116,8 +117,9 @@ class ReportContainer extends WidgetBase
public function onLoadAddPopup()
{
$sizes = [];
for ($i = 1; $i <= 10; $i++)
for ($i = 1; $i <= 10; $i++) {
$sizes[$i] = $i < 10 ? $i : $i.' (' . Lang::get('backend::lang.dashboard.full_width') . ')';
}
$this->vars['sizes'] = $sizes;
$this->vars['widgets'] = WidgetManager::instance()->listReportWidgets();
@ -130,15 +132,18 @@ class ReportContainer extends WidgetBase
$className = trim(Request::input('className'));
$size = trim(Request::input('size'));
if (!$className)
if (!$className) {
throw new ApplicationException('Please select a widget to add.');
}
if (!class_exists($className))
if (!class_exists($className)) {
throw new ApplicationException('The selected class doesn\'t exist.');
}
$widget = new $className($this->controller);
if (!($widget instanceof \Backend\Classes\ReportWidgetBase))
if (!($widget instanceof \Backend\Classes\ReportWidgetBase)) {
throw new ApplicationException('The selected class is not a report widget.');
}
$widgetInfo = $this->addWidget($widget, $size);
@ -162,8 +167,9 @@ class ReportContainer extends WidgetBase
} while (array_key_exists($alias, $widgets));
$sortOrder = 0;
foreach ($widgets as $widgetInfo)
foreach ($widgets as $widgetInfo) {
$sortOrder = max($sortOrder, $widgetInfo['sortOrder']);
}
$sortOrder++;
@ -184,22 +190,26 @@ class ReportContainer extends WidgetBase
$aliases = trim(Request::input('aliases'));
$orders = trim(Request::input('orders'));
if (!$aliases)
if (!$aliases) {
throw new ApplicationException('Invalid aliases string.');
}
if (!$orders)
if (!$orders) {
throw new ApplicationException('Invalid orders string.');
}
$aliases = explode(',', $aliases);
$orders = explode(',', $orders);
if (count($aliases) != count($orders))
if (count($aliases) != count($orders)) {
throw new ApplicationException('Invalid data posted.');
}
$widgets = $this->getWidgetsFromUserPreferences();
foreach ($aliases as $index=>$alias) {
if (isset($widgets[$alias]))
foreach ($aliases as $index => $alias) {
if (isset($widgets[$alias])) {
$widgets[$alias]['sortOrder'] = $orders[$index];
}
}
$this->setWidgetsToUserPreferences($widgets);
@ -219,8 +229,9 @@ class ReportContainer extends WidgetBase
$configuration['alias'] = $alias;
$className = $widgetInfo['class'];
if (!class_exists($className))
if (!class_exists($className)) {
continue;
}
$widget = new $className($this->controller, $configuration);
$widget->bindToController();
@ -228,7 +239,7 @@ class ReportContainer extends WidgetBase
$result[$alias] = ['widget' => $widget, 'sortOrder' => $widgetInfo['sortOrder']];
}
uasort($result, function($a, $b){
uasort($result, function ($a, $b) {
return $a['sortOrder'] - $b['sortOrder'];
});
@ -238,7 +249,9 @@ class ReportContainer extends WidgetBase
protected function getWidgetsFromUserPreferences()
{
$widgets = UserPreferences::forUser()->get($this->getUserPreferencesKey(), $this->defaultWidgets);
if (!is_array($widgets)) return [];
if (!is_array($widgets)) {
return [];
}
return $widgets;
}
@ -262,8 +275,9 @@ class ReportContainer extends WidgetBase
{
$widgets = $this->getWidgetsFromUserPreferences();
if (isset($widgets[$alias]))
if (isset($widgets[$alias])) {
unset($widgets[$alias]);
}
$this->setWidgetsToUserPreferences($widgets);
}
@ -271,8 +285,9 @@ class ReportContainer extends WidgetBase
protected function findWidgetByAlias($alias)
{
$widgets = $this->loadWidgets();
if (!isset($widgets[$alias]))
if (!isset($widgets[$alias])) {
throw new ApplicationException('The specified widget is not found.');
}
return $widgets[$alias]['widget'];
}
@ -320,8 +335,9 @@ class ReportContainer extends WidgetBase
];
foreach ($params as $name => $value) {
if (isset($property[$name]))
if (isset($property[$name])) {
continue;
}
$property[$name] = !is_array($value) ? Lang::get($value) : $value;
}

View File

@ -53,22 +53,26 @@ class Search extends WidgetBase
/*
* Process configuration
*/
if (isset($this->config->prompt))
if (isset($this->config->prompt)) {
$this->placeholder = trans($this->config->prompt);
}
if (isset($this->config->partial))
if (isset($this->config->partial)) {
$this->customPartial = $this->config->partial;
}
if (isset($this->config->growable))
if (isset($this->config->growable)) {
$this->growable = $this->config->growable;
}
/*
* Add CSS class styles
*/
$this->cssClasses[] = 'icon search';
if ($this->growable)
if ($this->growable) {
$this->cssClasses[] = 'growable';
}
}
/**
@ -78,10 +82,11 @@ class Search extends WidgetBase
{
$this->prepareVars();
if ($this->customPartial)
if ($this->customPartial) {
return $this->controller->makePartial($this->customPartial);
else
} else {
return $this->makePartial('search');
}
}
/**
@ -109,8 +114,9 @@ class Search extends WidgetBase
*/
$params = func_get_args();
$result = $this->fireEvent('search.submit', [$params]);
if ($result && is_array($result))
if ($result && is_array($result)) {
return Util::arrayMerge($result);
}
}
/**
@ -126,10 +132,11 @@ class Search extends WidgetBase
*/
public function setActiveTerm($term)
{
if (strlen($term))
if (strlen($term)) {
$this->putSession('term', $term);
else
} else {
$this->resetSession();
}
$this->activeTerm = $term;
}

View File

@ -43,10 +43,10 @@ class Toolbar extends WidgetBase
*/
if (isset($this->config->search)) {
if (is_string($this->config->search))
$searchConfig = $this->makeConfig($this->config->search);
if (is_string($this->config->search)) {
$searchConfig = $this->makeConfig(['partial' => $this->config->search]);
else
$searchConfig = $this->makeConfig($this->config->search);
}
$searchConfig->alias = $this->alias . 'Search';
$this->searchWidget = $this->makeWidget('Backend\Widgets\Search', $searchConfig);
@ -80,8 +80,9 @@ class Toolbar extends WidgetBase
public function makeControlPanel()
{
if (!isset($this->config->buttons))
if (!isset($this->config->buttons)) {
return false;
}
return $this->controller->makePartial($this->config->buttons, $this->vars);
}

View File

@ -25,7 +25,7 @@ class ServiceProvider extends ModuleServiceProvider
/*
* Register navigation
*/
BackendMenu::registerCallback(function($manager) {
BackendMenu::registerCallback(function ($manager) {
$manager->registerMenuItems('October.Cms', [
'cms' => [
'label' => 'cms::lang.cms.menu_label',
@ -86,7 +86,7 @@ class ServiceProvider extends ModuleServiceProvider
/*
* Register permissions
*/
BackendAuth::registerCallback(function($manager) {
BackendAuth::registerCallback(function ($manager) {
$manager->registerPermissions('October.Cms', [
'cms.manage_content' => ['label' => 'cms::lang.permissions.manage_content', 'tab' => 'Cms'],
'cms.manage_assets' => ['label' => 'cms::lang.permissions.manage_assets', 'tab' => 'Cms'],
@ -100,14 +100,14 @@ class ServiceProvider extends ModuleServiceProvider
/*
* Register widgets
*/
WidgetManager::instance()->registerFormWidgets(function($manager){
WidgetManager::instance()->registerFormWidgets(function ($manager) {
$manager->registerFormWidget('Cms\FormWidgets\Components');
});
/*
* Register settings
*/
SettingsManager::instance()->registerCallback(function($manager){
SettingsManager::instance()->registerCallback(function ($manager) {
$manager->registerSettingItems('October.Cms', [
'theme' => [
'label' => 'cms::lang.theme.settings_menu',
@ -123,7 +123,7 @@ class ServiceProvider extends ModuleServiceProvider
/*
* Register components
*/
ComponentManager::instance()->registerComponents(function($manager){
ComponentManager::instance()->registerComponents(function ($manager) {
$manager->registerComponent('Cms\Classes\ViewBag', 'viewBag');
});
}
@ -137,21 +137,22 @@ class ServiceProvider extends ModuleServiceProvider
{
parent::boot('cms');
Event::listen('pages.menuitem.listTypes', function() {
Event::listen('pages.menuitem.listTypes', function () {
return [
'cms-page'=>'CMS Page '
'cms-page' => 'CMS Page '
];
});
Event::listen('pages.menuitem.getTypeInfo', function($type) {
if ($type == 'cms-page')
Event::listen('pages.menuitem.getTypeInfo', function ($type) {
if ($type == 'cms-page') {
return CmsPage::getMenuTypeInfo($type);
}
});
Event::listen('pages.menuitem.resolveItem', function($type, $item, $url, $theme) {
if ($type == 'cms-page')
Event::listen('pages.menuitem.resolveItem', function ($type, $item, $url, $theme) {
if ($type == 'cms-page') {
return CmsPage::resolveMenuItem($item, $url, $theme);
}
});
}
}

View File

@ -41,8 +41,9 @@ class Asset extends CmsObject
$defaultTypes = ['css','js','less','sass','scss'];
$configTypes = Config::get('cms.editableAssetTypes');
if (!$configTypes)
if (!$configTypes) {
return $defaultTypes;
}
return $configTypes;
}
@ -64,5 +65,4 @@ class Asset extends CmsObject
{
return null;
}
}

View File

@ -73,8 +73,9 @@ class CmsCompoundObject extends CmsObject
*/
public static function load($theme, $fileName)
{
if (($obj = parent::load($theme, $fileName)) === null)
if (($obj = parent::load($theme, $fileName)) === null) {
return null;
}
CmsException::mask($obj, 200);
$parsedData = SectionParser::parse($obj->content);
@ -99,8 +100,9 @@ class CmsCompoundObject extends CmsObject
*/
public function __get($name)
{
if (is_array($this->settings) && array_key_exists($name, $this->settings))
if (is_array($this->settings) && array_key_exists($name, $this->settings)) {
return $this->settings[$name];
}
return parent::__get($name);
}
@ -113,8 +115,9 @@ class CmsCompoundObject extends CmsObject
*/
public function __isset($key)
{
if (parent::__isset($key) === true)
if (parent::__isset($key) === true) {
return true;
}
return isset($this->settings[$key]);
}
@ -134,8 +137,9 @@ class CmsCompoundObject extends CmsObject
public function runComponents()
{
foreach ($this->components as $component) {
if ($result = $component->onRun())
if ($result = $component->onRun()) {
return $result;
}
}
}
@ -149,13 +153,15 @@ class CmsCompoundObject extends CmsObject
$manager = ComponentManager::instance();
$components = [];
foreach ($this->settings as $setting => $value) {
if (!is_array($value))
if (!is_array($value)) {
continue;
}
$settingParts = explode(' ', $setting);
$settingName = $settingParts[0];
// if (!$manager->hasComponent($settingName))
// if (!$manager->hasComponent($settingName)) {
// continue;
// }
$components[$setting] = $value;
unset($this->settings[$setting]);
@ -192,25 +198,29 @@ class CmsCompoundObject extends CmsObject
$this->code = trim($this->code);
$this->markup = trim($this->markup);
$trim = function(&$values) use (&$trim) {
$trim = function (&$values) use (&$trim) {
foreach ($values as &$value) {
if (!is_array($value))
if (!is_array($value)) {
$value = trim($value);
else $trim($value);
} else {
$trim($value);
}
}
};
$trim($this->settings);
if (array_key_exists('components', $this->settings) && count($this->settings['components']) == 0)
if (array_key_exists('components', $this->settings) && count($this->settings['components']) == 0) {
unset($this->settings['components']);
}
$this->validate();
$content = [];
if ($this->settings)
if ($this->settings) {
$content[] = FileHelper::formatIniString($this->settings);
}
if ($this->code) {
if ($this->wrapCodeToPhpTags() && $this->originalData['code'] != $this->code) {
@ -219,8 +229,9 @@ class CmsCompoundObject extends CmsObject
$code = preg_replace('/\?>$/', '', $code);
$content[] = '<?php'.PHP_EOL.$this->code.PHP_EOL.'?>';
} else
} else {
$content[] = $this->code;
}
}
$content[] = $this->markup;
@ -237,8 +248,9 @@ class CmsCompoundObject extends CmsObject
*/
public function getViewBag()
{
if ($this->viewBagCache !== false)
if ($this->viewBagCache !== false) {
return $this->viewBagCache;
}
$componentName = 'viewBag';
@ -261,13 +273,15 @@ class CmsCompoundObject extends CmsObject
*/
public function getComponent($componentName)
{
if (!($componentSection = $this->hasComponent($componentName)))
if (!($componentSection = $this->hasComponent($componentName))) {
return null;
}
return ComponentManager::instance()->makeComponent(
$componentName,
null,
$this->settings['components'][$componentSection]);
$this->settings['components'][$componentSection]
);
}
/**
@ -277,17 +291,20 @@ class CmsCompoundObject extends CmsObject
*/
public function hasComponent($componentName)
{
foreach ($this->settings['components'] as $sectionName=>$values) {
if ($sectionName == $componentName)
foreach ($this->settings['components'] as $sectionName => $values) {
if ($sectionName == $componentName) {
return $componentName;
}
$parts = explode(' ', $sectionName);
if (count($parts) < 2)
if (count($parts) < 2) {
continue;
}
if (trim($parts[0]) == $componentName)
if (trim($parts[0]) == $componentName) {
return $sectionName;
}
}
return false;
@ -309,35 +326,40 @@ class CmsCompoundObject extends CmsObject
$cached = Cache::get($key, false);
$unserialized = $cached ? @unserialize($cached) : false;
$objectComponentMap = $unserialized ? $unserialized : [];
if ($objectComponentMap)
if ($objectComponentMap) {
self::$objectComponentPropertyMap = $objectComponentMap;
}
}
$objectCode = $this->getBaseFileName();
if (array_key_exists($objectCode, $objectComponentMap)) {
if (array_key_exists($componentName, $objectComponentMap[$objectCode]))
if (array_key_exists($componentName, $objectComponentMap[$objectCode])) {
return $objectComponentMap[$objectCode][$componentName];
}
return [];
}
if (!isset($this->settings['components']))
if (!isset($this->settings['components'])) {
$objectComponentMap[$objectCode] = [];
else {
foreach ($this->settings['components'] as $componentName=>$componentSettings) {
} else {
foreach ($this->settings['components'] as $componentName => $componentSettings) {
$nameParts = explode(' ', $componentName);
if (count($nameParts > 1))
if (count($nameParts > 1)) {
$componentName = trim($nameParts[0]);
}
$component = $this->getComponent($componentName);
if (!$component)
if (!$component) {
continue;
}
$componentProperties = [];
$propertyDefinitions = $component->defineProperties();
foreach ($propertyDefinitions as $propertyName=>$propertyInfo)
foreach ($propertyDefinitions as $propertyName => $propertyInfo) {
$componentProperties[$propertyName] = $component->property($propertyName);
}
$objectComponentMap[$objectCode][$componentName] = $componentProperties;
}
@ -347,8 +369,9 @@ class CmsCompoundObject extends CmsObject
Cache::put($key, serialize($objectComponentMap), Config::get('cms.parsedPageCacheTTL', 10));
if (array_key_exists($componentName, $objectComponentMap[$objectCode]))
if (array_key_exists($componentName, $objectComponentMap[$objectCode])) {
return $objectComponentMap[$objectCode][$componentName];
}
return [];
}
@ -388,7 +411,9 @@ class CmsCompoundObject extends CmsObject
* the content of the $settings property after the object
* is loaded from a file.
*/
protected function parseSettings() {}
protected function parseSettings()
{
}
/**
* Initializes the object properties from the cached data.
@ -418,14 +443,24 @@ class CmsCompoundObject extends CmsObject
*/
protected function validate()
{
$validation = Validator::make($this->settings, $this->settingsValidationRules, $this->settingsValidationMessages);
if ($validation->fails())
$validation = Validator::make(
$this->settings,
$this->settingsValidationRules,
$this->settingsValidationMessages
);
if ($validation->fails()) {
throw new ValidationException($validation);
}
if ($this->viewBagValidationRules && isset($this->settings['viewBag'])) {
$validation = Validator::make($this->settings['viewBag'], $this->viewBagValidationRules, $this->viewBagValidationMessages);
if ($validation->fails())
$validation = Validator::make(
$this->settings['viewBag'],
$this->viewBagValidationRules,
$this->viewBagValidationMessages
);
if ($validation->fails()) {
throw new ValidationException($validation);
}
}
}

View File

@ -50,8 +50,9 @@ class CmsException extends ApplicationException
$message = '';
}
if (isset(static::$errorCodes[$code]))
if (isset(static::$errorCodes[$code])) {
$this->errorType = static::$errorCodes[$code];
}
parent::__construct($message, $code, $previous);
}
@ -104,9 +105,15 @@ class CmsException extends ApplicationException
/*
* Expecting: syntax error, unexpected '!' in Unknown on line 4
*/
if (!starts_with($message, 'syntax error')) return false;
if (strpos($message, 'Unknown') === false) return false;
if (strpos($exception->getFile(), 'SectionParser.php') === false) return false;
if (!starts_with($message, 'syntax error')) {
return false;
}
if (strpos($message, 'Unknown') === false) {
return false;
}
if (strpos($exception->getFile(), 'SectionParser.php') === false) {
return false;
}
/*
* Line number from parse_ini_string() error.
@ -143,23 +150,28 @@ class CmsException extends ApplicationException
$check = false;
// Expected: */modules/cms/classes/CodeParser.php(165) : eval()'d code line 7
if (strpos($exception->getFile(), 'CodeParser.php')) $check = true;
if (strpos($exception->getFile(), 'CodeParser.php')) {
$check = true;
}
// Expected: */app/storage/cache/39/05/home.htm.php
if (strpos($exception->getFile(), $this->compoundObject->getFileName() . '.php')) $check = true;
if (strpos($exception->getFile(), $this->compoundObject->getFileName() . '.php')) {
$check = true;
}
if (!$check)
if (!$check) {
return false;
}
}
/*
* Errors occurring the PHP code base class (Cms\Classes\CodeBase)
*/
else {
} else {
$trace = $exception->getTrace();
if (isset($trace[1]['class'])) {
$class = $trace[1]['class'];
if (!is_subclass_of($class, 'Cms\Classes\CodeBase'))
if (!is_subclass_of($class, 'Cms\Classes\CodeBase')) {
return false;
}
}
}
@ -187,8 +199,9 @@ class CmsException extends ApplicationException
protected function processTwig(Exception $exception)
{
// Must be a Twig related exception
if (!$exception instanceof Twig_Error)
if (!$exception instanceof Twig_Error) {
return false;
}
$this->message = $exception->getRawMessage();
$this->line = $exception->getTemplateLine();
@ -220,5 +233,4 @@ class CmsException extends ApplicationException
return;
}
}
}

View File

@ -80,27 +80,32 @@ class CmsObject implements ArrayAccess
*/
public static function loadCached($theme, $fileName)
{
if (!FileHelper::validatePath($fileName, static::getMaxAllowedPathNesting()))
if (!FileHelper::validatePath($fileName, static::getMaxAllowedPathNesting())) {
throw new SystemException(Lang::get('cms::lang.cms_object.invalid_file', ['name'=>$fileName]));
}
if (!strlen(File::extension($fileName)))
if (!strlen(File::extension($fileName))) {
$fileName .= '.'.static::$defaultExtension;
}
$filePath = static::getFilePath($theme, $fileName);
if (array_key_exists($filePath, ObjectMemoryCache::$cache))
if (array_key_exists($filePath, ObjectMemoryCache::$cache)) {
return ObjectMemoryCache::$cache[$filePath];
}
$key = self::getObjectTypeDirName().crc32($filePath);
clearstatcache($filePath);
$cached = Cache::get($key, false);
if ($cached !== false && ($cached = @unserialize($cached)) !== false) {
if ($cached['mtime'] != @File::lastModified($filePath))
if ($cached['mtime'] != @File::lastModified($filePath)) {
$cached = false;
}
}
if ($cached && !File::isFile($filePath))
if ($cached && !File::isFile($filePath)) {
$cached = false;
}
if ($cached !== false) {
/*
@ -151,19 +156,23 @@ class CmsObject implements ArrayAccess
*/
public static function load($theme, $fileName)
{
if (!FileHelper::validatePath($fileName, static::getMaxAllowedPathNesting()))
if (!FileHelper::validatePath($fileName, static::getMaxAllowedPathNesting())) {
throw new SystemException(Lang::get('cms::lang.cms_object.invalid_file', ['name'=>$fileName]));
}
if (!strlen(File::extension($fileName)))
if (!strlen(File::extension($fileName))) {
$fileName .= '.'.static::$defaultExtension;
}
$fullPath = static::getFilePath($theme, $fileName);
if (!File::isFile($fullPath))
if (!File::isFile($fullPath)) {
return null;
}
if (($content = @File::get($fullPath)) === false)
if (($content = @File::get($fullPath)) === false) {
return null;
}
$obj = new static($theme);
$obj->fileName = $fileName;
@ -209,8 +218,9 @@ class CmsObject implements ArrayAccess
public function getBaseFileName()
{
$pos = strrpos($this->fileName, '.');
if ($pos === false)
if ($pos === false) {
return $this->fileName;
}
return substr($this->fileName, 0, $pos);
}
@ -258,8 +268,9 @@ class CmsObject implements ArrayAccess
]);
}
if (!strlen(File::extension($fileName)))
if (!strlen(File::extension($fileName))) {
$fileName .= '.htm';
}
$this->fileName = $fileName;
return $this;
@ -298,15 +309,20 @@ class CmsObject implements ArrayAccess
*/
public function fill(array $attributes)
{
foreach ($attributes as $key=>$value) {
if (!in_array($key, static::$fillable))
throw new ApplicationException(Lang::get('cms::lang.cms_object.invalid_property', ['name'=>$key]));
foreach ($attributes as $key => $value) {
if (!in_array($key, static::$fillable)) {
throw new ApplicationException(Lang::get(
'cms::lang.cms_object.invalid_property',
['name' => $key]
));
}
$methodName = 'set'.ucfirst($key);
if (method_exists($this, $methodName))
if (method_exists($this, $methodName)) {
$this->$methodName($value);
else
} else {
$this->$key = $value;
}
}
}
@ -317,31 +333,48 @@ class CmsObject implements ArrayAccess
{
$fullPath = static::getFilePath($this->theme, $this->fileName);
if (File::isFile($fullPath) && $this->originalFileName !== $this->fileName)
throw new ApplicationException(Lang::get('cms::lang.cms_object.file_already_exists', ['name'=>$this->fileName]));
if (File::isFile($fullPath) && $this->originalFileName !== $this->fileName) {
throw new ApplicationException(Lang::get(
'cms::lang.cms_object.file_already_exists',
['name'=>$this->fileName]
));
}
$dirPath = rtrim(static::getFilePath($this->theme, ''), '/');
if (!file_exists($dirPath) || !is_dir($dirPath)) {
if (!File::makeDirectory($dirPath, 0777, true, true))
throw new ApplicationException(Lang::get('cms::lang.cms_object.error_creating_directory', ['name'=>$dirPath]));
if (!File::makeDirectory($dirPath, 0777, true, true)) {
throw new ApplicationException(Lang::get(
'cms::lang.cms_object.error_creating_directory',
['name'=>$dirPath]
));
}
}
if (($pos = strpos($this->fileName, '/')) !== false) {
$dirPath = static::getFilePath($this->theme, dirname($this->fileName));
if (!is_dir($dirPath) && !File::makeDirectory($dirPath, 0777, true, true))
throw new ApplicationException(Lang::get('cms::lang.cms_object.error_creating_directory', ['name'=>$dirPath]));
if (!is_dir($dirPath) && !File::makeDirectory($dirPath, 0777, true, true)) {
throw new ApplicationException(Lang::get(
'cms::lang.cms_object.error_creating_directory',
['name'=>$dirPath]
));
}
}
$newFullPath = $fullPath;
if (@File::put($fullPath, $this->content) === false)
throw new ApplicationException(Lang::get('cms::lang.cms_object.error_saving', ['name'=>$this->fileName]));
if (@File::put($fullPath, $this->content) === false) {
throw new ApplicationException(Lang::get(
'cms::lang.cms_object.error_saving',
['name'=>$this->fileName]
));
}
if (strlen($this->originalFileName) && $this->originalFileName !== $this->fileName) {
$fullPath = static::getFilePath($this->theme, $this->originalFileName);
if (File::isFile($fullPath))
if (File::isFile($fullPath)) {
@unlink($fullPath);
}
}
clearstatcache();
@ -378,24 +411,27 @@ class CmsObject implements ArrayAccess
*/
public static function listInTheme($theme, $skipCache = false)
{
if (!$theme)
if (!$theme) {
throw new ApplicationException(Lang::get('cms::lang.theme.active.not_set'));
}
$dirPath = $theme->getPath().'/'.static::getObjectTypeDirName();
$result = [];
if (!File::isDirectory($dirPath))
if (!File::isDirectory($dirPath)) {
return $result;
}
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirPath));
$it->setMaxDepth(1); // Support only a single level of subdirectories
$it->rewind();
while($it->valid()) {
while ($it->valid()) {
if ($it->isFile() && in_array($it->getExtension(), static::$allowedExtensions)) {
$filePath = $it->getBasename();
if ($it->getDepth() > 0)
if ($it->getDepth() > 0) {
$filePath = basename($it->getPath()).'/'.$filePath;
}
$page = $skipCache ? static::load($theme, $filePath) : static::loadCached($theme, $filePath);
$result[] = $page;
@ -426,8 +462,9 @@ class CmsObject implements ArrayAccess
public function __get($name)
{
$methodName = 'get'.ucfirst($name);
if (method_exists($this, $methodName))
if (method_exists($this, $methodName)) {
return $this->$methodName();
}
return null;
}
@ -440,8 +477,9 @@ class CmsObject implements ArrayAccess
public function __isset($key)
{
$methodName = 'get'.ucfirst($key);
if (method_exists($this, $methodName))
if (method_exists($this, $methodName)) {
return true;
}
return false;
}
@ -540,18 +578,24 @@ class CmsObject implements ArrayAccess
* Initializes the object properties from the cached data.
* @param array $cached The cached data array.
*/
protected function initFromCache($cached) {}
protected function initFromCache($cached)
{
}
/**
* Initializes a cache item.
* @param array &$item The cached item array.
*/
protected function initCacheItem(&$item) {}
protected function initCacheItem(&$item)
{
}
/**
* Returns the directory name corresponding to the object type.
* For pages the directory name is "pages", for layouts - "layouts", etc.
* @return string
*/
public static function getObjectTypeDirName() {}
public static function getObjectTypeDirName()
{
}
}

View File

@ -69,13 +69,15 @@ class CmsObjectQuery
*/
public function find($fileName)
{
if (!$this->theme)
if (!$this->theme) {
$this->inEditTheme();
}
if ($this->useCache)
if ($this->useCache) {
return forward_static_call([$this->cmsObject, 'loadCached'], $this->theme, $fileName);
else
} else {
return forward_static_call([$this->cmsObject, 'load'], $this->theme, $fileName);
}
}
/**
@ -84,8 +86,9 @@ class CmsObjectQuery
*/
public function all()
{
if (!$this->theme)
if (!$this->theme) {
$this->inEditTheme();
}
$collection = forward_static_call([$this->cmsObject, 'listInTheme'], $this->theme, !$this->useCache);
$collection = new CmsObjectCollection($collection);
@ -108,5 +111,4 @@ class CmsObjectQuery
$className = get_class($this);
throw new \BadMethodCallException("Call to undefined method {$className}::{$method}()");
}
}

View File

@ -27,7 +27,10 @@ class CmsPropertyHelper
*/
public static function listPages()
{
Flash::warning("CmsPropertyHelper::listPages() is deprecated, use Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName') instead.");
Flash::warning(
"CmsPropertyHelper::listPages() is deprecated, use Page::sortBy('baseFileName')->lists('baseFileName',
'baseFileName') instead."
);
return Page::sortBy('baseFileName')->lists('baseFileName', 'baseFileName');
}
}

View File

@ -45,19 +45,25 @@ class CodeBase extends Extendable implements ArrayAccess
* This event is triggered when all components are initialized and before AJAX is handled.
* The layout's onInit method triggers before the page's onInit method.
*/
public function onInit() {}
public function onInit()
{
}
/**
* This event is triggered in the beginning of the execution cycle.
* The layout's onStart method triggers before the page's onStart method.
*/
public function onStart() {}
public function onStart()
{
}
/**
* This event is triggered in the end of the execution cycle, but before the page is displayed.
* The layout's onEnd method triggers after the page's onEnd method.
*/
public function onEnd() {}
public function onEnd()
{
}
/**
* ArrayAccess implementation
@ -99,8 +105,9 @@ class CodeBase extends Extendable implements ArrayAccess
*/
public function __call($method, $parameters)
{
if (method_exists($this, $method))
if (method_exists($this, $method)) {
return call_user_func_array([$this, $method], $parameters);
}
return call_user_func_array([$this->controller, $method], $parameters);
}
@ -115,11 +122,13 @@ class CodeBase extends Extendable implements ArrayAccess
*/
public function __get($name)
{
if (($value = $this->page->{$name}) !== null)
if (($value = $this->page->{$name}) !== null) {
return $value;
}
if (array_key_exists($name, $this->controller->vars))
if (array_key_exists($name, $this->controller->vars)) {
return $this[$name];
}
return null;
}

View File

@ -99,13 +99,15 @@ class CodeParser
$body = preg_replace($pattern, '', $body);
$parentClass = $this->object->getCodeClassParent();
if ($parentClass !== null)
if ($parentClass !== null) {
$parentClass = ' extends '.$parentClass;
}
$fileContents = '<?php '.PHP_EOL;
foreach ($namespaces[0] as $namespace)
foreach ($namespaces[0] as $namespace) {
$fileContents .= $namespace;
}
$fileContents .= 'class '.$className.$parentClass.PHP_EOL;
$fileContents .= '{'.PHP_EOL;
@ -115,15 +117,18 @@ class CodeParser
$this->validate($fileContents);
$dir = dirname($path);
if (!File::isDirectory($dir) && !@File::makeDirectory($dir, 0777, true))
if (!File::isDirectory($dir) && !@File::makeDirectory($dir, 0777, true)) {
throw new SystemException(Lang::get('system::lang.directory.create_fail', ['name'=>$dir]));
}
if (!@File::put($path, $fileContents))
if (!@File::put($path, $fileContents)) {
throw new SystemException(Lang::get('system::lang.file.create_fail', ['name'=>$dir]));
}
$cached = $this->getCachedInfo();
if (!$cached)
if (!$cached) {
$cached = [];
}
$result['className'] = $className;
$result['source'] = 'parser';
@ -148,8 +153,9 @@ class CodeParser
{
$data = $this->parse();
if (!class_exists($data['className']))
if (!class_exists($data['className'])) {
require_once $data['filePath'];
}
$className = $data['className'];
return new $className($page, $layout, $controller);
@ -186,8 +192,9 @@ class CodeParser
protected function getCachedInfo()
{
$cached = Cache::get($this->dataCacheKey, false);
if ($cached !== false && ($cached = @unserialize($cached)) !== false)
if ($cached !== false && ($cached = @unserialize($cached)) !== false) {
return $cached;
}
return null;
}
@ -200,8 +207,9 @@ class CodeParser
{
$cached = $this->getCachedInfo();
if ($cached !== null) {
if (array_key_exists($this->filePath, $cached))
if (array_key_exists($this->filePath, $cached)) {
return $cached[$this->filePath];
}
}
return null;

View File

@ -113,19 +113,29 @@ abstract class ComponentBase extends Extendable
/**
* Executed when this component is first initialized, before AJAX requests.
*/
public function init() {}
public function onInit() {} // Deprecated: Remove ithis line if year >= 2015
public function init()
{
}
// @deprecated: Remove this line if year >= 2015
public function onInit()
{
}
/**
* Executed when this component is bound to a page or layout, part of
* the page life cycle.
*/
public function onRun() {}
public function onRun()
{
}
/**
* Executed when this component is rendered on a page or layout.
*/
public function onRender() {}
public function onRender()
{
}
/**
* Dynamically handle calls into the controller instance.
@ -135,11 +145,13 @@ abstract class ComponentBase extends Extendable
*/
public function __call($method, $parameters)
{
if (method_exists($this, $method))
if (method_exists($this, $method)) {
return call_user_func_array([$this, $method], $parameters);
}
if (method_exists($this->controller, $method))
if (method_exists($this->controller, $method)) {
return call_user_func_array([$this->controller, $method], $parameters);
}
throw new CmsException(Lang::get('cms::lang.component.method_not_found', [
'name' => get_class($this),
@ -161,12 +173,13 @@ abstract class ComponentBase extends Extendable
* @param $default A default value to return if no value is found.
* @return string
*/
public function propertyOrParam($name, $default = null)
public function propertyOrParam($name, $default = null)
{
$value = $this->property($name, $default);
if (substr($value, 0, 1) == ':')
if (substr($value, 0, 1) == ':') {
return $this->param(substr($value, 1), $default);
}
return $value;
}
@ -202,5 +215,4 @@ abstract class ComponentBase extends Extendable
// return $this->pageUrl($page, $params);
// }
}

View File

@ -38,7 +38,9 @@ class ComponentHelpers
];
foreach ($params as $name => $value) {
if (isset($property[$name])) continue;
if (isset($property[$name])) {
continue;
}
$property[$name] = $value;
}
@ -47,13 +49,15 @@ class ComponentHelpers
*/
$translate = ['title', 'description', 'options'];
foreach ($property as $name => $value) {
if (!in_array($name, $translate))
if (!in_array($name, $translate)) {
continue;
}
if (is_array($value)) {
array_walk($property[$name], function(&$_value, $key) { $_value = Lang::get($_value); });
}
else {
array_walk($property[$name], function (&$_value, $key) {
$_value = Lang::get($_value);
});
} else {
$property[$name] = Lang::get($value);
}
}
@ -76,8 +80,9 @@ class ComponentHelpers
$result['oc.alias'] = $component->alias;
$properties = $component->defineProperties();
foreach ($properties as $name => $params)
foreach ($properties as $name => $params) {
$result[$name] = $component->property($name);
}
return json_encode($result);
}

View File

@ -61,8 +61,9 @@ class ComponentManager
foreach ($plugins as $plugin) {
$components = $plugin->registerComponents();
if (!is_array($components))
if (!is_array($components)) {
continue;
}
foreach ($components as $className => $code) {
$this->registerComponent($className, $code, $plugin);
@ -91,23 +92,31 @@ class ComponentManager
*/
public function registerComponent($className, $code = null, $plugin = null)
{
if (!$this->classMap)
if (!$this->classMap) {
$this->classMap = [];
}
if (!$this->codeMap)
if (!$this->codeMap) {
$this->codeMap = [];
}
if (!$code)
if (!$code) {
$code = Str::getClassId($className);
}
if ($code == 'viewBag' && $className != 'Cms\Classes\ViewBag')
throw new SystemException(sprintf('The component code viewBag is reserved. Please use another code for the component class %s.', $className));
if ($code == 'viewBag' && $className != 'Cms\Classes\ViewBag') {
throw new SystemException(sprintf(
'The component code viewBag is reserved. Please use another code for the component class %s.',
$className
));
}
$className = Str::normalizeClassName($className);
$this->codeMap[$code] = $className;
$this->classMap[$className] = $code;
if ($plugin !== null)
if ($plugin !== null) {
$this->pluginMap[$className] = $plugin;
}
}
/**
@ -116,8 +125,9 @@ class ComponentManager
*/
public function listComponents()
{
if ($this->codeMap === null)
if ($this->codeMap === null) {
$this->loadComponents();
}
return $this->codeMap;
}
@ -128,8 +138,9 @@ class ComponentManager
*/
public function listComponentDetails()
{
if ($this->detailsCache !== null)
if ($this->detailsCache !== null) {
return $this->detailsCache;
}
$details = [];
foreach ($this->listComponents() as $componentAlias => $componentClass) {
@ -148,12 +159,14 @@ class ComponentManager
{
$codes = $this->listComponents();
if (isset($codes[$name]))
if (isset($codes[$name])) {
return $codes[$name];
}
$name = Str::normalizeClassName($name);
if (isset($this->classMap[$name]))
if (isset($this->classMap[$name])) {
return $name;
}
return null;
}
@ -166,8 +179,9 @@ class ComponentManager
public function hasComponent($name)
{
$className = $this->resolve($name);
if (!$className)
if (!$className) {
return false;
}
return isset($this->classMap[$className]);
}
@ -182,11 +196,19 @@ class ComponentManager
public function makeComponent($name, $cmsObject = null, $properties = [])
{
$className = $this->resolve($name);
if (!$className)
throw new SystemException(sprintf('Class name is not registered for the component %s. Check the component plugin.', $name));
if (!$className) {
throw new SystemException(sprintf(
'Class name is not registered for the component %s. Check the component plugin.',
$name
));
}
if (!class_exists($className))
throw new SystemException(sprintf('Component class not found %s.Check the component plugin.', $className));
if (!class_exists($className)) {
throw new SystemException(sprintf(
'Component class not found %s.Check the component plugin.',
$className
));
}
$component = new $className($cmsObject, $properties);
$component->name = $name;
@ -202,8 +224,9 @@ class ComponentManager
public function findComponentPlugin($component)
{
$className = Str::normalizeClassName(get_class($component));
if (isset($this->pluginMap[$className]))
if (isset($this->pluginMap[$className])) {
return $this->pluginMap[$className];
}
return null;
}

View File

@ -59,8 +59,9 @@ class ComponentPartial extends CmsObject
if (!File::isFile($path)) {
$sharedDir = dirname($component->getPath()).'/partials';
$sharedPath = $sharedDir.'/'.$fileName;
if (File::isFile($sharedPath))
if (File::isFile($sharedPath)) {
return $sharedPath;
}
}
return $path;

View File

@ -37,8 +37,9 @@ class Content extends CmsCompoundObject
*/
public static function load($theme, $fileName)
{
if ($obj = parent::load($theme, $fileName))
if ($obj = parent::load($theme, $fileName)) {
$obj->parsedMarkup = $obj->parseMarkup();
}
return $obj;
}
@ -70,8 +71,9 @@ class Content extends CmsCompoundObject
{
$result = $this->markup;
if (strtolower(File::extension($this->fileName)) == 'md')
if (strtolower(File::extension($this->fileName)) == 'md') {
$result = Markdown::parse($this->markup);
}
return $result;
}

View File

@ -108,8 +108,9 @@ class Controller extends BaseController
public function __construct($theme = null)
{
$this->theme = $theme ? $theme : Theme::getActiveTheme();
if (!$this->theme)
if (!$this->theme) {
throw new CmsException(Lang::get('cms::lang.theme.active.not_found'));
}
$this->assetPath = Config::get('cms.themesDir').'/'.$this->theme->getDirName();
$this->router = new Router($this->theme);
@ -138,29 +139,34 @@ class Controller extends BaseController
*/
public function run($url = '/')
{
if ($url === null)
if ($url === null) {
$url = Request::path();
}
if (!strlen($url))
if (!strlen($url)) {
$url = '/';
}
/*
* Handle hidden pages
*/
$page = $this->router->findByUrl($url);
if ($page && $page->hidden) {
if (!BackendAuth::getUser())
if (!BackendAuth::getUser()) {
$page = null;
}
}
/*
* Extensibility
*/
if ($event = $this->fireEvent('page.beforeDisplay', [$url, $page], true))
if ($event = $this->fireEvent('page.beforeDisplay', [$url, $page], true)) {
return $event;
}
if ($event = Event::fire('cms.page.beforeDisplay', [$this, $url, $page], true))
if ($event = Event::fire('cms.page.beforeDisplay', [$this, $url, $page], true)) {
return $event;
}
/*
* If the page was not found, render the 404 page - either provided by the theme or the built-in one.
@ -169,11 +175,13 @@ class Controller extends BaseController
$this->setStatusCode(404);
// Log the 404 request
if (!App::runningUnitTests())
if (!App::runningUnitTests()) {
RequestLog::add();
}
if (!$page = $this->router->findByUrl('/404'))
if (!$page = $this->router->findByUrl('/404')) {
return Response::make(View::make('cms::404'), $this->statusCode);
}
}
$this->page = $page;
@ -182,10 +190,11 @@ class Controller extends BaseController
* If the page doesn't refer any layout, create the fallback layout.
* Otherwise load the layout specified in the page.
*/
if (!$page->layout)
if (!$page->layout) {
$layout = Layout::initFallback($this->theme);
elseif (($layout = Layout::loadCached($this->theme, $page->layout)) === null)
} elseif (($layout = Layout::loadCached($this->theme, $page->layout)) === null) {
throw new CmsException(Lang::get('cms::lang.layout.not_found', ['name'=>$page->layout]));
}
$this->layout = $layout;
@ -224,29 +233,38 @@ class Controller extends BaseController
/*
* Extensibility
*/
if ($event = $this->fireEvent('page.init', [$url, $page], true))
if ($event = $this->fireEvent('page.init', [$url, $page], true)) {
return $event;
}
if ($event = Event::fire('cms.page.init', [$this, $url, $page], true))
if ($event = Event::fire('cms.page.init', [$this, $url, $page], true)) {
return $event;
}
/*
* Execute AJAX event
*/
if ($ajaxResponse = $this->execAjaxHandlers())
if ($ajaxResponse = $this->execAjaxHandlers()) {
return $ajaxResponse;
}
/*
* Execute postback handler
*/
if (($handler = post('_handler')) && ($handlerResponse = $this->runAjaxHandler($handler)) && $handlerResponse !== true)
if (
($handler = post('_handler')) &&
($handlerResponse = $this->runAjaxHandler($handler)) &&
$handlerResponse !== true
) {
return $handlerResponse;
}
/*
* Execute page lifecycle
*/
if ($cycleResponse = $this->execPageCycle())
if ($cycleResponse = $this->execPageCycle()) {
return $cycleResponse;
}
/*
* Render the page
@ -260,8 +278,9 @@ class Controller extends BaseController
$template = $this->twig->loadTemplate($this->page->getFullPath());
$this->pageContents = $template->render($this->vars);
CmsException::unmask();
} else
} else {
$this->pageContents = $apiResult;
}
/*
* Render the layout
@ -275,14 +294,17 @@ class Controller extends BaseController
/*
* Extensibility
*/
if ($event = $this->fireEvent('page.display', [$url, $page], true))
if ($event = $this->fireEvent('page.display', [$url, $page], true)) {
return $event;
}
if ($event = Event::fire('cms.page.display', [$this, $url, $page], true))
if ($event = Event::fire('cms.page.display', [$this, $url, $page], true)) {
return $event;
}
if (!is_string($result))
if (!is_string($result)) {
return $result;
}
return Response::make($result, $this->statusCode);
}
@ -302,15 +324,17 @@ class Controller extends BaseController
'auto_reload' => true,
'debug' => $isDebugMode,
];
if (!Config::get('cms.twigNoCache'))
if (!Config::get('cms.twigNoCache')) {
$options['cache'] = storage_path().'/twig';
}
$this->twig = new Twig_Environment($this->loader, $options);
$this->twig->addExtension(new CmsTwigExtension($this));
$this->twig->addExtension(new SystemTwigExtension);
if ($isDebugMode)
if ($isDebugMode) {
$this->twig->addExtension(new DebugExtension($this));
}
}
/**
@ -342,13 +366,15 @@ class Controller extends BaseController
{
if (!$this->layout->isFallBack()) {
foreach ($this->layout->settings['components'] as $component => $properties) {
list($name, $alias) = strpos($component, ' ') ? explode(' ', $component) : array($component, $component);
list($name, $alias) = strpos($component, ' ') ?
explode(' ', $component) : array($component, $component);
$this->addComponent($name, $alias, $properties, true);
}
}
foreach ($this->page->settings['components'] as $component => $properties) {
list($name, $alias) = strpos($component, ' ') ? explode(' ', $component) : array($component, $component);
list($name, $alias) = strpos($component, ' ') ?
explode(' ', $component) : array($component, $component);
$this->addComponent($name, $alias, $properties);
}
}
@ -366,15 +392,16 @@ class Controller extends BaseController
$manager = ComponentManager::instance();
if ($addToLayout) {
if (!$componentObj = $manager->makeComponent($name, $this->layoutObj, $properties))
if (!$componentObj = $manager->makeComponent($name, $this->layoutObj, $properties)) {
throw new CmsException(Lang::get('cms::lang.component.not_found', ['name'=>$name]));
}
$componentObj->alias = $alias;
$this->vars[$alias] = $this->layout->components[$alias] = $componentObj;
}
else {
if (!$componentObj = $manager->makeComponent($name, $this->pageObj, $properties))
} else {
if (!$componentObj = $manager->makeComponent($name, $this->pageObj, $properties)) {
throw new CmsException(Lang::get('cms::lang.component.not_found', ['name'=>$name]));
}
$componentObj->alias = $alias;
$this->vars[$alias] = $this->page->components[$alias] = $componentObj;
@ -396,8 +423,9 @@ class Controller extends BaseController
/*
* Validate the handler name
*/
if (!preg_match('/^(?:\w+\:{2})?on[A-Z]{1}[\w+]*$/', $handler))
if (!preg_match('/^(?:\w+\:{2})?on[A-Z]{1}[\w+]*$/', $handler)) {
throw new CmsException(Lang::get('cms::lang.ajax_handler.invalid_name', ['name'=>$handler]));
}
/*
* Validate the handler partial list
@ -406,11 +434,11 @@ class Controller extends BaseController
$partialList = explode('&', $partialList);
foreach ($partialList as $partial) {
if (!preg_match('/^(?:\w+\:{2}|@)?[a-z0-9\_\-\.\/]+$/i', $partial))
if (!preg_match('/^(?:\w+\:{2}|@)?[a-z0-9\_\-\.\/]+$/i', $partial)) {
throw new CmsException(Lang::get('cms::lang.partial.invalid_name', ['name'=>$partial]));
}
}
}
else {
} else {
$partialList = [];
}
@ -419,23 +447,26 @@ class Controller extends BaseController
/*
* Execute the handler
*/
if (!$result = $this->runAjaxHandler($handler))
if (!$result = $this->runAjaxHandler($handler)) {
throw new CmsException(Lang::get('cms::lang.ajax_handler.not_found', ['name'=>$handler]));
}
/*
* If the handler returned an array, we should add it to output for rendering.
* If it is a string, add it to the array with the key "result".
*/
if (is_array($result))
if (is_array($result)) {
$responseContents = array_merge($responseContents, $result);
elseif (is_string($result))
} elseif (is_string($result)) {
$responseContents['result'] = $result;
}
/*
* Render partials and return the response as array that will be converted to JSON automatically.
*/
foreach ($partialList as $partial)
foreach ($partialList as $partial) {
$responseContents[$partial] = $this->renderPartial($partial);
}
/*
* If the handler returned a redirect, process it so framework.js knows to redirect
@ -446,27 +477,28 @@ class Controller extends BaseController
}
return Response::make()->setContent($responseContents);
}
catch (ValidationException $ex) {
} catch (ValidationException $ex) {
/*
* Handle validation errors
*/
$responseContents['X_OCTOBER_ERROR_FIELDS'] = $ex->getFields();
$responseContents['X_OCTOBER_ERROR_MESSAGE'] = $ex->getMessage();
return Response::make($responseContents, 406);
}
catch (ApplicationException $ex) {
} catch (ApplicationException $ex) {
return Response::make($ex->getMessage(), 500);
}
catch (Exception $ex) {
} catch (Exception $ex) {
/*
* Display a "dumbed down" error if custom page is activated
* otherwise display a more detailed error.
*/
if (Config::get('cms.customErrorPage', false))
if (Config::get('cms.customErrorPage', false)) {
return Response::make($ex->getMessage(), 500);
}
return Response::make(sprintf('"%s" on line %s of %s', $ex->getMessage(), $ex->getLine(), $ex->getFile()), 500);
return Response::make(
sprintf('"%s" on line %s of %s', $ex->getMessage(), $ex->getLine(), $ex->getFile()),
500
);
}
}
@ -493,11 +525,10 @@ class Controller extends BaseController
$result = $componentObj->$handlerName();
return ($result) ?: true;
}
}
/*
* Process code section handler
*/
else {
} else {
if (method_exists($this->pageObj, $handler)) {
$result = $this->pageObj->$handler();
return ($result) ?: true;
@ -540,11 +571,13 @@ class Controller extends BaseController
/*
* Extensibility
*/
if ($event = $this->fireEvent('page.start', [], true))
if ($event = $this->fireEvent('page.start', [], true)) {
return $event;
}
if ($event = Event::fire('cms.page.start', [$this], true))
if ($event = Event::fire('cms.page.start', [$this], true)) {
return $event;
}
/*
* Run layout functions
@ -556,7 +589,9 @@ class Controller extends BaseController
|| ($result = $this->layoutObj->onBeforePageStart())) ? $result: null;
CmsException::unmask();
if ($response) return $response;
if ($response) {
return $response;
}
}
/*
@ -568,7 +603,9 @@ class Controller extends BaseController
|| ($result = $this->pageObj->onEnd())) ? $result : null;
CmsException::unmask();
if ($response) return $response;
if ($response) {
return $response;
}
/*
* Run remaining layout functions
@ -582,11 +619,13 @@ class Controller extends BaseController
/*
* Extensibility
*/
if ($event = $this->fireEvent('page.end', [], true))
if ($event = $this->fireEvent('page.end', [], true)) {
return $event;
}
if ($event = Event::fire('cms.page.end', [$this], true))
if ($event = Event::fire('cms.page.end', [$this], true)) {
return $event;
}
return $response;
}
@ -602,11 +641,13 @@ class Controller extends BaseController
/*
* Extensibility
*/
if ($event = $this->fireEvent('page.render', [$contents], true))
if ($event = $this->fireEvent('page.render', [$contents], true)) {
return $event;
}
if ($event = Event::fire('cms.page.render', [$this, $contents], true))
if ($event = Event::fire('cms.page.render', [$this, $contents], true)) {
return $event;
}
return $contents;
}
@ -624,8 +665,9 @@ class Controller extends BaseController
/*
* Alias @ symbol for ::
*/
if (substr($name, 0, 1) == '@')
if (substr($name, 0, 1) == '@') {
$name = '::' . substr($name, 1);
}
/*
* Process Component partial
@ -640,23 +682,23 @@ class Controller extends BaseController
if (!strlen($componentAlias)) {
if ($this->componentContext !== null) {
$componentObj = $this->componentContext;
}
elseif (($componentObj = $this->findComponentByPartial($partialName)) === null) {
if ($throwException)
} elseif (($componentObj = $this->findComponentByPartial($partialName)) === null) {
if ($throwException) {
throw new CmsException(Lang::get('cms::lang.partial.not_found', ['name'=>$name]));
else
} else {
return false;
}
}
}
/*
* Component alias is supplied
*/
else {
} else {
if (($componentObj = $this->findComponentByName($componentAlias)) === null) {
if ($throwException)
if ($throwException) {
throw new CmsException(Lang::get('cms::lang.component.not_found', ['name'=>$componentAlias]));
else
} else {
return false;
}
}
}
@ -674,31 +716,33 @@ class Controller extends BaseController
/*
* Check the component partial
*/
if ($partial === null)
if ($partial === null) {
$partial = ComponentPartial::loadCached($componentObj, $partialName);
}
if ($partial === null) {
if ($throwException)
if ($throwException) {
throw new CmsException(Lang::get('cms::lang.partial.not_found', ['name'=>$name]));
else
} else {
return false;
}
}
/*
* Set context for self access
*/
$this->vars['__SELF__'] = $componentObj;
}
else {
} else {
/*
* Process theme partial
*/
if (($partial = Partial::loadCached($this->theme, $name)) === null) {
if ($throwException)
if ($throwException) {
throw new CmsException(Lang::get('cms::lang.partial.not_found', ['name'=>$name]));
else
} else {
return false;
}
}
}
@ -721,28 +765,29 @@ class Controller extends BaseController
/*
* Extensibility
*/
if ($event = $this->fireEvent('page.beforeRenderContent', [$name], true))
if ($event = $this->fireEvent('page.beforeRenderContent', [$name], true)) {
$content = $event;
elseif ($event = Event::fire('cms.page.beforeRenderContent', [$this, $name], true))
} elseif ($event = Event::fire('cms.page.beforeRenderContent', [$this, $name], true)) {
$content = $event;
/*
* Load content from theme
*/
elseif (($content = Content::loadCached($this->theme, $name)) === null)
} elseif (($content = Content::loadCached($this->theme, $name)) === null) {
throw new CmsException(Lang::get('cms::lang.content.not_found', ['name'=>$name]));
}
$fileContent = $content->parsedMarkup;
/*
* Extensibility
*/
if ($event = $this->fireEvent('page.renderContent', [$name, $fileContent], true))
if ($event = $this->fireEvent('page.renderContent', [$name, $fileContent], true)) {
return $event;
}
if ($event = Event::fire('cms.page.renderContent', [$this, $name, $fileContent], true))
if ($event = Event::fire('cms.page.renderContent', [$this, $name, $fileContent], true)) {
return $event;
}
return $fileContent;
}
@ -756,8 +801,9 @@ class Controller extends BaseController
if ($componentObj = $this->findComponentByName($name)) {
$componentObj->id = uniqid($name);
$componentObj->setProperties(array_merge($componentObj->getProperties(), $parameters));
if ($result = $componentObj->onRender())
if ($result = $componentObj->onRender()) {
return $result;
}
}
return $this->renderPartial($name.'::default', [], false);
@ -830,8 +876,9 @@ class Controller extends BaseController
*/
public function pageUrl($name, $parameters = [], $routePersistence = true, $absolute = true)
{
if (!$name)
if (!$name) {
return null;
}
/*
* Second parameter can act as third
@ -841,14 +888,17 @@ class Controller extends BaseController
$parameters = [];
}
if ($routePersistence)
if ($routePersistence) {
$parameters = array_merge($this->router->getParameters(), $parameters);
}
if (!$url = $this->router->findByFile($name, $parameters))
if (!$url = $this->router->findByFile($name, $parameters)) {
return null;
}
if (substr($url, 0, 1) == '/')
if (substr($url, 0, 1) == '/') {
$url = substr($url, 1);
}
return URL::action('Cms\Classes\Controller@run', ['slug' => $url], $absolute);
}
@ -874,10 +924,11 @@ class Controller extends BaseController
if (is_array($url)) {
$_url = Request::getBaseUrl();
$_url .= CombineAssets::combine($url, $themePath);
}
else {
} else {
$_url = Request::getBasePath().$themePath;
if ($url !== null) $_url .= '/'.$url;
if ($url !== null) {
$_url .= '/'.$url;
}
}
return $_url;
@ -900,11 +951,13 @@ class Controller extends BaseController
*/
protected function findComponentByName($name)
{
if (isset($this->page->components[$name]))
if (isset($this->page->components[$name])) {
return $this->page->components[$name];
}
if (isset($this->layout->components[$name]))
if (isset($this->layout->components[$name])) {
return $this->layout->components[$name];
}
return null;
}
@ -916,13 +969,15 @@ class Controller extends BaseController
protected function findComponentByHandler($handler)
{
foreach ($this->page->components as $component) {
if (method_exists($component, $handler))
if (method_exists($component, $handler)) {
return $component;
}
}
foreach ($this->layout->components as $component) {
if (method_exists($component, $handler))
if (method_exists($component, $handler)) {
return $component;
}
}
return null;
@ -936,20 +991,24 @@ class Controller extends BaseController
{
foreach ($this->page->components as $component) {
$fileName = ComponentPartial::getFilePath($component, $partial);
if (!strlen(File::extension($fileName)))
if (!strlen(File::extension($fileName))) {
$fileName .= '.htm';
}
if (File::isFile($fileName))
if (File::isFile($fileName)) {
return $component;
}
}
foreach ($this->layout->components as $component) {
$fileName = ComponentPartial::getFilePath($component, $partial);
if (!strlen(File::extension($fileName)))
if (!strlen(File::extension($fileName))) {
$fileName .= '.htm';
}
if (File::isFile($fileName))
if (File::isFile($fileName)) {
return $component;
}
}
return null;
@ -970,7 +1029,10 @@ class Controller extends BaseController
// if (($page = Page::loadCached($theme, $page)) && isset($page->settings['components'])) {
// foreach ($page->settings['components'] as $component => $properties) {
// list($name, $alias) = strpos($component, ' ') ? explode(' ', $component) : array($component, $component);
// list($name, $alias) = strpos($component, ' ') ?
// explode(' ', $component) :
// array($component, $component)
// ;
// if ($manager->resolve($name) == $class) {
// $componentObj->setProperties($properties);
// $componentObj->alias = $alias;
@ -984,7 +1046,10 @@ class Controller extends BaseController
// $layout = $page->settings['layout'];
// if (($layout = Layout::loadCached($theme, $layout)) && isset($layout->settings['components'])) {
// foreach ($layout->settings['components'] as $component => $properties) {
// list($name, $alias) = strpos($component, ' ') ? explode(' ', $component) : array($component, $component);
// list($name, $alias) = strpos($component, ' ') ?
// explode(' ', $component) :
// array($component, $component)
// ;
// if ($manager->resolve($name) == $class) {
// $componentObj->setProperties($properties);
// $componentObj->alias = $alias;
@ -996,5 +1061,4 @@ class Controller extends BaseController
// return null;
// }
}

View File

@ -30,8 +30,9 @@ class FileHelper
public static function validateExtension($fileName, $allowedExtensions, $allowEmpty = true)
{
$extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
if (!strlen($extension))
if (!strlen($extension)) {
return $allowEmpty;
}
return in_array($extension, $allowedExtensions);
}
@ -46,19 +47,24 @@ class FileHelper
*/
public static function validatePath($filePath, $maxNesting = 2)
{
if (strpos($filePath, '..') !== false)
if (strpos($filePath, '..') !== false) {
return false;
}
if (strpos($filePath, './') !== false || strpos($filePath, '//') !== false)
if (strpos($filePath, './') !== false || strpos($filePath, '//') !== false) {
return false;
}
$segments = explode('/', $filePath);
if ($maxNesting !== null && count($segments) > $maxNesting)
if ($maxNesting !== null && count($segments) > $maxNesting) {
return false;
}
foreach ($segments as $segment)
if (!self::validateName($segment))
foreach ($segments as $segment) {
if (!self::validateName($segment)) {
return false;
}
}
return true;
}
@ -74,20 +80,23 @@ class FileHelper
$content = null;
$sections = [];
foreach ($data as $key=>$value) {
foreach ($data as $key => $value) {
if (is_array($value)) {
if ($level == 1)
if ($level == 1) {
$sections[$key] = self::formatIniString($value, $level+1);
else {
foreach ($value as $val)
} else {
foreach ($value as $val) {
$content .= $key.'[] = "'.self::escapeIniString($val).'"'.PHP_EOL;
}
}
} elseif (strlen($value))
} elseif (strlen($value)) {
$content .= $key.' = "'.self::escapeIniString($value).'"'.PHP_EOL;
}
}
foreach ($sections as $key=>$section)
foreach ($sections as $key => $section) {
$content .= PHP_EOL.'['.$key.']'.PHP_EOL.$section.PHP_EOL;
}
return trim($content);
}

View File

@ -10,7 +10,9 @@ class Layout extends CmsCompoundObject
{
const FALLBACK_FILE_NAME = 'fallback';
protected function parseSettings() {}
protected function parseSettings()
{
}
/**
* Returns the directory name corresponding to the object type.

View File

@ -12,5 +12,7 @@ class LayoutCode extends CodeBase
* This event is triggered after the layout components are executed,
* but before the page's onStart event.
*/
public function onBeforePageStart() {}
public function onBeforePageStart()
{
}
}

View File

@ -36,7 +36,9 @@ class Page extends CmsCompoundObject
];
}
protected function parseSettings() {}
protected function parseSettings()
{
}
/**
* Returns the directory name corresponding to the object type.
@ -64,8 +66,9 @@ class Page extends CmsCompoundObject
*/
public function getLayoutOptions()
{
if (!($theme = Theme::getEditTheme()))
if (!($theme = Theme::getEditTheme())) {
throw new ApplicationException(Lang::get('cms::lang.theme.edit.not_found'));
}
$layouts = Layout::listInTheme($theme, true);
$result = [];
@ -106,8 +109,9 @@ class Page extends CmsCompoundObject
* request processing.
*/
$controller = Controller::getController();
if (!$controller)
if (!$controller) {
$controller = new Controller;
}
return $controller->pageUrl($page, $params, true, $absolute);
}
@ -124,8 +128,8 @@ class Page extends CmsCompoundObject
* false if omitted.
* - dynamicItems - Boolean value indicating whether the item type could generate new menu items.
* Optional, false if omitted.
* - cmsPages - a list of CMS pages (objects of the Cms\Classes\Page class), if the item type requires a CMS page reference to
* resolve the item URL.
* - cmsPages - a list of CMS pages (objects of the Cms\Classes\Page class), if the item type requires
* a CMS page reference to resolve the item URL.
* @param string $type Specifies the menu item type
* @return array Returns an array
*/
@ -173,8 +177,9 @@ class Page extends CmsCompoundObject
$result = null;
if ($item->type == 'cms-page') {
if (!$item->reference)
if (!$item->reference) {
return;
}
$pageUrl = self::url($item->reference);

View File

@ -18,7 +18,8 @@ use October\Rain\Router\Helper as RouterHelper;
* add the question mark after its name:
* <pre>/blog/post/:post_id?</pre>
* By default parameters in the middle of the URL are required, for example:
* <pre>/blog/:post_id?/comments - although the :post_id parameter is marked as optional, it will be processed as required.</pre>
* <pre>/blog/:post_id?/comments - although the :post_id parameter is marked as optional,
* it will be processed as required.</pre>
* Optional parameters can have default values which are used as fallback values in case if the real
* parameter value is not presented in the URL. Default values cannot contain the pipe symbols and question marks.
* Specify the default value after the question mark:
@ -74,16 +75,21 @@ class Router
$url = RouterHelper::normalizeUrl($url);
$apiResult = Event::fire('cms.router.beforeRoute', [$url], true);
if ($apiResult !== null)
if ($apiResult !== null) {
return $apiResult;
}
for ($pass = 1; $pass <= 2; $pass++) {
$fileName = null;
$urlList = [];
$cacheable = Config::get('cms.enableRoutesCache') && in_array(Config::get('cache.driver'), ['apc', 'memcached', 'redis', 'array']);
if ($cacheable)
$cacheable = Config::get('cms.enableRoutesCache') && in_array(
Config::get('cache.driver'),
['apc', 'memcached', 'redis', 'array']
);
if ($cacheable) {
$fileName = $this->getCachedUrlFileName($url, $urlList);
}
/*
* Find the page by URL and cache the route
@ -96,8 +102,9 @@ class Router
$fileName = $router->matchedRoute();
if ($cacheable) {
if (!$urlList || !is_array($urlList))
if (!$urlList || !is_array($urlList)) {
$urlList = [];
}
$urlList[$url] = $fileName;
@ -140,8 +147,9 @@ class Router
*/
public function findByFile($fileName, $parameters = [])
{
if (!strlen(File::extension($fileName)))
if (!strlen(File::extension($fileName))) {
$fileName .= '.htm';
}
$router = $this->getRouterObject();
return $router->url($fileName, $parameters);
@ -153,8 +161,9 @@ class Router
*/
protected function getRouterObject()
{
if (self::$routerObj !== null)
if (self::$routerObj !== null) {
return self::$routerObj;
}
/*
* Load up each route rule
@ -178,8 +187,9 @@ class Router
*/
protected function getUrlMap()
{
if (!count(self::$urlMap))
if (!count(self::$urlMap)) {
$this->loadUrlMap();
}
return self::$urlMap;
}
@ -196,10 +206,11 @@ class Router
$key = $this->getCacheKey('page-url-map');
$cacheable = Config::get('cms.enableRoutesCache');
if ($cacheable)
if ($cacheable) {
$cached = Cache::get($key, false);
else
} else {
$cached = false;
}
if (!$cached || ($unserialized = @unserialize($cached)) === false) {
/*
@ -208,15 +219,17 @@ class Router
$pages = $this->theme->listPages();
$map = [];
foreach ($pages as $page) {
if (!$page->url)
if (!$page->url) {
continue;
}
$map[] = ['file' => $page->getFileName(), 'pattern' => $page->url];
}
self::$urlMap = $map;
if ($cacheable)
if ($cacheable) {
Cache::put($key, serialize($map), Config::get('cms.urlCacheTtl', 1));
}
return false;
}
@ -259,8 +272,9 @@ class Router
*/
public function getParameter($name, $default = null)
{
if (isset($this->parameters[$name]) && !empty($this->parameters[$name]))
if (isset($this->parameters[$name]) && !empty($this->parameters[$name])) {
return $this->parameters[$name];
}
return $default;
}
@ -296,8 +310,9 @@ class Router
$urlList = Cache::get($key, false);
if ($urlList && ($urlList = @unserialize($urlList)) && is_array($urlList)) {
if (array_key_exists($url, $urlList))
if (array_key_exists($url, $urlList)) {
return $urlList[$url];
}
}
return null;

View File

@ -33,8 +33,9 @@ class SectionParser
{
$sections = preg_split('/^={2,}\s*/m', $content, -1);
$count = count($sections);
foreach ($sections as &$section)
foreach ($sections as &$section) {
$section = trim($section);
}
$result = [
'settings' => [],
@ -51,13 +52,12 @@ class SectionParser
$result['code'] = preg_replace('/\?\>\s*$/', '', $result['code']);
$result['markup'] = $sections[2];
}
elseif ($count == 2) {
} elseif ($count == 2) {
$result['settings'] = parse_ini_string($sections[0], true);
$result['markup'] = $sections[1];
}
elseif ($count == 1)
} elseif ($count == 1) {
$result['markup'] = $sections[0];
}
return $result;
}
@ -83,12 +83,10 @@ class SectionParser
$result['settings'] = self::adjustLinePosition($content);
$result['code'] = self::calculateLinePosition($content);
$result['markup'] = self::calculateLinePosition($content, 2);
}
elseif ($count == 2) {
} elseif ($count == 2) {
$result['settings'] = self::adjustLinePosition($content);
$result['markup'] = self::calculateLinePosition($content);
}
elseif ($count == 1) {
} elseif ($count == 1) {
$result['markup'] = 1;
}
@ -106,11 +104,13 @@ class SectionParser
$count = 0;
$lines = explode(PHP_EOL, $content);
foreach ($lines as $number => $line) {
if (trim($line) == self::SECTION_SEPARATOR)
if (trim($line) == self::SECTION_SEPARATOR) {
$count++;
}
if ($count == $instance)
if ($count == $instance) {
return static::adjustLinePosition($content, $number);
}
}
return null;
@ -150,7 +150,7 @@ class SectionParser
}
/*
* PHP namespaced line (use x;)
* PHP namespaced line (use x;) {
* Don't increase the line count, it will be rewritten by Cms\Classes\CodeParser
*/
if (preg_match_all('/(use\s+[a-z0-9_\\\\]+;\n?)/mi', $line) == 1) {

View File

@ -60,8 +60,9 @@ class Theme
*/
public function getPath($dirName = null)
{
if (!$dirName)
if (!$dirName) {
$dirName = $this->getDirName();
}
return base_path().Config::get('cms.themesDir').'/'.$dirName;
}
@ -108,8 +109,9 @@ class Theme
*/
public static function getActiveTheme()
{
if (self::$activeThemeCache !== false)
if (self::$activeThemeCache !== false) {
return self::$activeThemeCache;
}
$activeTheme = Config::get('cms.activeTheme');
@ -119,21 +121,25 @@ class Theme
->pluck('value')
;
if ($dbResult !== null)
if ($dbResult !== null) {
$activeTheme = $dbResult;
}
}
$apiResult = Event::fire('cms.activeTheme', [], true);
if ($apiResult !== null)
if ($apiResult !== null) {
$activeTheme = $apiResult;
}
if (!strlen($activeTheme))
if (!strlen($activeTheme)) {
throw new SystemException(Lang::get('cms::lang.theme.active.not_set'));
}
$theme = new static;
$theme->load($activeTheme);
if (!File::isDirectory($theme->getPath()))
if (!File::isDirectory($theme->getPath())) {
return self::$activeThemeCache = null;
}
return self::$activeThemeCache = $theme;
}
@ -160,24 +166,29 @@ class Theme
*/
public static function getEditTheme()
{
if (self::$editThemeCache !== false)
if (self::$editThemeCache !== false) {
return self::$editThemeCache;
}
$editTheme = Config::get('cms.editTheme');
if (!$editTheme)
if (!$editTheme) {
$editTheme = static::getActiveTheme()->getDirName();
}
$apiResult = Event::fire('cms.editTheme', [], true);
if ($apiResult !== null)
if ($apiResult !== null) {
$editTheme = $apiResult;
}
if (!strlen($editTheme))
if (!strlen($editTheme)) {
throw new SystemException(Lang::get('cms::lang.theme.edit.not_set'));
}
$theme = new static;
$theme->load($editTheme);
if (!File::isDirectory($theme->getPath()))
if (!File::isDirectory($theme->getPath())) {
return self::$editThemeCache = null;
}
return self::$editThemeCache = $theme;
}
@ -195,8 +206,9 @@ class Theme
$result = [];
foreach ($it as $fileinfo) {
if (!$fileinfo->isDir() || $fileinfo->isDot())
if (!$fileinfo->isDir() || $fileinfo->isDot()) {
continue;
}
$theme = new static;
$theme->load($fileinfo->getFilename());
@ -212,12 +224,14 @@ class Theme
*/
public function getConfig()
{
if ($this->configCache !== null)
if ($this->configCache !== null) {
return $this->configCache;
}
$path = $this->getPath().'/theme.yaml';
if (!File::exists($path))
if (!File::exists($path)) {
return $this->configCache = [];
}
return $this->configCache = Yaml::parseFile($path);
}
@ -225,14 +239,16 @@ class Theme
/**
* Returns a value from the theme configuration file by its name.
* @param string $name Specifies the configuration parameter name.
* @param mixed $default Specifies the default value to return in case if the parameter doesn't exist in the configuration file.
* @param mixed $default Specifies the default value to return in case if the parameter
* doesn't exist in the configuration file.
* @return mixed Returns the parameter value or a default value
*/
public function getConfigValue($name, $default = null)
{
$config = $this->getConfig();
if (isset($config[$name]))
if (isset($config[$name])) {
return $config[$name];
}
return $default;
}
@ -246,8 +262,9 @@ class Theme
{
$previewPath = '/assets/images/theme-preview.png';
$path = $this->getPath().$previewPath;
if (!File::exists($path))
if (!File::exists($path)) {
return URL::asset('modules/cms/assets/images/default-theme-preview.png');
}
return URL::asset('themes/'.$this->getDirName().$previewPath);
}

View File

@ -28,8 +28,9 @@ class ViewBag extends ComponentBase
public function __call($method, $parameters)
{
if (array_key_exists($method, $this->properties) && !method_exists($this, $method))
if (array_key_exists($method, $this->properties) && !method_exists($this, $method)) {
return $this->properties[$method];
}
return parent::__call($method, $parameters);
}
@ -38,7 +39,7 @@ class ViewBag extends ComponentBase
{
$result = [];
foreach ($this->properties as $name=>$value) {
foreach ($this->properties as $name => $value) {
$result[$name] = [
'title' => $name,
'type' => 'string'

View File

@ -51,32 +51,32 @@ class Index extends Controller
BackendMenu::setContext('October.Cms', 'cms', 'pages');
try {
if (!($theme = Theme::getEditTheme()))
if (!($theme = Theme::getEditTheme())) {
throw new ApplicationException(Lang::get('cms::lang.theme.edit.not_found'));
}
$this->theme = $theme;
new TemplateList($this, 'pageList', function() use ($theme) {
new TemplateList($this, 'pageList', function () use ($theme) {
return Page::listInTheme($theme, true);
});
new TemplateList($this, 'partialList', function() use ($theme) {
new TemplateList($this, 'partialList', function () use ($theme) {
return Partial::listInTheme($theme, true);
});
new TemplateList($this, 'layoutList', function() use ($theme) {
new TemplateList($this, 'layoutList', function () use ($theme) {
return Layout::listInTheme($theme, true);
});
new TemplateList($this, 'contentList', function() use ($theme) {
new TemplateList($this, 'contentList', function () use ($theme) {
return Content::listInTheme($theme, true);
});
new ComponentList($this, 'componentList');
new AssetList($this, 'assetList');
}
catch (Exception $ex) {
} catch (Exception $ex) {
$this->handleError($ex);
}
}
@ -97,8 +97,9 @@ class Index extends Controller
$this->addJs('/modules/backend/formwidgets/codeeditor/assets/vendor/ace/ace.js', 'core');
$aceModes = ['markdown', 'plain_text', 'html', 'less', 'css', 'scss', 'sass', 'javascript'];
foreach ($aceModes as $mode)
foreach ($aceModes as $mode) {
$this->addJs('/modules/backend/formwidgets/codeeditor/assets/vendor/ace/mode-'.$mode.'.js', 'core');
}
$this->bodyClass = 'compact-container side-panel-not-fixed';
$this->pageTitle = 'cms::lang.cms.menu_label';
@ -142,13 +143,15 @@ class Index extends Controller
$settings = $this->upgradeSettings($settings);
$templateData = [];
if ($settings)
if ($settings) {
$templateData['settings'] = $settings;
}
$fields = ['markup', 'code', 'fileName', 'content'];
foreach ($fields as $field) {
if (array_key_exists($field, $_POST))
if (array_key_exists($field, $_POST)) {
$templateData[$field] = Request::input($field);
}
}
if (!empty($templateData['markup']) && Config::get('cms.convertLineEndings', false) === true) {
@ -156,8 +159,9 @@ class Index extends Controller
}
if (!Request::input('templateForceSave') && $template->mtime) {
if (Request::input('templateMtime') != $template->mtime)
if (Request::input('templateMtime') != $template->mtime) {
throw new ApplicationException('mtime-mismatch');
}
}
$template->fill($templateData);
@ -197,8 +201,9 @@ class Index extends Controller
$type = Request::input('type');
$template = $this->createTemplate($type);
if ($type == 'asset')
if ($type == 'asset') {
$template->setInitialPath($this->widget->assetList->getCurrentRelativePath());
}
$widget = $this->makeTemplateFormWidget($type, $template);
@ -225,14 +230,13 @@ class Index extends Controller
$deleted = [];
try {
foreach ($templates as $path=>$selected) {
foreach ($templates as $path => $selected) {
if ($selected) {
$this->loadTemplate($type, $path)->delete();
$deleted[] = $path;
}
}
}
catch (Exception $ex) {
} catch (Exception $ex) {
$error = $ex->getMessage();
}
@ -276,21 +280,26 @@ class Index extends Controller
public function onExpandMarkupToken()
{
if (!$alias = post('tokenName'))
if (!$alias = post('tokenName')) {
throw new ApplicationException(trans('cms::lang.component.no_records'));
}
// Can only expand components at this stage
if ((!$type = post('tokenType')) && $type != 'component')
if ((!$type = post('tokenType')) && $type != 'component') {
return;
}
if (!($names = (array) post('component_names')) || !($aliases = (array) post('component_aliases')))
if (!($names = (array) post('component_names')) || !($aliases = (array) post('component_aliases'))) {
throw new ApplicationException(trans('cms::lang.component.not_found', ['name' => $alias]));
}
if (($index = array_get(array_flip($aliases), $alias, false)) === false)
if (($index = array_get(array_flip($aliases), $alias, false)) === false) {
throw new ApplicationException(trans('cms::lang.component.not_found', ['name' => $alias]));
}
if (!$componentName = array_get($names, $index))
if (!$componentName = array_get($names, $index)) {
throw new ApplicationException(trans('cms::lang.component.not_found', ['name' => $alias]));
}
$manager = ComponentManager::instance();
$componentObj = $manager->makeComponent($componentName);
@ -306,8 +315,9 @@ class Index extends Controller
protected function validateRequestTheme()
{
if ($this->theme->getDirName() != Request::input('theme'))
if ($this->theme->getDirName() != Request::input('theme')) {
throw new ApplicationException(trans('cms::lang.theme.edit.not_match'));
}
}
protected function resolveTypeClassName($type)
@ -320,8 +330,9 @@ class Index extends Controller
'asset' => '\Cms\Classes\Asset',
];
if (!array_key_exists($type, $types))
if (!array_key_exists($type, $types)) {
throw new ApplicationException(trans('cms::lang.template.invalid_type'));
}
return $types[$type];
}
@ -330,8 +341,9 @@ class Index extends Controller
{
$class = $this->resolveTypeClassName($type);
if (!($template = call_user_func(array($class, 'load'), $this->theme, $path)))
if (!($template = call_user_func(array($class, 'load'), $this->theme, $path))) {
throw new ApplicationException(trans('cms::lang.template.not_found'));
}
return $template;
}
@ -340,8 +352,9 @@ class Index extends Controller
{
$class = $this->resolveTypeClassName($type);
if (!($template = new $class($this->theme)))
if (!($template = new $class($this->theme))) {
throw new ApplicationException(trans('cms::lang.template.not_found'));
}
return $template;
}
@ -350,16 +363,18 @@ class Index extends Controller
{
if ($type == 'page') {
$result = $template->title ?: $template->getFileName();
if (!$result)
if (!$result) {
$result = trans('cms::lang.page.new');
}
return $result;
}
if ($type == 'partial' || $type == 'layout' || $type == 'content' || $type == 'asset') {
$result = in_array($type, ['asset', 'content']) ? $template->getFileName() : $template->getBaseFileName();
if (!$result)
if (!$result) {
$result = trans('cms::lang.'.$type.'.new');
}
return $result;
}
@ -377,8 +392,9 @@ class Index extends Controller
'asset' => '@/modules/cms/classes/asset/fields.yaml',
];
if (!array_key_exists($type, $formConfigs))
if (!array_key_exists($type, $formConfigs)) {
throw new ApplicationException(trans('cms::lang.template.not_found'));
}
$widgetConfig = $this->makeConfig($formConfigs[$type]);
$widgetConfig->model = $template;
@ -391,23 +407,27 @@ class Index extends Controller
protected function upgradeSettings($settings)
{
if (!array_key_exists('component_properties', $_POST))
if (!array_key_exists('component_properties', $_POST)) {
return $settings;
}
if (!array_key_exists('component_names', $_POST) || !array_key_exists('component_aliases', $_POST))
if (!array_key_exists('component_names', $_POST) || !array_key_exists('component_aliases', $_POST)) {
throw new ApplicationException(trans('cms::lang.component.invalid_request'));
}
$count = count($_POST['component_properties']);
if (count($_POST['component_names']) != $count || count($_POST['component_aliases']) != $count)
if (count($_POST['component_names']) != $count || count($_POST['component_aliases']) != $count) {
throw new ApplicationException(trans('cms::lang.component.invalid_request'));
}
for ($index = 0; $index < $count; $index ++) {
$componentName = $_POST['component_names'][$index];
$componentAlias = $_POST['component_aliases'][$index];
$section = $componentName;
if ($componentAlias != $componentName)
if ($componentAlias != $componentName) {
$section .= ' '.$componentAlias;
}
$properties = json_decode($_POST['component_properties'][$index], true);
unset($properties['oc.alias']);
@ -431,5 +451,4 @@ class Index extends Controller
$markup = str_replace("\r", "\n", $markup);
return $markup;
}
}

View File

@ -36,7 +36,6 @@ class Themes extends Controller
public function index()
{
}
public function index_onSetActiveTheme()

View File

@ -30,8 +30,9 @@ class Components extends FormWidgetBase
{
$result = [];
if (!isset($this->model->settings['components']))
if (!isset($this->model->settings['components'])) {
return $result;
}
$manager = ComponentManager::instance();
$manager->listComponents();
@ -50,12 +51,11 @@ class Components extends FormWidgetBase
$plugin = $manager->findComponentPlugin($componentObj);
if ($plugin) {
$pluginDetails = $plugin->pluginDetails();
if (isset($pluginDetails['icon']))
if (isset($pluginDetails['icon'])) {
$componentObj->pluginIcon = $pluginDetails['icon'];
}
}
}
catch (Exception $ex) {
} catch (Exception $ex) {
$componentObj = new UnknownComponent(null, $properties, $ex->getMessage());
$componentObj->alias = $alias;
$componentObj->pluginIcon = 'icon-bug';

View File

@ -3,7 +3,7 @@
/*
* Register CMS routes before all user routes.
*/
App::before(function($request) {
App::before(function ($request) {
/*
* The CMS module intercepts all URLs that were not

View File

@ -49,7 +49,11 @@ class ComponentTokenParser extends Twig_TokenParser
break;
default:
throw new Twig_Error_Syntax(sprintf('Invalid syntax in the partial tag. Line %s', $lineno), $stream->getCurrent()->getLine(), $stream->getFilename());
throw new Twig_Error_Syntax(
sprintf('Invalid syntax in the partial tag. Line %s', $lineno),
$stream->getCurrent()->getLine(),
$stream->getFilename()
);
break;
}
}

View File

@ -35,7 +35,15 @@ class DebugExtension extends Twig_Extension
*/
protected $commentMap = [];
protected $blockMethods = ['componentDetails', 'defineProperties', 'getPropertyOptions', 'offsetExists', 'offsetGet', 'offsetSet', 'offsetUnset'];
protected $blockMethods = [
'componentDetails',
'defineProperties',
'getPropertyOptions',
'offsetExists',
'offsetGet',
'offsetSet',
'offsetUnset'
];
/**
* Creates the extension instance.
@ -54,7 +62,11 @@ class DebugExtension extends Twig_Extension
public function getFunctions()
{
return array(
new Twig_SimpleFunction('dump', [$this, 'runDump'], array('is_safe' => ['html'], 'needs_context' => true, 'needs_environment' => true)),
new Twig_SimpleFunction('dump', [$this, 'runDump'], array(
'is_safe' => ['html'],
'needs_context' => true,
'needs_environment' => true
)),
);
}
@ -84,8 +96,7 @@ class DebugExtension extends Twig_Extension
}
$result .= $this->dump($vars, static::PAGE_CAPTION);
}
else {
} else {
$this->variablePrefix = false;
for ($i = 2; $i < $count; $i++) {
$var = func_get_arg($i);
@ -124,19 +135,21 @@ class DebugExtension extends Twig_Extension
$info = [];
if (!is_array($variables)) {
if ($variables instanceof Paginator)
if ($variables instanceof Paginator) {
$variables = $this->paginatorToArray($variables);
elseif (is_object($variables))
} elseif (is_object($variables)) {
$variables = $this->objectToArray($variables);
else
} else {
$variables = [$variables];
}
}
$output = [];
$output[] = '<table>';
if ($caption)
if ($caption) {
$output[] = $this->makeTableHeader($caption);
}
foreach ($variables as $key => $item) {
$output[] = $this->makeTableRow($key, $item);
@ -185,15 +198,12 @@ class DebugExtension extends Twig_Extension
{
if ($this->variablePrefix === true) {
$output = '{{ <span>%s</span> }}';
}
elseif (is_array($this->variablePrefix)) {
} elseif (is_array($this->variablePrefix)) {
$prefix = implode('.', $this->variablePrefix);
$output = '{{ <span>'.$prefix.'.%s</span> }}';
}
elseif ($this->variablePrefix) {
} elseif ($this->variablePrefix) {
$output = '{{ <span>'.$this->variablePrefix.'.%s</span> }}';
}
else {
} else {
$output = '%s';
}
@ -228,8 +238,9 @@ class DebugExtension extends Twig_Extension
protected function getType($variable)
{
$type = gettype($variable);
if ($type == 'string' && substr($variable, 0, 12) == '___METHOD___')
if ($type == 'string' && substr($variable, 0, 12) == '___METHOD___') {
return 'method';
}
return $type;
}
@ -244,17 +255,15 @@ class DebugExtension extends Twig_Extension
$class = get_class($variable);
$label = class_basename($variable);
if ($variable instanceof ComponentBase)
if ($variable instanceof ComponentBase) {
$label = '<strong>Component</strong>';
elseif ($variable instanceof Collection)
} elseif ($variable instanceof Collection) {
$label = 'Collection('.$variable->count().')';
elseif ($variable instanceof Paginator)
} elseif ($variable instanceof Paginator) {
$label = 'Paged Collection('.$variable->count().')';
elseif ($variable instanceof Model)
} elseif ($variable instanceof Model) {
$label = 'Model';
}
return '<abbr title="'.e($class).'">'.$label.'</abbr>';
}
@ -268,17 +277,21 @@ class DebugExtension extends Twig_Extension
{
$type = $this->getType($variable);
if ($type == 'method')
if ($type == 'method') {
return $this->evalMethodDesc($variable);
}
if (isset($this->commentMap[$key]))
if (isset($this->commentMap[$key])) {
return $this->commentMap[$key];
}
if ($type == 'array')
if ($type == 'array') {
return $this->evalArrDesc($variable);
}
if ($type == 'object')
if ($type == 'object') {
return $this->evalObjDesc($variable);
}
return '';
}
@ -291,8 +304,9 @@ class DebugExtension extends Twig_Extension
protected function evalMethodDesc($variable)
{
$parts = explode('|', $variable);
if (count($parts) < 2)
if (count($parts) < 2) {
return null;
}
$method = $parts[1];
return isset($this->commentMap[$method]) ? $this->commentMap[$method] : null;
@ -370,13 +384,25 @@ class DebugExtension extends Twig_Extension
$methods = [];
foreach ($info->getMethods() as $method) {
if (!$method->isPublic()) continue; // Only public
if ($method->class != $class) continue; // Only locals
if (!$method->isPublic()) {
continue; // Only public
}
if ($method->class != $class) {
continue; // Only locals
}
$name = $method->getName();
if (in_array($name, $this->blockMethods)) continue; // Blocked methods
if (preg_match('/^on[A-Z]{1}[\w+]*$/', $name)) continue; // AJAX methods
if (preg_match('/^get[A-Z]{1}[\w+]*Options$/', $name)) continue; // getSomethingOptions
if (substr($name, 0, 1) == '_') continue; // Magic/hidden method
if (in_array($name, $this->blockMethods)) {
continue; // Blocked methods
}
if (preg_match('/^on[A-Z]{1}[\w+]*$/', $name)) {
continue; // AJAX methods
}
if (preg_match('/^get[A-Z]{1}[\w+]*Options$/', $name)) {
continue; // getSomethingOptions
}
if (substr($name, 0, 1) == '_') {
continue; // Magic/hidden method
}
$name .= '()';
$methods[$name] = '___METHOD___|'.$name;
$this->commentMap[$name] = $this->evalDocBlock($method);
@ -384,8 +410,12 @@ class DebugExtension extends Twig_Extension
$vars = [];
foreach ($info->getProperties() as $property) {
if (!$property->isPublic()) continue; // Only public
if ($property->class != $class) continue; // Only locals
if (!$property->isPublic()) {
continue; // Only public
}
if ($property->class != $class) {
continue; // Only locals
}
$name = $property->getName();
$vars[$name] = $object->{$name};
$this->commentMap[$name] = $this->evalDocBlock($property);
@ -426,8 +456,9 @@ class DebugExtension extends Twig_Extension
];
$type = gettype($variable);
if ($type == 'NULL')
if ($type == 'NULL') {
$css['color'] = '#999';
}
return $this->arrayToCss($css);
}
@ -484,5 +515,4 @@ class DebugExtension extends Twig_Extension
return join('; ', $strings);
}
}

View File

@ -151,8 +151,9 @@ class Extension extends Twig_Extension
*/
public function placeholderFunction($name, $default = null)
{
if (($result = Block::get($name)) === null)
if (($result = Block::get($name)) === null) {
return null;
}
$result = str_replace('<!-- X_OCTOBER_DEFAULT_BLOCK_CONTENT -->', trim($default), $result);
return $result;
@ -199,8 +200,9 @@ class Extension extends Twig_Extension
*/
public function displayBlock($name, $default = null)
{
if (($result = Block::placeholder($name)) === null)
if (($result = Block::placeholder($name)) === null) {
return $default;
}
$result = str_replace('<!-- X_OCTOBER_DEFAULT_BLOCK_CONTENT -->', trim($default), $result);
return $result;

Some files were not shown because too many files have changed in this diff Show More