private function _load_config() { $fpath_config_dist = $this->home . '/config.inc.php.dist'; $fpath_config = $this->home . '/config.inc.php'; if (is_file($fpath_config_dist) and is_readable($fpath_config_dist)) { $found_config_dist = true; } if (is_file($fpath_config) and is_readable($fpath_config)) { $found_config = true; } if ($found_config_dist or $found_config) { ob_start(); if ($found_config_dist) { include $fpath_config_dist; $vboxadm_config_dist = $vboxadm_config; } if ($found_config) { include $fpath_config; } $config_array = array_merge($vboxadm_config_dist, $vboxadm_config); $this->config = $config_array; $this->vboxapi->setConfig($this->config); //$this->vboxapi->setDebug(1); ob_end_clean(); } else { raise_error(array('code' => 527, 'type' => 'php', 'message' => "Failed to load vboxadm plugin config"), true, true); } }
public static function filter($type, DirItem $item) { if (is_array($type)) { foreach ($type as $_type) { if (self::filter($_type, $item)) { return true; } } } /* * Обработаем callback */ if (is_callable($type)) { return !!call_user_func($type, $item); } $type = $type ? $type : self::ALL; switch ($type) { case self::ALL: return true; case self::IMAGES: return $item->isImg(); case self::DIRS: return $item->isDir(); case self::FILES: return $item->isFile(); case self::ARCHIVES: return $item->checkExtension(array(PsConst::EXT_RAR, PsConst::EXT_ZIP)); default: //Если ни один из фильтров не подошел, проверим, может мы фильтруем по расшерению? if (PsConst::hasExt($type)) { return $item->checkExtension($type); } raise_error("Unknown dir item filter type: [{$type}]."); } }
function __autoload($class) { // parse the class into the correct file format $class_file = strtolower($class) . '.php'; // an array of possible paths containing the class $paths = array('library/', 'application/controllers/', 'application/models/', 'application/library'); // get the config object $config = get_config(); // get the system path $sys_path = $config->get('path.system'); // loop through the paths foreach ($paths as $path) { // append the system path $path = $sys_path . '/' . $path; // append the class file to each path $path .= $class_file; // check if the file exists if (file_exists($path)) { // include the class require_once $path; // break once we have a matching path break; } } // check if we have the class if (!class_exists($class)) { // fake the class' existence if not eval("class " . $class . "{}"); // raise custom error raise_error('Cannot find class: ' . $class); } }
/** * Основной метод получения экземпляра. * * @param type $silentOnDoubleTry - признак, стоит ли нам ругаться, если мы * обнаруживаем зацикливание при попытке получения экземпляра класса. * * Это нужно для классов, которые выполняют сложную логику в конструкторе, которая * может привести к повторному вызову ::inst() внутри этого конструктора. * * Классы, которые используют эту возможность: * @link DbChangeListener - менеджер прослушивания изменений в БД */ protected static function inst($silentOnDoubleTry = false) { $class = get_called_class(); if (array_key_exists($class, self::$_insts_)) { return self::$_insts_[$class]; } if (array_key_exists($class, self::$_instsrq_)) { if ($silentOnDoubleTry) { return null; } raise_error("Double try to get singleton of [{$class}]"); } self::$_instsrq_[$class] = true; //Создаём экземпляр $sec = Secundomer::startedInst("Creating singleton of {$class}"); self::$_insts_[$class] = new $class(); $sec->stop(); //Экземпляр успешно создан unset(self::$_instsrq_[$class]); //Теперь добавим в профайлер. Всё это нужно для защиты от зацикливания. PsProfiler::inst(__CLASS__)->add($class, $sec); //Добавим к глобальному секундомеру - текущий $SECUNDOMER = self::$_secundomer_ ? self::$_secundomer_ : (self::$_secundomer_ = Secundomer::inst()); $SECUNDOMER->addSecundomer($sec); //Отлогируем PsLogger::inst(__CLASS__)->info("+ {$class} ({$sec->getAverage()} / {$SECUNDOMER->getTotalTimeRounded()})"); return self::$_insts_[$class]; }
/** * Dovecot Password File Driver (dovecotpfd) * * Roundcube password plugin driver that adds functionality to change passwords stored in * Dovecot passwd/userdb files (see: http://wiki.dovecot.org/AuthDatabase/PasswdFile) * * Copyright (C) 2011, Charlie Orford * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * * SCRIPT REQUIREMENTS: * * - PHP 5.3.0 or higher, shell access and the ability to run php scripts from the CLI * * - chgdovecotpw and dovecotpfd-setuid.c (these two files should have been bundled with this driver) * * - dovecotpfd-setuid.c must be compiled and the resulting dovecotpfd-setuid binary placed in the same directory * as this script (see dovecotpfd-setuid.c source for compilation instructions, security info and options) * * - chgdovecotpw must be placed in a location where dovecotpfd-setuid can access it once it has changed UID (normally /usr/sbin is a good choice) * * - chgdovecotpw should only be executable by the user dovecotpfd-setuid changes UID to * * - the dovecot passwd/userdb file must be accessible and writable by the same user dovecotpfd-setuid changes UID to * * - dovecotpw (usually packaged with dovecot itself and found in /usr/sbin) must be available and executable by chgdovecotpw * * * @version 1.1 (2011-09-08) * @author Charlie Orford (charlie.orford@attackplan.net) **/ function password_save($currpass, $newpass) { $rcmail = rcmail::get_instance(); $currdir = realpath(dirname(__FILE__)); list($user, $domain) = explode("@", $_SESSION['username']); $username = rcmail::get_instance()->config->get('password_dovecotpfd_format') == "%n" ? $user : $_SESSION['username']; $scheme = rcmail::get_instance()->config->get('password_dovecotpfd_scheme'); // Set path to dovecot passwd/userdb file // (the example below shows how you can support multiple passwd files, one for each domain. If you just use one file, replace sprintf with a simple string of the path to the passwd file) $passwdfile = sprintf("/home/mail/%s/passwd", $domain); // Build command to call dovecotpfd-setuid wrapper $exec_cmd = sprintf("%s/dovecotpfd-setuid -f=%s -u=%s -s=%s -p=\"%s\" 2>&1", $currdir, escapeshellcmd(realpath($passwdfile)), escapeshellcmd($username), escapeshellcmd($scheme), escapeshellcmd($newpass)); // Call wrapper to change password if ($ph = @popen($exec_cmd, "r")) { $response = ""; while (!feof($ph)) { $response .= fread($ph, 8192); } if (pclose($ph) == 0) { return PASSWORD_SUCCESS; } raise_error(array('code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Password plugin: {$currdir}/dovecotpfd-setuid returned an error"), true, false); return PASSWORD_ERROR; } else { raise_error(array('code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Password plugin: error calling {$currdir}/dovecotpfd-setuid"), true, false); return PASSWORD_ERROR; } }
/** * Основной метод, регистрирующий класс для закрытия * * @param Destructable $inst - Экземпляр класса, которй будет гарантированно закрыт в свою очередь * @param int $order - порядок закрытия */ public static function registerDestructable(Destructable $inst, $order) { /* * Класс получаем через get_called_class(), так как PsShotdownSdk может быть переопределён проектным */ $class = get_called_class(); /* * Проверяем, что нам передан валидный order */ $order = PsUtil::assertClassHasConstVithValue($class, null, PsCheck::int($order)); /* * Регистрируем shutdown */ if (is_null(self::$DESTRUCTS)) { PsUtil::assertClassHasDifferentConstValues($class); self::$DESTRUCTS = array(); register_shutdown_function(array(__CLASS__, '_doShotdown')); } /* * Проверим, что нет попытки повторной регистрации с тем-же order */ if (array_key_exists($order, self::$DESTRUCTS)) { raise_error("Попытка повторно зарегистрировать Destructable с порядком [{$order}] для класса " . get_class($inst)); } /* * Регистрируем класс на закрытие */ self::$DESTRUCTS[$order] = $inst; }
public function __construct($name, $comment) { check_condition(defined($name), "Глобальное свойство [{$name}] не определено."); $this->name = $name; $this->val = constant($name); $this->comment = $comment; $type = gettype($this->val); //Определим тип switch ($type) { case PsConst::PHP_TYPE_BOOLEAN: $this->type = self::TYPE_BOOLEAN; break; case PsConst::PHP_TYPE_INTEGER: case PsConst::PHP_TYPE_DOUBLE: case PsConst::PHP_TYPE_FLOAT: $this->type = self::TYPE_NUMERIC; break; case PsConst::PHP_TYPE_STRING: $this->type = self::TYPE_STRING; break; default: /* * "array" * "object" * "resource" * "NULL" * "unknown type" */ raise_error("Неизвестный тип [{$type}] для глобального свойства {$name}."); break; } $this->info = "{$this->name} ({$this->type})"; }
/** * Метод регистрируем маппинг */ protected final function register(Mapping $mapping) { if (array_key_exists($mapping->getHash(), $this->mappings)) { raise_error("Маппинг '{$mapping}' уже заругистрирован"); } else { $this->mappings[$mapping->getHash()] = $mapping; } }
function load($file) { if (!file_exists($file)) { raise_error("{$file}: File does not exist", 'YamlParserError'); return false; } return Spyc::YAMLLoad($file); }
function save($currpass, $newpass) { $rcmail = rcmail::get_instance(); $format = $rcmail->config->get('password_virtualmin_format', 0); $username = $_SESSION['username']; switch ($format) { case 1: // username%domain $domain = substr(strrchr($username, "%"), 1); break; case 2: // username.domain (could be bogus) $pieces = explode(".", $username); $domain = $pieces[count($pieces) - 2] . "." . end($pieces); break; case 3: // domain.username (could be bogus) $pieces = explode(".", $username); $domain = $pieces[0] . "." . $pieces[1]; break; case 4: // username-domain $domain = substr(strrchr($username, "-"), 1); break; case 5: // domain-username $domain = str_replace(strrchr($username, "-"), "", $username); break; case 6: // username_domain $domain = substr(strrchr($username, "_"), 1); break; case 7: // domain_username $pieces = explode("_", $username); $domain = $pieces[0]; break; case 8: // domain taken from alias, username left as it was $email = $rcmail->user->data['alias']; $domain = substr(strrchr($email, "@"), 1); break; default: // username@domain $domain = substr(strrchr($username, "@"), 1); } $username = escapeshellcmd($username); $domain = escapeshellcmd($domain); $newpass = escapeshellcmd($newpass); $curdir = INSTALL_PATH . 'plugins/password/helpers'; exec("{$curdir}/chgvirtualminpasswd modify-user --domain {$domain} --user {$username} --pass {$newpass}", $output, $returnvalue); if ($returnvalue == 0) { return PASSWORD_SUCCESS; } else { raise_error(array('code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Password plugin: Unable to execute {$curdir}/chgvirtualminpasswd"), true, false); } return PASSWORD_ERROR; }
private function _db_connect($mode) { $this->db = rcube_db::factory($this->config['db_dsn'], '', false); $this->db->db_connect($mode); // check DB connections and exit on failure if ($err_str = $this->db->is_error()) { raise_error(array('code' => 603, 'type' => 'db', 'message' => $err_str), FALSE, TRUE); } }
/** * Constructor * * @param string $lang Language code */ function __construct($lang = 'en') { $this->rc = rcmail::get_instance(); $this->engine = $this->rc->config->get('spellcheck_engine', 'googie'); $this->lang = $lang ? $lang : 'en'; if ($this->engine == 'pspell' && !extension_loaded('pspell')) { raise_error(array('code' => 500, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Pspell extension not available"), true, true); } $this->options = array('ignore_syms' => $this->rc->config->get('spellcheck_ignore_syms'), 'ignore_nums' => $this->rc->config->get('spellcheck_ignore_nums'), 'ignore_caps' => $this->rc->config->get('spellcheck_ignore_caps'), 'dictionary' => $this->rc->config->get('spellcheck_dictionary')); }
/** * chpasswd Driver * * Driver that adds functionality to change the systems user password via * the 'chpasswd' command. * * For installation instructions please read the README file. * * @version 1.0 * @author Alex Cartwright <acartwright@mutinydesign.co.uk) */ function password_save($currpass, $newpass) { $cmd = sprintf('echo \'%1$s:%2$s\' | %3$s; echo $?', addcslashes($_SESSION['username'], "'"), addcslashes($newpass, "'"), rcmail::get_instance()->config->get('password_chpasswd_cmd')); if (exec($cmd) == 0) { return PASSWORD_SUCCESS; } else { raise_error(array('code' => 600, 'type' => 'php', 'file' => __FILE__, 'message' => "Password plugin: Unable to execute {$cmd}"), true, false); } return PASSWORD_ERROR; }
public static function ident($item) { if ($item instanceof AbstractPost) { return self::postId($item->getPostType(), $item->getIdent()); } if ($item instanceof Rubric) { return self::rubricId($item->getPostType(), $item->getIdent()); } raise_error('В IdHelper передан элемент неподдрживаемого типа: ' . PsUtil::getClassName($item)); }
/** * Метод ищет в строке подстроки, удовлетворяющие шаблону и заменяет их по очереди на подстановки, * переданные в виде массива. Поиск идёт по регулярному выражению! * * @param string $pattern - шаблон * @param string $text - текст * @param array $tokens - массив подстановок * @return string */ public static function replace($pattern, $text, array $tokens) { self::$inst = self::$inst ? self::$inst : new PregReplaceCyclic(); self::$inst->tokens = check_condition($tokens, 'Не переданы элементы для замены'); if (is_assoc_array($tokens)) { raise_error('Недопустим ассоциативный массив подстановок. Передан: ' . array_to_string($tokens, true)); } self::$inst->idx = 0; self::$inst->count = count($tokens); return preg_replace_callback($pattern, array(self::$inst, '_replace'), $text); }
/** * Название класса */ public static final function isInScope($scope) { switch ($scope) { case ENTITY_SCOPE_ALL: return true; case ENTITY_SCOPE_SDK: return self::isSdk(); case ENTITY_SCOPE_PROJ: return !self::isSdk(); } return raise_error("Invalid entity scope [{$scope}]"); }
public static final function inst($type) { switch ($type) { case PsLogger::OUTPUT_FILE: return new FileLogWriter(); case PsLogger::OUTPUT_CONSOLE: return new ConsoleLogWriter(); case PsLogger::OUTPUT_BROWSER: return new BrowserLogWriter(); } raise_error("Unknown log writer type: [{$type}]."); }
protected function executeImpl(ArrayAdapter $params) { $action = $params->str('action'); switch ($action) { case 'saveIni': ConfigIni::saveIniContent($params->str('scope'), $params->str('content')); break; default: raise_error("Неизвестный тип действия: [{$action}]"); } return new AjaxSuccess(); }
function db_query($query) { global $debug_mode; // Perform Query $result = mysql_query($query); // Check result // This shows the actual query sent to MySQL, and the error. Useful for debugging. if (!$result) { raise_error(604, mysql_errno() . " " . mysql_error() . " : " . $query); } return $result; }
/** * Метод декодирования шаблонных сообщений * * @return TemplateMessageContent */ public function decodeTemplateMsg(DiscussionMsg $msg) { try { check_condition($msg->isTemplated(), "Сообщение {$msg} не шаблонизировано"); $result = $this->getFoldedEntityByDbCode($msg->getTemplateId())->getClassInst()->decodeMsg($msg); if ($result instanceof TemplateMessageContent) { return $result; } raise_error(is_string($result) && !isEmpty($result) ? $result : 'Шаблонное сообщение обработано некорректно'); } catch (Exception $ex) { return new TemplateMessageError($ex); } }
/** * Virtualmin Password Driver * * Driver that adds functionality to change the users Virtualmin password. * The code is derrived from the Squirrelmail "Change Cyrus/SASL Password" Plugin * by Thomas Bruederli. * * It only works with virtualmin on the same host where RoundCube runs * and requires shell access and gcc in order to compile the binary. * * @version 1.0 * @author Martijn de Munnik */ function password_save($currpass, $newpass) { $curdir = realpath(dirname(__FILE__)); $username = escapeshellcmd($_SESSION['username']); $domain = substr(strrchr($username, "@"), 1); exec("{$curdir}/chgvirtualminpasswd modify-user --domain {$domain} --user {$username} --pass {$newpass}", $output, $returnvalue); if ($returnvalue == 0) { return PASSWORD_SUCCESS; } else { raise_error(array('code' => 600, 'type' => 'php', 'file' => __FILE__, 'message' => "Password plugin: Unable to execute {$curdir}/chgvirtualminpasswd"), true, false); } return PASSWORD_ERROR; }
/** * chpasswd Driver * * Driver that adds functionality to change the systems user password via * the 'chpasswd' command. * * For installation instructions please read the README file. * * @version 1.0 * @author Alex Cartwright <acartwright@mutinydesign.co.uk) */ function password_save($currpass, $newpass) { $cmd = rcmail::get_instance()->config->get('password_chpasswd_cmd'); $username = $_SESSION['username']; $handle = popen($cmd, "w"); fwrite($handle, "{$username}:{$newpass}\n"); if (pclose($handle) == 0) { return PASSWORD_SUCCESS; } else { raise_error(array('code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Password plugin: Unable to execute {$cmd}"), true, false); } return PASSWORD_ERROR; }
function password_save($currpass, $newpass) { $curdir = RCUBE_PLUGINS_DIR . 'password/helpers'; $username = escapeshellcmd($_SESSION['username']); $args = rcmail::get_instance()->config->get('password_dbmail_args', ''); exec("{$curdir}/chgdbmailusers -c {$username} -w {$newpass} {$args}", $output, $returnvalue); if ($returnvalue == 0) { return PASSWORD_SUCCESS; } else { raise_error(array('code' => 600, 'type' => 'php', 'file' => __FILE__, 'line' => __LINE__, 'message' => "Password plugin: Unable to execute {$curdir}/chgdbmailusers"), true, false); } return PASSWORD_ERROR; }
/** * Метод возвращает текстовое описание состояния кода */ public function getStateDescr() { $state = $this->getState(); switch ($state) { case UserCodesBean::CODE_STATUS_NOT_EXISTS: return 'Код не зарегестрирован'; case UserCodesBean::CODE_STATUS_INVALID: return 'Код некорректен'; case UserCodesBean::CODE_STATUS_ACTIVE: return 'Код активен'; case UserCodesBean::CODE_STATUS_USED: return 'Код уже использован'; } raise_error("Неизвестное состояние кода [{$this->code}]: {$state}"); }
function load_con_config() { $config = $this->api->dir . 'ispconfig3_account/config/config.inc.php'; if (file_exists($config)) { if (!$this->rcmail_inst->config->load_from_file($config)) { raise_error(array('code' => 527, 'type' => 'php', 'message' => "Failed to load config from {$config}"), TRUE, FALSE); } } else { if (file_exists($config . ".dist")) { if (!$this->rcmail_inst->config->load_from_file($config . '.dist')) { raise_error(array('code' => 527, 'type' => 'php', 'message' => "Failed to load config from {$config}"), TRUE, FALSE); } } } }
function load_config() { $config = $this->home . '/config/config.inc.php'; if (file_exists($config)) { if (!$this->rcmail_inst->config->load_from_file($config)) { raise_error(array('code' => 527, 'type' => 'php', 'message' => "Failed to load config from {$config}"), true, false); } } else { if (file_exists($config . ".dist")) { if (!$this->rcmail_inst->config->load_from_file($config . '.dist')) { raise_error(array('code' => 527, 'type' => 'php', 'message' => "Failed to load config from {$config}"), true, false); } } } }
/** * PAM Password Driver * * @version 1.0 * @author Aleksander Machniak */ function password_save($currpass, $newpass) { $user = $_SESSION['username']; if (extension_loaded('pam')) { if (pam_auth($user, $currpass, $error, false)) { if (pam_chpass($user, $currpass, $newpass)) { return PASSWORD_SUCCESS; } } else { raise_error(array('code' => 600, 'type' => 'php', 'file' => __FILE__, 'message' => "Password plugin: PAM authentication failed for user {$user}: {$error}"), true, false); } } else { raise_error(array('code' => 600, 'type' => 'php', 'file' => __FILE__, 'message' => "Password plugin: PECL-PAM module not loaded"), true, false); } return PASSWORD_ERROR; }
/** * SASL Password Driver * * Driver that adds functionality to change the users Cyrus/SASL password. * The code is derrived from the Squirrelmail "Change SASL Password" Plugin * by Galen Johnson. * * It only works with saslpasswd2 on the same host where RoundCube runs * and requires shell access and gcc in order to compile the binary. * * For installation instructions please read the README file. * * @version 1.0 * @author Thomas Bruederli */ function password_save($currpass, $newpass) { $curdir = realpath(dirname(__FILE__)); $username = escapeshellcmd($_SESSION['username']); $args = rcmail::get_instance()->config->get('password_saslpasswd_args', ''); if ($fh = popen("{$curdir}/chgsaslpasswd -p {$args} {$username}", 'w')) { fwrite($fh, $newpass . "\n"); $code = pclose($fh); if ($code == 0) { return PASSWORD_SUCCESS; } } else { raise_error(array('code' => 600, 'type' => 'php', 'file' => __FILE__, 'message' => "Password plugin: Unable to execute {$curdir}/chgsaslpasswd"), true, false); } return PASSWORD_ERROR; }
/** * Основной метод, выполняющий обновление пользователя * * @param type $userId * @param array $whatAssoc * @param array $whereAssoc * @return type */ private function updateUser($userId, array $whatAssoc, array $whereAssoc = array()) { //Сразу валидируем код пользователя $userId = AuthManager::validateUserId($userId); //В апдейте можно использовать только ассоциативные параметры Query::assertOnlyAssocParams($whatAssoc); //Получим список обновляемых колонок $columns = check_condition(array_keys($whatAssoc), 'Не переданы параметры обновления пользователя'); //Проверим на наличие запрещённых полей $denyColumns = array_intersect(self::$UPDATE_DENY_FIELDS, $columns); if ($denyColumns) { raise_error('Cледующие параметры пользователя не могут быть обновлены: ' . array_to_string(array_values($denyColumns))); } //Проверим на наличие неизвестных полей $unknownColumns = array_diff($columns, self::getColumns()); if ($unknownColumns) { raise_error('Попытка обновить недопустимые параметры пользователя: ' . array_to_string(array_values($unknownColumns))); } //Загружаем текущее состояние, на всякий случай предварительно сбросив кеш $OLD = $this->getUserDataById($this->reset($userId)); //Сбрасываем кеш и выполняем обновление $whereAssoc[self::FIELD_ID] = $this->reset($userId); $updated = $this->update(Query::update('users', $whatAssoc, $whereAssoc)); if ($updated <= 0) { return; //--- } //Загружаем новое состояние $NEW = $this->getUserDataById($this->reset($userId)); //Сравним и запишем аудит $DIF = array(); foreach ($OLD as $column => $oldValue) { if (in_array($column, self::$SKIP_AUDIT_ON_UPDATE_FIELDS)) { continue; //--- } $newValue = $NEW[$column]; if (strcmp(trim($oldValue), trim($newValue)) != 0) { $DIF[$column] = $newValue; } } if (empty($DIF)) { return; //--- } UserAudit::inst()->onUpdate($userId, $DIF); }
function db_query($query) { global $b_debugmode; // Perform Query $result = mysql_query($query); // Check result // This shows the actual query sent to MySQL, and the error. Useful for debugging. if (!$result) { if ($b_debugmode) { // echo mysql_errno() . ": " . mysql_error() . "\n<br>"; $message = '<b>Invalid query:</b><br>' . mysql_error() . '<br><br>'; $message .= '<b>Whole query:</b><br>' . $query . '<br><br>'; // die($message); } raise_error('db_query_error: ' . $message); } return $result; }