Показаны сообщения с ярлыком CodeIgniter. Показать все сообщения
Показаны сообщения с ярлыком CodeIgniter. Показать все сообщения

четверг, 8 ноября 2012 г.

DX Auth: нашёлся на github'е

Некоторое время назад остро стояла проблема где скачать DX Auth, на http://dexcell.shinsengumiteam.com/dx_auth библиотека стала не доступна.

Несколько дней назад обнаружил свежую версию библиотеки на github'е: https://github.com/eyoosuf/DX-Auth

Там же но в ветке initial https://github.com/eyoosuf/DX-Auth/tree/initial можно найти версию 1.0.6.

суббота, 18 декабря 2010 г.

DX Auth: Примеры. Пример с правами доступа

В последнем фрагменте перевода, руководства пользователя библиотеки DX Auth фреймворка CodeIgniter, мы рассмотрим пример установки прав доступа используя модель application/models/dx_auth/permissions.php.

пятница, 17 декабря 2010 г.

DX Auth: Примеры. Пример использования reCAPTCHA

Десятая часть перевода документации библиотеки авторизации DX Auth для фреймворка CodeIgniter.

Рассмотрим расширенный пример контроллера Auth, демонстрирующий возможность использования reCAPTCHA с библиотекой DX Auth. Убедитесь, что вы указали общий и личный ключ в файле конфигурации, иначе пример не будет работать.

среда, 15 декабря 2010 г.

DX Auth: Примеры. Расширенный пример

Девятая часть перевода документации библиотеки авторизации DX Auth для фреймворка CodeIgniter.
Это более расширенный пример использования библиотеки DX Auth, для реализации контроллера Auth.
Все пояснения вы можете увидеть в комментариях кода контроллера.

DX Auth: Примеры. Простой пример

Перед тестированием пример убедитесь, что вы установили DX Auth в соответствии с инструкцией.

Библиотека DX Auth довольно проста в использовании, например создадим контроллер Auth, с классом Auth.

воскресенье, 12 декабря 2010 г.

DX Auth: Руководство пользователя. Модели.

Шестая часть перевода документации библиотеки авторизации DX Auth для фреймворка CodeIgniter.

Библиотека DX Auth поставляется с несколькими моделями, которые расположены в каталоге 'models/dx_auth/'

Модели содержат функции для работы с определёнными таблицами. Вы можете использовать функционал этих моделей для создания своей административной панели. По названию функций легко понять какие действия они выполняют, что облегчает их использование.

Итак, вот список моделей расположенных в каталоге 'models/dx_auth/':

  • users.php содержит набор функций для работы с таблицей 'DX_users_table'
  • user_profile.php содержит набор функций для работы с таблицей 'DX_user_profile_table'
  • user_temp.php содержит набор функций для работы с таблицей 'DX_user_temp_table'
  • user_autologin.php содержит набор функций для работы с таблицей 'DX_user_autologin'
  • roles.php содержит набор функций для работы с таблицей 'DX_roles_table'
  • permissions.php содержит набор функций для работы с таблицей 'DX_permissions_table'
  • login_attempts.php содержит набор функций для работы с таблицей 'DX_login_attempts_table'

DX Auth: Руководство пользователя. Конфигурация

Пятая часть перевода документации библиотеки авторизации DX Auth для фреймворка CodeIgniter.

Это файл конфигурации библиотеки DX Auth. Все параметры прокомментированы в коде.

DX Auth: Руководство пользователя. События

Четвёртая часть перевода документации библиотеки авторизации DX Auth для фреймворка CodeIgniter.

События, функции которые вызываются при определённых условиях. В данном случае срабатывание происходит, когда их вызывают определённые функции библиотеки DX Auth. Для обработки этих событий вам нужно открыть 'libraries/DX_Auth_Event.php' и разместить ваш код в нужных функциях - обработчиках событий.

понедельник, 6 декабря 2010 г.

DX Auth: Руководство пользователя. Справочник по функциям класса

Третья часть перевода документации библиотеки авторизации DX Auth для фреймворка CodeIgniter.


Далее приведён список функций которые вы можете использовать в работе с библиотекой DX Auth.

  • Основные функции
  • reCAPTCHA функции
  • Устаревшие функции

воскресенье, 5 декабря 2010 г.

DX Auth: Руководство пользователя. Начало

Вторая часть перевода документации библиотеки авторизации DX Auth для фреймворка CodeIgniter.

После выполнения установки DX Auth с примерами входящими в комплект и настройкой файла application/config/config.php вы можете увидеть простой пример работы приложения с подключенной библиотекой.

Что вы можете сделать:

  • {Ваш CI url}/auth/login/ - вход на сайт
  • {Ваш CI url}/auth/logout/ - выход с сайта
  • {Ваш CI url}/auth/register/ - регистрация нового пользователя
  • {Ваш CI url}/auth/register_recaptcha/ - регистрация нового пользователя с использованием reCAPTCHA
  • {Ваш CI url}/auth/forgot_password/ - восстановление забытого пароля
  • {Ваш CI url}/auth/change_password/ - смена пароля
  • {Ваш CI url}/auth/cancel_account/ - удаление аккаунта вошедшего пользователя

Для доступа в панель управления вам нужно зайти под пользователем 'admin' или другим пользователем у роли которого есть доступ к администрированию.

  • {Ваш CI url}/backend/users/ - для управления пользователями
  • {Ваш CI url}/backend/unactivated_users/ - для управления не активированными пользователями
  • {Ваш CI url}/backend/roles/ - для управления ролями
  • {Ваш CI url}/backend/uri_permissions/ - для управления URI разрешениями
  • {Ваш CI url}/backend/custom_permissions/ - для управления пользовательскими разрешениями

Обычно {Ваш CI url} состоит из комбинации 'base_url' и 'index_page' вашего конфигурационного файла.

CodeIgniter: библиотека DX Auth

DX Auth библиотека авторизации для фреймворка CodeIgniter. Даёт возможность легко подключать к вашему проекту гибкую систему авторизации, настраиваемую от простой до полной системы аутентификации.

DX Auth позволяет использовать интернационализацию настраиваемую через языковые файлы.

Библиотека DX Auth основана на библиотеке CL Auth 0.2.5 разработанной Джейсоном Эшдауном (Jason Ashdown).

вторник, 30 ноября 2010 г.

Ion Auth: Справочник по функциям класса

Вторая часть перевода документации по системе авторизации Ion Auth для CodeIgniter. как следует из названия, в этой части описываются методы библиотеки ion_auth

Первая часть: CodeIgniter: библиотека Ion Auth

Методы доступные в моделе вызываются через контроллер с помощью "магических" методов PHP5 . В своих приложениях вы не должны использовать вызовы, типа ion_auth_model->method()

Репозитарий github с Ion Auth

понедельник, 29 ноября 2010 г.

CodeIgniter: библиотека Ion Auth

Ion Auth - это простая и легковесная библиотека авторизации для CodeIgniter, разработанная Беном Эдмундсом.

Огромное преимущество этой системы в том, что она работоспособна практически из "коробки" и требует минимум настроек для своей полноценной работы. Но это не означает, что её нельзя кастомизировать под свои нужды.

Библиотека Ion Auth, является дальнейшим развитием системы Redux Auth для работы с пользователями

пятница, 30 апреля 2010 г.

CodeIgniter: Хэлпер show_errors

Сделал хэлпер с show_403(), по аналогии с show_404().

Код выложил в googlecode.

error_403.php для /application/errors/ прилагается :)

CodeIgniter 2.0: load_class

Изменился формат вызова load_class.
Был:

/**
* Class registry
*
* This function acts as a singleton. If the requested class does not
* exist it is instantiated and set to a static variable. If it has
* previously been instantiated the variable is returned.
*
* @access public
* @param string the class name being requested
* @param bool optional flag that lets classes get loaded but not instantiated
* @return object
*/
function &load_class($class, $instantiate = TRUE)

Стал:

/**
* Class registry
*
* This function acts as a singleton. If the requested class does not
* exist it is instantiated and set to a static variable. If it has
* previously been instantiated the variable is returned.
*
* @access public
* @param string the class name being requested
* @param string the directory where the class should be found
* @param string the class name prefix
* @return object
*/
function &load_class($class, $directory = 'libraries', $prefix = 'CI_')


Benchmark, Config, Controller, Exceptions, Hooks, Input, Lang, Loader, Model, Output, Router, Unicode, URI - теперь в 'core'.

P.S. Сегодня долго с Exceptions бился...

пятница, 19 марта 2010 г.

CodeIgniter 2.0. В ожидании релиза.

Близится релиз второй версии CodeIgniter'а.

Changelog:

General changes
  • PHP 4 support is deprecated. Features new to 2.0.0 may not support PHP 4, and all legacy features will no longer support PHP 4 as of 2.1.0.
  • Scaffolding, having been deprecated for a number of versions, has been removed.
  • Plugins have been removed, in favor of Helpers. The CAPTCHA plugin has been converted to a Helper and documented. The JavaScript calendar plugin was removed due to the ready availability of great JavaScript calendars, particularly with jQuery.
  • Added new special Library type: Drivers.
  • Added routing overrides to the main index.php file, enabling the normal routing to be overridden on a per "index" file basis.
  • Added the ability to set config values (or override config values) directly from data set in the main index.php file. This allows a single application to be used with multiple front controllers, each having its own config values.
  • Added $config['directory_trigger'] to the config file so that a controller sub-directory can be specified when running _GET strings instead of URI segments.
  • Added ability to set "Package" paths - specific paths where the Loader and Config classes should try to look first for a requested file. This allows distribution of sub-applications with their own libraries, models, config files, etc. in a single "package" directory. See the Loader class documentation for more details.
  • In-development code is now hosted at BitBucket.

Libraries
  • Added Security library, which now contains the xss_clean function, filename_security function and other security related functions.
  • Added CSRF (Cross-site Reference Forgery) protection to the Security library.
  • Added $parse_exec_vars property to Output library.
  • Added ability to enable / disable individual sections of the Profiler
  • Added a wildcard option $config['allowed_types'] = '*' to the File Uploading Class.
  • Added an 'object' config variable to the XML-RPC Server library so that one can specify the object to look for requested methods, instead of assuming it is in the $CI superobject.
  • Added "is_object" into the list of unit tests capable of being run.
  • Table library will generate an empty cell with a blank string, or NULL value.
  • Added ability to set tag attributes for individual cells in the Table library
  • Added a parse_string() method to the Parser Class.
  • Added HTTP headers and Config information to the Profiler output.
  • Added Chrome and Flock to the list of detectable browsers by browser() in the User Agent Class.
  • The Unit Test Class now has an optional "notes" field available to it, and allows for discrete display of test result items using $this->unit->set_test_items().

Database
  • Added swap_pre value to database configuration.
  • Added autoinit value to database configuration.
  • Added stricton value to database configuration.
  • Added database_exists() to the Database Utilities Class.
  • Semantic change to db->version() function to allow a list of exceptions for databases with functions to return version string instead of specially formed SQL queries. Currently this list only includes Oracle and SQLite.
  • Fixed a bug where driver specific table identifier protection could lead to malformed queries in the field_data() functions.
  • Fixed a bug where an undefined class variable was referenced in database drivers.

Helpers
  • Added convert_accented_characters() function to text helper.
  • Added accept-charset to the list of inserted attributes of form_open() in the Form Helper.
  • Deprecated the dohash() function in favour of do_hash() for naming consistency.
  • Non-backwards compatible change made to get_dir_file_info() in the File Helper. No longer recurses by default so as to encourage responsible use (this function can cause server performance issues when used without caution).
  • Modified the second parameter of directory_map() in the Directory Helper to accept an integer to specify recursion depth.
  • Modified delete_files() in the File Helper to return FALSE on failure.
  • Added an optional second parameter to byte_format() in the Number Helper to allow for decimal precision.
  • Added alpha, and sha1 string types to random_string() in the String Helper.

Other Changes
  • Updated loader to automatically apply the sub-class prefix as an option when loading classes. Class names can be prefixed with the standard "CI_" or the same prefix as the subclass prefix, or no prefix at all.
  • Increased randomness with is_really_writable() to avoid file collisions when hundreds or thousands of requests occur at once.
  • Switched some DIR_WRITE_MODE constant uses to FILE_WRITE_MODE where files and not directories are being operated on.
  • get_mime_by_extension() is now case insensitive.
  • Added "default" to the list Reserved Names.
  • Added 'application/x-msdownload' for .exe files and ''application/x-gzip-compressed' for .tgz files to config/mimes.php.
  • Documented append_output() in the Output Class.
  • Documented a second argument in the decode() function for the Encryption Class.
  • Documentd db->close().

Bug fixes for 2.0.0

  • Fixed a bug where a failed query would not have a saved query execution time causing errors in the Profiler
  • Fixed a bug that was writing log entries when multiple identical helpers and plugins were loaded.
  • Fixed assorted user guide typos or examples (#10693, #8951, #7825, #8660, #7883, #6771, #10656).
  • Fixed a language key in the profiler: "profiler_no_memory_usage" to "profiler_no_memory".
  • Fixed an error in the Zip library that didn't allow downloading on PHP 4 servers.
  • Fixed a bug in the Form Validation library where fields passed as rule parameters were not being translated (#9132)
  • Modified inflector helper to properly pluralize words that end in 'ch' or 'sh'
  • Fixed a bug in xss_clean() that was not allowing hyphens in query strings of submitted URLs.
  • Fixed bugs in get_dir_file_info() and get_file_info() in the File Helper with recursion, and file paths on Windows.
  • Fixed a bug where Active Record override parameter would not let you disable Active Record if it was enabled in your database config file.
  • Fixed a bug in reduce_double_slashes() in the String Helper to properly remove duplicate leading slashes (#7585)
  • Fixed a bug in values_parsing() of the XML-RPC library which prevented NULL variables typed as 'string' from being handled properly.
  • Fixed a bug were form_open_multipart() didn't accept string attribute arguments (#10930).
  • Fixed a bug (#10470) where get_mime_by_extension() was case sensitive.
  • Fixed a bug where some error messages for the SQLite and Oracle drivers would not display.

пятница, 19 февраля 2010 г.

Русификация calendar_lang.php в CodeIgniter

Оказалось в русском языке существует несколько вариантов сокращений. Взял, "советский", из википедии, знакомый с детства :)


<?php
$lang['cal_su'] = "Вс";
$lang['cal_mo'] = "Пн";
$lang['cal_tu'] = "Вт";
$lang['cal_we'] = "Ср";
$lang['cal_th'] = "Чт";
$lang['cal_fr'] = "Пт";
$lang['cal_sa'] = "Сб";
$lang['cal_sun'] = "Вск";
$lang['cal_mon'] = "Пнд";
$lang['cal_tue'] = "Втр";
$lang['cal_wed'] = "Срд";
$lang['cal_thu'] = "Чтв";
$lang['cal_fri'] = "Птн";
$lang['cal_sat'] = "Сбт";
$lang['cal_sunday'] = "Воскресенье";
$lang['cal_monday'] = "Понедельник";
$lang['cal_tuesday'] = "Вторник";
$lang['cal_wednesday'] = "Среда";
$lang['cal_thursday'] = "Четверг";
$lang['cal_friday'] = "Пятница";
$lang['cal_saturday'] = "Суббота";
$lang['cal_jan'] = "Янв";
$lang['cal_feb'] = "Фев";
$lang['cal_mar'] = "Мар";
$lang['cal_apr'] = "Апр";
$lang['cal_may'] = "Май";
$lang['cal_jun'] = "Июн";
$lang['cal_jul'] = "Июл";
$lang['cal_aug'] = "Авг";
$lang['cal_sep'] = "Сен";
$lang['cal_oct'] = "Окт";
$lang['cal_nov'] = "Ноя";
$lang['cal_dec'] = "Дек";
$lang['cal_january'] = "Январь";
$lang['cal_february'] = "Февраль";
$lang['cal_march'] = "Март";
$lang['cal_april'] = "Апрель";
$lang['cal_mayl'] = "Май";
$lang['cal_june'] = "Июнь";
$lang['cal_july'] = "Июль";
$lang['cal_august'] = "Август";
$lang['cal_september'] = "Сентябрь";
$lang['cal_october'] = "Октябрь";
$lang['cal_november'] = "Ноябрь";
$lang['cal_december'] = "Декабрь";


/* End of file calendar_lang.php */
/* Location: ./system/language/russian/calendar_lang.php */

среда, 17 февраля 2010 г.

MY_Loader.php расширения загрузчика для подключения "глобальных моделей"


<?php
/**
* MY_Loader Class
*
* Loads global_models
*
* @package CodeIgniter
* @subpackage Libraries
* @author snake.nf
* @category Loader
*/
class MY_Loader extends CI_Loader
{
function MY_Loader()
{
parent::CI_Loader();
}

/**
* Global Model Loader
*
* This function lets users load and instantiate global models.
*
* @access public
* @param string the name of the class
* @param string name for the model
* @param bool database connection
* @return void
*/
function global_model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach($model as $babe)
{
$this->model($babe);
}
return;
}

if ($model == '')
{
return;
}

// Is the model in a sub-folder? If so, parse out the filename and path.
if (strpos($model, '/') === FALSE)
{
$path = '';
}
else
{
$x = explode('/', $model);
$model = end($x);
unset($x[count($x)-1]);
$path = implode('/', $x).'/';
}

if ($name == '')
{
$name = $model;
}

if (in_array($name, $this->_ci_models, TRUE))
{
return;
}

$CI =& get_instance();
if (isset($CI->$name))
{
show_error('The model name you are loading is the name of a resource that is already being used: '.$name);
}

$model = strtolower($model);

if ( ! file_exists(APPPATH.'../global_models/'.$path.$model.EXT))
{
show_error('Unable to locate the model you have specified: '.$model);
}

if ($db_conn !== FALSE AND ! class_exists('CI_DB'))
{
if ($db_conn === TRUE)
$db_conn = '';

$CI->load->database($db_conn, FALSE, TRUE);
}

if ( ! class_exists('Model'))
{
load_class('Model', FALSE);
}

require_once(APPPATH.'../global_models/'.$path.$model.EXT);

$model = ucfirst($model);

$CI->$name = new $model();
$CI->$name->_assign_libraries();

$this->_ci_models[] = $name;
}

}
?>

CodeIgniter: Multiple Applications и общие модели в приложениях

CodeIgniter Недавно столкнулся с тем, что в приложениях backend и frontend используются общие модели. Пытался найти в CodeIgniter механизм подключения общих моделей для нескольких приложений. В течении дня были просмотрены несколько русско- и англоязычных сообществ и их форумов, множество блогов и т.д.
Все кто используют frontend и backend на CodeIgniter умалчивают о том, как они работают с моделями.
К вечеру уже начал подниматься вопрос о переходе с CodeIgniter на другой фреймворк, в частности на Zend Framework. После беглого осмотра возможностей Zend Framework'a не нашёл нативной возможности подключения внешних моделей. :(

Сегодня решил по глубже посмотреть ядро CodeIgniter, на предмет добавления хака для работы с общими моделями.
Решение вопроса былой найдено в классе ядра CI_Loader.
Собственно вопрос решался изменением двух строк 162 и 180 в которых используются пути к моделям.
Строка 162:
if ( ! file_exists(APPPATH.'models/'.$path.$model.EXT))
Cтрока 180:
require_once(APPPATH.'models/'.$path.$model.EXT)
Первой мыслью было просто заменить пути и не париться, но тогда лишился бы возможности использовать локальные модели для каждого приложения.
Просмотрев документацию по созданию классов ядра, нашёл более простое и нативное решение. Расширение класса ядра CI_Loader.
class MY_Loader extends CI_Loader {

function My_Loader()
{
parent::CI_Loader();
}

function global_model($model, $name = '', $db_conn = FALSE)
{
....
}

}

global_model полностью копирует model за исключением двух строк в которых изменяем пути.
Остаётся положить MY_Loader в libraries обоих приложений и теперь имеем возможность использовать глобальные и локальные модели.

На мой взгляд такой вариант наиболее оптимальным, т.к. это не вност изменения в ядро системы, легко переноситься в другие приложения, не требует лишних телодвижений при обновлении CodeIgniter'а.

Естественно нельзя использовать локальные и глобальные модели с одинаковыми именами. В контроллерах, за исключеним замены $this->load->model('Model_name'), на $this->load->global_model('Model_name') для глобальных моделей, ничего менять не придётся, т.к. мы только расширим Loader.

На практике пока не опробовано, но займусь этим в ближайшее время.