Ejemplo n.º 1
0
 public static function getInstance()
 {
     if (self::$instance === null) {
         self::$instance = new self();
     }
     return self::$instance;
 }
Ejemplo n.º 2
0
 private function doPackage()
 {
     $manifest = $this->parsePackageManifest();
     if (isset($manifest['package'])) {
         return call_user_func(array($this, $manifest['package']['type'] . $manifest['package']['action']), $manifest);
     }
     $cache = cmsCache::getInstance();
     $cache->clean('controllers');
     $cache->clean('events');
     return '';
 }
Ejemplo n.º 3
0
 public function run($id = false)
 {
     if (!$id) {
         cmsTemplate::getInstance()->renderJSON(array('error' => true));
     }
     $item = $this->model->getItemByField('controllers', 'id', $id);
     if (!$item) {
         cmsTemplate::getInstance()->renderJSON(array('error' => true));
     }
     $is_pub = $item['is_enabled'] ? false : true;
     $this->model->update('controllers', $id, array('is_enabled' => $is_pub));
     $cache = cmsCache::getInstance();
     $cache->clean('controllers');
     $cache->clean('events');
     cmsTemplate::getInstance()->renderJSON(array('error' => false, 'is_on' => $is_pub));
 }
Ejemplo n.º 4
0
 /**
  * Возвращает записи из базы, применяя все наложенные ранее фильтры
  * @return array
  */
 public function get($table_name, $item_callback = false, $key_field = 'id')
 {
     $this->table = $table_name;
     $sql = $this->getSQL();
     // сбрасываем фильтры
     $this->resetFilters();
     // если указан ключ кеша для этого запроса
     // то пробуем получить результаты из кеша
     if ($this->cache_key) {
         $cache_key = $this->cache_key . '.' . md5($sql);
         $cache = cmsCache::getInstance();
         if (false !== ($items = $cache->get($cache_key))) {
             $this->stopCache();
             return $items;
         }
     }
     $result = $this->db->query($sql);
     // если запрос ничего не вернул, возвращаем ложь
     if (!$this->db->numRows($result)) {
         return false;
     }
     $items = array();
     // перебираем все вернувшиеся строки
     while ($item = $this->db->fetchAssoc($result)) {
         $key = $key_field ? $item[$key_field] : false;
         // если задан коллбек для обработки строк,
         // то пропускаем строку через него
         if (is_callable($item_callback)) {
             $item = $item_callback($item, $this);
             if ($item === false) {
                 continue;
             }
         }
         // добавляем обработанную строку в результирующий массив
         if ($key) {
             $items[$key] = $item;
         } else {
             $items[] = $item;
         }
     }
     // если указан ключ кеша для этого запроса
     // то сохраняем результаты в кеше
     if ($this->cache_key) {
         $cache->set($cache_key, $items);
         $this->stopCache();
     }
     $this->db->freeResult($result);
     // возвращаем строки
     return $items;
 }
Ejemplo n.º 5
0
 /**
  * Обновляет кеш списка привязки слушателей к событиям
  * @return boolean
  */
 public static function getAllListeners()
 {
     $cache = cmsCache::getInstance();
     $cache_key = 'events';
     if (false !== ($structure = $cache->get($cache_key))) {
         return $structure;
     }
     $manifests = cmsCore::getControllersManifests();
     if (!$manifests) {
         return false;
     }
     $structure = array();
     foreach ($manifests as $controller_name => $manifest) {
         if (!isset($manifest['hooks'])) {
             continue;
         }
         if (!is_array($manifest['hooks'])) {
             continue;
         }
         foreach ($manifest['hooks'] as $event_name) {
             $structure[$event_name][] = $controller_name;
         }
     }
     $cache->set($cache_key, $structure, 86400);
     return $structure;
 }
Ejemplo n.º 6
0
 public function deleteUserEntries($user_id)
 {
     cmsCache::getInstance()->clean("activity.entries");
     return $this->delete('activity', $user_id, 'user_id');
 }
Ejemplo n.º 7
0
    $root = str_replace(str_replace(DIRECTORY_SEPARATOR, '/', realpath(ROOT)), '', str_replace(DIRECTORY_SEPARATOR, '/', PATH));
    header('location:' . $root . '/install/');
    die;
}
// Загружаем локализацию
cmsCore::loadLanguage();
// устанавливаем локаль языка
if (function_exists('lang_setlocale')) {
    lang_setlocale();
}
// Устанавливаем часовую зону
date_default_timezone_set($config->time_zone);
// Подключаем все необходимые классы и библиотеки
cmsCore::loadLib('html.helper');
cmsCore::loadLib('strings.helper');
cmsCore::loadLib('files.helper');
cmsCore::loadLib('spyc.class');
// подключаем хелпер шаблона, если он есть
if (!cmsCore::includeFile('templates/' . $config->template . '/assets/helper.php')) {
    cmsCore::loadLib('template.helper');
}
// Инициализируем ядро
$core = cmsCore::getInstance();
// Подключаем базу
$core->connectDB();
if (!$core->db->ready()) {
    cmsCore::error(ERR_DATABASE_CONNECT, $core->db->connectError());
}
// Запускаем кеш
cmsCache::getInstance()->start();
Ejemplo n.º 8
0
 public function deleteTracking($id)
 {
     cmsCache::getInstance()->clean('comments.tracks');
     return $this->delete('comments_tracks', $id);
 }
Ejemplo n.º 9
0
 public function deleteUserVotes($user_id)
 {
     cmsCache::getInstance()->clean('rating.votes');
     return $this->delete('rating_log', $user_id, 'user_id');
 }
Ejemplo n.º 10
0
 public function renamePhoto($id, $title)
 {
     if (!$title) {
         $title = sprintf(LANG_PHOTOS_PHOTO_UNTITLED, $id);
     }
     $photo = $this->getPhoto($id);
     $this->update("photos", $id, array('title' => $title));
     cmsCache::getInstance()->clean("photos.{$photo['album_id']}");
 }
Ejemplo n.º 11
0
function migratePhotos()
{
    $model = cmsCore::getModel('photos');
    $config = cmsConfig::getInstance();
    $photos = $model->orderByList(array(array('by' => 'album_id', 'to' => 'asc'), array('by' => 'date_pub', 'to' => 'asc')))->limit(false)->get('photos', function ($item, $model) {
        $item['image'] = cmsModel::yamlToArray($item['image']);
        return $item;
    });
    if (!$photos) {
        return false;
    }
    $album_ids = $last_photo_id = $order = array();
    foreach ($photos as $photo) {
        $album_ids[] = $photo['album_id'];
        $_order = isset($order[$photo['album_id']]) ? $order[$photo['album_id']] : 1;
        $_widths = $_heights = $sizes = $width_presets = array();
        foreach ($photo['image'] as $preset => $path) {
            if (!is_readable($config->upload_path . $path)) {
                continue;
            }
            $s = getimagesize($config->upload_path . $path);
            if ($s === false) {
                continue;
            }
            $_widths[] = $s[0];
            $_heights[] = $s[1];
            $sizes[$preset] = array('width' => $s[0], 'height' => $s[1]);
            $width_presets[$s[0]] = $preset;
        }
        $order[$photo['album_id']] = $_order + 1;
        $last_photo_id[$photo['album_id']] = $photo['id'];
        // exif
        $max_size_preset = $width_presets[max($_widths)];
        $image_data = img_get_params($config->upload_path . $photo['image'][$max_size_preset]);
        $date_photo = isset($image_data['exif']['date']) ? $image_data['exif']['date'] : false;
        $camera = isset($image_data['exif']['camera']) ? $image_data['exif']['camera'] : null;
        unset($image_data['exif']['date'], $image_data['exif']['camera'], $image_data['exif']['orientation']);
        $photo['slug'] = $model->getPhotoSlug($photo);
        $photo['sizes'] = $sizes;
        $photo['height'] = max($_heights);
        $photo['width'] = max($_widths);
        $photo['ordering'] = $_order;
        $photo['orientation'] = $image_data['orientation'];
        $photo['date_photo'] = $date_photo;
        $photo['camera'] = $camera;
        $photo['exif'] = !empty($image_data['exif']) ? $image_data['exif'] : null;
        $model->filterEqual('id', $photo['id'])->updateFiltered('photos', $photo);
    }
    $album_ids = array_unique($album_ids);
    foreach ($album_ids as $album_id) {
        cmsCache::getInstance()->clean("photos.{$album_id}");
        $model->updateAlbumCoverImage($album_id, array($last_photo_id[$album_id]));
        $model->updateAlbumPhotosCount($album_id);
    }
}
Ejemplo n.º 12
0
 public function updateUserRating($user_id, $score)
 {
     $this->filterEqual('id', $user_id);
     if ($score > 0) {
         $this->increment('{users}', 'rating', abs($score));
     }
     if ($score < 0) {
         $this->decrement('{users}', 'rating', abs($score));
     }
     cmsCache::getInstance()->clean("users.list");
     cmsCache::getInstance()->clean("users.user.{$user_id}");
 }
Ejemplo n.º 13
0
 public function removeDoubles($tag_id)
 {
     $this->select('COUNT(i.tag_id) as qty')->filterEqual('tag_id', $tag_id)->groupBy('target_controller, target_subject, target_id')->get('tags_bind', function ($item, $model) {
         if ($item['qty'] > 1) {
             $model->delete('tags_bind', $item['id']);
         }
     });
     cmsCache::getInstance()->clean("tags.tags");
 }
Ejemplo n.º 14
0
 public function updateCommentsCount($subject, $id, $comments_count)
 {
     $item = $this->getPhoto($id);
     if (!$item) {
         return false;
     }
     $this->update('photos', $item['id'], array('comments' => $comments_count));
     cmsCache::getInstance()->clean("photos.{$item['album_id']}");
     return true;
 }
Ejemplo n.º 15
0
//                   produced by InstantSoft, instantsoft.ru                  //
//                        LICENSED BY GNU/GPL v2                              //
//                                                                            //
/******************************************************************************/
session_start();
define('VALID_RUN', true);
// Устанавливаем кодировку
header('Content-type:text/html; charset=utf-8');
header('X-Powered-By: InstantCMS');
require_once 'bootstrap.php';
if (cmsConfig::get('emulate_lag')) {
    usleep(350000);
}
// Инициализируем шаблонизатор
$template = cmsTemplate::getInstance();
if (href_to('auth', 'login') != $_SERVER['REQUEST_URI']) {
    if (!cmsConfig::get('is_site_on') && !cmsUser::isAdmin()) {
        cmsCore::errorMaintenance();
    }
}
cmsEventsManager::hook('engine_start');
//Запускаем роутинг и контроллер
$core->route($_SERVER['REQUEST_URI']);
$core->runController();
$core->runWidgets();
//Выводим готовую страницу
$template->renderPage();
cmsEventsManager::hook('engine_stop');
// Останавливаем кеш
cmsCache::getInstance()->stop();
Ejemplo n.º 16
0
 public function deleteUPS($key, $user_id)
 {
     if ($user_id && $key) {
         $this->filterEqual('user_id', $user_id)->filterEqual('skey', $key);
     } elseif ($user_id) {
         $this->filterEqual('user_id', $user_id);
     } elseif ($key) {
         $this->filterEqual('skey', $key);
     } else {
         return false;
     }
     $ret = $this->deleteFiltered('{users}_personal_settings');
     cmsCache::getInstance()->clean('users.ups');
     return $ret;
 }
Ejemplo n.º 17
0
                    </span>
                    <?php 
if ($config->debug && cmsUser::isAdmin()) {
    ?>
                        <span class="item">
                            SQL: <a href="#sql_debug" class="ajax-modal"><?php 
    echo $core->db->query_count;
    ?>
</a>
                        </span>
                        <?php 
    if ($config->cache_enabled) {
        ?>
                            <span class="item">
                                Cache: <?php 
        echo cmsCache::getInstance()->query_count;
        ?>
                            </span>
                        <?php 
    }
    ?>
                        <span class="item">
                            Mem: <?php 
    echo round(memory_get_usage() / 1024 / 1024, 2);
    ?>
 Mb
                        </span>
                        <span class="item">
                            Time: <?php 
    echo number_format(cmsCore::getTime(), 4);
    ?>
Ejemplo n.º 18
0
 public function reorderWidgetsBindings($position, $items, $page_id = 0)
 {
     cmsCache::getInstance()->clean("widgets.bind");
     $this->reorderByList('widgets_bind', $items, array('position' => $position));
     $update_data = array('page_id' => $page_id);
     if ($position == '_unused') {
         $update_data['page_id'] = null;
     }
     $this->filterIn('id', $items)->updateFiltered('widgets_bind', $update_data);
 }
Ejemplo n.º 19
0
 public function approveContentItem($ctype_name, $id, $moderator_user_id)
 {
     $table_name = $this->table_prefix . $ctype_name;
     $this->update($table_name, $id, array('is_approved' => 1, 'approved_by' => $moderator_user_id, 'date_approved' => ''));
     cmsCache::getInstance()->clean("content.list.{$ctype_name}");
     cmsCache::getInstance()->clean("content.item.{$ctype_name}");
     return true;
 }
Ejemplo n.º 20
0
 public function deleteMenuItem($id)
 {
     $item = $this->getMenuItem($id);
     $tree = $this->getMenuItemsTree($item['menu_id'], false);
     $level = false;
     $node_start = false;
     $to_delete = array($id);
     $to_reorder = array();
     foreach ($tree as $item) {
         if ($item['id'] == $id) {
             $node_start = true;
             $level = $item['level'];
             continue;
         }
         if ($node_start) {
             if ($item['level'] > $level) {
                 $to_delete[] = $item['id'];
                 continue;
             } else {
                 $node_start = false;
             }
         }
         $to_reorder[] = $item['id'];
     }
     foreach ($to_delete as $item_id) {
         $this->delete('menu_items', $item_id);
     }
     $this->reorderByList('menu_items', $to_reorder);
     cmsCache::getInstance()->clean("menu.items");
     return true;
 }
Ejemplo n.º 21
0
 public function updateCommentsCount($ctype_name, $id, $comments_count)
 {
     $table_name = $this->table_prefix . $ctype_name;
     $this->update($table_name, $id, array('comments' => $comments_count));
     cmsCache::getInstance()->clean("content.list.{$ctype_name}");
     cmsCache::getInstance()->clean("content.item.{$ctype_name}");
     return true;
 }
Ejemplo n.º 22
0
 public function deleteUserEntries($user_id)
 {
     $this->delete('wall_entries', $user_id, 'user_id');
     $this->delete('wall_entries', $user_id, 'profile_id');
     cmsCache::getInstance()->clean('wall.entries');
     cmsCache::getInstance()->clean('wall.count');
 }
Ejemplo n.º 23
0
 /**
  * Сохраняет опции контроллера
  * @param string $controller_name
  * @param array $options
  * @return boolean
  */
 static function saveOptions($controller_name, $options)
 {
     $model = new cmsModel();
     $model->filterEqual('name', $controller_name);
     $model->updateFiltered('controllers', array('options' => $options));
     cmsCache::getInstance()->clean('controllers');
     return true;
 }
Ejemplo n.º 24
0
 public function runWidget($widget)
 {
     $user = cmsUser::getInstance();
     $is_user_view = $user->isInGroups($widget['groups_view']);
     $is_user_hide = !empty($widget['groups_hide']) && $user->isInGroups($widget['groups_hide']) && !$user->is_admin;
     if ($is_user_hide) {
         return false;
     }
     if (!$is_user_view) {
         return false;
     }
     $path = 'system/' . cmsCore::getWidgetPath($widget['name'], $widget['controller']);
     $file = $path . '/widget.php';
     cmsCore::includeFile($file);
     cmsCore::loadWidgetLanguage($widget['name'], $widget['controller']);
     $class = 'widget' . ($widget['controller'] ? string_to_camel('_', $widget['controller']) : '') . string_to_camel('_', $widget['name']);
     $widget_object = new $class($widget);
     $cache_key = "widgets.{$widget['id']}";
     $cache = cmsCache::getInstance();
     if (!$widget_object->isCacheable() || false === ($result = $cache->get($cache_key))) {
         $result = call_user_func_array(array($widget_object, 'run'), array());
         if ($result) {
             // Отдельно кешируем имя шаблона виджета, поскольку оно могло быть
             // изменено внутри виджета, а в кеш у нас попадает только тот массив
             // который возвращается кодом виджета (без самих свойств $widget_object)
             $result['_wd_template'] = $widget_object->getTemplate();
         }
         $cache->set($cache_key, $result);
     }
     if ($result === false) {
         return false;
     }
     if (isset($result['_wd_template'])) {
         $widget_object->setTemplate($result['_wd_template']);
     }
     cmsTemplate::getInstance()->renderWidget($widget_object, $result);
 }
Ejemplo n.º 25
0
 public function updateMembershipRole($group_id, $user_id, $new_role)
 {
     cmsCache::getInstance()->clean("groups.members");
     return $this->filterEqual('group_id', $group_id)->filterEqual('user_id', $user_id)->updateFiltered('groups_members', array('role' => $new_role, 'date_updated' => null));
 }
Ejemplo n.º 26
0
 public function unbindAllWidgets()
 {
     cmsCache::getInstance()->clean('widgets.bind');
     $this->filterNotNull('page_id')->updateFiltered('widgets_bind', array('position' => '_unused', 'page_id' => null));
 }