How to: Multi-site CodeIgniter Set-up

Setting the base URL

The first step of getting CodeIgniter working anywhere automatically is curing it of it’s most pointless configuration setting. It seems CodeIgniter would like to be told where it is, which really doesn’t need to happen. We could solve this in many ways, but instead of extending or replacing any core code, I would prefer to put a little snippet of code into the main application/config/config.php. Enter this code into the file and it will automatically support pretty much any kind of URL.

if (!defined('BASEPATH')) exit('No direct script access allowed');
/* |-----| Base Site URL |-----|
URL to your CodeIgniter root. 
Typically this will be your base URL, WITH a trailing slash:
   $config['base_url'] = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https' : 'http';
   $config['base_url'] .= '://'. $_SERVER['HTTP_HOST'];
   $config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
   $config['base_url'] = 'http://localhost/';

Setting a SITE constant

So the website URL is now set and links are fully working around the site. Next we need a way to work out throughout our code which site is currently being used. Amongst other things, this will help us with selecting the right database settings later.

Set a constant for whichever site you happen to be running, if its not here it will fatal error.
   case '':
   case '':
      define('SITE', 'example');

   case '':
   case '':
      define('SITE', 'example2');
      define('SITE', 'default');

Domain based database settings

Now that CodeIgniter has its links working and it knows what site it is trying to run, it needs to know the database configuration for this domain. To do that, we can break down our config into domain specific “Database groups”.

if (!defined('BASEPATH')) exit('No direct script access allowed'); 
This file will contain the settings needed to access your database.
For complete instructions please consult the "Database Connection" page of the User Guide. 
['hostname'] The hostname of your database server.
['username'] The username used to connect to the database
['password'] The password used to connect to the database
['database'] The name of the database you want to connect to
['dbdriver'] The database type. ie: mysql. Currently supported: mysql, mysqli, postgre, odbc, mssql
['dbprefix'] You can add an optional prefix, which will be added to the table name when using the Active Record class
['pconnect'] TRUE/FALSE - Whether to use a persistent connection
['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
['active_r'] TRUE/FALSE - Whether to load the active record class
['cache_on'] TRUE/FALSE - Enables/disables query caching
['cachedir'] The path to the folder where cache files should be stored
The $active_group variable lets you choose which connection group to make active. By default there is only one group (the "default" group).
$active_record = TRUE;
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "";
$db['default']['password'] = "";
$db['default']['database'] = "";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";

$db['example']['hostname'] = "localhost";
$db['example']['username'] = "root";
$db['example']['password'] = "";
$db['example']['database'] = "example";
$db['example']['dbdriver'] = "mysql";
$db['example']['dbprefix'] = "";
$db['example']['active_r'] = TRUE;
$db['example']['pconnect'] = TRUE;
$db['example']['db_debug'] = TRUE;
$db['example']['cache_on'] = FALSE;
$db['example']['cachedir'] = "";
$db['example']['char_set'] = "utf8";
$db['example']['dbcollat'] = "utf8_general_ci";

//Example 2
$db['example2']['hostname'] = "localhost";
$db['example2']['username'] = "root";
$db['example2']['password'] = "root";
$db['example2']['database'] = "testfoo";
$db['example2']['dbdriver'] = "mysql";
$db['example2']['dbprefix'] = "";
$db['example2']['active_r'] = TRUE;
$db['example2']['pconnect'] = TRUE;
$db['example2']['db_debug'] = TRUE;
$db['example2']['cache_on'] = FALSE;
$db['example2']['cachedir'] = "";
$db['example2']['char_set'] = "utf8";
$db['example2']['dbcollat'] = "utf8_general_ci";
// Check the configuration group in use exists, if not use the default
$active_group = (defined('SITE') && array_key_exists(SITE, $db)) ? SITE : 'default';

The little snippet of code at the bottom will check to see if the SITE constant you have set matches up with a database group. If it doesn’t, it will use the default configuration group.
Your CodeIgniter set-up should now work with any domain you happen to point to it. You even run simple little if(SITE == ‘example2’) checks anywhere within your code to do special code for a certain site, although I would not recommend you doing this too heavily.

Как импортировать *.so библиотеку в Android Studio

Если при запуске прилки – вылетает ошибка:
java.lang.UnsatisfiedLinkError: Couldn’t load mylibrary: findLibrary returned null
То надо сделать следующее:
переместить сюда:


Как экспортировать jks в pem и pk8

keytool -importkeystore -srckeystore trololo.jks -destkeystore trololo.p12 -srcalias trololoalias -srcstoretype jks -deststoretype pkcs12
openssl pkcs12 -in trololo.p12 -out trololo.pem
openssl pkcs8 -topk8 -outform DER -in trololo.pem -inform PEM -out trololo.pk8 -nocrypt

Если в windows вылетает предупреждение:

WARNING: can't open config file: /usr/local/ssl/openssl.cnf

Надо набрать команду:

set OPENSSL_CONF=<path to openssl>bin\openssl.cfg

Доступ в директорию по sFTP в Ubuntu

Задача стоит в следующем – дать доступ по sFTP только в определенную директорию для определенного юзера. FTP все-таки ставить не хочется.

Что мы делаем:

Создаем группу sftp:

sudo groupadd -g 6000 sftp

Создаем пользователя:

sudo useradd -g sftp -u 6000 testuser -d / -m

Создаем директорию для этого юзера:

sudo mkdir /var/www/
sudo mkdir /var/www/

Устанавливаем права на директории:

sudo chown root /var/www/
sudo chown testuser:sftp /var/www/

Как видно – права установленны разные. Root – это необходимо для chroot, чтобы можно было залогиниться по sFTP, а на внутреннюю папку data – стоят уже права пользователя, чтобы он мог производить в ней манипуляции с файлами.

Редактируем /etc/ssh/sshd_config

Subsystem sftp internal-sftp
      Match Group sftp
      ChrootDirectory /var/www%h
      ForceCommand internal-sftp

Если ниже идет UsePAM yes – убираем ее над Subsystem.

Перезагружаем ssh:

sudo service ssh restart

Вот и все! Теперь все юзеры, которые будут добавлены в группу sftp будут иметь доступ только к одной директории.

Multidex для android ниже 5.x

Итак, чтобы заработал нормально multidex и прилка не крэшилась со всякими ошибками на android 4.x и ниже, надо сделать следующее:

1) В build.gradle добавить:

defaultConfig {
    multiDexEnabled true
dependencies {
    compile ''
afterEvaluate {
    tasks.matching {'dex')
    }.each { dx ->
        if (dx.additionalParameters == null) {
            dx.additionalParameters = ['--multi-dex']
        } else {
            dx.additionalParameters += '--multi-dex'

        // Add more additional parameters like this:
        dx.additionalParameters += '--minimal-main-dex'

2) Если у прилки есть Application class:

import android.content.Context;
    protected void attachBaseContext(Context base) {

3) Если Application class отсутствует, то в manifest в application:




Ну и очень неплохо все расписано вот тут у человека:
DEX’s 64k limit is not a problem anymore, well almost…
MultiDex solution for 64k limit in Dalvik

Android Gradle командная строка

Установка JAVA:

sudo apt-get update
sudo apt-get install openjdk-7-jdk

Для Ubuntu x64:

sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386 libc6:i386 lib32z1
cd /usr/lib32
sudo ln -sf
cd /usr/lib
sudo ln -sf /usr/lib32/

Чтобы сохранить путь навсегда. Необходимо записать его в файл профиля для юзера и для root:

sudo nano ~/.bashrc:
sudo apt-get install python-software-properties
apt-get install software-properties-common
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

Выбор версии JAVA:

sudo update-alternatives --config java

Установка необходимых пакетов:

sudo apt-get install git-core gnupg flex bison gperf build-essential \
  zip curl zlib1g-dev gcc-multilib g++-multilib libc6-dev-i386 \
  lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z-dev ccache \
  libgl1-mesa-dev libxml2-utils xsltproc unzip

Установка SDK и обновлений из командной строки:

cd /opt
tar zxf android-sdk_r24.4.1-linux.tgz
cd /opt/android-sdk-linux/tools
./android update sdk -u

-u – это значит без интерфейса. Также можно использовать --no-ui.

Чтобы запускался ./gradlew:

chmod +x gradlew

Чтобы установить определенную SDK и прочее:

./android list sdk --all
./android update sdk -u -a -t <package number>
./android update sdk -u -a -t 1,2,3,4,...,n