text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Config.php Parameters — ownCloud Server Administration Manual 8.1 documentation</title>

    <link rel="stylesheet" href="../_static/style.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/style.css" type="text/css" />
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />

    <link rel="top" title="ownCloud Server Administration Manual 8.1 documentation" href="../index.html" />
    <link rel="up" title="ownCloud Server Configuration" href="index.html" />
    <link rel="next" title="Email Configuration" href="email_configuration.html" />
    <link rel="prev" title="Defining Background Jobs" href="background_jobs_configuration.html" />

ownCloud Server Administration Manual

Table of Contents

ownCloud 8.1 Server Administration Manual Introduction

ownCloud 8.1 Release Notes

What’s New for Admins in ownCloud 8

Installation

User Management

File Sharing and Management

ownCloud Server Configuration

Warnings on Admin Page

Using the occ Command

Configuring the Activity App

Configuring the ClamAV Antivirus Scanner

Automatic Configuration Setup

Defining Background Jobs

Config.php Parameters

Default Parameters

Default config.php Examples

User Experience

Mail Parameters

Proxy Configurations

Deleted Items (trash bin)

ownCloud Verifications

Logging

Alternate Code Locations

Apps

Previews

LDAP

Maintenance

SSL

Miscellaneous

Memory caching backend configuration

All other config options

App config options

Email Configuration

Linking External Sites

JavaScript and CSS Asset Management

Knowledge Base Configuration

Language Configuration

Logging Configuration

Hardening and Security Guidance

Server Tuning & Performance Tips

Reverse Proxy Configuration

Enabling Full-Text Search

Using Third Party PHP Components

Database Configuration

Maintenance

Operations

Issues and Troubleshooting

ownCloud Videos

Enterprise Subscription Installation (ES Only)

Creating Branded ownCloud Clients (ES only)

External Storage (ES only)

User Management (ES only)

Enabling Anonymous Uploads with Files Drop (ES Only)

Config.php Parameters¶

ownCloud uses the <tt class="docutils literal">config/config.php</tt> file to control server operations.
<tt class="docutils literal">config/config.sample.php</tt> lists all the configurable parameters within
ownCloud. This document provides a more detailed reference. Many options are
configurable on your Admin page, so it is usually not necessary to edit
<tt class="docutils literal">config/config.php</tt>.

Default Parameters¶

These parameters are configured by the ownCloud installer, and are required
for your ownCloud server to operate.

'instanceid' => '',

This is a unique identifier for your ownCloud installation, created
automatically by the installer. This example is for documentation only,
and you should never use it because it will not work. A valid <tt class="docutils literal">instanceid</tt>
is created when you install ownCloud.

‘instanceid’ => ‘d3c944a9a’,

'passwordsalt' => '',

The salt used to hash all passwords, auto-generated by the ownCloud
installer. (There are also per-user salts.) If you lose this salt you lose
all your passwords. This example is for documentation only, and you should
never use it.

'hashingCost' => 10,

The hashing cost used by hashes generated by ownCloud
Using a higher value requires more time and CPU power to calculate the hashes

'trusted_domains' =>
  array (
    'demo.example.org',
    'otherdomain.example.org',
  ),

Your list of trusted domains that users can log into. Specifying trusted
domains prevents host header poisoning. Do not remove this, as it performs
necessary security checks.

'datadirectory' => '/var/www/owncloud/data',

Where user files are stored; this defaults to <tt class="docutils literal">data/</tt> in the ownCloud
directory. The SQLite database is also stored here, when you use SQLite.

(SQLite is available only in ownCloud Community Edition)

'version' => '',

The current version number of your ownCloud installation. This is set up
during installation and update, so you shouldn’t need to change it.

'dbtype' => 'sqlite',

Identifies the database used with this installation. See also config option
<tt class="docutils literal">supportedDatabases</tt>

Available:

sqlite (SQLite3 - Community Edition Only)

mysql (MySQL/MariaDB)

pgsql (PostgreSQL)

oci (Oracle - Enterprise Edition Only)

mssql (Microsoft SQL Server - Enterprise Edition Only)

'dbhost' => '',

Your host server name, for example <tt class="docutils literal">localhost</tt>, <tt class="docutils literal">hostname</tt>,
<tt class="docutils literal">hostname.example.com</tt>, or the IP address. To specify a port use
<tt class="docutils literal">hostname:####</tt>; to specify a Unix socket use
<tt class="docutils literal">localhost:/path/to/socket</tt>.

'dbname' => 'owncloud',

The name of the ownCloud database, which is set during installation. You
should not need to change this.

'dbuser' => '',

The user that ownCloud uses to write to the database. This must be unique
across ownCloud instances using the same SQL database. This is set up during
installation, so you shouldn’t need to change it.

'dbpassword' => '',

The password for the database user. This is set up during installation, so
you shouldn’t need to change it.

'dbtableprefix' => '',

Prefix for the ownCloud tables in the database.

'dbdriveroptions' => array(
        PDO::MYSQL_ATTR_SSL_CA => '/file/path/to/ca_cert.pem',
),

Additional driver options for the database connection, eg. to enable SSL
encryption in MySQL.

'sqlite.journal_mode' => 'DELETE',

sqlite3 journal mode can be specified using this config parameter - can be
‘WAL’ or ‘DELETE’ see for more details https://www.sqlite.org/wal.html

'installed' => false,

Indicates whether the ownCloud instance was installed successfully; <tt class="docutils literal">true</tt>
indicates a successful installation, and <tt class="docutils literal">false</tt> indicates an unsuccessful
installation.
.. DEFAULT_SECTION_END
.. Generated content above. Don’t change this.

Default config.php Examples¶

When you use SQLite as your ownCloud database, your <tt class="docutils literal">config.php</tt> looks like
this after installation. The SQLite database is stored in your ownCloud
<tt class="docutils literal">data/</tt> directory. SQLite is a simple, lightweight embedded database that
is good for testing and for simple installations, but for production ownCloud
systems you should use MySQL, MariaDB, or PosgreSQL.

<?php
$CONFIG = array (
  'instanceid' => 'occ6f7365735',
  'passwordsalt' => '2c5778476346786306303',
  'trusted_domains' =>
  array (
    0 => 'localhost',
    1 => 'studio',
  ),
  'datadirectory' => '/var/www/owncloud/data',
  'dbtype' => 'sqlite3',
  'version' => '7.0.2.1',
  'installed' => true,
);

This example is from a new ownCloud installation using MariaDB:

<?php
$CONFIG = array (
  'instanceid' => 'oc8c0fd71e03',
  'passwordsalt' => '515a13302a6b3950a9d0fdb970191a',
  'trusted_domains' =>
  array (
    0 => 'localhost',
    1 => 'studio',
    2 => '192.168.10.155'
  ),
  'datadirectory' => '/var/www/owncloud/data',
  'dbtype' => 'mysql',
   'version' => '7.0.2.1',
  'dbname' => 'owncloud',
  'dbhost' => 'localhost',
  'dbtableprefix' => 'oc_',
  'dbuser' => 'oc_carla',
  'dbpassword' => '67336bcdf7630dd80b2b81a413d07',
  'installed' => true,
);

User Experience¶

These optional parameters control some aspects of the user interface. Default
values, where present, are shown.

'default_language' => 'en',

This sets the default language on your ownCloud server, using ISO_639-1
language codes such as <tt class="docutils literal">en</tt> for English, <tt class="docutils literal">de</tt> for German, and <tt class="docutils literal">fr</tt> for
French. It overrides automatic language detection on public pages like login
or shared items. User’s language preferences configured under “personal ->
language” override this setting after they have logged in.

'defaultapp' => 'files',

Set the default app to open on login. Use the app names as they appear in the
URL after clicking them in the Apps menu, such as documents, calendar, and
gallery. You can use a comma-separated list of app names, so if the first
app is not enabled for a user then ownCloud will try the second one, and so
on. If no enabled apps are found it defaults to the Files app.

'knowledgebaseenabled' => true,

<tt class="docutils literal">true</tt> enables the Help menu item in the user menu (top right of the
ownCloud Web interface). <tt class="docutils literal">false</tt> removes the Help item.

'enable_avatars' => true,

<tt class="docutils literal">true</tt> enables avatars, or user profile photos. These appear on the User
page, on user’s Personal pages and are used by some apps (contacts, mail,
etc). <tt class="docutils literal">false</tt> disables them.

'allow_user_to_change_display_name' => true,

<tt class="docutils literal">true</tt> allows users to change their display names (on their Personal
pages), and <tt class="docutils literal">false</tt> prevents them from changing their display names.

'remember_login_cookie_lifetime' => 60*60*24*15,

Lifetime of the remember login cookie, which is set when the user clicks the
<tt class="docutils literal">remember</tt> checkbox on the login screen. The default is 15 days, expressed
in seconds.

'session_lifetime' => 60 * 60 * 24,

The lifetime of a session after inactivity; the default is 24 hours,
expressed in seconds.

'session_keepalive' => true,

Enable or disable session keep-alive when a user is logged in to the Web UI.

Enabling this sends a “heartbeat” to the server to keep it from timing out.

'skeletondirectory' => '',

The directory where the skeleton files are located. These files will be
copied to the data directory of new users. Leave empty to not copy any
skeleton files.

'user_backends' => array(
        array(
                'class' => 'OC_User_IMAP',
                'arguments' => array('{imap.gmail.com:993/imap/ssl}INBOX')
        )
),

The <tt class="docutils literal">user_backends</tt> app (which needs to be enabled first) allows you to
configure alternate authentication backends. Supported backends are:
IMAP (OC_User_IMAP), SMB (OC_User_SMB), and FTP (OC_User_FTP).

Mail Parameters¶

These configure the email settings for ownCloud notifications and password
resets.

'mail_domain' => 'example.com',

The return address that you want to appear on emails sent by the ownCloud
server, for example <tt class="docutils literal">oc-admin@example.com</tt>, substituting your own domain,
of course.

'mail_from_address' => 'owncloud',

FROM address that overrides the built-in <tt class="docutils literal">sharing-noreply</tt> and
<tt class="docutils literal">lostpassword-noreply</tt> FROM addresses.

'mail_smtpdebug' => false,

Enable SMTP class debugging.

'mail_smtpmode' => 'sendmail',

Which mode to use for sending mail: <tt class="docutils literal">sendmail</tt>, <tt class="docutils literal">smtp</tt>, <tt class="docutils literal">qmail</tt> or
<tt class="docutils literal">php</tt>.

If you are using local or remote SMTP, set this to <tt class="docutils literal">smtp</tt>.

If you are using PHP mail you must have an installed and working email system
on the server. The program used to send email is defined in the <tt class="docutils literal">php.ini</tt>
file.

For the <tt class="docutils literal">sendmail</tt> option you need an installed and working email system on
the server, with <tt class="docutils literal">/usr/sbin/sendmail</tt> installed on your Unix system.

For <tt class="docutils literal">qmail</tt> the binary is /var/qmail/bin/sendmail, and it must be installed
on your Unix system.

'mail_smtphost' => '127.0.0.1',

This depends on <tt class="docutils literal">mail_smtpmode</tt>. Specified the IP address of your mail
server host. This may contain multiple hosts separated by a semi-colon. If
you need to specify the port number append it to the IP address separated by
a colon, like this: <tt class="docutils literal">127.0.0.1:24</tt>.

'mail_smtpport' => 25,

This depends on <tt class="docutils literal">mail_smtpmode</tt>. Specify the port for sending mail.

'mail_smtptimeout' => 10,

This depends on <tt class="docutils literal">mail_smtpmode</tt>. This set an SMTP server timeout, in
seconds. You may need to increase this if you are running an anti-malware or
spam scanner.

'mail_smtpsecure' => '',

This depends on <tt class="docutils literal">mail_smtpmode</tt>. Specify when you are using <tt class="docutils literal">ssl</tt> or
<tt class="docutils literal">tls</tt>, or leave empty for no encryption.

'mail_smtpauth' => false,

This depends on <tt class="docutils literal">mail_smtpmode</tt>. Change this to <tt class="docutils literal">true</tt> if your mail
server requires authentication.

'mail_smtpauthtype' => 'LOGIN',

This depends on <tt class="docutils literal">mail_smtpmode</tt>. If SMTP authentication is required, choose
the authentication type as <tt class="docutils literal">LOGIN</tt> (default) or <tt class="docutils literal">PLAIN</tt>.

'mail_smtpname' => '',

This depends on <tt class="docutils literal">mail_smtpauth</tt>. Specify the username for authenticating to
the SMTP server.

'mail_smtppassword' => '',

This depends on <tt class="docutils literal">mail_smtpauth</tt>. Specify the password for authenticating to
the SMTP server.

Proxy Configurations¶

'overwritehost' => '',

The automatic hostname detection of ownCloud can fail in certain reverse
proxy and CLI/cron situations. This option allows you to manually override
the automatic detection; for example <tt class="docutils literal">www.example.com</tt>, or specify the port
<tt class="docutils literal">www.example.com:8080</tt>.

'overwriteprotocol' => '',

When generating URLs, ownCloud attempts to detect whether the server is
accessed via <tt class="docutils literal">https</tt> or <tt class="docutils literal">http</tt>. However, if ownCloud is behind a proxy
and the proxy handles the <tt class="docutils literal">https</tt> calls, ownCloud would not know that
<tt class="docutils literal">ssl</tt> is in use, which would result in incorrect URLs being generated.

Valid values are <tt class="docutils literal">http</tt> and <tt class="docutils literal">https</tt>.

'overwritewebroot' => '',

ownCloud attempts to detect the webroot for generating URLs automatically.

For example, if <tt class="docutils literal">www.example.com/owncloud</tt> is the URL pointing to the
ownCloud instance, the webroot is <tt class="docutils literal">/owncloud</tt>. When proxies are in use, it
may be difficult for ownCloud to detect this parameter, resulting in invalid
URLs.

'overwritecondaddr' => '',

This option allows you to define a manual override condition as a regular
expression for the remote IP address. For example, defining a range of IP
addresses starting with <tt class="docutils literal">10.0.0.</tt> and ending with 1 to 3:
<tt class="docutils literal">^10\.0\.0\.[1-3]$</tt>

'overwrite.cli.url' => '',

Use this configuration parameter to specify the base url for any urls which
are generated within ownCloud using any kind of command line tools (cron or
occ). The value should contain the full base URL:
<tt class="docutils literal">https://www.example.com/owncloud</tt>

'proxy' => '',

The URL of your proxy server, for example <tt class="docutils literal">proxy.example.com:8081</tt>.

'proxyuserpwd' => '',

The optional authentication for the proxy to use to connect to the internet.

The format is: <tt class="docutils literal">username:password</tt>.

Deleted Items (trash bin)¶

These parameters control the Deleted files app.

'trashbin_retention_obligation' => 30,

When the trash bin app is enabled (default), this is the number of days a
file will be kept in the trash bin. Default is 30 days.

'trashbin_auto_expire' => true,

Disable or enable auto-expiration for the trash bin. By default
auto-expiration is enabled.

ownCloud Verifications¶

ownCloud performs several verification checks. There are two options,
<tt class="docutils literal">true</tt> and <tt class="docutils literal">false</tt>.

'appcodechecker' => true,

Checks an app before install whether it uses private APIs instead of the
proper public APIs. If this is set to true it will only allow to install or
enable apps that pass this check.

'updatechecker' => true,

Check if ownCloud is up-to-date and shows a notification if a new version is
available.

'has_internet_connection' => true,

Is ownCloud connected to the Internet or running in a closed network?

'check_for_working_webdav' => true,

Allows ownCloud to verify a working WebDAV connection. This is done by
attempting to make a WebDAV request from PHP.

'check_for_working_htaccess' => true,

This is a crucial security check on Apache servers that should always be set
to <tt class="docutils literal">true</tt>. This verifies that the <tt class="docutils literal">.htaccess</tt> file is writable and works.

If it is not, then any options controlled by <tt class="docutils literal">.htaccess</tt>, such as large
file uploads, will not work. It also runs checks on the <tt class="docutils literal">data/</tt> directory,
which verifies that it can’t be accessed directly through the web server.

'config_is_read_only' => false,

In certain environments it is desired to have a read-only config file.

When this switch is set to <tt class="docutils literal">true</tt> ownCloud will not verify whether the
configuration is writable. However, it will not be possible to configure
all options via the web-interface. Furthermore, when updating ownCloud
it is required to make the config file writable again for the update
process.

Logging¶

'log_type' => 'owncloud',

By default the ownCloud logs are sent to the <tt class="docutils literal">owncloud.log</tt> file in the
default ownCloud data directory.

If syslogging is desired, set this parameter to <tt class="docutils literal">syslog</tt>.
Setting this parameter to <tt class="docutils literal">errorlog</tt> will use the PHP error_log function
for logging.

'logfile' => 'owncloud.log',

Change the ownCloud logfile name from <tt class="docutils literal">owncloud.log</tt> to something else.

'loglevel' => 2,

Loglevel to start logging at. Valid values are: 0 = Debug, 1 = Info, 2 =
Warning, 3 = Error. The default value is Warning.

'log.condition' => [
        'shared_secret' => '57b58edb6637fe3059b3595cf9c41b9',
        'users' => ['sample-user'],
        'apps' => ['files'],
],

Log condition for log level increase based on conditions. Once one of these
conditions is met, the required log level is set to debug. This allows to
debug specific requests, users or apps

Supported conditions:

<tt class="docutils literal">shared_secret</tt>: if a request parameter with the name log_secret is set to

this value the condition is met

<tt class="docutils literal">users</tt>:  if the current request is done by one of the specified users,

this condition is met

<tt class="docutils literal">apps</tt>:   if the log message is invoked by one of the specified apps,

this condition is met

Defaults to an empty array.

'logdateformat' => 'F d, Y H:i:s',

This uses PHP.date formatting; see http://php.net/manual/en/function.date.php

'logtimezone' => 'Europe/Berlin',

The default timezone for logfiles is UTC. You may change this; see
http://php.net/manual/en/timezones.php

'log_query' => false,

Append all database queries and parameters to the log file. Use this only for
debugging, as your logfile will become huge.

'cron_log' => true,

Log successful cron runs.

'cron.lockfile.location' => '',

Location of the lock file for cron executions can be specified here.

Default is within the tmp directory. The file is named in the following way:
owncloud-server-$INSTANCEID-cron.lock
where $INSTANCEID is the string specified in the instanceid field.
Because the cron lock file is accessed in regular intervals, it may prevent
enabled disk drives from spinning down. A different location for this file
can solve such issues.

'log_rotate_size' => false,

Enables log rotation and limits the total size of logfiles. The default is 0,
or no rotation. Specify a size in bytes, for example 104857600 (100 megabytes
= 100 * 1024 * 1024 bytes). A new logfile is created with a new name when the
old logfile reaches your limit. The total size of all logfiles is double the
<tt class="docutils literal">log_rotate_sizerotation</tt> value.

Alternate Code Locations¶

Some of the ownCloud code may be stored in alternate locations.

'3rdpartyroot' => '',

ownCloud uses some 3rd party PHP components to provide certain functionality.

These components are shipped as part of the software package and reside in
<tt class="docutils literal">owncloud/3rdparty</tt>. Use this option to configure a different location.

'3rdpartyurl' => '',

If you have an alternate <tt class="docutils literal">3rdpartyroot</tt>, you must also configure the URL as
seen by a Web browser.

'customclient_desktop' =>
        'http://owncloud.org/sync-clients/',
'customclient_android' =>
        'https://play.google.com/store/apps/details?id=com.owncloud.android',
'customclient_ios' =>
        'https://itunes.apple.com/us/app/owncloud/id543672169?mt=8',

This section is for configuring the download links for ownCloud clients, as
seen in the first-run wizard and on Personal pages.

Apps¶

Options for the Apps folder, Apps store, and App code checker.

'appstoreenabled' => true,

When enabled, admins may install apps from the ownCloud app store.

The app store is disabled by default for ownCloud Enterprise Edition

'appstoreurl' => 'https://api.owncloud.com/v1',

The URL of the appstore to use.

'appstore.experimental.enabled' => false,

Whether to show experimental apps in the appstore interface

Experimental apps are not checked for security issues and are new or known
to be unstable and under heavy development. Installing these can cause data
loss or security breaches.

'apps_paths' => array(
        array(
                'path'=> '/var/www/owncloud/apps',
                'url' => '/apps',
                'writable' => true,
        ),
),

Use the <tt class="docutils literal">apps_paths</tt> parameter to set the location of the Apps directory,
which should be scanned for available apps, and where user-specific apps
should be installed from the Apps store. The <tt class="docutils literal">path</tt> defines the absolute
file system path to the app folder. The key <tt class="docutils literal">url</tt> defines the HTTP web path
to that folder, starting from the ownCloud web root. The key <tt class="docutils literal">writable</tt>
indicates if a web server can write files to that folder.

'appcodechecker' => true,

Checks an app before install whether it uses private APIs instead of the
proper public APIs. If this is set to true it will only allow to install or
enable apps that pass this check.

Previews¶

ownCloud supports previews of image files, the covers of MP3 files, and text
files. These options control enabling and disabling previews, and thumbnail
size.

'enable_previews' => true,

By default, ownCloud can generate previews for the following filetypes:

Images files

Covers of MP3 files

Text documents

Valid values are <tt class="docutils literal">true</tt>, to enable previews, or
<tt class="docutils literal">false</tt>, to disable previews

'preview_max_x' => 2048,

The maximum width, in pixels, of a preview. A value of <tt class="docutils literal">null</tt> means there
is no limit.

'preview_max_y' => 2048,

The maximum height, in pixels, of a preview. A value of <tt class="docutils literal">null</tt> means there
is no limit.

'preview_max_scale_factor' => 10,

If a lot of small pictures are stored on the ownCloud instance and the
preview system generates blurry previews, you might want to consider setting
a maximum scale factor. By default, pictures are upscaled to 10 times the
original size. A value of <tt class="docutils literal">1</tt> or <tt class="docutils literal">null</tt> disables scaling.

'preview_max_filesize_image' => 50,

max file size for generating image previews with imagegd (default behaviour)
If the image is bigger, it’ll try other preview generators,
but will most likely show the default mimetype icon

Value represents the maximum filesize in megabytes
Default is 50
Set to -1 for no limit

'preview_libreoffice_path' => '/usr/bin/libreoffice',

custom path for LibreOffice/OpenOffice binary

'preview_office_cl_parameters' =>
        ' --headless --nologo --nofirststartwizard --invisible --norestore '.
        '-convert-to pdf -outdir ',

Use this if LibreOffice/OpenOffice requires additional arguments.

'enabledPreviewProviders' => array(
        'OC\Preview\PNG',
        'OC\Preview\JPEG',
        'OC\Preview\GIF',
        'OC\Preview\BMP',
        'OC\Preview\XBitmap',
        'OC\Preview\MP3',
        'OC\Preview\TXT',
        'OC\Preview\MarkDown'
),

Only register providers that have been explicitly enabled

The following providers are enabled by default:

OC\Preview\PNG

OC\Preview\JPEG

OC\Preview\GIF

OC\Preview\BMP

OC\Preview\XBitmap

OC\Preview\MarkDown

OC\Preview\MP3

OC\Preview\TXT

The following providers are disabled by default due to performance or privacy
concerns:

OC\Preview\Illustrator

OC\Preview\Movie

OC\Preview\MSOffice2003

OC\Preview\MSOffice2007

OC\Preview\MSOfficeDoc

OC\Preview\OpenDocument

OC\Preview\PDF

OC\Preview\Photoshop

OC\Preview\Postscript

OC\Preview\StarOffice

OC\Preview\SVG

OC\Preview\TIFF

OC\Preview\Font

Note

Troubleshooting steps for the MS Word previews are available
at the Configuring the Collaborative Documents App
section of the Administrators Manual.

The following providers are not available in Microsoft Windows:

OC\Preview\Movie

OC\Preview\MSOfficeDoc

OC\Preview\MSOffice2003

OC\Preview\MSOffice2007

OC\Preview\OpenDocument

OC\Preview\StarOffice

LDAP¶

Global settings used by LDAP User and Group Backend

'ldapUserCleanupInterval' => 51,

defines the interval in minutes for the background job that checks user
existance and marks them as ready to be cleaned up. The number is always
minutes. Setting it to 0 disables the feature.

See command line (occ) methods ldap:show-remnants and user:delete

Maintenance¶

These options are for halting user activity when you are performing server
maintenance.

'maintenance' => false,

Enable maintenance mode to disable ownCloud

If you want to prevent users to login to ownCloud before you start doing some
maintenance work, you need to set the value of the maintenance parameter to
true. Please keep in mind that users who are already logged-in are kicked out
of ownCloud instantly.

'singleuser' => false,

When set to <tt class="docutils literal">true</tt>, the ownCloud instance will be unavailable for all users
who are not in the <tt class="docutils literal">admin</tt> group.

SSL¶

'openssl' => array(
        'config' => '/absolute/location/of/openssl.cnf',
),

Extra SSL options to be used for configuration.

Miscellaneous¶

'blacklisted_files' => array('.htaccess'),

Blacklist a specific file or files and disallow the upload of files
with this name. <tt class="docutils literal">.htaccess</tt> is blocked by default.

WARNING: USE THIS ONLY IF YOU KNOW WHAT YOU ARE DOING.

'share_folder' => '/',

Define a default folder for shared files and folders other than root.

'theme' => '',

If you are applying a theme to ownCloud, enter the name of the theme here.

The default location for themes is <tt class="docutils literal">owncloud/themes/</tt>.

'cipher' => 'AES-256-CFB',

The default cipher for encrypting files. Currently AES-128-CFB and
AES-256-CFB are supported.

'minimum.supported.desktop.version' => '1.7.0',

The minimum ownCloud desktop client version that will be allowed to sync with
this server instance. All connections made from earlier clients will be denied
by the server. Defaults to the minimum officially supported ownCloud version at
the time of release of this server version.

When changing this, note that older unsupported versions of the ownCloud desktop
client may not function as expected, and could lead to permanent data loss for
clients or other unexpected results.

Memory caching backend configuration¶

Available cache backends:
- OCMemcacheAPC        Alternative PHP Cache backend
- OCMemcacheAPCu       APC user backend
- OCMemcacheArrayCache In-memory array-based backend (not recommended)
- OCMemcacheMemcached  Memcached backend
- OCMemcacheRedis      Redis backend
- OCMemcacheXCache     XCache backend

'memcache.local' => '\OC\Memcache\APCu',

Memory caching backend for locally stored data
Used for host-specific data, e.g. file paths

'memcache.distributed' => '\OC\Memcache\Memcached',

Memory caching backend for distributed data
Used for installation-specific data, e.g. database caching
If unset, defaults to the value of memcache.local

'redis' => array(
        'host' => 'localhost', // can also be a unix domain socket: '/tmp/redis.sock'
        'port' => 6379,
        'timeout' => 0.0,
        'dbindex' => 0, // Optional, if undefined SELECT will not run and will use Redis Server's default DB Index.
),

Connection details for redis to use for memory caching.

'memcached_servers' => array(
        // hostname, port and optional weight. Also see:
        // http://www.php.net/manual/en/memcached.addservers.php
        // http://www.php.net/manual/en/memcached.addserver.php
        array('localhost', 11211),
        //array('other.host.local', 11211),
),

Server details for one or more memcached servers to use for memory caching.

'cache_path' => '',

Location of the cache folder, defaults to <tt class="docutils literal">data/$user/cache</tt> where
<tt class="docutils literal">$user</tt> is the current user. When specified, the format will change to
<tt class="docutils literal">$cache_path/$user</tt> where <tt class="docutils literal">$cache_path</tt> is the configured cache directory
and <tt class="docutils literal">$user</tt> is the user.

'quota_include_external_storage' => false,

EXPERIMENTAL: option whether to include external storage in quota
calculation, defaults to false.

'filesystem_check_changes' => 1,

Specifies how often the filesystem is checked for changes made outside
ownCloud.

0 -> Never check the filesystem for outside changes, provides a performance
increase when it’s certain that no changes are made directly to the
filesystem

1 -> Check each file or folder at most once per request, recommended for
general use if outside changes might happen.

2 -> Check every time the filesystem is used, causes a performance hit when
using external storages, not recommended for regular use.

'asset-pipeline.enabled' => false,

All css and js files will be served by the web server statically in one js
file and one css file if this is set to <tt class="docutils literal">true</tt>.

'assetdirectory' => '/var/www/owncloud',

The parent of the directory where css and js assets will be stored if
piplelining is enabled; this defaults to the ownCloud directory. The assets
will be stored in a subdirectory of this directory named ‘assets’. The
server must be configured to serve that directory as $WEBROOT/assets.

You will only likely need to change this if the main ownCloud directory
is not writeable by the web server in your configuration.

'mount_file' => 'data/mount.json',

Where <tt class="docutils literal">mount.json</tt> file should be stored, defaults to <tt class="docutils literal">data/mount.json</tt>

'filesystem_cache_readonly' => false,

When <tt class="docutils literal">true</tt>, prevent ownCloud from changing the cache due to changes in the
filesystem for all storage.

'objectstore' => array(
        'class' => 'OC\\Files\\ObjectStore\\Swift',
        'arguments' => array(
                // trystack will user your facebook id as the user name
                'username' => 'facebook100000123456789',
                // in the trystack dashboard go to user -> settings -> API Password to
                // generate a password
                'password' => 'Secr3tPaSSWoRdt7',
                // must already exist in the objectstore, name can be different
                'container' => 'owncloud',
                // create the container if it does not exist. default is false
                'autocreate' => true,
                // required, dev-/trystack defaults to 'RegionOne'
                'region' => 'RegionOne',
                // The Identity / Keystone endpoint
                'url' => 'http://8.21.28.222:5000/v2.0',
                // required on dev-/trystack
                'tenantName' => 'facebook100000123456789',
                // dev-/trystack uses swift by default, the lib defaults to 'cloudFiles'
                // if omitted
                'serviceName' => 'swift',
        ),
),

The example below shows how to configure ownCloud to store all files in a
swift object storage.

It is important to note that ownCloud in object store mode will expect
exclusive access to the object store container because it only stores the
binary data for each file. The metadata is currently kept in the local
database for performance reasons.

WARNING: The current implementation is incompatible with any app that uses
direct file IO and circumvents our virtual filesystem. That includes
Encryption and Gallery. Gallery will store thumbnails directly in the
filesystem and encryption will cause severe overhead because key files need
to be fetched in addition to any requested file.

One way to test is applying for a trystack account at http://trystack.org/

'supportedDatabases' => array(
        'sqlite',
        'mysql',
        'pgsql',
        'oci',
        'mssql'
),

Database types that are supported for installation.

Available:

sqlite (SQLite3 - Community Edition Only)

mysql (MySQL)

pgsql (PostgreSQL)

oci (Oracle - Enterprise Edition Only)

mssql (Microsoft SQL Server - Enterprise Edition Only)

All other config options¶

'secret' => '',

Secret used by ownCloud for various purposes, e.g. to encrypt data. If you
lose this string there will be data corruption.

'trusted_proxies' => array('203.0.113.45', '198.51.100.128'),

List of trusted proxy servers

'forwarded_for_headers' => array('HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR'),

Headers that should be trusted as client IP address in combination with
trusted_proxies

'max_filesize_animated_gifs_public_sharing' => 10,

max file size for animating gifs on public-sharing-site.

If the gif is bigger, it’ll show a static preview

Value represents the maximum filesize in megabytes
Default is 10
Set to -1 for no limit

'filelocking.enabled' => false,

Enables the EXPERIMENTAL file locking.

This is disabled by default as it is experimental.

Prevents concurrent processes to access the same files
at the same time. Can help prevent side effects that would
be caused by concurrent operations.

WARNING: EXPERIMENTAL

'memcache.locking' => '\\OC\\Memcache\\Redis',

Memory caching backend for file locking
Because most memcache backends can clean values without warning using redis is recommended

'copied_sample_config' => true,

This entry is just here to show a warning in case somebody copied the sample
configuration. DO NOT ADD THIS SWITCH TO YOUR CONFIGURATION!

If you, brave person, have read until here be aware that you should not
modify ANY settings in this file without reading the documentation.

App config options¶

Retention for activities of the activity app:

'activity_expire_days' => 365,

Every day a cron job is ran, which deletes all activities for all users
which are older then the number of days that is set for <tt class="docutils literal">activity_expire_days</tt>


text:
namespace Tigwi.UI.Models
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// The interface specification for an account
    /// </summary>
    public interface IAccountModel
    {
        #region Public Properties

        /// <summary>
        /// Gets or sets the account's owner.
        /// </summary>
        IUserModel Admin { get; set; }

        /// <summary>
        /// Gets a collection of all the lists followed by the account.
        /// </summary>
        IListModelCollection AllFollowedLists { get; }

        /// <summary>
        /// Gets a collection of all the lists owned by the account.
        /// </summary>
        IListModelEnumerable AllOwnedLists { get; }

        /// <summary>
        /// Gets or sets the account's description.
        /// </summary>
        string Description { get; set; }

        /// <summary>
        /// Gets the account ID.
        /// </summary>
        Guid Id { get; }

        /// <summary>
        /// Gets the lists of whose the account is a member.
        /// </summary>
        IListModelCollection MemberOfLists { get; }

        /// <summary>
        /// Gets the account's name.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// Gets the account's personal list.
        /// </summary>
        IListModel PersonalList { get; }

        /// <summary>
        /// Gets the public lists followed by the account.
        /// </summary>
        IListModelEnumerable PublicFollowedLists { get; }

        /// <summary>
        /// Gets the public lists owned by the account.
        /// </summary>
        IListModelEnumerable PublicOwnedLists { get; }

        /// <summary>
        /// Gets all the users who can post to the account's timeline.
        /// </summary>
        ICollection<IUserModel> Users { get; }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecanora gangalizodes Nyl.

### Remarks
null


text:
<?php
namespace Topxia\Service\Thread\Tests;

use Topxia\Service\Common\BaseTestCase;
//  use Topxia\Service\Common\ServiceException;
use Topxia\Service\User\CurrentUser;

class ThreadServiceTest extends BaseTestCase
{
    /**
    * 基础API
    */
    public function testGetThread()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $foundThread = $this->getThreadService()->getThread($Thread['id']);
        $this->assertEquals('title', $foundThread['title']);
        $this->assertEquals('xxx', $foundThread['content']);
    }
    public function testSearchThreads()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $textClassroom = array(
            'title' => 'test',
        );
        $classroom = $this->getClassroomService()->addClassroom($textClassroom);

        $thread1 = array();
        $thread1['title'] = 'title';
        $thread1['content'] = 'xxx';
        $thread1['userId'] = $user['id'];
        $thread1['targetId'] = $classroom['id'];
        $thread1['targetType'] = 'classroom';
        $thread1['type'] = 'question';
        $threadNew1 = $this->getThreadService()->CreateThread($thread1);
        $thread2 = array();
        $thread2['title'] = 'title';
        $thread2['content'] = 'xxx';
        $thread2['userId'] = $user['id'];
        $thread2['targetId'] = $classroom['id'];
        $thread2['targetType'] = 'classroom';
        $thread2['type'] = 'discussion';
        $threadNew2 = $this->getThreadService()->CreateThread($thread2);

        $conditions = array('targetId' => $classroom['id']);
        $foundThreads = $this->getThreadService()->searchThreads($conditions, 'created', 0, 20);
        $this->assertEquals(2, count($foundThreads));
        $conditions = array('targetId' => $classroom['id'], 'type' => 'discussion');
        $foundThreads = $this->getThreadService()->searchThreads($conditions, 'created', 0, 20);
        $this->assertEquals(1, count($foundThreads));
    }
    public function testSearchThreadCount()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $textClassroom = array(
            'title' => 'test',
        );
        $classroom = $this->getClassroomService()->addClassroom($textClassroom);

        $thread1 = array();
        $thread1['title'] = 'title';
        $thread1['content'] = 'xxx';
        $thread1['userId'] = $user['id'];
        $thread1['targetId'] = $classroom['id'];
        $thread1['targetType'] = 'classroom';
        $thread1['type'] = 'question';
        $threadNew1 = $this->getThreadService()->CreateThread($thread1);
        $thread2 = array();
        $thread2['title'] = 'hello';
        $thread2['content'] = 'xxx';
        $thread2['userId'] = $user['id'];
        $thread2['targetId'] = $classroom['id'];
        $thread2['targetType'] = 'classroom';
        $thread2['type'] = 'discussion';
        $threadNew2 = $this->getThreadService()->CreateThread($thread2);

        $conditions = array('type' => 'question');
        $foundThreads = $this->getThreadService()->searchThreads($conditions, 'created', 0, 20);
        $this->assertEquals(1, count($foundThreads));
    }
    public function testFindThreadsByTargetAndUserId()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $thread = $this->CreateProtecThread();
        $foundThreads = $this->getThreadService()->findThreadsByTargetAndUserId(array('type' => $thread['targetType'], 'id' => $thread['targetId']), $user['id'], 0, 11);
        $this->assertEquals(1, count($foundThreads));
    }
    public function testFindZeroPostThreadsByTarget()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $textClassroom = array(
            'title' => 'test',
        );
        $classroom = $this->getClassroomService()->addClassroom($textClassroom);

        $thread = array();
        $thread['title'] = 'title';
        $thread['content'] = 'xxx';
        $thread['userId'] = $user['id'];
        $thread['targetId'] = $classroom['id'];
        $thread['targetType'] = 'classroom';
        $thread['type'] = 'question';
        $Thread = $this->getThreadService()->CreateThread($thread);
        $thread = array();
        $thread['title'] = 'title2';
        $thread['content'] = 'xxx2';
        $thread['userId'] = $user['id'];
        $thread['targetId'] = $classroom['id'];
        $thread['targetType'] = 'classroom';
        $thread['type'] = 'question';
        $Thread2 = $this->getThreadService()->CreateThread($thread);
        $post1 = array(
          'id' => '1',
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content1',
          );
        $post2 = array(
          'id' => '2',
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'hhh',
          );
        $createdPost1 = $this->getThreadService()->createPost($post1);
        $createdPost2 = $this->getThreadService()->createPost($post2);
        $zeroThread = $this->getThreadService()->findZeroPostThreadsByTarget(array('type' => $thread['targetType'], 'id' => $thread['targetId']), 0, 11);
        $this->assertEquals(2,$Thread2['id']);
    }
    /**
     * 创建话题
     */
    public function testCreateThread()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $this->assertEquals('title', $Thread['title']);
        $this->assertEquals('xxx', $Thread['content']);
    }
    public function testUpdateThread()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $fields = array(
          'title' => 'title2',
          'content' =>'hello123',
          );
        $Thread = $this->getThreadService()->updateThread($Thread['id'],$fields);
        $this->assertEquals($fields['title'],$Thread['title']);
    }
    public function testDeleteThread()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $post = array(
            'targetId' => $Thread['targetId'],
            'targetType' => $Thread['targetType'],
            'threadId' => $Thread['id'],
            'content' => 'post thread',
        );
        $createdPost = $this->getThreadService()->createPost($post);
        $this->getThreadService()->deleteThread($Thread['id']);
        $foundThread = $this->getThreadService()->getThread($Thread['id']);
        $this->assertNull($foundThread);
    }
    public function testSetThreadSticky()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $thread = $this->CreateProtecThread();
        $this->getThreadService()->setThreadSticky($thread['id']);
        $result = $this->getThreadService()->getThread($thread['id']);
        $this->assertEquals(1,$result['sticky']);
    }
    public function testCancelThreadSticky()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $this->getThreadService()->setThreadSticky($Thread['id']);
        $result = $this->getThreadService()->getThread($Thread['id']);
        $this->assertEquals(1,$result['sticky']);
        $this->getThreadService()->cancelThreadSticky($Thread['id']);
        $result = $this->getThreadService()->getThread($Thread['id']);
        $this->assertEquals(0,$result['sticky']);
    }
    public function testSetThreadNice()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $this->getThreadService()->setThreadNice($Thread['id']);
        $result = $this->getThreadService()->getThread($Thread['id']);
        $this->assertEquals(1,$result['nice']);
    }
    public function testCancelThreadNice()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $this->getThreadService()->setThreadNice($Thread['id']);
        $result = $this->getThreadService()->getThread($Thread['id']);
        $this->assertEquals(1,$result['nice']);
        $this->getThreadService()->cancelThreadNice($Thread['id']);
        $result = $this->getThreadService()->getThread($Thread['id']);
        $this->assertEquals(0,$result['nice']);
    }
    public function testSetThreadSolved()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $this->getThreadService()->setThreadSolved($Thread['id']);
        $result = $this->getThreadService()->getThread($Thread['id']);
        $this->assertEquals(1,$result['solved']);
    }
    public function testCancelThreadSolved()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $this->getThreadService()->setThreadSolved($Thread['id']);
        $result = $this->getThreadService()->getThread($Thread['id']);
        $this->assertEquals(1,$result['solved']);
        $this->getThreadService()->cancelThreadSolved($Thread['id']);
        $result = $this->getThreadService()->getThread($Thread['id']);
        $this->assertEquals(0,$result['solved']);
    }
     /**
     * 点击查看话题
     *
     * 此方法,用来增加话题的查看数。
     *
     * @param integer $courseId 课程ID
     * @param integer $threadId 话题ID
     *
     */
    public function testHitThread()
    {

                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $this->getThreadService()->hitThread($Thread['targetId'],$Thread['id']);
        $result = $this->getThreadService()->getThread($Thread['id']);
        $this->assertEquals(1,$result['hitNum']);
        $this->getThreadService()->hitThread($Thread['targetId'],$Thread['id']);
        $this->getThreadService()->hitThread($Thread['targetId'],$Thread['id']);
        $this->getThreadService()->hitThread($Thread['targetId'],$Thread['id']);
        $result = $this->getThreadService()->getThread($Thread['id']);
        $this->assertEquals(4,$result['hitNum']);
    }
     /**
     * 获得话题的回帖
     *
     * @param integer $courseId 话题的课程ID
     * @param integer $threadId 话题ID
     * @param string  $sort     排序方式: defalut按帖子的发表时间顺序;best按顶的次序排序。
     * @param integer $start    开始行数
     * @param integer $limit    获取数据的限制行数
     *
     * @return array 获得的话题回帖列表。
     */
    public function testFindThreadPosts()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $post = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content',
          );
        $post2 = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content2',
          );
        $createdPost = $this->getThreadService()->createPost($post);
        $createdPost2 = $this->getThreadService()->createPost($post);
        $createdPost=$this->getThreadService()->findThreadPosts($Thread['targetId'],$Thread['id'],'default',0,20);
        $this->assertEquals(2,count($createdPost));
    }
    /**
     * 获得话题回帖的数量
     * @param  integer $courseId 话题的课程ID
     * @param  integer $threadId 话题ID
     * @return integer 话题回帖的数量
     */
    public function testGetThreadPostCount()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();

        $post = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content',
          );
        $createdPost = $this->getThreadService()->createPost($post);
        $Thread = $this->getThreadService()->getThreadPostCount($Thread['targetId'],$Thread['id']);
        $this->assertEquals('1',$Thread);
    }
     /**
     * 回复话题
     **////
    public function testGetPost()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();

        $post = array(
          'id' => '1',
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content',
          );
        $createdPost = $this->getThreadService()->createPost($post);
        $foundPost = $this->getThreadService()->getPost($createdPost['id']);
        $this->assertEquals($post['content'],$foundPost['content']);
    }
    public function testGetPostPostionInThread()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $post1 = array(
          'id' => '1',
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content',
          );
        $post2 = array(
          'id' => '2',
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content',
          );
        $createdPost1 = $this->getThreadService()->createPost($post1);
        $createdPost2 = $this->getThreadService()->createPost($post2);
        $getPostion = $this->getThreadService()->getPostPostionInThread($createdPost2['id']);
        $this->assertEquals(2,$getPostion);

    }
    public function testGetPostPostionInArticle()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $article= array(
          'title'=> 'articletitle',
          'body' => 'hello,im stefanie',
          'thumb' => '123',
          'originalThumb' =>'123',
          'categoryId'=> '1',
          'source' => 'source',
          'sourceUrl' => ' ',
          'status' => 'published',
          'userId' => $user['id'],
          'publishedTime' => 'now',
          'tags' => '1',
        );
        $article = $this->getArticleService()->createArticle($article);
        $post3 = array(
          'id' => '1',
          'targetType' => 'article',
          'targetId' => $article['id'],
          'content' => 'post content',
          );

        $createdPost1 = $this->getThreadService()->createPost($post3);

        $result = $this->getThreadService()->getPostPostionInArticle($article['id'],$post3['id']);
        $this->assertEquals(1, $result);;
    }
    public function testFindPostsByParentId()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $post = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content',
          );
        $createdPost = $this->getThreadService()->createPost($post);
        $post2 = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'child post',
          'parentId' => $createdPost['id'],
          );
        $createdPost2 = $this->getThreadService()->createPost($post2);
        $findPost = $this->getThreadService()->findPostsByParentId($createdPost['id'],0,20);

        $this->assertEquals(1,count($findPost));
    }
    public function testFindPostsCountByParentId()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $post = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content',
          );
        $createdPost = $this->getThreadService()->createPost($post);
        $post2 = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'child post2',
          'parentId' => $createdPost['id'],
          );
        $createdPost2 = $this->getThreadService()->createPost($post2);
        $post3 = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'child post3',
          'parentId' => $createdPost['id'],
          );
        $createdPost3 = $this->getThreadService()->createPost($post3);
        $post4 = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'child post4',
          'parentId' => $createdPost['id'],
          );
        $createdPost4 = $this->getThreadService()->createPost($post4);
        $findPostCount = $this->getThreadService()->findPostsCountByParentId($createdPost['id']);
        $this->assertEquals(3, $findPostCount);
    }

    public function testCreatePost()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $post = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content',
          );
        $createdPost = $this->getThreadService()->createPost($post);
        $this->assertTrue(is_array($createdPost));
        $this->assertEquals($post['targetId'], $createdPost['targetId']);
        $this->assertEquals($post['threadId'], $createdPost['threadId']);

        $thread = $this->getThreadService()->getThread($post['targetId'], $post['threadId']);
        $this->assertEquals(1, $thread['postNum']);
    }
    public function testDeletePost()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $post = array(
            'targetId' => $Thread['targetId'],
            'targetType' => $Thread['targetType'],
            'threadId' => $Thread['id'],
            'content' => 'post thread',
        );
        $createdPost = $this->getThreadService()->createPost($post);
        $this->getThreadService()->deletePost($createdPost['targetId'], $createdPost['id']);
        $foundPosts = $this->getThreadService()->findThreadPosts($createdPost['targetId'], $createdPost['threadId'], 'default', 0, 20);

        $this->assertTrue(is_array($foundPosts));
        $this->assertEmpty($foundPosts);

        $thread = $this->getThreadService()->getThread($post['targetId'], $post['threadId']);
        $this->assertEquals(0, $thread['postNum']);
    }
    public function testSearchPostsCount()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();

        $post1 = array(
          'id' => '1',
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content1',
          );
        $post2 = array(
          'id' => '2',
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'abc',
          );
        $post3 = array(
          'id' => '3',
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'efd',
          );
        $createdPost1 = $this->getThreadService()->createPost($post1);
        $createdPost2 = $this->getThreadService()->createPost($post2);
        $createdPost3 = $this->getThreadService()->createPost($post3);
        $conditions = array('threadId' => $Thread['id']);
        $count= $this->getThreadService()->SearchPostsCount($conditions);
        $this->assertEquals(3, $count);
        $this->assertEquals(1, count($count));
        $conditions = array('threadId' => $Thread['id'],'id'=>'2');
        $count= $this->getThreadService()->SearchPostsCount($conditions);
        $this->assertEquals(1, $count);
    }
    public function testSearchPosts()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();

        $post1 = array(
          'id' => '1',
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content1',
          );
        $post2 = array(
          'id' => '2',
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'eeeeeee',
          );
        $post3 = array(
          'id' => '3',
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'create',
          );
        $createdPost1 = $this->getThreadService()->createPost($post1);
        $createdPost2 = $this->getThreadService()->createPost($post2);
        $createdPost3 = $this->getThreadService()->createPost($post3);
        $sort = 'created';
        $orderBys = $this->filterSort($sort);
        $conditions = array('targetId' => $Thread['id']);
        $foundPosts = $this->getThreadService()->searchPosts($conditions, $orderBys, 0, 20);
        $this->assertEquals(3, count($foundPosts));
    }
    public function testVoteUpPost()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $post = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content',
          );
        $createdPost = $this->getThreadService()->createPost($post);
        $result = $this->getThreadService()->voteUpPost($createdPost['id']);
        $this->assertEquals('ok', $result['status']);

    }
    public function testSetPostAdopted()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $user = $this->getCurrentUser();
        $post = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content',
          );
        $createdPost = $this->getThreadService()->createPost($post);
        $this->getThreadService()->setPostAdopted($createdPost['id']);
        $foundPost = $this->getThreadService()->getPost($createdPost['id']);
        $this->assertEquals('1', $foundPost['adopted']);
    }

    public function testCancelPostAdopted()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $user = $this->getCurrentUser();
        $post = array(
          'targetType' => $Thread['targetType'],
          'targetId' => $Thread['targetId'],
          'threadId' => $Thread['id'],
          'content' => 'post content',
          );
        $createdPost = $this->getThreadService()->createPost($post);
        $this->getThreadService()->setPostAdopted($createdPost['id']);
        $foundPost = $this->getThreadService()->getPost($createdPost['id']);
        $this->assertEquals('1', $foundPost['adopted']);
        $this->getThreadService()->cancelPostAdopted($foundPost['id']);
        $result = $this->getThreadService()->getPost($foundPost['id']);
        $this->assertEquals('0', $result['adopted']);
    }
    public function testCanAccess()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $thread = $this->CreateProtecThread();
        $this->getThreadService()->canAccess('thread.create',$thread);
    }
    public function testTryAccess()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $thread = $this->CreateProtecThread();
        $this->getThreadService()->tryAccess('thread.create',$thread);

    }

    /**
     * 话题成员
     **/
    public function testFindMembersCountByThreadId()
    {
        $currentUser = new CurrentUser();
        $currentUser->fromArray(array(
            'id' => 2,
            'nickname' => 'user',
            'email' => 'user@user.com',
            'password' => 'user',
            'currentIp' => '127.0.0.1',
            'roles' => array('ROLE_USER','ROLE_SUPER_ADMIN','ROLE_TEACHER'),
        ));
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $fields = array(
          'threadId' => $Thread['id'],
          'userId' => $currentUser['id'],
          'nickname' => 'xiaofang'
         );
        $member = $this->getThreadService()->createMember($fields);
        $currentUser2 = new CurrentUser();
        $currentUser2->fromArray(array(
            'id' => 1,
            'nickname' => 'user2',
            'email' => 'user2@user.com',
            'password' => 'user',
            'currentIp' => '127.0.0.1',
            'roles' => array('ROLE_USER','ROLE_SUPER_ADMIN','ROLE_TEACHER'),
        ));
        $this->getServiceKernel()->setCurrentUser($currentUser2);
        $fields2 = array(
          'threadId' => $Thread['id'],
          'userId' => $currentUser2['id'],
          'nickname' => 'xiaofang'
         );
        $member = $this->getThreadService()->createMember($fields2);
        $memberCount = $this->getThreadService()->findMembersCountByThreadId($Thread['id']);
        $this->assertEquals(2, $memberCount);
    }
    public function testFindMembersByThreadId()
    {
        $currentUser = new CurrentUser();
        $currentUser->fromArray(array(
            'id' => 1,
            'nickname' => 'user',
            'email' => 'user@user.com',
            'password' => 'user',
            'currentIp' => '127.0.0.1',
            'roles' => array('ROLE_USER','ROLE_SUPER_ADMIN','ROLE_TEACHER'),
        ));
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        $fields = array(
          'threadId' => $Thread['id'],
          'userId' => $currentUser['id'],
          'nickname' => 'xiaofang'
         );
        $member = $this->getThreadService()->createMember($fields);
        $findMember = $this->getThreadService()->findMembersByThreadId($Thread['id'],0,11);
        $this->assertEquals(1, count($findMember));

    }

    public function testGetMemberByThreadIdAndUserId()
    {
        $Thread = $this->CreateProtecThread();
        $currentUser = new CurrentUser();
        $currentUser->fromArray(array(
            'id' => 1,
            'nickname' => 'user',
            'email' => 'user@user.com',
            'password' => 'user',
            'currentIp' => '127.0.0.1',
            'roles' => array('ROLE_USER','ROLE_SUPER_ADMIN','ROLE_TEACHER'),
        ));
        $this->getServiceKernel()->setCurrentUser($currentUser);

        $fields = array(
          'threadId' => $Thread['id'],
          'userId' => $currentUser['id'],
          'nickname' => 'xiaofang'
         );
        $member = $this->getThreadService()->createMember($fields);
        $result = $this->getThreadService()->getMemberByThreadIdAndUserId($Thread['id'],$currentUser['id']);
        $this->assertEquals('xiaofang', $result['nickname']);
    }

    public function testFindMembersByThreadIdAndUserIds()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();

        $fields = array(
          'threadId' => $Thread['id'],
          'userId' => $currentUser['id'],
          'nickname' => 'xiaofang'
         );
        $member = $this->getThreadService()->createMember($fields);
        $result = $this->getThreadService()->findMembersByThreadIdAndUserIds($Thread['id'],array($currentUser['id']));
        $this->assertEquals('1', count($result));
    }
    public function testCreateMember()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        // $user = $this->getCurrentUser();
        $fields = array(
          'threadId' => $Thread['id'],
          'userId' => $user['id'],
          'nickname' => 'xiaofang'
         );
        $member = $this->getThreadService()->createMember($fields);
        $this->assertEquals('xiaofang', $member['nickname']);

    }
    public function testDeleteMember()
    {
                $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        // $user = $this->getCurrentUser();
        $fields = array(
          'threadId' => $Thread['id'],
          'userId' => $user['id'],
          'nickname' => 'xiaofang'
         );
        $member = $this->getThreadService()->createMember($fields);
        $this->assertEquals('xiaofang', $member['nickname']);
        $member = $this->getThreadService()->deleteMember($member['id']);
        $this->assertEmpty($member);
    }
    public function testDeleteMembersByThreadId()
    {
             $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);
        $Thread = $this->CreateProtecThread();
        // $user = $this->getCurrentUser();
        $fields = array(
          'threadId' => $Thread['id'],
          'userId' => $user['id'],
          'nickname' => 'xiaofang'
         );
        $member = $this->getThreadService()->createMember($fields);
        $this->assertEquals('xiaofang', $member['nickname']);
        $member = $this->getThreadService()->DeleteMembersByThreadId($Thread['id']);
        $this->assertEmpty($member);
    }
    /**
    * 扩展API
    */
    /*public function testFindTeacherIds()
    {
        $user = $this->createUser();
        $currentUser = new CurrentUser();
        $currentUser->fromArray($user);
        $this->getServiceKernel()->setCurrentUser($currentUser);

        $textClassroom = array(
          'title' => 'test',
          'id'    => 1,
          'categoryId'=>1,
          'status' => 'published'
          );

        $coures = array(
          'title'=>'coures',
          );
        $coures = $this->getCourseService()->createCourse($coures);
        $this->getCourseService()->publishCourse($coures['id']);
        $coures = $this->getCourseService()->getCourse($coures['id']);
        $classroom = $this->getClassroomService()->addClassroom($textClassroom);
        $this->getClassroomService()->publishClassroom($classroom['id']);
        $this->getClassroomService()->addCoursesToClassroom($classroom['id'],array($coures['id']));
        $classroom = $this->getClassroomService()->getClassroom($classroom['id']);
        $enabled = $this->getClassroomService()->isCourseInClassroom($coures['id'], $classroom['id']);

        $thread = array();
        $thread['title'] = 'title';
        $thread['content'] = 'xxx';
        $thread['userId'] = $user['id'];
        $thread['targetId'] = $classroom['id'];
        $thread['targetType'] = 'classroom';
        $thread['type'] = 'question';
        $Thread = $this->getThreadService()->createThread($thread);

        $this->getThreadService()->setThreadSolved($Thread['id']);
        $result = $this->getThreadService()->getThread($Thread['id']);
        $teacherId = $this->getThreadService()->findTeacherIds($Thread);
        $this->assertEquals($user['id'],$teacherId[0]);
    }*/

    protected function filterSort($sort)
    {
      switch ($sort) {
        case 'created':
          $orderBys = array(
            array('isStick', 'DESC'),
            array('createdTime', 'DESC'),
          );
          break;
        case 'posted':
          $orderBys = array(
            array('isStick', 'DESC'),
            array('latestPostTime', 'DESC'),
          );
          break;
        case 'createdNotStick':
          $orderBys = array(
            array('createdTime', 'DESC'),
          );
          break;
        case 'postedNotStick':
          $orderBys = array(
            array('latestPostTime', 'DESC'),
          );
          break;
        case 'popular':
          $orderBys = array(
            array('hitNum', 'DESC'),
          );
          break;

        default:
          throw $this->createServiceException('参数sort不正确。');
      }
      return $orderBys;
    }
    protected function getThreadService()
    {
        return $this->getServiceKernel()->createService('Thread.ThreadService');
    }
    protected function createUser()
    {
        $user = array();
        $user['email'] = "user@user.com";
        $user['nickname'] = "user";
        $user['password'] = "user";
        $user = $this->getUserService()->register($user);
        $user['currentIp'] = '127.0.0.1';
        $user['roles'] = array('ROLE_USER','ROLE_SUPER_ADMIN','ROLE_TEACHER');
        return $user;
    }
    private function getClassroomService()
    {
        return $this->getServiceKernel()->createService('Classroom:Classroom.ClassroomService');
    }
    private function getArticleService()
    {
        return $this->getServiceKernel()->createService('Article.ArticleService');
    }
    private function getCourseService()
    {
      return $this->getServiceKernel()->createService('Course.CourseService');
    }
    protected function getUserService()
    {
        return $this->getServiceKernel()->createService('User.UserService');
    }
    protected function getNotifiactionService()
    {
        return $this->createService('User.NotificationService');
    }
    protected function CreateProtecThread()
    {
        $textClassroom = array(
            'title' => 'test',
        );
        $classroom = $this->getClassroomService()->addClassroom($textClassroom);

        $thread = array();
        $thread['title'] = 'title';
        $thread['content'] = 'xxx';
        $thread['userId'] = 2;
        $thread['targetId'] = $classroom['id'];
        $thread['targetType'] = 'classroom';
        $thread['type'] = 'question';
        $threadNew = $this->getThreadService()->CreateThread($thread);
        return $threadNew;
    }
}


text:
In my latest project I ended up with really complex `db/seeds.rb` file
for different clients so that various scenarios can be demonstrated on
a "demo" server.

Ten minutes before meeting people were running crazy that
they cannot log-in to the demo server. Within nine minutes I manage to
locate the bug and fix it & deploy the fix. Well the bug was not even
a bug, it was just a typo in `db/seeds.rb` file.

This was kind of a revelation for me. Old mind-set that "db seed
files don't need tests as they represent temporary state" was replaced
with "yes they do need tests if they are subject to frequent change or
dynamic business requirement"

## how to test db:seed

The way how I'm testing my seed files is within the seed files at the
end of reseed. Yes this may not be the best idea because to discover
that something went wrong we are destroying old database values. But in my
case (where I keep really good track of database dumps) it works for
me.

```ruby
# Gemfile

# ...

gem 'rspec-rails'

# ...

```

```ruby
# db/seeds.rb
require 'rspec/expectations'

case Rails.env.to_s
when 'staging'
  # ...
when 'demo'
  include RSpec::Matchers   # important !

  # adding people & permissions
  carl = User.create email: 'carl@test.com'
  carl.add_permission :admin

  # tests
  expect(User.find_by email: 'carl@test.com').to be_present
  expect(User.find_by(email: 'carl@test.com').permissions).to include(:admin)
end
```

Seed tests (or however we want to call them) are different than regular
specs/tests we run them once as a part of the reseed process therefore
there is a wider window for not spotting some cached instance variable or
something. I would rather let my `rake db:seed` task to take 2 seconds
more than I would spend 20 minutes fixing db:seeds over weekend.
Plus are just running them once or twice a week.

Like I said this works for my requirement but I would recommend to have a look on
[this SO question](http://stackoverflow.com/questions/6004057/w-rspec-how-to-seed-the-database-on-load)
for more suggestions. Especially if you need to seed database before
running specs one interesting ide is this:

```ruby
# spec/spec_helper.rb
Spec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
    Rails.application.load_seed # loading seeds
  end
end
```

## Word on Gemfile

I agree that it's stupid to have `RSpec` exposed for every enviroment
(production or staging env may not need them). Solution for this is easy:

```ruby
# Gemfile

group :development, :test, :staging, :demo do
  gem 'rspec-rails', require: false
end
```

...or if we want to be more hardcore

```ruby
# Gemfile

group :demo do
  gem 'rspec-expectations', require: false
end

group :development, :test do
  gem 'rspec-rails', require: false
end
```

## RSpec in IRB console

If you look for a way how to load RSpec in irb:

```ruby
require 'rspec/expectations'
include RSpec::Matchers
1.should eq 1
# => true
```

Published: 2014-06-02

Keywords: Rails 4, Ruby 2.1.2,  RSpec, specs, seeds, database, seed, irb rspec


text:
		<title>PixelBox Example 9</title>
		<link rel="stylesheet" href="css/normalize.css"/>
		<link rel="stylesheet" href="css/index.css"/>
		<meta content="yes" name="apple-mobile-web-app-capable" />
		<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1"/>

		Source

			PixelBox
			by Kirill Edelman for three.js


text:
var Language = {
	copy_to_clipboard : "Show card ID",
	help_text : "Trello 3000 Help",
	ignore_filters : "Ignore filters"
}


text:
---
layout: article
title: "Encapsulamento"
categories: java
author: sakurai
date: 2020-05-12 23:38:00
tags: [java, encapsulamento]
published: true
excerpt: Encapsular, nada mais é do que proteger membros de outra classe de acesso externo, permitindo somente sua manipulação de forma indireta.
comments: true
image:
  teaser: teaser-java.png
ads: false
---

## Encapsulamento

Encapsular, nada mais é do que proteger membros de outra classe de acesso externo, permitindo somente sua manipulação de forma indireta. Isso é possível da seguinte maneira:

Consideremos o seguinte exemplo de uma classe Livro:

{% highlight java %}
package br.encapsulamento;

/**
 * Classe utilizada para representar o Livro.
 */
public class Livro {
    private String titulo;
    private String autor;

    public String getAutor() {
        return autor;
    }

    public void setAutor(String autor) {
        this.autor = autor;
    }

    public String getTitulo() {
        return titulo;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }
}
{% endhighlight %}

Note que os dois atributos da classe (titulo e autor) são do tipo **private**, que permite apenas o acesso destas informações a partir da própria classe, logo para que seja possível ler ou alterar essas informações criamos métodos ditos **métodos assessores** ou então **getters** e **setters**.

A princípio parece ser algo sem muita utilidade, mas desta forma podemos criar atributos os quais podemos apenas ler informações ou ainda gerar tratamentos específicos sempre que outra classe solicita a alteração de um atributo de nossa classe.

Encapsule aquilo que pode ser alterado com frequência na sua aplicação, por exemplo:

{% highlight java %}
package br.encapsulamento;

/**
 * Classe utilizada para representar um Professor
 */
public class Professor {
    private int registro;
    private String nome;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getRegistro() {
        return registro;
    }

    public void setRegistro(int registro) {
        this.registro = registro;
    }
}
{% endhighlight %}

{% highlight java %}
package br.encapsulamento;

/**
 * Classe utilizada para representar um Aluno.
 */
public class Aluno {
    private int matricula;
    private String nome;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getMatricula() {
        return matricula;
    }

    public void setMatricula(int matricula) {
        this.matricula = matricula;
    }
}
{% endhighlight %}

Note que os atributos das classes **Professor** e **Aluno** possuem a visibilidade **private**, dessa forma eles só podem ser acessados pelas suas classes, também criamos métodos **set** (métodos utilizados para alterar o valor de uma propriedade) e **get** (método utilizado para obter o valor de uma propriedade) para cada atributo.

Dado a classe Professor e Aluno, queremos consultar os alunos e professores pelo nome:

{% highlight java %}
package br.encapsulamento;

/**
 * Classe utilizada para consultar os alunos e professores
 * através de seu nome.
 */
public class Consultar {
    public Aluno[] consultarAlunoPorNome(Aluno[] alunos, String nome) {
        Aluno[] alunosEncontrados = new Aluno[alunos.length];
        int contAlunos = 0;

        for(int i = 0; i < alunos.length; i++) {
            if(alunos[i].getNome().equals(nome)) {
                alunosEncontrados[contAlunos++] = alunos[i];
            }
        }

        Aluno[] retorno = new Aluno[contAlunos];
        for(int i = 0; i < contAlunos; i++) {
            retorno[i] = alunosEncontrados[i];
        }

        return retorno;
    }

    public Professor[] consultarProfessorPorNome(Professor[] professores,
String nome) {
        Professor[] profEncontrados = new Professor[professores.length];
        int contProfessores = 0;

        for(int i = 0; i < professores.length; i++) {
            if(professores[i].getNome().equals(nome)) {
                profEncontrados[contProfessores++] = professores[i];
            }
        }

        Professor[] retorno = new Professor[contProfessores];
        for(int i = 0; i < contProfessores; i++) {
            retorno[i] = profEncontrados[i];
        }

        return retorno;
    }
}
{% endhighlight %}

Agora digamos que nosso programa que busca os alunos e professores esta funcionando corretamente, e precisamos adicionar outra busca que procura coordenadores pelo seu nome.

{% highlight java %}
package br.encapsulamento;

/**
 * Classe utilizada para representar um Coordenador.
 */
public class Coordenador {
    private String cursoCoordenado;
    private String nome;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getCursoCoordenado() {
        return cursoCoordenado;
    }

    public void setCursoCoordenado(String cursoCoordenado) {
        this.cursoCoordenado = cursoCoordenado;
    }
}
{% endhighlight %}

Para consultar o coordenador pelo nome, precisamos usar um método bem parecido com o que consulta o aluno e professor, mas se notarmos as classes **Aluno**, **Professor** e **Coordenador** tem o atributo **nome** em comum e é exatamente por este atributo que os consultamos.

Se criarmos uma classe **Pessoa** para ser uma classe Pai dessas classes e se a classe Pai tiver o atributo **nome**, então todas as subclasses recebem este atributo por herança:

{% highlight java %}
package br.encapsulamento;

/**
 * Classe utilizada para representar um Pessoa.
 */
public class Pessoa {
    private String nome;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }
}
{% endhighlight %}

As subclasses Professor, Aluno e Coordenador ficaram da seguinte forma:

{% highlight java %}
package br.encapsulamento;

/**
 * Classe utilizada para representar um Professor.
 */
public class Professor extends Pessoa {
    private int registro;

    public int getRegistro() {
        return registro;
    }

    public void setRegistro(int registro) {
        this.registro = registro;
    }
}
{% endhighlight %}

{% highlight java %}
package br.encapsulamento;

/**
 * Classe utilizada para representar um Aluno.
 */
public class Aluno extends Pessoa {
    private int matricula;

    public int getMatricula() {
        return matricula;
    }

    public void setMatricula(int matricula) {
        this.matricula = matricula;
    }
}
{% endhighlight %}

{% highlight java %}
package br.encapsulamento;

/**
 * Classe utilizada para representar o Coordenador.
 */
public class Coordenador extends Pessoa {
    private String cursoCoordenado;

    public String getCursoCoordenado() {
        return cursoCoordenado;
    }

    public void setCursoCoordenado(String cursoCoordenado) {
        this.cursoCoordenado = cursoCoordenado;
    }
}
{% endhighlight %}

Para consultar o Aluno, Professor e Coordenador vamos criar apenas um método que recebe um vetor de Pessoa e o nome que será procurado e retorna um vetor com as Pessoas encontradas:

{% highlight java %}
package br.encapsulamento;

/**
 * Classe utilizada para consultar de uma forma genérica qualquer
 * subclasse de Pessoa através de seu nome.
 */
public class ConsultarPessoa {
    public Pessoa[] consultarAlunoPorNome(Pessoa[] pessoas, String nome) {
        Pessoa[] pessoasEncontradas = new Pessoa[pessoas.length];
        int contPessoas = 0;

        for(int i = 0; i < pessoas.length; i++) {
            if(pessoas[i].getNome().equals(nome)) {
                pessoasEncontradas[contPessoas++] = pessoas[i];
            }
        }

        Pessoa[] retorno = new Pessoa[contPessoas];
        for(int i = 0; i < contPessoas; i++) {
            retorno[i] = pessoasEncontradas[i];
        }

        return retorno;
    }
}
{% endhighlight %}

Dessa forma usamos herança e encapsulamos a forma de encontrar um Aluno, Pessoa e Coordenador, agora se tivermos que adicionar um Diretor, por exemplo, nosso método de consulta não precisa ser alterado, precisamos apenas criar a classe Diretor e fazer ela filha da classe Pessoa.


text:
<?php declare( strict_types = 1 );
namespace CodeKandis\Phlags\Tests\UnitTests\Validation;

use CodeKandis\Phlags\Tests\Fixtures\ValidFlagable;
use CodeKandis\Phlags\Validation\ValueValidator;
use PHPUnit\Framework\TestCase;

/**
 * Represents the test case for the interface `CodeKandis\Phlags\Validation\ValueValidator`.
 * @package codekandis/phlags
 * @author Christian Ramelow <info@codekandis.net>
 */
class ValueValidatorTest extends TestCase
{
	/**
	 * Tests if the flagable validator is working as expected.
	 * @param string $flagableClassName The class name of the flagable to validate.
	 * @param array $reflectedFlags The reflected flags of the flagable.
	 * @param int $maxValue The maximum value of the flagable.
	 * @param mixed $value The value to validate.
	 * @param array $errorMessages The error messages of the validation.
	 * @param bool $expectedSucceeded The success state of the validation.
	 * @dataProvider valuesAndResultsDataProvider
	 */
	public function testsProperValidation( string $flagableClassName, array $reflectedFlags, int $maxValue, $value, array $errorMessages, bool $expectedSucceeded ): void
	{
		$flagable = new $flagableClassName;

		$validator = new ValueValidator ();
		$validator->validate( $flagable, $reflectedFlags, $maxValue, $value );

		static::assertEquals( $errorMessages, $validator->getErrorMessages() );
		static::assertEquals( $expectedSucceeded, $validator->succeeded() );
	}

	/**
	 * Provides the data to validate a value.
	 * @return array The data sets.
	 */
	public function valuesAndResultsDataProvider(): array
	{
		return [
			0  => [
				'flagableClassName' => ValidFlagable::class,
				'reflectedFlags'    => [
					'FLAG_A' => 1,
					'FLAG_B' => 2,
					'FLAG_C' => 4,
				],
				'maxValue'          => 7,
				'value'             => ValidFlagable::FLAG_A,
				'errorMessages'     => [],
				'expectedSucceeded' => true
			],
			1  => [
				'flagableClassName' => ValidFlagable::class,
				'reflectedFlags'    => [
					'FLAG_A' => 1,
					'FLAG_B' => 2,
					'FLAG_C' => 4,
				],
				'maxValue'          => 7,
				'value'             => new ValidFlagable( ValidFlagable::FLAG_A ),
				'errorMessages'     => [],
				'expectedSucceeded' => true
			],
			2  => [
				'flagableClassName' => ValidFlagable::class,
				'reflectedFlags'    => [
					'FLAG_A' => 1,
					'FLAG_B' => 2,
					'FLAG_C' => 4,
				],
				'maxValue'          => 7,
				'value'             => 'FLAG_A',
				'errorMessages'     => [],
				'expectedSucceeded' => true
			],
			3  => [
				'flagableClassName' => ValidFlagable::class,
				'reflectedFlags'    => [
					'FLAG_A' => 1,
					'FLAG_B' => 2,
					'FLAG_C' => 4,
				],
				'maxValue'          => 7,
				'value'             => 'FLAG_A|FLAG_B',
				'errorMessages'     => [],
				'expectedSucceeded' => true
			],
			4  => [
				'flagableClassName' => ValidFlagable::class,
				'reflectedFlags'    => [
					'FLAG_A' => 1,
					'FLAG_B' => 2,
					'FLAG_C' => 4,
				],
				'maxValue'          => 7,
				'value'             => 'foobar',
				'errorMessages'     => [
					"The value 'foobar' cannot be resolved to a flag value.",
				],
				'expectedSucceeded' => false
			],
			5  => [
				'flagableClassName' => ValidFlagable::class,
				'reflectedFlags'    => [
					'FLAG_A' => 1,
					'FLAG_B' => 2,
					'FLAG_C' => 4,
				],
				'maxValue'          => 7,
				'value'             => 'FLAG_A|FLAG_D',
				'errorMessages'     => [
					"The value 'FLAG_D' cannot be resolved to a flag value.",
				],
				'expectedSucceeded' => false
			],
			6  => [
				'flagableClassName' => ValidFlagable::class,
				'reflectedFlags'    => [
					'FLAG_A' => 1,
					'FLAG_B' => 2,
					'FLAG_C' => 4,
				],
				'maxValue'          => 7,
				'value'             => -42,
				'errorMessages'     => [
					"Invalid type in value '-42'. Unsigned 'int', 'string' or instance of 'CodeKandis\Phlags\Tests\Fixtures\ValidFlagable' expected.",
				],
				'expectedSucceeded' => false
			],
			7  => [
				'flagableClassName' => ValidFlagable::class,
				'reflectedFlags'    => [
					'FLAG_A' => 1,
					'FLAG_B' => 2,
					'FLAG_C' => 4,
				],
				'maxValue'          => 7,
				'value'             => -42.5,
				'errorMessages'     => [
					"Invalid type in value '-42.5'. Unsigned 'int', 'string' or instance of 'CodeKandis\Phlags\Tests\Fixtures\ValidFlagable' expected.",
				],
				'expectedSucceeded' => false
			],
			8  => [
				'flagableClassName' => ValidFlagable::class,
				'reflectedFlags'    => [
					'FLAG_A' => 1,
					'FLAG_B' => 2,
					'FLAG_C' => 4,
				],
				'maxValue'          => 7,
				'value'             => '-42',
				'errorMessages'     => [
					"Invalid type in stringified value '-42'. Unsigned 'int' or flag name of flagable 'CodeKandis\Phlags\Tests\Fixtures\ValidFlagable' expected.",
				],
				'expectedSucceeded' => false
			],
			9  => [
				'flagableClassName' => ValidFlagable::class,
				'reflectedFlags'    => [
					'FLAG_A' => 1,
					'FLAG_B' => 2,
					'FLAG_C' => 4,
				],
				'maxValue'          => 7,
				'value'             => '-42.5',
				'errorMessages'     => [
					"Invalid type in stringified value '-42.5'. Unsigned 'int' or flag name of flagable 'CodeKandis\Phlags\Tests\Fixtures\ValidFlagable' expected.",
				],
				'expectedSucceeded' => false
			],
			10 => [
				'flagableClassName' => ValidFlagable::class,
				'reflectedFlags'    => [
					'FLAG_A' => 1,
					'FLAG_B' => 2,
					'FLAG_C' => 4,
				],
				'maxValue'          => 7,
				'value'             => 42,
				'errorMessages'     => [
					"The value '42' exceeds the maximum flag value of '7'.",
				],
				'expectedSucceeded' => false
			],
			11 => [
				'flagableClassName' => ValidFlagable::class,
				'reflectedFlags'    => [
					'FLAG_A' => 1,
					'FLAG_B' => 2,
					'FLAG_C' => 4,
				],
				'maxValue'          => 7,
				'value'             => 'FLAG_A|-42|FLAG_D',
				'errorMessages'     => [
					"Invalid type in stringified value '-42'. Unsigned 'int' or flag name of flagable 'CodeKandis\Phlags\Tests\Fixtures\ValidFlagable' expected.",
					"The value 'FLAG_D' cannot be resolved to a flag value.",
				],
				'expectedSucceeded' => false
			]
		];
	}
}