Exemple #1
0
 /**
  * Генерирует файл сайтмапа
  */
 public static function generate()
 {
     $register = new SystemRegister('System/Sitemap');
     if ($register->get('sitemap.xml')->value == 0) {
         return;
     }
     // Получаем все url сайта
     $sql = 'SELECT * FROM `' . SITEMAP_TABLE . '` where `visible`="1"';
     $aSitemap = DB::query($sql);
     //
     $xmlDocument = new DOMDocument('1.0', 'utf-8');
     //
     $urlset = $xmlDocument->createElement('urlset');
     $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
     foreach ($aSitemap as $row) {
         $url = $xmlDocument->createElement('url');
         $loc = $xmlDocument->createElement('loc');
         $lastmod = $xmlDocument->createElement('lastmod');
         $changefreq = $xmlDocument->createElement('changefreq');
         $priority = $xmlDocument->createElement('priority');
         $loc->nodeValue = \Extasy\CMS::getWWWRoot() . substr($row['full_url'], 1);
         $lastmod->nodeValue = $row['date_updated'];
         $changefreq->nodeValue = $row['sitemap_xml_change'];
         $priority->nodeValue = $row['sitemap_xml_priority'];
         $url->appendChild($loc);
         $url->appendChild($lastmod);
         $url->appendChild($changefreq);
         $url->appendChild($priority);
         $urlset->appendChild($url);
     }
     $xmlDocument->appendChild($urlset);
     // Пишем в папку xml
     $xmlContents = $xmlDocument->saveXML();
     file_put_contents(FILE_PATH . 'sitemap.xml', $xmlContents);
 }
Exemple #2
0
 public static function getAutoIncrement($table)
 {
     Trace::addMessage(__CLASS__, sprintf('Getting auto_increment from table:"%s"', $table));
     $result = parent::getAutoIncrement($table);
     Trace::addMessage(__CLASS__, sprintf('Auto_increment fetched'));
     return $result;
 }
Exemple #3
0
 public static function dbFixture($tableName, $data)
 {
     $sql = sprintf(' TRUNCATE `%s` ', $tableName);
     \Faid\DB::post($sql);
     //
     foreach ($data as $row) {
         \Faid\DBSimple::insert($tableName, $row);
     }
 }
 public function cleanup($period = 0)
 {
     if (!empty($period)) {
         DBSimple::delete(self::TableName, array(sprintf('`actionDate` <= NOW() - INTERVAL %s', $period)));
     } else {
         $sql = sprintf('truncate %s ', self::TableName);
         DB::post($sql);
     }
 }
Exemple #5
0
 public static function checkLoginOrEmailExists($login, $email)
 {
     $sql = 'SELECT * FROM `%s` WHERE STRCMP(`login`,"%s") = 0 or (LENGTH("%s") > 0 and STRCMP(`email`,"%s") = 0) ';
     $sql = sprintf($sql, USERS_TABLE, DB::escape($login), DB::escape($email), DB::escape($email));
     $aResult = DB::query($sql);
     if (!empty($aResult)) {
         throw new Exception('Login or email already registered. Login - ' . $login . ' Email:' . $email);
     }
 }
Exemple #6
0
 protected static function lookForEmail($email)
 {
     $sql = 'SELECT * FROM `%s` WHERE STRCMP(`email`,"%s") = 0';
     $sql = sprintf($sql, USERS_TABLE, $email);
     $aFound = DB::get($sql);
     if (empty($aFound)) {
         throw new \NotFoundException('Email not found in database');
     }
     return $aFound;
 }
Exemple #7
0
 /**
  * Тест установки sitemap-индекса к конфигу  
  */
 public function testSetupLink()
 {
     $schema = CConfig::getSchema('test');
     $schema->setupSitemapLink(2);
     $this->assertEquals(2, $schema->getSitemapLink());
     // Проверяет на уровне бд
     $sql = 'SELECT `sitemapId` FROM `custom_config_schema` WHERE `name`="%s" ';
     $sql = sprintf($sql, 'test');
     $field = DB::getField($sql, 'sitemapId');
     //
     $this->assertEquals('2', $field);
 }
Exemple #8
0
    protected function createTable()
    {
        $sql = <<<SQL
create table `test_document` (
\t`id` int not null auto_increment,
\t`name` varchar(255 ) not null default '',
\tprimary key (`id`)
);
SQL;
        DB::post($sql);
        DBSimple::insert(Model::TableName, array('name' => 'sitemap document'));
    }
Exemple #9
0
 protected function loadLastFail()
 {
     $lastId = !empty($this->successId) ? $this->successId : 0;
     $condition = array('user_id' => $this->user->id->getValue(), 'status' => LoginAttempt::FailStatus, sprintf('`id` > "%d"', DB::escape($lastId)), sprintf('`date` < NOW() '));
     $this->failCount = DBSimple::getRowsCount(LoginAttempt::TableName, $condition);
     $last = DBSimple::get(LoginAttempt::TableName, $condition, 'order by `id` desc');
     if (!empty($last)) {
         $model = new LoginAttempt($last);
         $this->failLastIp = $model->host->getValue();
         $this->failLastDate = $model->date->getValue();
     }
 }
Exemple #10
0
 protected function loadConfigurationFile()
 {
     try {
         $sql = sprintf('truncate %s ', Job::TableName);
         DB::post($sql);
         $path = \Faid\Configure\Configure::read(self::ConfigureKey);
         $validator = new ReadableFile($path);
         if ($validator->isValid()) {
             include $path;
         }
         \CMSLog::addMessage(__CLASS__, 'Schedule restarted');
     } catch (\Exception $e) {
         \CMSLog::addMessage(__CLASS__, $e);
         return ['error' => 'internal error'];
     }
     return;
 }
Exemple #11
0
 public function __construct(Dispatcher $dispatcher, $environment = null)
 {
     if (empty(self::$instance)) {
         self::$instance = $this;
     }
     \Trace::addMessage('CMS', 'CMS::load');
     $this->loadEnvironment($environment);
     \Faid\DB::checkConnection();
     SystemRegisterSample::startup();
     $this->dispatcher = $dispatcher;
     self::autoloadConfig();
     $this->initializeRoutes();
     $this->initializeApis();
     \Trace::addMessage('CMS', '`init` event');
     \EventController::callEvent(self::SystemInitEvent, $this);
     $this->processSecurity();
     \Trace::addMessage('CMS', 'Стартовало');
 }
Exemple #12
0
 /**
  * Возвращает по ID его предка
  */
 public static function createById($nId)
 {
     $nId = IntegerHelper::toNatural($nId);
     //
     $sql = 'SELECT * FROM `%s` WHERE `id`="%d"';
     $sql = sprintf($sql, SYSTEMREGISTER_TABLE, $nId);
     //
     $aResult = DB::get($sql);
     if (empty($aResult)) {
         throw new SystemRegisterException('Key with id="' . $nId . '" not found');
     }
     // Нашли корневой элемент
     if ($aResult['parent'] == 0) {
         $result = new SystemRegister($aResult['name']);
     } else {
         $result = self::createById($aResult['parent'])->get($aResult['name']);
     }
     return $result;
 }
Exemple #13
0
 /**
  * Loads sitemap data for collected data
  */
 public function loadSitemapData()
 {
     if (empty($this->data)) {
         return;
     }
     //
     $sqlFilter = array();
     foreach ($this->data as $row) {
         $sqlFilter[] = intval($row['id']);
     }
     //
     $sql = 'SELECT * FROM `%s` WHERE `document_id` IN (%s) and STRCMP(`document_name`,"%s") = 0 and visible = 1';
     $sql = sprintf($sql, SITEMAP_TABLE, implode($sqlFilter, ','), $this->modelName);
     $tmp = DB::query($sql);
     $this->sitemapInfoMap = array();
     foreach ($tmp as $row) {
         $this->sitemapInfoMap[$row['document_id']] = $row;
     }
     return $this;
 }
Exemple #14
0
    /**
     * Осуществляет сортировку по определенному полю у конкретного документа
     */
    public static function sortByField($nId, $szDocumentName, $szFieldName, $bAsc = true)
    {
        //
        $nId = IntegerHelper::toNatural($nId);
        $szDocumentName = \Faid\DB::escape($szDocumentName);
        $szFieldName = \Faid\DB::escape($szFieldName);
        $bAsc = intval($bAsc);
        //
        // Получаем всех детей элемента, которые имеют указанный документ в кач. имени
        //
        $szTable = call_user_func([$szDocumentName, 'getTableName']);
        $sql = <<<SQL
\tSELECT `sitemap`.id,`sitemap`.document_id
\tFROM `%s` as `sitemap` 
\tINNER JOIN `%s` as `document` 
\tON `sitemap`.`parent` = %d and `sitemap`.document_id = `document`.id and `sitemap`.document_name = "%s" 
\tORDER BY `document`.%s %s
SQL;
        $sql = sprintf($sql, SITEMAP_TABLE, $szTable, $nId, $szDocumentName, $szFieldName, $bAsc ? ' ASC' : ' DESC');
        $aDocumentsData = DB::query($sql);
        // Получаем всех остальных детей
        $sql = 'SELECT * FROM `%s` WHERE `parent`="%d" and STRCMP(`document_name`,"%s") <> 0 ORDER by `order`';
        $sql = sprintf($sql, SITEMAP_TABLE, $nId, $szDocumentName);
        $aOtherData = DB::query($sql);
        // Выстраиваем детей совмещаем массивы, неотсортированные элементы остаются на своих местах
        $aResult = array();
        $nOrder = 0;
        while (sizeof($aDocumentsData) > 0 || sizeof($aOtherData) > 0) {
            if (!empty($aOtherData) && $aOtherData[0]['order'] == $nOrder) {
                $aElement = array_shift($aOtherData);
                $aResult[] = $aElement['id'];
            } else {
                //
                $aElement = array_shift($aDocumentsData);
                $aResult[] = $aElement['id'];
            }
            $nOrder++;
        }
        //
        Sitemap::manualOrder($nId, $aResult);
    }
Exemple #15
0
    public function update($group, $permissions)
    {
        if (empty($group)) {
            $this->AddAlert('Группа пользователей не выбрана');
            $this->jump('./');
        }
        set_time_limit(0);
        $page = 0;
        $groupInfo = DBSimple::get(ACL_TABLE, ['name' => $group]);
        if (empty($groupInfo)) {
            throw new \InvalidArgumentException(sprintf('Group "%s" not found, failed to update group permissions', htmlspecialchars($group)));
        }
        $permissions = $this->filterPermissionsByGroup($group, $permissions);
        do {
            // получаем пользователей
            $sql = <<<SQL
\tselect u.* from %s as u
\tinner join %s as r
\ton r.entity = concat("%s", u.id)
\twhere r.actionId = "%s"
\torder by id asc
\tlimit %d,%d
SQL;
            $sql = sprintf($sql, \UserAccount::getTableName(), \ACL_GRANT_TABLE, \Faid\DB::escape(\UserAccount::ModelName), $groupInfo['id'], $page * self::Limit, self::Limit);
            $data = DB::query($sql);
            // устанавливаем каждому права
            foreach ($data as $row) {
                $user = new \UserAccount($row);
                $tmp = $user->rights->getValue();
                $tmp = array_merge($tmp, $permissions);
                $user->rights = $tmp;
                $user->update();
            }
            $page++;
        } while (sizeof($data) != 0);
        $this->addAlert('Права обновлены');
        $this->jump('./');
    }
Exemple #16
0
 public static function autoLoadFromCookie()
 {
     $isCookieSet = !empty($_COOKIE[self::cookieName]);
     if (!$isCookieSet) {
         return;
     }
     $passwordHash = $_COOKIE[self::cookieName];
     // Запрос провещяюрий есть ли юзер или нет и не забанен ли он
     $sql = 'SELECT * FROM `%s` WHERE LENGTH(`confirmation_code`) = 0 and md5(CONCAT(`password`,"%s",`id`)) = "%s"';
     $sql = sprintf($sql, USERS_TABLE, DB::escape(\Faid\Configure\Configure::read(\Extasy\CMS::SaltConfigureKey)), DB::escape($passwordHash));
     //
     $aFound = DB::get($sql);
     if (empty($aFound)) {
         return false;
     }
     try {
         self::forceLogin(new UserAccount($aFound));
         return true;
     } catch (Exception $e) {
         // Игнорируем случай неверной аутентификации
     }
     return false;
 }
Exemple #17
0
 protected function action()
 {
     set_time_limit(0);
     $sitemapIndex = new DOMDocument('1.0', 'utf-8');
     $el = $sitemapIndex->createElement('sitemapindex');
     $el->setAttribute('xmlns', "http://www.sitemaps.org/schemas/sitemap/0.9");
     $sitemapIndex->appendChild($el);
     $sitemapUrlCount = DB::getField('select count(*) as `count` from `sitemap`', 'count');
     $counter = 0;
     while ($counter < $sitemapUrlCount) {
         $sql = 'select * from `sitemap` where `document_name` <> "statistic_page" and `document_name` <> "externallink" order by `id` asc limit %d,%d';
         $sql = sprintf($sql, $counter, self::SitemapLimit);
         $urlList = DB::query($sql);
         // Создаем первый документ
         $sitemap = $this->createSitemapDocument();
         // Обрабатываем его
         $this->processUrls($sitemapIndex, $sitemap, $urlList);
         // СОхраняем результат
         $this->storeSitemap($sitemapIndex, $sitemap);
         $counter += self::SitemapLimit;
     }
     file_put_contents(FILE_PATH . 'sitemap.xml', $sitemapIndex->saveXML());
     self::restart();
 }
Exemple #18
0
<?php

use Faid\DB;
$sql = <<<SQL
\tcreate table schedule_job (
\t\t`id` int not null auto_increment,
\t\t`status` int not null default 0,
\t\t`action` varchar(255) not null default '',
\t\t`class` varchar(255) not null default '',
\t\t`dateCreated` datetime not null default "0000-00-00 00:00:00",
\t\t`actionDate` datetime not null default "0000-00-00 00:00:00",
\t\t`repeatable` int not null default 0,
\t\t`period` int not null default 0,
\t\t`data` blob null,
\t\tprimary key (`id`),
\t\tindex status (`status`)
\t)
SQL;
DB::post($sql);
Exemple #19
0
 protected function changeLogin($password, $login)
 {
     $login = \Faid\DB::$connection->real_escape_string($login);
     $oUser = UsersLogin::getCurrentSession();
     if ($login == $oUser->login->getValue()) {
         return;
     }
     if ($this->register->get('front-end')->ignore_password_field->value == 0) {
         $isSamePassword = $this->checkPassword($password, $oUser);
         if (!$isSamePassword) {
             $this->addValidationError('updatePassword');
             return;
         }
     }
     $sql = 'SELECT * FROM `%s` WHERE `login` = "%s" and `id` <> %d';
     $sql = sprintf($sql, USERS_TABLE, $login, $oUser->id->getValue());
     //
     $aGet = DB::get($sql);
     // Ого! уже есть акк с таким емейлом, навиду подстава! ;)
     if (!empty($aGet)) {
         $this->addValidationError('updateLogin');
         return;
     }
     $old_login = $oUser->email->getValue();
     $oUser->login->setValue($login);
     $oUser->update();
     EventController::callEvent('users_after_update_login', $oUser, $old_login, $login);
     $this->addSuccess('updateLogin');
 }
Exemple #20
0
 public function setUp()
 {
     DB::post('truncate table test_model');
     DBSimple::insert('test_model', array('id' => 1, 'name' => self::fixtureName));
 }
Exemple #21
0
    protected function getCounts()
    {
        $sql = <<<SQL
\t\tselect 
\t\t\t(select count(*) from `custom_config_groups`) as `tabcount`,
\t\t\t(select count(*) from `custom_config_items`) as `controlcount`
SQL;
        $result = DB::get($sql);
        return $result;
    }
Exemple #22
0
 protected function execQuery($sql, $bUseAssoc = true)
 {
     $aResult = DB::query($sql, $bUseAssoc);
     return $aResult;
 }
Exemple #23
0
 /**
  * Возвращает список всех пользователей системы
  */
 public static function selectAllUsers()
 {
     $sql = 'select * from `%s` WHERE `id` > 2 order by `login` ';
     $sql = sprintf($sql, CMS_AUTH_TABLE);
     return DB::query($sql);
 }
Exemple #24
0
 public static function getPagingInfo()
 {
     $sql = 'select FOUND_ROWS() as `found` ';
     $result = DB::get($sql);
     $found = !empty($result['found']) ? intval($result['found']) : 0;
     return array('page' => self::$lastSearchRequest->page, 'total' => $found);
 }
Exemple #25
0
 public static function createCache()
 {
     self::clearCache();
     self::disableCache();
     // Получаем все ряды, выстроенные по предку
     $sql = 'SELECT * FROM `%s` ORDER by `parent` ASC,`id` ASC';
     $sql = sprintf($sql, SYSTEMREGISTER_TABLE);
     $aData = DB::query($sql);
     // Перебор всех рядов
     $parent = -1;
     $aChild = array();
     foreach ($aData as $row) {
         // Если предок изменился, то генерируем другой childCache
         if ($row['parent'] != $parent) {
             if (!empty($aChild)) {
                 self::storeChildCache($parent, $aChild);
                 $aChild = array();
             }
             $parent = $row['parent'];
             $aChild[] = $row;
         } else {
             $aChild[] = $row;
         }
         // Добавляем в getCache
         self::storeGetCache($row['name'], $parent, $row);
     }
     self::enableCache();
     SimpleCache::set(SYSTEM_REGISTER_GET_CACHE, self::$aGetCache);
     SimpleCache::set(SYSTEM_REGISTER_CHILD_CACHE, self::$aChildCache);
 }
Exemple #26
0
 protected static function cleanDB()
 {
     $sql = sprintf(' delete from %s where `date` < "%s"', self::TableName, date('Y-m-d H:i:s', strtotime('-' . self::$config['Period'])));
     DB::post($sql);
 }
Exemple #27
0
 /**
  * Проверяет что урл доступен
  */
 protected static function checkUrlAvailable($sitemapId, $parentId, $urlKey)
 {
     $sitemapId = IntegerHelper::toNatural($sitemapId);
     $parentId = IntegerHelper::toNatural($parentId);
     $urlKey = \Faid\DB::escape($urlKey);
     // Получаем все документы с указанным url_key и parent
     $sql = 'select * from `%s` where parent = "%d" and `url_key`="%s" ';
     $sql = sprintf($sql, SITEMAP_TABLE, $parentId, $urlKey);
     $data = DB::query($sql);
     // Если их 0, то всё ок
     if (sizeof($data) == 0) {
         return;
     }
     // Если их больше 1
     if (sizeof($data) > 1) {
         // бросаем исключение
         $message = 'Sitemap tree conflict in parent_id=%d and url_key=%s ';
         $message = sprintf($message, $parentId, $urlKey);
         throw new SiteMapException($message);
     }
     // Если одна, то сравниваем индексы
     $data = $data[0];
     if ($data['id'] != $sitemapId) {
         // не совпадают
         // бросаем исключение
         $message = 'Sitemap tree conflict for sitemap_id=%d in parent_id=%d and url_key=%s url already used by sitemap_id="%d"';
         $message = sprintf($message, $sitemapId, $parentId, $urlKey, $data['id']);
         throw new SiteMapException($message);
     }
 }
Exemple #28
0
 /**
  * Тестируем каскадное удаление
  */
 public function testRecursiveRemoving()
 {
     $document = new TestDocument();
     $document->name = 'Test inserting';
     $document->insert();
     $nRoot = Sitemap::addPage('Test inserting', 'xx', TestDocument::ModelName, 1, 0);
     $document = new TestDocument();
     $document->name = 'Test inserting2';
     $document->insert();
     Sitemap::addPage('Test inserting2', 'xx', TestDocument::ModelName, 2, $nRoot);
     //
     Sitemap::removeDocument(TestDocument::ModelName, '1');
     // Проверяем удаление из бд
     $result = DB::get(sprintf('SELECT COUNT(*) as `count` FROM `%s`', TestDocument::TableName));
     $this->assertEquals($result['count'], 0);
 }
Exemple #29
0
/**
*   -------------------------------------------------------------------------------------------
*   @desc Создает строку для поиска в MySQL таблице
*   @return
*   -------------------------------------------------------------------------------------------
*/
function to_search_string($str)
{
    return addCslashes(str_replace('\\', '\\\\', htmlspecialchars(\Faid\DB::escape(trim($str)))), '_%');
}
<?php 
use Faid\DB;
use Faid\DBSimple;
use Extasy\Audit\Record;
use Extasy\Audit\Log;
DB::post('TRUNCATE audit_logs');
DB::post('TRUNCATE audit_records');
//
$sql = 'select distinct category from cms_log order by category asc';
$data = DB::query($sql);
foreach ($data as $row) {
    $log = createLog($row);
    importMessages($log, $row['category']);
}
function createLog($row)
{
    $log = new Log();
    $log->name = 'Developer.' . $row['category'];
    $log->enable_logging = true;
    if (CMSLog::RuntimeErrors == $row['category']) {
        $log->critical = true;
    }
    $log->insert();
    return $log;
}
function importMessages($log, $category)
{
    $data = selectMessages($category);
    foreach ($data as $record) {
        Record::add($log->name, $record['message'], $record['message']);