source: trunk/core/cms.php @ 810

Revision 810, 149.4 KB checked in by r2, 11 months ago (diff)

свойство $inCore->component должно быть публичным

  • Property svn:executable set to *
Line 
1<?php
2/******************************************************************************/
3//                                                                            //
4//                             InstantCMS v1.8                                //
5//                        http://www.instantcms.ru/                           //
6//                                                                            //
7//                   written by InstantCMS Team, 2007-2010                    //
8//                produced by InstantSoft, (www.instantsoft.ru)               //
9//                                                                            //
10//                        LICENSED BY GNU/GPL v2                              //
11//                                                                            //
12/******************************************************************************/
13
14if(!defined('VALID_CMS')) { die('ACCESS DENIED'); }
15
16define('CORE_VERSION',          '1.8');
17define('CORE_BUILD',            '1');
18define('CORE_VERSION_DATE', '2011-04-04');
19define('CORE_BUILD_DATE',       '2011-04-04');
20
21if (!defined('USER_UPDATER')) { define('USER_UPDATER', -1); }
22if (!defined('USER_MASSMAIL')) { define('USER_MASSMAIL', -2); }
23
24class cmsCore {
25
26    private static  $instance;
27
28    private         $start_time;
29
30    private         $menu_item;
31    private         $menu_id = 0;
32    private         $menu_struct;
33    private         $is_menu_id_strict;
34
35    private         $uri;
36    public          $component;
37    private         $is_content = false;
38
39    private         $module_configs = array();
40    private         $component_configs = array();
41
42    private         $smarty = false;
43
44    private function __construct($install_mode=false) {
45
46        if ($install_mode){ return; }
47
48        //ïîäêëþ÷èì áàçó è êîíôèã
49        $this->loadClass('db');
50        $this->loadClass('config');
51
52        $inConf = cmsConfig::getInstance();
53
54        //ïðîâåðÿåì áûë ëè ïåðåîïðåäåëåí øàáëîí ÷åðåç ñåññèþ
55        //íàïðèìåð, èç ìîäóëÿ "âûáîð øàáëîíà"
56        if (isset($_SESSION['template'])) { $inConf->template = $_SESSION['template']; }
57
58        define('TEMPLATE', $inConf->template);
59        define('TEMPLATE_DIR', PATH.'/templates/'.$inConf->template.'/');
60        define('DEFAULT_TEMPLATE_DIR', PATH.'/templates/_default_/');
61
62        //çàãðóçèì ñòðóêòóðó ìåíþ â ïàìÿòü
63        $this->loadMenuStruct();
64
65        //ïîëó÷èì URI
66        $this->uri = $this->detectURI();
67
68        //îïðåäåëèì êîìïîíåíò
69        $this->component = $this->detectComponent();
70
71    }
72
73    private function __clone() {} 
74
75    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
76
77    public $single_run_plugins = array('wysiwyg');
78
79    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
80    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
81    public static function getInstance($install_mode=false) {
82        if (self::$instance === null) { 
83            self::$instance = new self($install_mode);
84        } 
85        return self::$instance;
86    }
87
88    public function getHost(){
89
90        $this->loadClass('idna_convert');
91
92        $IDN = new idna_convert();
93
94        $host = iconv('utf-8', 'cp1251', $IDN->decode($_SERVER['HTTP_HOST']));
95
96        return $host;
97
98    }
99
100    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
101    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
102    public function startGenTimer() {
103
104        $start_time         = microtime();
105        $start_array        = explode(" ",$start_time);
106        $this->start_time   = $start_array[1] + $start_array[0];
107        return true;
108
109    }
110
111    public function getGenTime(){
112
113        $end_time   = microtime();
114        $end_array  = explode(" ", $end_time);
115        $end_time   = $end_array[1] + $end_array[0];
116        $time       = $end_time - $this->start_time;
117
118        return $time;
119
120    }
121
122    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
123    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
124    public static function loadLanguage($file) {   
125        global $_CFG;
126        global $_LANG;
127
128        $langfile = PATH.'/languages/'.$_CFG['lang'].'/'.$file.'.php';
129
130        if (!file_exists($langfile)){ $langfile = PATH.'/languages/ru/'.$file.'.php'; }
131
132        if (!file_exists($langfile)){ return false; }
133
134        include_once($langfile);
135        return true;
136    }
137
138    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
139    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
140    /**
141     * Ñîðòèðóåò àññîöèàòèâíûé ìàññèâ
142     * @param array $array
143     * @param string $sort_by (êðèòåðèé ñîðòèðîâêè)
144     * @param int $desc (1 - ïî âîçðàñòàíèþ, 0 - ïî óáûâàíèþ)
145     * @param string $f (ôóíêöèÿ ñðàâíåíèÿ)
146     * @return array
147     */
148    public static function sortArray($array, $sort_by, $desc = 0, $f='strcmp') {
149
150                if (!$desc) { $desc = 1; } else { $desc = -1;}
151               
152                usort($array, create_function('$a, $b', "return $desc*$f(\$b['$sort_by'], \$a['$sort_by']);"));
153
154        return($array);
155
156    }
157
158    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
159    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
160    /**
161     * Ïðåîáðàçóåò ìàññèâ â YAML
162     * @param array $array
163     * @return string
164     */
165    public function arrayToYaml($array) {
166
167        $this->includeFile('includes/spyc/spyc.php');
168
169        $yaml = Spyc::YAMLDump($array,2,40);
170
171        return $yaml;
172
173    }
174
175    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
176    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
177    /**
178     * Ïðåîáðàçóåò YAML â ìàññèâ
179     * @param string $yaml
180     * @return array
181     */
182    public function yamlToArray($yaml) {
183
184        $this->includeFile('includes/spyc/spyc.php');
185
186        $array = Spyc::YAMLLoad($yaml);
187
188        return $array;
189
190    }
191
192    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
193    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
194    /**
195     * Ïðîèçâîäèò ñîáûòèå, âûçûâàÿ âñå íàçíà÷åííûå íà íåãî ïëàãèíû
196     * @param string $event
197     * @param mixed $item
198     * @return mixed
199     */
200    public static function callEvent($event, $item){
201
202        //ïîëó÷àåì âñå àêòèâíûå ïëàãèíû, ïðèâÿçàííûå ê óêàçàííîìó ñîáûòèþ
203        $plugins = self::getInstance()->getEventPlugins($event);
204
205        //åñëè àêòèâíûõ ïëàãèíîâ íåò, âîçâðàùàåì ýëåìåíò $item áåç èçìåíåíèé
206        if (!$plugins) { return $item; }
207
208        //ïåðåáèðàåì ïëàãèíû è âûçûâàåì êàæäûé èç íèõ, ïåðåäàâàÿ ýëåìåíò $item
209        foreach($plugins as $plugin_name){
210
211            $plugin = self::getInstance()->loadPlugin( $plugin_name );
212
213            if ($plugin!==false){
214                $item = $plugin->execute($event, $item);
215                self::getInstance()->unloadPlugin($plugin);
216
217                if ( in_array($plugin->info['type'], self::getInstance()->single_run_plugins)) {
218                    return $item;
219                }
220            }
221           
222        }
223
224        //âîçðàùàåì $item îáðàòíî
225        return $item;
226
227    }
228
229    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
230    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
231    /**
232     * Âîçâðàùàåò ìàññèâ ñ èìåíàìè ïëàãèíîâ, ïðèâÿçàííûõ ê ñîáûòèþ $event
233     * @param string $event
234     * @return array
235     */
236    public function getEventPlugins($event) {
237        $inDB = cmsDatabase::getInstance();
238
239        $plugins_sql = "SELECT p.plugin as plugin
240                        FROM cms_plugins p, cms_event_hooks e
241                        WHERE p.published = 1 AND e.plugin_id = p.id AND e.event = '{$event}'
242                        LIMIT 10";
243
244        $result = $inDB->query($plugins_sql);
245
246        if ( !$inDB->num_rows($result) ) { return false; }
247
248        $plugins_list = array();
249
250        while($plugin = $inDB->fetch_assoc($result)){
251            $plugins_list[] = $plugin['plugin'];
252        }
253
254        return $plugins_list;
255    }
256
257    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
258    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
259    /**
260     * Óñòàíàâëèâàåò ïëàãèí è äåëàåò åãî ïðèâÿçêó ê ñîáûòèÿì
261     * Âîçâðàùàåò ID óñòàíîâëåííîãî ïëàãèíà
262     * @param array $plugin
263     * @param array $events
264     * @param array $config
265     * @return int
266     */
267    public function installPlugin($plugin, $events, $config) {
268        $inDB = cmsDatabase::getInstance();
269
270        if (!$plugin['type']) { $plugin['type'] = 'plugin'; }
271
272        $config_yaml    = $this->arrayToYaml($config);
273
274        if (!$config_yaml) { $config_yaml = ''; }
275
276        //äîáàâëÿåì ïëàãèí â áàçó
277        $install_query  = "INSERT INTO cms_plugins (id, plugin, title, description, author, version, plugin_type, published, config)
278                           VALUE ('', '{$plugin['plugin']}', '{$plugin['title']}', '{$plugin['description']}', '{$plugin['author']}',
279                                  '{$plugin['version']}', '{$plugin['type']}', 0, '{$config_yaml}')";
280
281        $inDB->query($install_query);
282
283        //ïîëó÷àåì ID ïëàãèíà
284        $plugin_id = $inDB->get_last_id('cms_plugins');
285
286        //âîçâðàùàåì ëîæü, åñëè ïëàãèí íå óñòàíîâèëñÿ
287        if (!$plugin_id)    { return false; }
288
289        //äîáàâëÿåì õóêè ñîáûòèé äëÿ ïëàãèíà
290        foreach($events as $event){
291            $event_query = "INSERT INTO cms_event_hooks (event, plugin_id) VALUES ('{$event}', {$plugin_id})";
292            $inDB->query($event_query);
293        }
294
295        //âîçðàùàåì ID óñòàíîâëåííîãî ïëàãèíà
296        return $plugin_id;
297    }
298
299    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
300    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
301    /**
302     * Äåëàåò àïãðåéä óñòàíîâëåííîãî ïëàãèíà
303     * @param array $plugin
304     * @param array $events
305     * @param array $config
306     * @return bool
307     */
308    public function upgradePlugin($plugin, $events, $config) {
309        $inDB = cmsDatabase::getInstance();
310
311        //íàõîäèì ID óñòàíîâëåííîé âåðñèè
312        $plugin_id = $this->getPluginId( $plugin['plugin'] );
313
314        //åñëè ïëàãèí åùå íå áûë óñòàíîâëåí, âûõîäèì
315        if (!$plugin_id) { return false; }
316
317        //çàãðóæàåì òåêóùèå íàñòðîéêè ïëàãèíà
318        $old_config = $this->loadPluginConfig( $plugin['plugin'] );
319
320        //óäàëÿåì íàñòðîéêè, êîòîðûå áîëüøå íå íóæíû
321        foreach($old_config as $param=>$value){
322            if ( !isset($config[$param]) ){
323                unset($old_config[$param]);
324            }
325        }
326
327        //äîáàâëÿåì íàñòðîéêè, êîòîðûõ ðàíüøå íå áûëî
328        foreach($config as $param=>$value){
329            if ( !isset($old_config[$param]) ){
330                $old_config[$param] = $value;
331            }
332        }
333
334        //êîíâåðòèðóåì ìàññèâ íàñòðîåê â YAML
335        $config_yaml   = $this->arrayToYaml($old_config);
336
337        //îáíîâëÿåì ïëàãèí â áàçå
338        $update_query  = "UPDATE cms_plugins
339                          SET title='{$plugin['title']}',
340                              description='{$plugin['description']}',
341                              author='{$plugin['author']}',
342                              version='{$plugin['version']}',
343                              config='{$config_yaml}'
344                          WHERE id = {$plugin_id}";
345
346        $inDB->query($update_query);
347
348        //äîáàâëÿåì íîâûå õóêè ñîáûòèé äëÿ ïëàãèíà
349        foreach($events as $event){
350            if ( !$this->isPluginHook($plugin_id, $event) ){
351                $event_query = "INSERT INTO cms_event_hooks (event, plugin_id) VALUES ('{$event}', {$plugin_id})";
352                $inDB->query($event_query);
353            }
354        }
355
356        //ïëàãèí óñïåøíî îáíîâëåí
357        return true;
358    }
359
360    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
361    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
362    /**
363     * Óäàëÿåò óñòàíîâëåííûé ïëàãèí
364     * @param array $plugin
365     * @param array $events
366     * @return bool
367     */
368    public function removePlugin($plugin_id) {
369        $inDB = cmsDatabase::getInstance();
370
371        //åñëè ïëàãèí íå áûë óñòàíîâëåí, âûõîäèì
372        if (!$plugin_id) { return false; }
373
374        //óäàëÿåì ïëàãèí èç áàçû
375        $delete_query  = "DELETE FROM cms_plugins WHERE id = {$plugin_id}";
376
377        $inDB->query($delete_query);
378
379        //Óäàëÿåì õóêè ñîáûòèé ïëàãèíà
380        $unhook_query  = "DELETE FROM cms_event_hooks WHERE plugin_id = {$plugin_id}";
381
382        $inDB->query($unhook_query);
383
384        //ïëàãèí óñïåøíî óäàëåí
385        return true;
386    }
387
388    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
389    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
390    /**
391     * Âîçâðàùàåò ñïèñîê ïëàãèíîâ, èìåþùèõñÿ íà äèñêå, íî íå óñòàíîâëåííûõ
392     * @return array
393     */
394    public function getNewPlugins() {
395       
396        $inDB = cmsDatabase::getInstance();
397
398        $new_plugins    = array();
399        $all_plugins    = $this->getPluginsDirs();
400
401        if (!$all_plugins) { return false; }
402
403        foreach($all_plugins as $plugin){           
404            $installed = $inDB->rows_count('cms_plugins', "plugin='{$plugin}'", 1);
405            if (!$installed){
406                $new_plugins[] = $plugin;
407            }
408        }
409
410        if (!$new_plugins) { return false; }
411
412        return $new_plugins;
413    }
414
415    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
416    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
417    /**
418     * Âîçâðàùàåò ñïèñîê ïëàãèíîâ, âåðñèÿ êîòîðûõ èçìåíèëàñü â áîëüøóþ ñòîðîíó
419     * @return array
420     */
421    public function getUpdatedPlugins() {
422
423        $upd_plugins    = array();
424        $all_plugins    = $this->getPluginsDirs();
425
426        if (!$all_plugins) { return false; }
427
428        foreach($all_plugins as $plugin){
429            $plugin_obj     = $this->loadPlugin($plugin);
430            $version        = $this->getPluginVersion($plugin);
431            if ($version){
432                if ($version < $plugin_obj->info['version']){
433                    $upd_plugins[] = $plugin;
434                }
435            }
436        }
437
438        if (!$upd_plugins) { return false; }
439
440        return $upd_plugins;
441    }
442
443    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
444    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
445    /**
446     * Âîçâðàùàåò ñïèñîê ïàïîê ñ ïëàãèíàìè
447     * @return array
448     */
449    public function getPluginsDirs() {
450        $dir    = PATH . '/plugins';
451        $pdir   = opendir($dir);
452
453        $plugins = array();
454
455        while ($nextfile = readdir($pdir)){
456            if (
457                    ($nextfile != '.')  &&
458                    ($nextfile != '..') &&
459                    is_dir($dir.'/'.$nextfile) &&
460                    ($nextfile!='.svn') &&
461                    (substr($nextfile, 0, 2)=='p_')
462               ) {
463                $plugins[$nextfile] = $nextfile;
464            }
465        }
466
467        if (!sizeof($plugins)){ return false; }
468
469        return $plugins;
470    }
471
472    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
473    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
474    /**
475     * Âîçâðàùàåò ID ïëàãèíà ïî íàçâàíèþ
476     * @param string $plugin
477     * @return int
478     */
479    public function getPluginId($plugin){
480
481        $inDB = cmsDatabase::getInstance();
482
483        return $inDB->get_field('cms_plugins', "plugin='{$plugin}'", 'id');
484       
485    }
486
487    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
488    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
489    /**
490     * Âîçâðàùàåò íàçâàíèå ïëàãèíà ïî ID
491     * @param int $plugin_id
492     * @return string
493     */
494    public function getPluginById($plugin_id){
495
496        $inDB = cmsDatabase::getInstance();
497
498        return $inDB->get_field('cms_plugins', "id='{$plugin_id}'", 'plugin');
499
500    }
501
502    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
503    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
504    /**
505     * Âîçâðàùàåò âåðñèþ ïëàãèíà ïî íàçâàíèþ
506     * @param string $plugin
507     * @return float
508     */
509    public function getPluginVersion($plugin){
510
511        $inDB = cmsDatabase::getInstance();
512
513        return $inDB->get_field('cms_plugins', "plugin='{$plugin}'", 'version');
514
515    }
516
517    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
518    /**
519     * Óñòàíàâëèâàåò êîìïîíåíò
520     * Âîçâðàùàåò ID óñòàíîâëåííîãî ïëàãèíà
521     * @param array $component
522     * @param array $config
523     * @return int
524     */
525    public function installComponent($component, $config) {
526        $inDB = cmsDatabase::getInstance();
527
528        $config_yaml    = $this->arrayToYaml($config);
529
530        if (!$config_yaml) { $config_yaml = ''; }
531
532        //äîáàâëÿåì êîìïîíåíò â áàçó
533        $install_query  = "INSERT INTO cms_components (`title`, `link`, `config`, `internal`, `author`, `published`, `version`, `system`)
534                           VALUES ('{$component['title']}', '{$component['link']}', '{$config_yaml}', '{$component['internal']}',
535                                    '{$component['author']}', '1', '{$component['version']}', '0')";
536
537        $inDB->query($install_query);
538
539        //ïîëó÷àåì ID êîìïîíåíòà
540        $component_id = $inDB->get_last_id('cms_components');
541
542        //âîçâðàùàåì ëîæü, åñëè êîìïîíåíò íå óñòàíîâèëñÿ
543        if (!$component_id)    { return false; }
544
545        //âîçðàùàåì ID óñòàíîâëåííîãî êîìïîíåíòà
546        return $component_id;
547    }
548
549    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
550    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
551    /**
552     * Äåëàåò àïãðåéä óñòàíîâëåííîãî êîìïîíåíòà
553     * @param array $component
554     * @param array $config
555     * @return bool
556     */
557    public function upgradeComponent($component, $config) {
558        $inDB = cmsDatabase::getInstance();
559
560        //íàõîäèì ID óñòàíîâëåííîé âåðñèè
561        $component_id = $this->getComponentId( $component['link'] );
562
563        //åñëè êîìïîíåíò åùå íå áûë óñòàíîâëåí, âûõîäèì
564        if (!$component_id) { return false; }
565
566        //çàãðóæàåì òåêóùèå íàñòðîéêè êîìïîíåíòà
567        $old_config = $this->loadComponentConfig( $component['link'] );
568
569        //óäàëÿåì íàñòðîéêè, êîòîðûå áîëüøå íå íóæíû
570        foreach($old_config as $param=>$value){
571            if ( !isset($config[$param]) ){
572                unset($old_config[$param]);
573            }
574        }
575
576        //äîáàâëÿåì íàñòðîéêè, êîòîðûõ ðàíüøå íå áûëî
577        foreach($config as $param=>$value){
578            if ( !isset($old_config[$param]) ){
579                $old_config[$param] = $value;
580            }
581        }
582
583        //êîíâåðòèðóåì ìàññèâ íàñòðîåê â YAML
584        $config_yaml   = $this->arrayToYaml($old_config);
585
586        //îáíîâëÿåì êîìïîíåíò â áàçå
587        $update_query  = "UPDATE cms_components
588                          SET title='{$component['title']}',
589                              author='{$component['author']}',
590                              version='{$component['version']}',
591                              internal='{$component['internal']}',
592                              config='{$config_yaml}'
593                          WHERE id = {$component_id}";
594
595        $inDB->query($update_query);
596
597        //êîìïîíåíò óñïåøíî îáíîâëåí
598        return true;
599    }
600
601    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
602    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
603    /**
604     * Óäàëÿåò óñòàíîâëåííûé êîìïîíåíò
605     * @param int $component_id
606     * @return bool
607     */
608    public function removeComponent($component_id) {
609
610        $inDB = cmsDatabase::getInstance();
611
612        //åñëè êîìïîíåíò íå áûë óñòàíîâëåí, âûõîäèì
613        if (!$component_id) { return false; }
614
615        //îïðåäåëÿåì íàçâàíèå êîìïîíåíòà ïî id
616        $component = $this->getComponentById($component_id);
617
618        //óäàëÿåì çàâèñèìûå ìîäóëè êîìïîíåíòà
619        if ($this->loadComponentInstaller($component)){
620            $_component = call_user_func('info_component_'.$component);
621            if (isset($_component['modules'])){
622                if (is_array($_component['modules'])){
623                    foreach($_component['modules'] as $module=>$title){
624                        $module_id = $this->getModuleId($module);
625                        if ($module_id) { $this->removeModule($module_id); }
626                    }
627                }
628            }
629        }
630
631        //óäàëÿåì êîìïîíåíò èç áàçû, íî òîëüêî åñëè îí íå ñèñòåìíûé
632        $delete_query  = "DELETE FROM cms_components WHERE id = {$component_id} AND system = 0";
633
634        $inDB->query($delete_query);
635
636        //êîìïîíåíò óñïåøíî óäàëåí
637        return true;
638       
639    }
640
641    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
642    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
643    /**
644     * Âîçâðàùàåò ñïèñîê êîìïîíåíòîâ, èìåþùèõñÿ íà äèñêå, íî íå óñòàíîâëåííûõ
645     * @return array
646     */
647    public function getNewComponents() {
648
649        $inDB = cmsDatabase::getInstance();
650
651        $new_components    = array();
652        $all_components    = $this->getComponentsDirs();
653
654        if (!$all_components) { return false; }
655
656        foreach($all_components as $component){
657
658            $installer_file = PATH . '/components/' . $component . '/install.php';
659
660            if (file_exists($installer_file)){
661
662                $installed = $inDB->rows_count('cms_components', "link='{$component}'", 1);
663                if (!$installed){
664                    $new_components[] = $component;
665                }
666
667            }
668           
669        }
670
671        if (!$new_components) { return false; }
672
673        return $new_components;
674    }
675
676    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
677    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
678    /**
679     * Âîçâðàùàåò ñïèñîê êîìïîíåíòîâ, âåðñèÿ êîòîðûõ èçìåíèëàñü â áîëüøóþ ñòîðîíó
680     * @return array
681     */
682    public function getUpdatedComponents() {
683
684        $inDB = cmsDatabase::getInstance();
685
686        $upd_components    = array();
687        $all_components    = $inDB->get_table('cms_components');
688
689        if (!$all_components) { return false; }
690
691        foreach($all_components as $component){           
692            if($this->loadComponentInstaller($component['link'])){
693                $version    = $component['version'];
694                $_component = call_user_func('info_component_'.$component['link']);
695                if ($version){
696                    if ($version < $_component['version']){
697                        $upd_components[] = $component['link'];
698                    }
699                }
700            }
701        }
702
703        if (!$upd_components) { return false; }
704
705        return $upd_components;
706    }
707
708    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
709    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
710    /**
711     * Âîçâðàùàåò ñïèñîê ïàïîê ñ êîìïîíåíòàìè
712     * @return array
713     */
714    public function getComponentsDirs() {
715        $dir    = PATH . '/components';
716        $pdir   = opendir($dir);
717
718        $components = array();
719
720        while ($nextfile = readdir($pdir)){
721            if (
722                    ($nextfile != '.')  &&
723                    ($nextfile != '..') &&
724                    is_dir($dir.'/'.$nextfile) &&
725                    ($nextfile!='.svn')
726               ) {
727                $components[$nextfile] = $nextfile;
728            }
729        }
730
731        if (!sizeof($components)){ return false; }
732
733        return $components;
734    }
735
736    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
737    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
738    /**
739     * Âîçâðàùàåò ID êîìïîíåíòà ïî íàçâàíèþ
740     * @param string $component
741     * @return int
742     */
743    public function getComponentId($component){
744
745        $inDB = cmsDatabase::getInstance();
746
747        return $inDB->get_field('cms_components', "link='{$component}'", 'id');
748
749    }
750
751    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
752    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
753    /**
754     * Âîçâðàùàåò íàçâàíèå êîìïîíåíòà ïî ID
755     * @param int $component_id
756     * @return string
757     */
758    public function getComponentById($component_id){
759
760        $inDB = cmsDatabase::getInstance();
761
762        $link = $inDB->get_field('cms_components', "id={$component_id}", 'link');
763
764        return $link;
765
766    }
767
768    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
769    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
770    /**
771     * Âîçâðàùàåò âåðñèþ êîìïîíåíòà ïî íàçâàíèþ
772     * @param string $component
773     * @return float
774     */
775    public function getComponentVersion($component){
776
777        $inDB = cmsDatabase::getInstance();
778
779        return $inDB->get_field('cms_components', "link='{$component}'", 'version');
780
781    }
782
783    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
784    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
785
786    public function loadComponentInstaller($component){
787
788        $installer_file = PATH . '/components/' . $component . '/install.php';
789
790        if (!file_exists($installer_file)){ return false; }
791
792        $this->includeFile('components/'.$component.'/install.php');
793
794        return true;
795
796    }
797
798    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
799    /**
800     * Óñòàíàâëèâàåò ìîäóëü
801     * Âîçâðàùàåò ID óñòàíîâëåííîãî ìîäóëÿ
802     * @param array $module
803     * @param array $config
804     * @return int
805     */
806    public function installModule($module, $config) {
807
808        $inDB = cmsDatabase::getInstance();
809
810        $config_yaml    = $this->arrayToYaml($config);
811
812        if (!$config_yaml) { $config_yaml = ''; }
813
814        //äîáàâëÿåì ìîäóëü â áàçó
815        $install_query  = "INSERT INTO cms_modules (`position`, `name`, `title`, `is_external`,
816                                                    `content`, `ordering`, `showtitle`, `published`,
817                                                    `user`, `config`, `original`, `css_prefix`,
818                                                    `access_list`, `cache`, `cachetime`, `cacheint`,
819                                                    `template`, `is_strict_bind`, `version`)
820                VALUES ('{$module['position']}', '{$module['name']}', '{$module['title']}', '1',
821                        '{$module['link']}', '1', '1', '1',
822                        '0', '{$config_yaml}', '1', '',
823                        '', '0', '1', 'HOUR',
824                        'module.tpl', '0', '{$module['version']}')";
825
826        $inDB->query($install_query);
827
828        //ïîëó÷àåì ID ìîäóëÿ
829        $module_id = $inDB->get_last_id('cms_modules');
830
831        //âîçâðàùàåì ëîæü, åñëè ìîäóëü íå óñòàíîâèëñÿ
832        if (!$module_id)    { return false; }
833
834        //âîçðàùàåì ID óñòàíîâëåííîãî ìîäóëÿ
835        return $module_id;
836
837    }
838
839    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
840    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
841    /**
842     * Äåëàåò àïãðåéä óñòàíîâëåííîãî ìîäóëÿ
843     * @param array $component
844     * @param array $config
845     * @return bool
846     */
847    public function upgradeModule($module, $config) {
848        $inDB = cmsDatabase::getInstance();
849
850        //íàõîäèì ID óñòàíîâëåííîé âåðñèè
851        $module_id = $this->getModuleId( $module['link'] );
852
853        //åñëè ìîäóëü åùå íå áûë óñòàíîâëåí, âûõîäèì
854        if (!$module_id) { return false; }
855
856        //çàãðóæàåì òåêóùèå íàñòðîéêè ìîäóëÿ
857        $old_config = $this->loadModuleConfig( $module_id );
858
859        //óäàëÿåì íàñòðîéêè, êîòîðûå áîëüøå íå íóæíû
860        foreach($old_config as $param=>$value){
861            if ( !isset($config[$param]) ){
862                unset($old_config[$param]);
863            }
864        }
865
866        //äîáàâëÿåì íàñòðîéêè, êîòîðûõ ðàíüøå íå áûëî
867        foreach($config as $param=>$value){
868            if ( !isset($old_config[$param]) ){
869                $old_config[$param] = $value;
870            }
871        }
872
873        //êîíâåðòèðóåì ìàññèâ íàñòðîåê â YAML
874        $config_yaml   = $this->arrayToYaml($old_config);
875
876        //îáíîâëÿåì ìîäóëü â áàçå
877        $update_query  = "UPDATE cms_modules
878                          SET title='{$module['title']}',
879                              name='{$module['name']}',
880                              version='{$module['version']}',
881                              config='{$config_yaml}'
882                          WHERE id = {$module_id}";
883
884        $inDB->query($update_query);
885
886        //ìîäóëü óñïåøíî îáíîâëåí
887        return true;
888    }
889
890    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
891    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
892    /**
893     * Óäàëÿåò óñòàíîâëåííûé ìîäóëü
894     * @param int $module_id
895     * @return bool
896     */
897    public function removeModule($module_id) {
898
899        $inDB = cmsDatabase::getInstance();
900
901        //åñëè ìîäóëü íå áûë óñòàíîâëåí, âûõîäèì
902        if (!$module_id) { return false; }
903
904        //óäàëÿåì ìîäóëü èç áàçû
905        $delete_query  = "DELETE FROM cms_modules WHERE id = {$module_id}";
906
907        $inDB->query($delete_query);
908
909        //ìîäóëü óñïåøíî óäàëåí
910        return true;
911
912    }
913
914    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
915    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
916    /**
917     * Âîçâðàùàåò ñïèñîê ìîäóëåé, èìåþùèõñÿ íà äèñêå, íî íå óñòàíîâëåííûõ
918     * @return array
919     */
920    public function getNewModules() {
921
922        $inDB = cmsDatabase::getInstance();
923
924        $new_modules    = array();
925        $all_modules    = $this->getModulesDirs();
926
927        if (!$all_modules) { return false; }
928
929        foreach($all_modules as $module){
930
931            $installer_file = PATH . '/modules/' . $module . '/install.php';
932
933            if (file_exists($installer_file)){
934
935                $installed = $inDB->rows_count('cms_modules', "content='{$module}' AND user=0", 1);
936                if (!$installed){
937                    $new_modules[] = $module;
938                }
939
940            }
941
942        }
943
944        if (!$new_modules) { return false; }
945
946        return $new_modules;
947    }
948
949    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
950    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
951    /**
952     * Âîçâðàùàåò ñïèñîê ìîäóëåé, âåðñèÿ êîòîðûõ èçìåíèëàñü â áîëüøóþ ñòîðîíó
953     * @return array
954     */
955    public function getUpdatedModules() {
956
957        $inDB = cmsDatabase::getInstance();
958
959        $upd_modules    = array();
960        $all_modules    = $inDB->get_table('cms_modules', 'user=0');
961
962        if (!$all_modules) { return false; }
963
964        foreach($all_modules as $module){
965            if($this->loadModuleInstaller($module['content'])){
966                $version    = $module['version'];
967                $_module    = call_user_func('info_module_'.$module['content']);
968                if ($version){
969                    if ($version < $_module['version']){
970                        $upd_modules[] = $module['content'];
971                    }
972                }
973            }
974        }
975
976        if (!$upd_modules) { return false; }
977
978        return $upd_modules;
979    }
980
981    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
982    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
983    /**
984     * Âîçâðàùàåò ñïèñîê ïàïîê ñ ìîäóëÿìè
985     * @return array
986     */
987    public function getModulesDirs() {
988        $dir    = PATH . '/modules';
989        $pdir   = opendir($dir);
990
991        $modules = array();
992
993        while ($nextfile = readdir($pdir)){
994            if (
995                    ($nextfile != '.')  &&
996                    ($nextfile != '..') &&
997                    is_dir($dir.'/'.$nextfile) &&
998                    ($nextfile!='.svn')
999               ) {
1000                $modules[$nextfile] = $nextfile;
1001            }
1002        }
1003
1004        if (!sizeof($modules)){ return false; }
1005
1006        return $modules;
1007    }
1008
1009    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1010    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1011    /**
1012     * Âîçâðàùàåò ID ìîäóëÿ ïî íàçâàíèþ
1013     * @param string $component
1014     * @return int
1015     */
1016    public function getModuleId($module){
1017
1018        $inDB = cmsDatabase::getInstance();
1019
1020        return $inDB->get_field('cms_modules', "content='{$module}' AND user=0", 'id');
1021
1022    }
1023
1024    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1025    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1026    /**
1027     * Âîçâðàùàåò íàçâàíèå ìîäóëÿ ïî ID
1028     * @param int $component_id
1029     * @return string
1030     */
1031    public function getModuleById($module_id){
1032
1033        $inDB = cmsDatabase::getInstance();
1034
1035        $link = $inDB->get_field('cms_modules', "id={$module_id} AND user=0", 'content');
1036
1037        return $link;
1038
1039    }
1040
1041    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1042    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1043    /**
1044     * Âîçâðàùàåò âåðñèþ ìîäóëÿ ïî íàçâàíèþ
1045     * @param string $component
1046     * @return float
1047     */
1048    public function getModuleVersion($module){
1049
1050        $inDB = cmsDatabase::getInstance();
1051
1052        return $inDB->get_field('cms_modules', "content='{$module}' AND user=0", 'version');
1053
1054    }
1055
1056    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1057    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1058
1059    public function loadModuleInstaller($module){
1060
1061        $installer_file = PATH . '/modules/' . $module . '/install.php';
1062
1063        if (!file_exists($installer_file)){ return false; }
1064
1065        $this->includeFile('modules/'.$module.'/install.php');
1066
1067        return true;
1068
1069    }
1070
1071    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1072    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1073    /**
1074     * Ïðîâåðÿåò äîñòóï (ìîäóëÿ, ìåíþ) ê ãðóïïå ïîëüçîâàòåëÿ
1075     * @param string $access_list
1076     * @return bool
1077     */
1078    public function checkContentAccess($access_list){
1079               
1080                $inUser = cmsUser::getInstance();
1081               
1082                // åñëè $access_list ïóñòà, òî ñ÷èòàåì ÷òî äîñòóï äëÿ âñåõ
1083                if (!$access_list) { return true; }
1084
1085                // àäìèíèñòðàòîðàì âñåãäà ïîêàçûâàåì ìîäóëü             
1086                if ($inUser->is_admin) { return true; }
1087
1088        $access_list = $this->yamlToArray($access_list);
1089
1090                // åñëè ïî êàêèì-òî ïðè÷èíàì $access_list íå ìàññèâ, òî ñ÷èòàåì ÷òî äîñòóï äëÿ âñåõ
1091                if (!is_array($access_list)) { return true; }
1092               
1093                // id ãðóïïû òåêóùåãî ïîëüçîâàòåëÿ
1094                $group_id = $inUser->group_id;
1095               
1096                return in_array($group_id, $access_list);
1097
1098    }
1099
1100    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1101    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1102    /**
1103     * Âîçâðàùàåò êîôèãóðàöèþ ïëàãèíà â âèäå ìàññèâà
1104     * @param string $plugin
1105     * @return float
1106     */
1107    public function loadPluginConfig($plugin){
1108
1109        $inDB = cmsDatabase::getInstance();
1110
1111        $config_yaml = $inDB->get_field('cms_plugins', "plugin='{$plugin}'", 'config');
1112
1113        return $this->yamlToArray($config_yaml);
1114
1115    }
1116
1117    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1118    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1119    /**
1120     * Ñîõðàíÿåò íàñòðîéêè ïëàãèíà â áàçó
1121     * @param string $plugin_name
1122     * @param array $config
1123     * @return bool
1124     */
1125    public function savePluginConfig($plugin_name, $config) {
1126
1127        $inDB = cmsDatabase::getInstance();
1128
1129        //êîíâåðòèðóåì ìàññèâ íàñòðîåê â YAML
1130        $config_yaml   = $this->arrayToYaml($config);
1131
1132        //îáíîâëÿåì ïëàãèí â áàçå
1133        $update_query  = "UPDATE cms_plugins
1134                          SET config='{$config_yaml}'
1135                          WHERE plugin = '{$plugin_name}'";
1136
1137        $inDB->query($update_query);
1138
1139        //íàñòðîéêè óñïåøíî ñîõðàíåíû
1140        return true;
1141       
1142    }
1143
1144    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1145    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1146    /**
1147     * Ïðîâåðÿåò ïðèâÿçêó ïëàãèíà ê ñîáûòèþ
1148     * @param int $plugin_id
1149     * @param string $event
1150     * @return bool
1151     */
1152    public function isPluginHook($plugin_id, $event) {
1153
1154        $inDB = cmsDatabase::getInstance();
1155
1156        return (bool)$inDB->num_rows('cms_event_hooks', "plugin_id={$plugin_id} AND event='{$event}'", 1);
1157
1158    }
1159
1160    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1161    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1162    /**
1163     * Çàãðóæàåò ïëàãèí è âîçâðàùàåò åãî îáúåêò
1164     * @param string $plugin
1165     * @return cmsPlugin
1166     */
1167    public function loadPlugin($plugin) {
1168        $plugin_file = PATH.'/plugins/'.$plugin.'/plugin.php';
1169        if (file_exists($plugin_file)){
1170            include_once($plugin_file);
1171            $plugin_obj = new $plugin();
1172            return $plugin_obj;
1173        }
1174        return false;
1175    }
1176
1177    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1178    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1179    /**
1180     * Óíè÷òîæàåò îáúåêò ïëàãèíà
1181     * @param cmsPlugin $plugin_obj
1182     * @return true
1183     */
1184    public function unloadPlugin($plugin_obj) {
1185        unset($plugin_obj);
1186        return true;
1187    }
1188
1189    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1190    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1191    /**
1192     * Çàãðóæàåò áèáëèîòåêó èç ôàéëà /core/lib_XXX.php, ãäå XXX = $lib
1193     * @param string $lib
1194     * @return bool
1195     */
1196    public function loadLib($lib){
1197        $libfile = PATH.'/core/lib_'.$lib.'.php';
1198        if (file_exists($libfile)){
1199            include_once($libfile);
1200            return true;
1201        }
1202        return false;
1203    }
1204
1205    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1206    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1207    /**
1208     * Çàãðóæàåò êëàññ èç ôàéëà /core/classes/XXX.class.php, ãäå XXX = $class
1209     * @param string $class
1210     * @return bool
1211     */
1212    public function loadClass($class){
1213        $classfile = PATH.'/core/classes/'.$class.'.class.php';
1214        if (file_exists($classfile)){
1215            include_once($classfile);
1216            return true;
1217        }
1218        return false;
1219    }
1220
1221    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1222    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1223    /**
1224     * Çàãðóæàåò ìîäåëü äëÿ óêàçàííîãî êîìïîíåíòà
1225     * @param string $component
1226     * @return bool
1227     */
1228    public function loadModel($component){
1229        $modelfile = PATH.'/components/'.$component.'/model.php';
1230        if (file_exists($modelfile)){
1231            include_once($modelfile);
1232            return true;
1233        }
1234        return false;
1235    }
1236
1237    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1238    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1239    /**
1240     * Ïîäêëþ÷àåò âíåøíèé ôàéë
1241     * @param string $lib
1242     */
1243    public function includeFile($file){
1244        include_once PATH.'/'.$file;
1245    }
1246
1247    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1248    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1249    /**
1250     * Ïîäêëþ÷àåò ôóíêöèè äëÿ ðàáîòû ñ ãðàôèêîé
1251     */
1252    public function includeGraphics(){
1253        include_once PATH.'/includes/graphic.inc.php';
1254    }
1255
1256    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1257    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1258    /**
1259     * Ïîäêëþ÷àåò ôàéë êîíôèãóðàöèè
1260     */
1261    public function includeConfig(){
1262        include_once PATH.'/includes/config.inc.php';
1263    }
1264
1265    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1266    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1267    /**
1268     * Ïîäêëþ÷àåò âèçóàëüíûé ðåäàêòîð
1269     */
1270    public function includeWysiwyg(){
1271        include_once PATH."/wysiwyg/fckeditor.php";
1272    }
1273
1274    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1275    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1276    public function insertEditor($name, $text='', $height='350', $width='500') {
1277
1278        $editor = self::callEvent('INSERT_WYSIWYG', array(
1279                                                        'name'=>$name,
1280                                                        'text'=>$text,
1281                                                        'height'=>$height,
1282                                                        'width'=>$width
1283                                                    ));
1284
1285        if (!is_array($editor)){ echo $editor; return; }
1286
1287        echo '<p>
1288                <div>Âèçóàëüíûé ðåäàêòîð íå íàéäåí ëèáî íå âêëþ÷åí.</div>
1289                <div>Åñëè ðåäàêòîð óñòàíîâëåí, âêëþ÷èòå åãî â àäìèíêå (ìåíþ <em>Äîïîëíåíèÿ</em> &rarr; <em>Ïëàãèíû</em>).</div>
1290              </p>';
1291
1292    }
1293
1294    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1295    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1296    /**
1297     * Óñòàíàâëèâàåò êóêèñ ïîñåòèòåëþ
1298     * @param string $name
1299     * @param string $value
1300     * @param int $time
1301     */
1302    public function setCookie($name, $value, $time){
1303        setcookie('InstantCMS['.$name.']', $value, $time, '/');       
1304    }
1305
1306    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1307    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1308    /**
1309     * Óäàëÿåò êóêèñ ïîëüçîâàòåëÿ
1310     * @param string $name
1311     */
1312    public function unsetCookie($name){
1313        setcookie('InstantCMS['.$name.']', '', time()-3600, '/');
1314    }
1315
1316    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1317    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1318    /**
1319     * Âîçâðàùàåò çíà÷åíèå êóêèñà
1320     * @param string $name
1321     * @return string || false
1322     */
1323    public function getCookie($name){
1324        if (isset($_COOKIE['InstantCMS'][$name])){
1325            return $_COOKIE['InstantCMS'][$name];
1326        } else {
1327            return false;
1328        }
1329    }
1330
1331    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1332    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1333    /**
1334     * Äîáàâëÿåò ñîîáùåíèå â ñåññèþ
1335     * @param string $message
1336     * @param string $class
1337     */
1338    public static function addSessionMessage($message, $class='info'){
1339        $_SESSION['core_message'][] = '<div class="message_'.$class.'">'.$message.'</div>';
1340    }
1341
1342    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1343    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1344    /*
1345     * Âîçâðàùàåò ìàññèâ ñîîáùåíèé ñîõðàíåííûõ â ñåññèè
1346     */
1347    public static function getSessionMessages(){
1348
1349        if (isset($_SESSION['core_message'])){
1350            $messages = $_SESSION['core_message'];
1351        } else {
1352            $messages = false;
1353        }
1354
1355        self::clearSessionMessages();
1356        return $messages;
1357
1358    }
1359
1360    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1361    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1362    /*
1363     * Î÷èùàåò î÷åðåäü ñîîáùåíèé ñåññèè
1364     */
1365    public static function clearSessionMessages(){
1366        unset($_SESSION['core_message']);
1367    }
1368
1369    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1370    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1371    /**
1372     * Îáíîâëÿåò ñòàòèñòèêó ïîñåùåíèé ñàéòà
1373     * @global array $_CFG
1374     */
1375    public function onlineStats(){
1376       
1377        $inDB = cmsDatabase::getInstance();
1378        $inUser = cmsUser::getInstance();
1379        global $_CFG;
1380
1381        $bots = array();
1382        $bots['Aport']              ='Aport';
1383        $bots['msnbot']             ='MSNbot';
1384        $bots['Yandex']             ='Yandex';
1385        $bots['Lycos.com']          ='Lucos';
1386        $bots['Googlebot']          ='Google';
1387        $bots['Openbot']            ='Openfind';
1388        $bots['FAST-WebCrawler']    ='AllTheWeb';
1389        $bots['TurtleScanner']      ='TurtleScanner';
1390        $bots['Yahoo-MMCrawler']    ='Y!MMCrawler';
1391        $bots['Yahoo!']             ='Yahoo!';
1392        $bots['rambler']            ='Rambler';
1393        $bots['W3C_Validator']      ='W3C Validator';
1394
1395        //óäàëÿåì ñòàðûå çàïèñè
1396        $sql = "DELETE FROM cms_online WHERE lastdate <= DATE_SUB(NOW(), INTERVAL 3 MINUTE)";
1397        $inDB->query($sql) ;
1398
1399        if (!$inUser->checkStatTimer()){ return true; }
1400
1401        $inUser->resetStatTimer();
1402
1403        //ñîáèðàåì èíôîðìàöèþ î òåêóùåì ïîëüçîâàòåëå
1404        $sess_id    = session_id();
1405        $ip         = $this->strClear($_SERVER['REMOTE_ADDR']);
1406        $useragent  = $this->strClear($_SERVER['HTTP_USER_AGENT']);
1407        $page       = $this->strClear($_SERVER['REQUEST_URI']);
1408        $refer      = $this->strClear($_SERVER['HTTP_REFERER']);
1409
1410        $user_id    = $inUser->id;
1411
1412        if (strstr(strtolower($useragent), 'select')) { return false; }
1413        if (strstr(strtolower($useragent), 'from'))   { return false; }
1414
1415        //ïðîâåðÿåì, åñòü ëè òåêóùèé ïîëüçîâàòåëü â òàáëèöå "êòî îíëàéí"
1416        $sql = "SELECT id FROM cms_online WHERE (sess_id = '$sess_id' AND ip = '$ip')";
1417        $result = $inDB->query($sql) ;
1418
1419        if (!$inDB->num_rows($result)){
1420            //Ïðîâåðÿåì, ïîëüçîâàòåëü ýòî èëè ïîèñêîâûé áîò
1421            $crawler = false;
1422            foreach($bots as $bot=>$uagent){ if (strpos($useragent, $uagent)) { $crawler = true; }      }
1423            //Åñëè íå áîò, âñòàâëÿåì çàïèñü â "êòî îíëàéí"
1424            if (!$crawler){
1425                $sql = "INSERT INTO cms_online (ip, sess_id, lastdate, user_id, viewurl) VALUES ('$ip', '$sess_id', NOW(), '$user_id', '$page')";
1426                $inDB->query($sql) ;
1427            }
1428        } else {
1429            //Åñëè ïîëüçîâàòåëü óæå îíëàéí, îáíîâëÿåì âðåìÿ
1430            $sql = "UPDATE cms_online
1431                     SET lastdate = NOW(),
1432                         user_id = '$user_id',
1433                         viewurl = '$page'
1434                     WHERE (sess_id = '$sess_id' AND ip = '$ip')";
1435            $inDB->query($sql) ;
1436        }
1437
1438        if (@$_CFG['stats']){ //åñëè âêëþ÷åí ñáîð ñòàòèñòèêè íà ñàéòå
1439            //ñìîòðèì, åñòü ëè çàïèñü ïðî òåêóùåãî ïîëüçîâàòåëÿ
1440            $sql = "SELECT id FROM cms_stats WHERE (ip = '$ip' AND page = '$page')";
1441            $result = $inDB->query($sql) ;
1442            //åñëè çàïèñè íåò - äîáàâëÿåì
1443            if (!$inDB->num_rows($result)){
1444                $sql = "INSERT INTO cms_stats (ip, logdate, page, agent, refer) VALUES ('$ip', NOW(), '$page', '$useragent', '$refer')";
1445                $inDB->query($sql) ;
1446            }
1447        }
1448
1449    }
1450
1451    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1452    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1453    /**
1454     * Âîçâðàùàåò òåêóùèé URI
1455     * Íóæíà äëÿ òîãî, ÷òîáû èìåòü âîçìîæíîñòü ïåðåîïðåäåëèòü URI.
1456     * Ïî ñóòè ÿâëÿåòñÿ ýìóëÿòîðîì âíóòðåííåãî mod_rewrite
1457     * @return string
1458     */
1459    private function detectURI(){
1460
1461        $uri    = $_SERVER['REQUEST_URI']; //$this->request('uri', 'str', '');
1462        $uri    = ltrim($uri, '/');
1463        $rules  = array();
1464
1465        $folder = rtrim($uri, '/');
1466
1467        if (strstr($uri, "?") && !preg_match('/^admin\/(.*)/i', $uri)){
1468            $query_str = substr($uri, strpos($uri, "?")+1);
1469            $uri = substr($uri, 0, strpos($uri, "?"));
1470            parse_str($query_str, $_REQUEST);
1471        }
1472
1473        if (in_array($folder, array('admin', 'install', 'migrate', 'index.php'))) { return; }
1474
1475        //ñïåöèàëüíûé õàê äëÿ ïîèñêà ïî ñàéòó, äëÿ ñîâìåñòèìîñòè ñî ñòàðûìè øàáëîíàìè
1476        if (strstr($_SERVER['QUERY_STRING'], 'view=search')){ $uri = 'search'; }
1477
1478        if(file_exists(PATH.'/url_rewrite.php')) {
1479            //ïîäêëþ÷àåì ñïèñîê rewrite-ïðàâèë
1480            $this->includeFile('url_rewrite.php');
1481            if(function_exists('rewrite_rules')){
1482                //ïîëó÷àåì ïðàâèëà
1483                $rules = rewrite_rules();
1484            }
1485        }
1486
1487        if(file_exists(PATH.'/custom_rewrite.php')) {
1488            //ïîäêëþ÷àåì ñïèñîê ïîëüçîâàòåëüñêèõ rewrite-ïðàâèë
1489            $this->includeFile('custom_rewrite.php');
1490            if(function_exists('custom_rewrite_rules')){
1491                //äîáàâëÿåì ê ïîëó÷åííûì ðàíåå ïðàâèëàì ïîëüçîâàòåëüñêèå
1492                $rules = array_merge($rules, custom_rewrite_rules());
1493            }
1494        }
1495
1496        $found = false;
1497
1498        if ($rules){
1499            //ïåðåáèðàåì ïðàâèëà
1500            foreach($rules as $rule_id=>$rule) {
1501                //íåáîëüøàÿ âàëèäàöèÿ ïðàâèëà
1502                if (!$rule['source'] || !$rule['target'] || !$rule['action']) { continue; }
1503                //ïðîâåðÿåì ñîâïàäåíèå âûðàæåíèÿ source ñ òåêóùèì uri
1504                if (preg_match($rule['source'], $uri, $matches)){
1505
1506                    //ïåðåáèðàåì ñîâïàâøèå ñåãìåíòû è äîáàâëÿåì èõ â target
1507                    //÷òîáû ñîõðàíèòü ïàðàìåòðû èç $uri â íîâîì àäðåñå
1508                    foreach($matches as $key=>$value){
1509                        if (!$key) { continue; }
1510                        if (strstr($rule['target'], '{'.$key.'}')){
1511                            $rule['target'] = str_replace('{'.$key.'}', $value, $rule['target']);
1512                        }
1513                    }
1514
1515                    //äåéñòâèå ïî-óìîë÷àíèþ: rewrite
1516                    if (!$rule['action']) { $rule['action'] = 'rewrite'; }
1517
1518                    //âûïîëíÿåì äåéñòâèå
1519                    switch($rule['action']){
1520                        case 'rewrite'      : $uri = $rule['target']; $found = true; break;
1521                        case 'redirect'     : $this->redirect($rule['target']); break;
1522                        case 'redirect-301' : $this->redirect($rule['target'], '301'); break;
1523                        case 'alias'        : $this->includeFile($rule['target']); $this->halt();break;
1524                    }
1525
1526                }
1527
1528                if ($found) { break; }
1529
1530            }
1531        }
1532
1533        return $uri;
1534       
1535    }
1536
1537    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1538    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1539    /**
1540     * Îïðåäåëÿåò òåêóùèé êîìïîíåíò
1541     * Ñ÷èòàåòñÿ, ÷òî êîìïîíåíò óêàçàí â ïåðâîì ñåãìåíòå URI,
1542     * èíà÷å ïîäêëþ÷àåòñÿ êîìïîíåíò äëÿ ãëàâíîé ñòðàíèöû
1543         * Êðèòåðèé "âêëþ÷åííîñòè" êîìïîíåíòà îïðåäåëÿåòñÿ â ôóíêöèè loadComponentConfig
1544     * @return string $component
1545     */
1546    private function detectComponent(){
1547
1548        $inConf     = cmsConfig::getInstance();
1549
1550        $component  = '';
1551
1552        //êîìïîíåíò íà ãëàâíîé
1553        if (!$this->uri && $inConf->homecom) { return $inConf->homecom; }
1554
1555        //îïðåäåëÿåì, åñòü ëè ñëýøè â àäðåñå
1556        $first_slash_pos = strpos($this->uri, '/');
1557
1558        if ($first_slash_pos){
1559            //åñëè åñòü ñëýøè, òî êîìïîíåíò ýòî ñåãìåíò äî ïåðâîãî ñëýøà
1560            $component  = substr($this->uri, 0, $first_slash_pos);
1561        } else {
1562            //åñëè ñëýøåé íåò, òî êîìïîíåíò ñîâïàäàåò ñ àäðåñîì
1563            $component  = $this->uri;           
1564        }
1565
1566
1567        if (is_dir(PATH.'/components/'.$component)){
1568            //åñëè êîìïîíåíò îïðåäåëåí è ñóùåñòâóåò
1569            return $component;
1570        } else {
1571            //åñëè êîìïîíåíò íå ñóùåñòâóåò, ñ÷èòàåì ÷òî ýòî content
1572            $this->uri = 'content/'.$this->uri;
1573            $this->is_content = true;
1574            return 'content';
1575        }
1576       
1577    }
1578
1579    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1580    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1581    /**
1582     * Ôóíêöèÿ ïîäêëþ÷àåò ôàéë router.php èç ïàïêè ñ òåêóùèì êîìïîíåíòîì
1583     * è âûçûâàåò ìåòîä route_component(), êîòîðûå âîçâðàùàåò ìàññèâ ïðàâèë
1584     * äëÿ àíàëèçà URI. Åñëè â ìàññèâå íàéäåíî ñîâïàäåíèå ñ òåêóùèì URI,
1585     * òî URI ïàðñèòñÿ è ïåðåìåííûå, ñîäåðæàùèåñÿ â íåì, çàáèâàþòñÿ â ìàññèâ $_REQUEST.
1586     * @return boolean
1587     */
1588    private function parseComponentRoute(){
1589
1590        $component = $this->component;
1591
1592        //ïðîâåðÿåì ÷òî êîìïîíåíò è àäðåñ óêàçàíû
1593        if (!$component || !$this->uri) { return false; }
1594
1595        if(!file_exists('components/'.$component.'/router.php')){ return false; }
1596                /**
1597                 * Êðèòåðèé "âêëþ÷åííîñòè" êîìïîíåíòà îïðåäåëÿåòñÿ â ôóíêöèè loadComponentConfig
1598                 */
1599        //ïîäêëþ÷àåì ñïèñîê ìàðøðóòîâ êîìïîíåíòà
1600        $this->includeFile('components/'.$component.'/router.php');
1601
1602        $routes = call_user_func('routes_'.$component);
1603
1604        //ïåðåáèðàåì âñå ìàðøðóòû
1605        foreach($routes as $route_id=>$route){
1606
1607            //ñðàâíèâàåì øàáëîí ìàðøðóòà ñ òåêóùèì URI
1608            preg_match($route['_uri'], $this->uri, $matches);
1609
1610            //Åñëè íàéäåíî ñîâïàäåíèå
1611            if ($matches){
1612
1613                //óäàëÿåì øàáëîí èç ïàðàìåòðîâ ìàðøðóòà, ÷òîáû íå ìåøàë ïðè ïåðåáîðå
1614                unset($route['_uri']);
1615
1616                //ïåðåáèðàåì ïàðàìåòðû ìàðøðóòà â âèäå êëþ÷=>çíà÷åíèå
1617                foreach($route as $key=>$value){
1618                    if (is_integer($key)){
1619                        //Åñëè êëþ÷ - öåëîå ÷èñëî, òî çíà÷åíèåì ÿâëÿåòñÿ ñåãìåíò URI
1620                        $_REQUEST[$value] = $matches[$key];
1621                    } else {
1622                        //èíà÷å, çíà÷åíèå áåðåòñÿ èç ìàðøðóòà
1623                        $_REQUEST[$key]   = $value;
1624                    }
1625                }
1626
1627                //ðàç íàéäåíî ñîâïàäåíèå, ïðåðûâàåì öèêë
1628                break;
1629
1630            }
1631
1632        }
1633
1634        return true;
1635
1636    }
1637
1638    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1639    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1640    /**
1641     * Ãåíåðèðóåò òåëî ñòðàíèöû, âûçûâàÿ íóæíûé êîìïîíåíò
1642     */
1643    public function proceedBody(){
1644
1645        $inPage         = cmsPage::getInstance();
1646        $inDB           = cmsDatabase::getInstance();       
1647        $inConf         = cmsConfig::getInstance();
1648        $is_component   = false;
1649        $component      = $this->component;
1650
1651        //ïðîâåðÿåì ÷òî êîìïîíåíò óêàçàí
1652        if (!$component) { return false; }
1653                /**
1654                 * Êðèòåðèé "âêëþ÷åííîñòè" êîìïîíåíòà îïðåäåëÿåòñÿ â ôóíêöèè loadComponentConfig
1655                 */
1656        //ïðîâåðÿåì ÷òî â íàçâàíèè òîëüêî áóêâû è öèôðû
1657        if (!preg_match("/^([a-z0-9])+$/", $component)){ cmsCore::error404(); }
1658       
1659        $this->loadLanguage('components/'.$component);
1660
1661        //ïðîâåðÿåì íàëè÷èå êîìïîíåíòà
1662        if(!file_exists('components/'.$component.'/frontend.php')){
1663            $inPage->page_body = '<p>Êîìïîíåíò íå íàéäåí!</p>';
1664            return false;
1665        }
1666
1667        //ïàðñèì àäðåñ è çàïîëíÿåì ìàññèâ $_REQUEST (âðåìåííîå ðåøåíèå)
1668        $this->parseComponentRoute();
1669
1670        ob_start();
1671
1672            require('components/'.$component.'/frontend.php');
1673            call_user_func($component);
1674
1675        if ($inConf->back_btn && $menuid != 1 && $inPage->back_button) {
1676            echo "<p><a href='javascript:history.go(-1)' class=\"backlink\">&larr; Íàçàä</a></p>";
1677        }
1678
1679        $component_html = ob_get_clean();
1680
1681        $inPage->page_body = '<div class="component">' . $component_html . '</div>';
1682
1683        if ($is_component) { $inPage->page_body = cmsCore::callEvent('AFTER_COMPONENT_'.mb_strtoupper($component), $inPage->page_body); }
1684
1685        return true;
1686       
1687    }
1688
1689    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1690    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1691    public static function error404(){
1692
1693        header("HTTP/1.0 404 Not Found");
1694        header("HTTP/1.1 404 Not Found");
1695        header("Status: 404 Not Found");
1696
1697        $inConf = cmsConfig::getInstance();
1698        $inPage = cmsPage::getInstance();
1699        $inCore = self::getInstance();
1700
1701        if (!$inPage->includeTemplateFile('special/error404.php')){
1702            echo '<h1>404</h1>';
1703        }
1704       
1705        $inCore->halt();
1706
1707    }
1708
1709    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1710    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1711    /**
1712     * Èíèöèàëèçèðóåò âëîæåííûå ìíîæåñòâà è âîçâðàùàåò îáúåêò CCelkoNastedSet
1713     * @return object NS
1714     */
1715    public function nestedSetsInit($table){
1716        $inDB = cmsDatabase::getInstance();
1717        $this->includeFile('includes/nestedsets.php');
1718        $ns = new CCelkoNastedSet();
1719        $ns->MyLink     = $inDB->db_link;
1720        $ns->TableName  = $table;
1721        return $ns;
1722    }
1723
1724    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1725    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1726    /**
1727     * Ïðîâåðÿåò, íóæíî ëè ïîêàçûâàòü ñïëåø-ñòðàíèöó (ïðèâåòñòâèå)
1728     * @global array $_CFG
1729     * @return bool
1730     */
1731    public function isSplash(){
1732        $inConf = cmsConfig::getInstance();       
1733        if ($inConf->splash){
1734            $show_splash = !($this->getCookie('splash') || isset($_SESSION['splash']));
1735            return $show_splash;
1736        } else { return false; }
1737    }
1738
1739    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1740    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1741    /**
1742     * Âîçâðàùàåò êëþ÷åâûå ñëîâà äëÿ çàäàííîãî òåêñòà
1743     * @param string $text
1744     * @return string
1745     */
1746    public function getKeywords($text){
1747        $this->includeFile('includes/keywords.inc.php');
1748        $params['content'] = $text; //page content
1749        $params['min_word_length'] = 5;  //minimum length of single words
1750        $params['min_word_occur'] = 2;  //minimum occur of single words
1751
1752        $params['min_2words_length'] = 5;  //minimum length of words for 2 word phrases
1753        $params['min_2words_phrase_length'] = 10; //minimum length of 2 word phrases
1754        $params['min_2words_phrase_occur'] = 2; //minimum occur of 2 words phrase
1755       
1756        $params['min_3words_length'] = 5;  //minimum length of words for 3 word phrases
1757        $params['min_3words_phrase_length'] = 10; //minimum length of 3 word phrases
1758        $params['min_3words_phrase_occur'] = 2; //minimum occur of 3 words phrase
1759        $keyword = new autokeyword($params, "cp1251");
1760        return $keyword->get_keywords();
1761    }
1762
1763    // REQUESTS /////////////////////////////////////////////////////////////////////////////////////////////////////////////
1764    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1765    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1766    /**
1767     * Ïðîâåðÿåò íàëè÷èå ïåðåìåííîé $var âî âõîäíûõ ïàðàìåòðàõ
1768     * @param string $var
1769     * @return bool
1770     */
1771    public function inRequest($var){
1772        return isset($_REQUEST[$var]);
1773    }
1774    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1775    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1776    /**
1777     * Ïðîâåðÿåò íàëè÷èå ïåðåìåííîé $var âî âõîäíûõ ïàðàìåòðàõ
1778     * @param string $var
1779     * @param string $type = int | str | html
1780     * @param string $default
1781     */
1782    public function request($var, $type='str', $default=false){
1783        if (isset($_REQUEST[$var])){
1784            switch($type){
1785                case 'int':   return (int)$_REQUEST[$var]; break;
1786                case 'str':   if ($_REQUEST[$var]) { return $this->strClear($_REQUEST[$var]); } else { return $default; } break;
1787                case 'email': if(preg_match("/^([a-zA-Z0-9\._-]+)@([a-zA-Z0-9\._-]+)\.([a-zA-Z]{2,4})$/i", $_REQUEST[$var])){ return $_REQUEST[$var]; } else { return $default; } break;
1788                case 'html':  if ($_REQUEST[$var]) { return $this->strClear($_REQUEST[$var], false); } else { return $default; } break;
1789                case 'array': if (is_array($_REQUEST[$var])) { return $_REQUEST[$var]; } else { return $default; } break;
1790                case 'array_int': if (is_array($_REQUEST[$var])) { foreach($_REQUEST[$var] as $k=>$i){ $arr[$k] = (int)$i; } return $arr; } else { return $default; } break;
1791                case 'array_str': if (is_array($_REQUEST[$var])) { foreach($_REQUEST[$var] as $k=>$s){ $arr[$k] = $this->strClear($s); } return $arr; } else { return $default; } break;
1792            }
1793        } else {
1794            return $default;
1795        }
1796    }
1797    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1798    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1799    public function redirectBack(){
1800        header('Location:'.$_SERVER['HTTP_REFERER']);
1801        $this->halt();
1802    }
1803
1804    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1805    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1806    public function redirect($url, $code='303'){
1807        if ($code == '301'){
1808            header('HTTP/1.1 301 Moved Permanently');
1809        } else {
1810            header('HTTP/1.1 303 See Other');
1811        }
1812        header('Location:'.$url);
1813        $this->halt();
1814    }
1815
1816    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1817    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1818    /**
1819     * Âîçâðàùàåò ïðåäûäóùèé URL äëÿ ðåäèðåêòà íàçàä. Åñëè íàõîäèò ïåðåìåííóþ $_REQUEST['back'], òî âîçâðàùàåò åå
1820     * @return string
1821     */
1822    public function getBackURL(){
1823        if($this->inRequest('back')){
1824            $back = $this->request('back');
1825        } else {
1826            if (isset($_SERVER['HTTP_REFERER'])){
1827                $back = $_SERVER['HTTP_REFERER'];
1828            } else { $back = "/"; }
1829        }
1830        return $back;
1831    }
1832
1833    // FILE UPLOADING //////////////////////////////////////////////////////////////////////////////////////////////////////////
1834    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1835    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1836    /**
1837     * Çàêà÷èâàåò ôàéë íà ñåðâåð è îòñëåæèâàåò îøèáêè
1838     * @param string $source
1839     * @param string $destination
1840     * @param int $errorCode
1841     * @return bool
1842     */
1843    public function moveUploadedFile($source, $destination, $errorCode){
1844        $max_size = ini_get('upload_max_filesize');
1845        $max_size = str_replace('M', 'Ìá', $max_size);
1846        $max_size = str_replace('K', 'Êá', $max_size);
1847
1848        //Possible upload errors
1849        $uploadErrors = array(
1850            UPLOAD_ERR_OK => 'Ôàéë óñïåøíî çàãðóæåí',
1851            UPLOAD_ERR_INI_SIZE => 'Ðàçìåð ôàéëà ïðåâûøàåò äîïóñòèìûé &mdash; '.$max_size,
1852            UPLOAD_ERR_FORM_SIZE => 'Ðàçìåð ôàéëà ïðåâûøàåò äîïóñòèìûé',
1853            UPLOAD_ERR_PARTIAL => 'Ôàéë áûë çàãðóæåí íå ïîëíîñòüþ',
1854            UPLOAD_ERR_NO_FILE => 'Ôàéë íå áûë çàãðóæåí',
1855            UPLOAD_ERR_NO_TMP_DIR => 'Íå íàéäåíà ïàïêà äëÿ âðåìåííûõ ôàéëîâ íà ñåðâåðå',
1856            UPLOAD_ERR_CANT_WRITE => 'Îøèáêà çàïèñè ôàéëà íà äèñê',
1857            UPLOAD_ERR_EXTENSION => 'Çàãðóçêà ôàéëà áûëà ïðåðâàíà ðàñøèðåíèåì PHP'
1858        );
1859
1860        if($errorCode !== UPLOAD_ERR_OK && isset($uploadErrors[$errorCode])){
1861            //if is error, save it and return false
1862            $_SESSION['file_upload_error'] = $uploadErrors[$errorCode];
1863            return false;
1864        } else {
1865            //clear error, if upload is ok
1866            $_SESSION['file_upload_error'] = '';
1867            //get upload directory and check it is writable
1868            $upload_dir = dirname($destination);
1869            if (!is_writable($upload_dir)){     @chmod($upload_dir, 0644); @chmod($upload_dir, 0755); }
1870            //move uploaded file
1871            return @move_uploaded_file($source, $destination);
1872        }
1873    }
1874
1875    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1876    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1877    public function uploadError(){
1878        if ($_SESSION['file_upload_error']){ return $_SESSION['file_upload_error']; } else { return false; }
1879    }
1880
1881    // SMARTY //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1882    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1883    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1884    /**
1885     * Çàãðóæàåò êëàññ Smarty
1886     */
1887    public function loadSmarty(){
1888
1889        $this->includeFile('/includes/smarty/libs/Smarty.class.php');
1890
1891        $this->smarty = new Smarty();
1892
1893        $this->smarty->compile_dir = PATH.'/cache';
1894       
1895    }
1896
1897    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1898    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1899    /**
1900     * Âîçâðàùàåò îáúåêò Smarty äëÿ äàëüíåéøåé ðàáîòû ñ øàáëîíîì
1901     * @param string $tpl_folder = modules / components / plugins
1902     * @param string $tpl_file
1903     * @return obj
1904     */
1905    public function initSmarty($tpl_folder='modules', $tpl_file=''){
1906
1907        global $_LANG;
1908
1909        if (!$this->smarty){ $this->loadSmarty(); }
1910
1911        $template_has_tpl = file_exists(TEMPLATE_DIR . "{$tpl_folder}/{$tpl_file}");
1912
1913        $this->smarty->template_dir = $template_has_tpl ? TEMPLATE_DIR . $tpl_folder : DEFAULT_TEMPLATE_DIR . $tpl_folder;
1914
1915        $this->smarty->assign('LANG', $_LANG);
1916        $this->smarty->register_modifier("NoSpam", "cmsSmartyNoSpam");
1917        $this->smarty->register_function('add_js', 'cmsSmartyAddJS');
1918        $this->smarty->register_function('add_css', 'cmsSmartyAddCSS');
1919        $this->smarty->register_function('wysiwyg', 'cmsSmartyWysiwyg');
1920        $this->smarty->register_function('comments', 'cmsSmartyComments');
1921        $this->smarty->register_function('profile_url', 'cmsSmartyProfileURL');
1922
1923        return $this->smarty;
1924       
1925    }
1926
1927    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1928    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1929    public function initSmartyModule(){
1930
1931        if (!$this->smarty){ $this->loadSmarty(); }
1932
1933        $template_has_dir = is_dir(TEMPLATE_DIR.'modules');
1934
1935        $this->smarty->template_dir = $template_has_dir ? TEMPLATE_DIR.'modules' : DEFAULT_TEMPLATE_DIR.'modules';
1936
1937        $this->smarty->register_modifier("NoSpam", "cmsSmartyNoSpam");
1938        $this->smarty->register_function('add_js', 'cmsSmartyAddJS');
1939        $this->smarty->register_function('add_css', 'cmsSmartyAddCSS');
1940        $this->smarty->register_function('wysiwyg', 'cmsSmartyWysiwyg');
1941        $this->smarty->register_function('profile_url', 'cmsSmartyProfileURL');
1942
1943        return $this->smarty;
1944    }
1945
1946    // CONFIGS //////////////////////////////////////////////////////////////////////////////////////////////////////////////
1947    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1948    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1949    /**
1950     * Âîçâðàùàåò ìàññèâ ñ íàñòðîéêàìè ìîäóëÿ
1951     * @param int $module_id
1952     * @return array
1953     */
1954    public function loadModuleConfig($module_id){
1955       
1956        $inDB = cmsDatabase::getInstance();
1957
1958        $config = array();
1959
1960        if (isset($this->module_configs[$module_id])) { return $this->module_configs[$module_id]; }
1961
1962        $config_yaml = $inDB->get_field('cms_modules', "id='{$module_id}'", 'config');
1963
1964        $config = $this->yamlToArray($config_yaml);
1965
1966        $this->cacheModuleConfig($module_id, $config);
1967
1968        return $config;
1969
1970    }
1971
1972    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1973    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
1974    /**
1975     * Ñîõðàíÿåò íàñòðîéêè ìîäóëÿ â áàçó
1976     * @param string $plugin_name
1977     * @param array $config
1978     * @return bool
1979     */
1980    public function saveModuleConfig($module_id, $config) {
1981
1982        $inDB = cmsDatabase::getInstance();
1983
1984        //êîíâåðòèðóåì ìàññèâ íàñòðîåê â YAML
1985        $config_yaml   = $this->arrayToYaml($config);
1986
1987        //îáíîâëÿåì ìîäóëü â áàçå
1988        $update_query  = "UPDATE cms_modules
1989                          SET config='{$config_yaml}'
1990                          WHERE id = {$module_id}";
1991
1992        $inDB->query($update_query);
1993
1994        //íàñòðîéêè óñïåøíî ñîõðàíåíû
1995        return true;
1996
1997    }
1998
1999    /**
2000     * Êýøèðóåò êîíôèãóðàöèþ ìîäóëÿ íà âðåìÿ âûïîëíåíèÿ ñêðèïòà
2001     * @param int $module_id
2002     * @param array $config
2003     * @return boolean
2004     */
2005    public function cacheModuleConfig($module_id, $config){
2006        $this->module_configs[$module_id] = $config;
2007        return true;
2008    }
2009
2010    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2011    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2012    /**
2013     * Âîçâðàùàåò êîôèãóðàöèþ êîìïîíåíòà â âèäå ìàññèâà
2014     * @param string $plugin
2015     * @return float
2016     */
2017    public function loadComponentConfig($component){
2018
2019        $inDB = cmsDatabase::getInstance();
2020
2021        $config = array();
2022
2023        if (isset($this->component_configs[$component])) { return $this->component_configs[$component]; }
2024
2025        $config_yaml = $inDB->get_fields('cms_components', "link='{$component}'", 'config, published');
2026
2027        $config = $this->yamlToArray($config_yaml['config']);
2028                $config['component_enabled'] = $config_yaml['published'];
2029
2030        $this->cacheComponentConfig($component, $config);
2031
2032        return $config;
2033
2034    }
2035
2036    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2037    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2038    /**
2039     * Ñîõðàíÿåò íàñòðîéêè êîìïîíåíòà â áàçó
2040     * @param string $plugin_name
2041     * @param array $config
2042     * @return bool
2043     */
2044    public function saveComponentConfig($component, $config) {
2045
2046        $inDB = cmsDatabase::getInstance();
2047
2048        //êîíâåðòèðóåì ìàññèâ íàñòðîåê â YAML
2049        $config_yaml   = $this->arrayToYaml($config);
2050
2051        //îáíîâëÿåì ïëàãèí â áàçå
2052        $update_query  = "UPDATE cms_components
2053                          SET config='{$config_yaml}'
2054                          WHERE link = '{$component}'";
2055
2056        $inDB->query($update_query);
2057
2058        //íàñòðîéêè óñïåøíî ñîõðàíåíû
2059        return true;
2060
2061    }
2062
2063    /**
2064     * Êýøèðóåò êîíôèãóðàöèþ êîìïîíåíòà íà âðåìÿ âûïîëíåíèÿ ñêðèïòà
2065     * @param string $component
2066     * @param array $config
2067     * @return boolean
2068     */
2069    public function cacheComponentConfig($component, $config){
2070        $this->component_configs[$component] = $config;
2071        return true;
2072    }
2073
2074
2075    // FILTERS //////////////////////////////////////////////////////////////////////////////////////////////////////////////
2076    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2077    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2078    /**
2079     * Âîçâðàùàåò ìàññèâ ñ óñòàíîâëåííûìè â ñèñòåìå ôèëüòðàìè
2080     * @return array or false
2081     */
2082    public function getFilters(){
2083        $inDB   = cmsDatabase::getInstance();
2084        $sql    = "SELECT * FROM cms_filters WHERE published = 1 ORDER BY id ASC";
2085        $result = $inDB->query($sql);
2086        if($inDB->num_rows($result)){
2087            $filters = array();
2088            while($f = $inDB->fetch_assoc($result)){
2089                $filters[$f['id']] = $f;
2090            }
2091            return $filters;
2092        } else { return false; }
2093    }
2094
2095    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2096    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2097    public function processFilters(&$content) {
2098
2099        $filters = $this->getFilters();
2100
2101        if ($filters){
2102            foreach($filters as $id=>$_filter){
2103                $this->includeFile('filters/'.$_filter['link'].'/filter.php');
2104                $_filter['link']($content);
2105            }
2106        }
2107
2108        return true;
2109
2110    }
2111
2112    // FILE DOWNLOADS STATS /////////////////////////////////////////////////////////////////////////////////////////////////
2113    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2114    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2115    /**
2116     * Âîçâðàùàåò êîëè÷åñòâî çàãðóçîê ôàéëà
2117     * @param string $fileurl
2118     * @return int
2119     */
2120    public function fileDownloadCount($fileurl){
2121       
2122        $inDB       = cmsDatabase::getInstance();
2123        $fileurl    = mysql_escape_string($fileurl);
2124       
2125        $sql        = "SELECT hits FROM cms_downloads WHERE fileurl = '$fileurl'";
2126        $result     = $inDB->query($sql) ;
2127       
2128        if ($inDB->num_rows($result)){
2129            $data = $inDB->fetch_assoc($result);
2130            return $data['hits'];
2131        } else {
2132            return 0;
2133        }
2134       
2135    }
2136
2137    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2138    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2139    /**
2140     * Âîçâðàùàåò òåã <img> ñ èêîíêîé, ñîîòâåòñòâóþùåé òèïó ôàéëà
2141     * @param string $filename
2142     * @return int
2143     */
2144    public function fileIcon($filename){
2145        $standart_icon = 'file.gif';
2146        $ftypes[0]['ext'] = 'avi mpeg mpg mp4 flv divx xvid vob';
2147        $ftypes[0]['icon'] = 'video.gif';
2148        $ftypes[1]['ext'] = 'mp3 ogg wav';
2149        $ftypes[1]['icon'] = 'audio.gif';
2150        $ftypes[2]['ext'] = 'zip rar gz arj 7zip';
2151        $ftypes[2]['icon'] = 'archive.gif';
2152        $ftypes[3]['ext'] = 'zip rar gz arj 7zip';
2153        $ftypes[3]['icon'] = 'archive.gif';
2154        $ftypes[4]['ext'] = 'gif jpg jpeg png bmp pcx wmf cdr ai';
2155        $ftypes[4]['icon'] = 'image.gif';
2156        $ftypes[5]['ext'] = 'pdf djvu';
2157        $ftypes[5]['icon'] = 'pdf.gif';
2158        $ftypes[6]['ext'] = 'doc';
2159        $ftypes[6]['icon'] = 'word.gif';
2160        $ftypes[7]['ext'] = 'iso mds mdf 000';
2161        $ftypes[7]['icon'] = 'cd.gif';
2162
2163        $path_parts = pathinfo($filename);
2164        $ext = $path_parts['extension'];
2165        $icon = '';
2166        foreach($ftypes as $key=>$value){
2167            if (strstr($ftypes[$key]['ext'], $ext)) { $icon = $ftypes[$key]['icon']; break; }
2168        }
2169
2170        if ($icon == '') { $icon = $standart_icon; }
2171
2172        $html = '<img src="/images/icons/filetypes/'.$icon.'" border="0" />';
2173        return $html;
2174    }
2175
2176    // MENU //////////////////////////////////////////////////////////////////////////////////////////////////////////////
2177    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2178    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2179    /**
2180     * Ïåðåòèðàåò ñîäåðæàíèå ñòðàíèöû
2181     * â ñëó÷àå îñòóòñòâèÿ ó ãðóïïû äîñòóïà ê òåêóùåìó ïóíêòó ìåíþ
2182     */
2183    public function checkMenuAccess(){
2184
2185                $inPage = cmsPage::getInstance();
2186
2187                global $menuid;
2188
2189                if (!$this->menu_item) { $this->menu_item = $this->getMenuItem($menuid); }
2190               
2191                $access_list = $this->menu_item['access_list'];
2192
2193                if (!$this->checkContentAccess($access_list) && $menuid != 0) { 
2194
2195            ob_start();
2196
2197            $inPage->includeTemplateFile('special/accessdenied.php');
2198
2199                        $inPage->page_body = ob_get_clean();
2200            return false;
2201
2202                } else {
2203
2204                        return true;
2205
2206                }
2207
2208    }
2209    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2210    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2211    /**
2212     * Âîçâðàùàåò çàãîëîâîê òåêóùåãî ïóíêòà ìåíþ
2213     * @return string
2214     */
2215    public function menuTitle(){
2216
2217        if ($this->menuId()==1) { return ''; }
2218
2219        if (!$this->menu_item) { $this->menu_item = $this->getMenuItem($this->menuId()); }
2220
2221        return $this->menu_item['title'];
2222
2223    }
2224    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2225    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2226    /**
2227     * Âîçâðàùàåò ññûëêó íà ïóíêò ìåíþ
2228     * @param string $link
2229     * @param string $linktype
2230     * @param int $menuid
2231     * @return string
2232     */
2233    public function menuSeoLink($link, $linktype, $menuid=1){
2234        return $link;
2235    }
2236    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2237    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2238    /**
2239     * Âîçâðàùàåò íàçâàíèå øàáëîíà, íàçíà÷åííîãî íà ïóíêò ìåíþ
2240     * Åñëè èñïîëüçóåòñÿ øàáëîí ïî-óìîë÷àíèþ, òî âîçâðàùàåò false
2241     * @param int $menuid
2242     * @return string or false
2243     */
2244    public function menuTemplate($menuid){
2245
2246        if (!$this->menu_item) { $this->menu_item = $this->getMenuItem($menuid); }
2247
2248        return $this->menu_item['template'];
2249
2250    }
2251
2252    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2253    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2254    /**
2255     * Âîçâðàùàåò true åñëè URI ñòðàíèöû è ññûëêà àêòèâíîãî ïóíêòà ìåíþ ñîâïàëè ïîëíîñòüþ
2256     * @return boolean
2257     */
2258    public function isMenuIdStrict() {
2259       
2260        return $this->is_menu_id_strict;
2261       
2262    }
2263
2264    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2265    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2266    /**
2267     * Âîçâðàùàåò ID òåêóùåãî ïóíêòà ìåíþ
2268     * @return int
2269     */
2270    public function menuId(){
2271
2272        //åñëè menu_id áûë îïðåäåëåí ðàíåå, òî âåðíåì è âûéäåì
2273        if ($this->menu_id) { return $this->menu_id; }
2274
2275        $view       = $this->request('view', 'str', '');
2276       
2277        if ($this->is_content){
2278            $uri = substr($this->uri, strlen('content/'));
2279        } else {
2280            $uri = $this->uri;
2281        }
2282
2283        $uri        = '/'.$uri;
2284
2285        //ôëàã, ïîêàçûâàþùèé áûëî ñîâïàäåíèå URI è ññûëêè ïóíòà ìåíþ
2286        //ïîëíûì èëè ÷àñòè÷íûì
2287        $is_strict  = false;
2288
2289        //ãëàâíàÿ ñòðàíèöà?
2290        $menuid     = ($uri == '/' ? 1 : 0);
2291        if ($menuid == 1) {
2292            $this->is_menu_id_strict = 1;
2293            return $menuid;
2294        }
2295
2296        //ïåðåâåðíåì ìàññèâ ìåíþ ÷òîáû ïåðåáèðàòü îò ïîñëåäíåãî ïóíêòà ê ïåðâîìó
2297        $menu       = array_reverse($this->menu_struct);
2298
2299        //ïåðåáèðàåì ìåíþ â ïîèñêàõ òåêóùåãî ïóíêòà
2300        foreach($menu as $item){
2301
2302            if (!$item['link']) { continue; }
2303
2304            //ïîëíîå ñîâïàäåíèå ññûëêè è àäðåñà?
2305            if ($uri == $item['link']){
2306                $menuid = $item['id'];
2307                $is_strict = true; //ïîëíîå ñîâïàäåíèå
2308                break;
2309            }
2310
2311            //÷àñòè÷íîå ñîâïàäåíèå ññûëêè è àäðåñà (ïî íà÷àëó ñòðîêè)?
2312            $uri_first_part = substr($uri, 0, strlen($item['link']));
2313            if ($uri_first_part == $item['link']){
2314                $menuid = $item['id'];
2315                break;
2316            }
2317           
2318        }
2319
2320        $this->menu_id              = $menuid;
2321        $this->is_menu_id_strict    = $is_strict;
2322
2323        return $menuid;
2324
2325    }
2326
2327    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2328    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2329    /**
2330     * Çàãðóæàåò äàííûå î òåêóùåì ïóíêòå ìåíþ
2331     * @return array
2332     */
2333    public function getMenuItem($menuid){
2334
2335        $inDB = cmsDatabase::getInstance();
2336
2337        return $this->menu_struct[$menuid];
2338       
2339    }
2340
2341    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2342    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2343    /**
2344     * Çàãðóæàåò âñþ ñòðóêòóðó ìåíþ
2345     *
2346     */
2347    private function loadMenuStruct(){
2348
2349        if (is_array($this->menu_struct)){ return; }
2350
2351        $inDB = cmsDatabase::getInstance();
2352
2353        $sql    = "SELECT * FROM cms_menu";
2354        $result = $inDB->query($sql);
2355
2356        if (!$inDB->num_rows($result)){ return; }
2357
2358        while ($item = $inDB->fetch_assoc($result)){
2359            $this->menu_struct[$item['id']] = $item;
2360        }
2361
2362        return;       
2363
2364    }
2365
2366    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2367    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2368    /**
2369     * Âîçâðàùàåò ID ïóíêòà ìåíþ, ê êîòîðîìó ïðèâÿçàí êîìïîíåíò
2370     * @param string $component
2371     * @return int
2372     */
2373    public function getComponentMenuId($component) {
2374
2375        $target_linkid      = array();
2376        $target_linktype    = array();
2377
2378        switch($component){
2379            case 'content':     $target_linktype    = array('content', 'category');
2380                                $target_linkid      = array('content');
2381                                break;
2382
2383            case 'catalog':     $target_linktype    = array('uccat');
2384                                $target_linkid      = array('catalog');
2385                                break;
2386
2387            case 'price':       $target_linktype    = array('pricecat');
2388                                $target_linkid      = array('price');
2389                                break;
2390
2391            case 'blogs':       $target_linktype    = array('blogs');
2392                                $target_linkid      = array('blogs', 'clubs');
2393                                break;
2394
2395            case 'photos':      $target_linkid      = array('photos', 'clubs');
2396                                break;
2397
2398            case 'users':       $target_linkid      = array('users');
2399                                break;
2400
2401            default:            $target_linktype    = array($component);
2402                                $target_linkid      = array($component);
2403                                break;
2404
2405        }
2406
2407        foreach($this->menu_struct as $item){
2408            if (in_array($item['linktype'], $target_linktype) ||
2409                in_array($item['linkid'], $target_linkid)){
2410                    return $item['id'];
2411            }
2412        }
2413
2414        return 0;
2415
2416    }
2417
2418    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2419    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2420
2421    public function getMenuStruct() {
2422        return $this->menu_struct;
2423    }
2424
2425    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2426    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2427    /**
2428     * Âîçâðàùàåò ïðÿìóþ ññûëêó íà ïóíêò ìåíþ ïî åãî òèïó è îïöèè
2429     * @param string $linktype
2430     * @param string $linkid
2431     * @param int $menuid
2432     * @return string
2433     */
2434    public function getMenuLink($linktype, $linkid, $menuid){
2435
2436        $inDB = cmsDatabase::getInstance();
2437        $inCore = cmsCore::getInstance();
2438
2439        $menulink = '';
2440
2441        if ($linktype=='component'){
2442            $menulink = '/'.$linkid;
2443        }
2444
2445        if ($linktype=='link'){
2446            $menulink = $linkid;
2447        }
2448
2449        if ($linktype=='category' || $linktype=='content'){
2450            $inCore->loadModel('content');
2451            $model = new cms_model_content();
2452            switch($linktype){
2453                case 'category': $menulink = $model->getCategoryURL(null, $inDB->get_field('cms_category', "id={$linkid}", 'seolink')); break;
2454                case 'content':  $menulink = $model->getArticleURL(null, $inDB->get_field('cms_content', "id={$linkid}", 'seolink')); break;
2455            }
2456        }
2457
2458        if ($linktype=='blog'){
2459            $inCore->loadModel('blogs');
2460            $model = new cms_model_blogs();
2461            $menulink = $model->getBlogURL(null, $inDB->get_field('cms_blogs', "id={$linkid}", 'seolink'));
2462        }
2463
2464        if ($linktype=='uccat'){
2465            $menulink = '/catalog/'.$linkid;
2466        }
2467
2468        if ($linktype=='pricecat'){
2469            $menulink = '/price/'.$linkid;
2470        }
2471        if ($linktype=='photoalbum'){
2472            $menulink = '/photos/'.$linkid;
2473        }
2474
2475        return $menulink;
2476
2477    }
2478
2479    // LISTS /////////////////////////////////////////////////////////////////////////////////////////////////////////////
2480    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2481    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2482    /**
2483     * Âîçâðàùàåò ýëåìåíòû <option> äëÿ ñïèñêà çàïèñåé èç óêàçàííîé òàáëèöû ÁÄ
2484     * @param string $table
2485     * @param int $selected
2486     * @param string $order_by
2487     * @param string $order_to
2488     * @param string $where
2489     * @return html
2490     */
2491    public function getListItems($table, $selected=0, $order_by='id', $order_to='ASC', $where='', $id_field='id', $title_field='title'){
2492        $inDB = cmsDatabase::getInstance();
2493        $html = '';
2494        $sql  = "SELECT {$id_field}, {$title_field} FROM {$table} \n";
2495        if ($where){
2496            $sql .= "WHERE {$where} \n";
2497        }
2498        $sql .= "ORDER BY {$order_by} {$order_to}";
2499        $result = $inDB->query($sql) ;
2500
2501        while($item = $inDB->fetch_assoc($result)){
2502            if (@$selected==$item[$id_field]){
2503                $s = 'selected';
2504            } else {
2505                $s = '';
2506            }
2507            $html .= '<option value="'.htmlspecialchars($item[$id_field]).'" '.$s.'>'.$item[$title_field].'</option>';
2508        }
2509        return $html;
2510    }
2511
2512    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2513    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2514    /**
2515     * Âîçâðàùàåò ýëåìåíòû <option> äëÿ ñïèñêà çàïèñåé èç óêàçàííîé òàáëèöû ÁÄ c âëîæåííûìè ìíîæåñòâàìè
2516     * @param string $table òàáëèöà
2517     * @param int $selected id âûäåëåííîãî ýëåìåíòà
2518     * @param string $differ èäåíòèôèêàòîð ìíîæåñòâà (NSDiffer)
2519     * @param string $need_field âûâîäèòü òîëüêî ýëåìåíòû ñîäåðæàùèå óêàçàííîå ïîëå
2520     * @param int $rootid êîðíåâîé ýëåìåíò
2521     * @return html
2522     */
2523    public function getListItemsNS($table, $selected=0, $differ='', $need_field='', $rootid=0, $no_padding=false){
2524        $inDB = cmsDatabase::getInstance();
2525        $html = '';
2526        $nested_sets = $this->nestedSetsInit($table);
2527
2528        $lookup = "parent_id=0 AND NSDiffer='{$differ}'";
2529       
2530        if(!$rootid) { $rootid = $inDB->get_field($table, $lookup, 'id'); }
2531
2532        if(!$rootid) { return; }
2533
2534        $rs_rows = $nested_sets->SelectSubNodes($rootid);
2535
2536        if ($rs_rows){
2537            while($node = $inDB->fetch_assoc($rs_rows)){
2538                if (!$need_field || $node[$need_field]){
2539                    if (@$selected==$node['id']){
2540                        $s = 'selected';
2541                    } else {
2542                        $s = '';
2543                    }
2544                    if (!$no_padding){
2545                        $padding = str_repeat('--', $node['NSLevel']) . ' ';
2546                    } else {
2547                        $padding = '';
2548                    }
2549                    $html .= '<option value="'.htmlspecialchars($node['id']).'" '.$s.'>'.$padding.$node['title'].'</option>';
2550                }
2551            }
2552        }
2553        return $html;
2554    }
2555
2556    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2557    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2558    /**
2559     * Âîçâðàùàåò ýëåìåíòû <option> äëÿ ñïèñêà òèïîâ äîñêè îáúÿâëåíèé
2560     * @param int $selected
2561     * @return html
2562     */
2563    public function boardTypesList($selected, $list=false){
2564        $inDB = cmsDatabase::getInstance();
2565        $html = '';
2566        if (!$list){
2567            $cfg = $this->loadComponentConfig('board');
2568            $list = explode("\n", $cfg['obtypes']);
2569        } else {
2570            $list = explode("\n", $list);
2571        }
2572        if ($list){
2573            foreach($list as $id=>$type){
2574                $type = trim($type);
2575                if (strtolower($selected) == strtolower($type)) { $sel = 'selected="selected"'; } else { $sel =''; }
2576                $html .= '<option value="'.ucfirst($type).'" '.$sel.'>'.ucfirst($type).'</option>';
2577            }
2578        }
2579        return $html;
2580    }
2581
2582    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2583    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2584    /**
2585     * Âîçâðàùàåò ýëåìåíòû <option> äëÿ ñïèñêà ãîðîäîâ äîñêè îáúÿâëåíèé
2586     * @param string $selected
2587     * @param string $none_label
2588     * @return html
2589     */
2590    public function boardCities($selected='', $none_label = 'Âñå ãîðîäà'){
2591        $inDB = cmsDatabase::getInstance();
2592        $sql = "SELECT city FROM cms_board_items WHERE published = 1 GROUP BY city";
2593        $result = $inDB->query($sql) ;
2594        $html = '<select name="city">';
2595        $html .= '<option value="">'.$none_label.'</option>';
2596        while($c = $inDB->fetch_assoc($result)){
2597            if (strtolower($selected)==strtolower($c['city'])){
2598                $s = 'selected';
2599            } else {
2600                $s = '';
2601            }
2602            $pretty = ucfirst(strtolower($c['city']));
2603            $html .= '<option value="'.$pretty.'" '.$s.'>'.$pretty.'</option>';
2604        }
2605        $html .= '</select>';
2606        return $html;
2607    }
2608
2609    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2610    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2611    /**
2612     * Âîçâðàùàåò ýëåìåíòû <option> äëÿ ñïèñêà øàáëîíîâ
2613     * @param string $selected
2614     */
2615    public function templatesList($selected=''){
2616        $dir = PATH.'/templates';
2617        $tdir = opendir($dir);
2618            while ($nextfile = readdir($tdir))
2619            {
2620                if(($nextfile!='.')&&($nextfile!='..')&&(is_dir($dir.'/'.$nextfile))&&($nextfile!='.svn'))
2621                {
2622                    if (@$selected==$nextfile){
2623                        $s = 'selected';
2624                    } else {
2625                        $s = '';
2626                    }
2627                    echo '<option value="'.$nextfile.'" '.$s.'>'.$nextfile.'</option>';
2628                }
2629            }
2630    }
2631
2632    /**
2633     * Âîçâðàùàåò ýëåìåíòû <option> äëÿ ñïèñêà ÿçûêîâ
2634     * @param string $selected
2635     */
2636    public function langList($selected=''){
2637        $dir = PATH.'/languages';
2638        $tdir = opendir($dir);
2639            while ($nextfile = readdir($tdir))
2640            {
2641                if(($nextfile!='.')&&($nextfile!='..')&&(is_dir($dir.'/'.$nextfile))&&($nextfile!='.svn'))
2642                {
2643                    if (@$selected==$nextfile){
2644                        $s = 'selected';
2645                    } else {
2646                        $s = '';
2647                    }
2648                    echo '<option value="'.$nextfile.'" '.$s.'>'.$nextfile.'</option>';
2649                }
2650            }
2651    }
2652
2653    // RATINGS  //////////////////////////////////////////////////////////////////////////////////////////////////////////
2654    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2655    /**
2656     * Ðåãèñòðèðóåò òèï öåëè äëÿ ðåéòèíãîâ â áàçå
2657     * @param string $target
2658     * @param string $component
2659     * @param boolean $is_user_affect
2660     * @param int $user_weight
2661     * @return boolean
2662     */
2663    public function registerRatingsTarget($target, $component, $target_title, $is_user_affect=true, $user_weight=1, $target_table='') {
2664
2665        $inDB = cmsDatabase::getInstance();
2666
2667        $is_user_affect = (int)$is_user_affect;
2668
2669        $sql  = "INSERT INTO cms_rating_targets (target, component, is_user_affect, user_weight, target_table, target_title)
2670                 VALUES ('$target', '$component', '$is_user_affect', '$user_weight', '$target_table', '$target_title')";
2671
2672        $inDB->query($sql);
2673
2674        return true;
2675
2676    }
2677
2678    /**
2679     * Óäàëÿåò âñå ðåéòèíãè äëÿ óêàçàííîé öåëè
2680     * @param string $target
2681     * @param int $item_id
2682     * @return boolean
2683     */
2684    public function deleteRatings($target, $item_id){
2685
2686        $inDB = cmsDatabase::getInstance();
2687
2688        $sql  = "DELETE FROM cms_ratings WHERE target='{$target}' AND item_id='{$item_id}'";
2689        $inDB->query($sql);
2690
2691        $sql  = "DELETE FROM cms_ratings_total WHERE target='{$target}' AND item_id='{$item_id}'";
2692        $inDB->query($sql);
2693
2694        return true;
2695
2696    }
2697
2698
2699    // COMMENTS //////////////////////////////////////////////////////////////////////////////////////////////////////////
2700    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2701    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2702        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2703    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2704    /**
2705     * Ïîäêëþ÷àåò êîììåíòàðèè
2706     */
2707    public function includeComments(){
2708        include_once PATH."/components/comments/frontend.php";
2709    }
2710
2711    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2712    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2713    /**
2714     * Ðåãèñòðèðóåò òèï öåëè äëÿ êîììåíòàðèåâ â áàçå
2715     * @param string $target - Öåëü
2716     * @param string $component - Êîìïîíåíò
2717     * @param string $title - Íàçâàíèå öåëè âî ìíîæ.÷èñëå (íàïðèìåð "Ñòàòüè")
2718     */
2719    public function registerCommentsTarget($target, $component, $title) {
2720
2721        $inDB = cmsDatabase::getInstance();
2722
2723        $sql  = "INSERT INTO cms_comment_targets (target, component, title)
2724                 VALUES ('$target', '$component', '$title')";
2725
2726        $inDB->query($sql);
2727
2728        return true;
2729
2730    }
2731
2732    public function getCommentsTargets() {
2733
2734        $inDB = cmsDatabase::getInstance();
2735
2736        $targets = $inDB->get_table('cms_comment_targets', 'id>0', '*');
2737
2738        return $targets;
2739
2740    }
2741
2742    /**
2743     * Óäàëÿåò âñå êîììåíòàðèè äëÿ óêàçàííîé öåëè
2744     * @param string $target
2745     * @param int $target_id
2746     * @return boolean
2747     */
2748    public function deleteComments($target, $target_id){
2749
2750        $inDB = cmsDatabase::getInstance();
2751
2752                $comments = $inDB->get_table('cms_comments', "target='{$target}' AND target_id='{$target_id}'", 'id');
2753
2754        if ($comments){
2755
2756            foreach($comments as $comment){
2757                cmsActions::removeObjectLog('add_comment', $comment['id']);
2758            }
2759                       
2760        $sql  = "DELETE FROM cms_comments WHERE target='{$target}' AND target_id='{$target_id}'";
2761
2762        $inDB->query($sql);
2763
2764        }
2765
2766        return true;
2767
2768    }
2769
2770    /**
2771     * Âîçâðàùàåò êîëè÷åñòâî êîììåíòàðèåâ äëÿ óêàçàííîé öåëè
2772     * @param string $target
2773     * @param int $target_id
2774     * @return int
2775     */
2776    public function getCommentsCount($target, $target_id){
2777        $inDB = cmsDatabase::getInstance();
2778        if ($this->isComponentInstalled('comments')){
2779            $sql = "SELECT id FROM cms_comments WHERE target = '$target' AND target_id = '$target_id' AND published = 1";
2780            $result = $inDB->query($sql) ;
2781            return $inDB->num_rows($result);
2782        } else { return 0; }
2783    }
2784
2785    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2786    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2787    /**
2788     * Âîçâðàùàåò ïàíåëü ñ âûáîðîì ñòðàíèö äëÿ ñòàòüè
2789     * @param int $pages
2790     * @param int $current
2791     * @return html
2792     */
2793    public function getPageBar($id, $title, $pages, $current){
2794
2795        $inDB = cmsDatabase::getInstance();
2796
2797        $html = '';
2798
2799        $this->loadModel('content');
2800        $model = new cms_model_content();
2801
2802        if($pages>1){
2803            $html .= '<div class="pagebar">';
2804            $html .= '<span class="pagebar_title"><strong>Ñòðàíèöû: </strong></span>';
2805            for ($p=1; $p<=$pages; $p++){
2806                if ($p != $current) {
2807                    $seolink = $inDB->get_field('cms_content', "id={$id}", 'seolink');                   
2808                    $link    = $model->getArticleURL($this->menuId(), $seolink, $p);
2809                    $html   .= ' <a href="'.$link.'" class="pagebar_page">'.$p.'</a> ';
2810                } else {
2811                    $html .= '<span class="pagebar_current">'.$p.'</span>';
2812                }
2813            }
2814            $html .= '</div>';
2815        }
2816        return $html;
2817    }
2818
2819    // UTILS ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2820    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2821    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2822
2823
2824    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2825    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2826    /**
2827     * Ïðîâåðÿåò, óñòàíîâëåí ëè êîìïîíåíò
2828     * @param string $component
2829     * @return bool
2830     */
2831    public function isComponentInstalled($component){
2832        $inDB = cmsDatabase::getInstance();
2833        return (bool)$inDB->rows_count('cms_components', "link='{$component}'", 1);
2834    }
2835
2836    public function isModuleInstalled($module) {
2837        $inDB = cmsDatabase::getInstance();
2838        return (bool)$inDB->rows_count('cms_modules', "content='{$module}' AND user=0", 1);
2839    }
2840
2841    // DATE METHODS /////////////////////////////////////////////////////////////////////////////////////////////////////////
2842    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2843    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2844    /**
2845     * Ïåðåâîäèò íàçâàíèå ìåñÿöà â äàòå íà ðóññêèé
2846     * @param string $datestr
2847     * @return string
2848     */
2849    public function getRusDate($datestr){
2850        $datestr = str_replace('January', 'ßíâàðü', $datestr);
2851        $datestr = str_replace('February', 'Ôåâðàëü', $datestr);
2852        $datestr = str_replace('March', 'Ìàðò', $datestr);
2853        $datestr = str_replace('April', 'Àïðåëü', $datestr);
2854        $datestr = str_replace('May', 'Ìàé', $datestr);
2855        $datestr = str_replace('June', 'Èþíü', $datestr);
2856        $datestr = str_replace('July', 'Èþëü', $datestr);
2857        $datestr = str_replace('August', 'Àâãóñò', $datestr);
2858        $datestr = str_replace('September', 'Ñåíòÿáðü', $datestr);
2859        $datestr = str_replace('October', 'Îêòÿáðü', $datestr);
2860        $datestr = str_replace('November', 'Íîÿáðü', $datestr);
2861        $datestr = str_replace('December', 'Äåêàáðü', $datestr);
2862        return $datestr;
2863    }
2864
2865    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2866    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2867        static function dateFormat($date, $is_full_m = true, $is_time=false, $is_now_time = true){
2868
2869        $inConf = cmsConfig::getInstance();
2870
2871            global $_LANG;
2872
2873        $date = date('Y-m-d H:i:s', strtotime($date)+($inConf->timediff*3600));
2874
2875                // ïîëó÷àåì çíà÷åíèå äàòû è âðåìåíè
2876                list($day, $time) = explode(' ', $date);
2877                switch( $day ) {
2878                // Åñëè äàòà ñîâïàäàåò ñ ñåãîäíÿøíåé
2879                case date('Y-m-d'):
2880                                        $result = ''.$_LANG['TODAY'].'';
2881                                        if ($is_now_time && $time) {
2882                                                list($h, $m, $s)  = explode(':', $time);
2883                                                $result .= ' '.$_LANG['IN'].' '.$h.':'.$m;
2884                                        }
2885                                        break;
2886                //Åñëè äàòà ñîâïàäàåò ñî â÷åðàøíåé
2887                case date( 'Y-m-d', mktime(0, 0, 0, date("m")  , date("d")-1, date("Y")) ):
2888                                        $result = ''.$_LANG['YESTERDAY'].'';
2889                                        if ($is_now_time && $time) {
2890                                                list($h, $m, $s)  = explode(':', $time);
2891                                                $result .= ' '.$_LANG['IN'].' '.$h.':'.$m;
2892                                        }
2893                                        break;
2894                        default: {
2895                                // Ðàçäåëÿåì îòîáðàæåíèå äàòû íà ñîñòàâëÿþùèå
2896                                list($y, $m, $d)  = explode('-', $day);
2897                                $month_full_str = array(
2898                                        ''.$_LANG['MONTH_01'].'', ''.$_LANG['MONTH_02'].'', ''.$_LANG['MONTH_03'].'',
2899                                        ''.$_LANG['MONTH_04'].'', ''.$_LANG['MONTH_05'].'', ''.$_LANG['MONTH_06'].'',
2900                                        ''.$_LANG['MONTH_07'].'', ''.$_LANG['MONTH_08'].'', ''.$_LANG['MONTH_09'].'',
2901                                        ''.$_LANG['MONTH_10'].'', ''.$_LANG['MONTH_11'].'', ''.$_LANG['MONTH_12'].''
2902                                 );
2903                                 $month_short_str = array(
2904                                        ''.$_LANG['MONTH_01_SHORT'].'', ''.$_LANG['MONTH_02_SHORT'].'', ''.$_LANG['MONTH_03_SHORT'].'',
2905                                        ''.$_LANG['MONTH_04_SHORT'].'', ''.$_LANG['MONTH_05_SHORT'].'', ''.$_LANG['MONTH_06_SHORT'].'',
2906                                        ''.$_LANG['MONTH_07_SHORT'].'', ''.$_LANG['MONTH_08_SHORT'].'', ''.$_LANG['MONTH_09_SHORT'].'',
2907                                        ''.$_LANG['MONTH_10_SHORT'].'', ''.$_LANG['MONTH_11_SHORT'].'', ''.$_LANG['MONTH_12_SHORT'].''
2908                                 );
2909                                 $month_int = array(
2910                                        '01', '02', '03',
2911                                        '04', '05', '06',
2912                                        '07', '08', '09',
2913                                        '10', '11', '12'
2914                                 );
2915                                 $day_int = array(
2916                                        '01', '02', '03',
2917                                        '04', '05', '06',
2918                                        '07', '08', '09'
2919                                 );
2920                                 $day_norm = array(
2921                                        '1', '2', '3',
2922                                        '4', '5', '6',
2923                                        '7', '8', '9'
2924                                 );
2925                                // Çàìåíà ÷èñëîâîãî îáîçíà÷åíèÿ ìåñÿöà íà ñëîâåñíîå (ñêëîíåííîå â ïàäåæå)
2926                                if ($is_full_m){
2927                                        $m = str_replace($month_int, $month_full_str, $m);
2928                                }else{
2929                                        $m = str_replace($month_int, $month_short_str, $m);
2930                                }
2931                                // Çàìåíà ÷èñåë 01 02 íà 1 2
2932                                $d = str_replace($day_int, $day_norm, $d);
2933                                // Ôîðìèðîâàíèå îêîí÷àòåëüíîãî ðåçóëüòàòà
2934                                $result = $d.' '.$m.' '.$y;
2935                                if( $is_time && $time)   {
2936                                        // Ïîëó÷àåì îòäåëüíûå ñîñòàâëÿþùèå âðåìåíè
2937                                        // Ñåêóíäû íàñ íå èíòåðåñóþò
2938                                        list($h, $m, $s)  = explode(':', $time);
2939                                        $result .= ' '.$_LANG['IN'].' '.$h.':'.$m;
2940                                }
2941                        }
2942                }
2943                 return $result;
2944        }
2945
2946    /**
2947     * Âîçâðàùàåò äåíü íåäåëè ïî äàòå
2948     * @param string $date
2949     * @return string
2950     */
2951    static function dateToWday($date){
2952               
2953        $inConf = cmsConfig::getInstance();
2954
2955            global $_LANG;
2956
2957        $date = date('Y-m-d H:i:s', strtotime($date)+($inConf->timediff*3600));
2958
2959                // ïîëó÷àåì çíà÷åíèå äàòû è âðåìåíè
2960                list($day, $time)  = explode(' ', $date);
2961                list($h, $min, $s) = explode(':', $time);
2962                list($y, $m, $d)   = explode('-', $day);
2963
2964                $days_week = array($_LANG['SUNDAY'], $_LANG['MONDAY'], $_LANG['TUESDAY'], $_LANG['WEDNESDAY'], $_LANG['THURSDAY'], $_LANG['FRIDAY'], $_LANG['SATURDAY']);
2965               
2966                $arr  = getdate(mktime($h, $min, $s, $m, $d, $y));
2967               
2968                $wday = $days_week[$arr['wday']];
2969       
2970                return $wday;
2971
2972    }
2973
2974    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2975    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2976    public function initAutoGrowText($element_id){
2977        $inPage = cmsPage::getInstance();
2978        $inPage->addHead('<script type="text/javascript" src="/includes/jquery/autogrow/jquery.autogrow.js"></script>');
2979        $inPage->addHead('<script type="text/javascript">$(document).ready (function() {$(\''.$element_id.'\').autogrow(); });</script>');
2980        return true;
2981    }
2982
2983    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2984    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2985    public function getDateForm($element, $seldate=false, $day_default=1, $month_default=1, $year_default=1980){
2986
2987        $year_from = 1950;
2988        $year_to = intval(date('Y'));
2989
2990        $html = '';
2991
2992        if(@$seldate){
2993            $parts = explode('-', $seldate);
2994            if ($parts[2]){
2995                $day_default = $parts[2];
2996            }
2997            if ($parts[1]){
2998                $month_default = $parts[1];
2999            }
3000            if ($parts[0]){
3001                $year_default = $parts[0];
3002            }
3003        }
3004
3005        $html .= '<select name="'.$element.'[day]">' . "\n";
3006        for($day=1; $day<=31;$day++){
3007            if ($day<10){ $day = '0'.$day; }
3008
3009            if (intval($day)==intval($day_default)){
3010                $html .= '<option value="'.$day.'" selected="selected">'.$day.'</option>'. "\n";
3011            } else {
3012                $html .= '<option value="'.$day.'">'.$day.'</option>'. "\n";
3013            }
3014        }
3015        $html .= '</select>'. "\n";
3016
3017        $months = array();
3018        $months['00'] = 'ßíâàðü';
3019        $months['01'] = 'Ôåâðàëü';
3020        $months['02'] = 'Ìàðò';
3021        $months['03'] = 'Àïðåëü';
3022        $months['04'] = 'Ìàé';
3023        $months['05'] = 'Èþíü';
3024        $months['06'] = 'Èþëü';
3025        $months['07'] = 'Àâãóñò';
3026        $months['08'] = 'Ñåíòÿáðü';
3027        $months['09'] = 'Îêòÿáðü';
3028        $months['10'] = 'Íîÿáðü';
3029        $months['11'] = 'Äåêàáðü';
3030
3031        $html .= '<select name="'.$element.'[month]">' . "\n";
3032        for($month=0; $month<12; $month++){
3033            if ($month<10){ $month = '0'.$month; }
3034
3035            if ((intval($month)+1)==intval($month_default)){
3036                $html .= '<option value="'.($month+1).'" selected="selected">'.$months[$month].'</option>'. "\n";
3037            } else {
3038                $html .= '<option value="'.($month+1).'">'.$months[$month].'</option>'. "\n";
3039            }
3040        }
3041        $html .= '</select>'. "\n";
3042
3043        $html .= '<select name="'.$element.'[year]">'. "\n";
3044        for($year=$year_from; $year<=$year_to;$year++){
3045            if ($year == $year_default){
3046                $html .= '<option value="'.$year.'" selected="selected">'.$year.'</option>'. "\n";
3047            } else {
3048                $html .= '<option value="'.$year.'">'.$year.'</option>'. "\n";
3049            }
3050        }
3051        $html .= '</select>'. "\n";
3052
3053        return $html;
3054    }
3055
3056    // USERS ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3057    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3058    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3059    /**
3060     * Ïðîâåðÿåò, ÿâëÿåòñÿ ëè ïîëüçîâàòåëü àäìèíèñòðàòîðîì
3061     * @param int $userid
3062     * @return bool
3063     */
3064    public function userIsAdmin($userid){
3065        $inDB = cmsDatabase::getInstance();
3066        $inUser = cmsUser::getInstance();
3067        if (!$userid) { return false; }
3068        if ($userid == $inUser->id) {
3069            return $inUser->is_admin;
3070        } else {
3071            $sql = "SELECT g.is_admin is_admin
3072                    FROM cms_users u
3073                                        LEFT JOIN cms_user_groups g ON g.id = u.group_id
3074                    WHERE u.id = '$userid' LIMIT 1";
3075            $result = $inDB->query($sql) ;
3076            if ($inDB->num_rows($result)){
3077                $data = $inDB->fetch_assoc($result);
3078                return $data['is_admin'];
3079            } else { return false; }
3080        }
3081    }
3082
3083    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3084    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3085    /**
3086     * Ïðîâåðÿåò, ÿâëÿåòñÿ ëè ïîëüçîâàòåëü ðåäàêòîðîì
3087     * @param int $userid
3088     * @return bool
3089     */
3090    public function userIsEditor($userid){
3091        $inDB = cmsDatabase::getInstance();
3092        if (!$userid) { return false; }
3093
3094        $sql = "SELECT c.id as id
3095                FROM cms_users u
3096                                LEFT JOIN cms_user_groups g ON g.id = u.group_id
3097                                LEFT JOIN cms_category c ON c.modgrp_id = g.id
3098                WHERE u.id = '$userid'
3099                LIMIT 1";
3100        $result = $inDB->query($sql) ;
3101
3102        if ($inDB->num_rows($result)){
3103            $editor_category = $inDB->fetch_assoc($result);
3104            return $editor_category['id'];
3105        } else { 
3106            return false; 
3107        }
3108    }
3109
3110    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3111    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3112    public function checkUserAccess($content_type, $content_id){
3113
3114        $inDB = cmsDatabase::getInstance();
3115        $inUser = cmsUser::getInstance();
3116
3117                if ($inUser->is_admin) { return true; }
3118
3119                $access   = $inDB->get_table('cms_content_access', "content_type = '$content_type' AND content_id = '$content_id'", 'group_id');
3120
3121                if (!$access || !is_array($access)) { return true; }
3122
3123                return in_array(array('group_id' => $inUser->group_id), $access);
3124
3125    }
3126
3127    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3128    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3129    /**
3130     * Âîçâðàùàåò ìàññèâ ñ àäìèíèñòðàòîðñêèìè ïðàâàìè äîñòóïà òåêóùåãî ïîëüçîâàòåëÿ
3131     * @return array
3132     */
3133    public function checkAdminAccess(){ //return admin access-options list
3134        $inUser     = cmsUser::getInstance();
3135        $inDB       = cmsDatabase::getInstance();
3136
3137        $group_id       = $inUser->group_id;
3138
3139        $sql = "SELECT access FROM cms_user_groups WHERE id = $group_id LIMIT 1";
3140        $result = $inDB->query($sql) ;
3141
3142        if ($inDB->num_rows($result)){
3143            $ac         = $inDB->fetch_assoc($result);
3144            $access_str = $ac['access'];
3145            $access     = str_replace(', ', ',', $access_str);
3146            $access     = explode(',', $access);
3147            return $access;
3148        }
3149
3150        return false;
3151    }
3152
3153    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3154    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3155    /**
3156     * Ïðîâåðÿåò ÷òî àäìèíèñòðàòîð èìååò ïðàâî íà óêàçàííîå äåéñòâèå
3157     * @param string $access_type
3158     * @param array $access_list
3159     * @return bool
3160     */
3161    public function isAdminCan($access_type, $access_list){ //$access_type like "admin/modules" or "admin/users"
3162        $inUser = cmsUser::getInstance();
3163        if (!$inUser->is_admin){ return false; }
3164        if($inUser->id==1) { return true; }
3165        if (in_array($access_type, $access_list)){ return true; }
3166        return false;
3167    }
3168
3169    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3170    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3171    /**
3172     * Ïðîâåðÿåò ÷òî ïîëüçîâàòåëü èìååò ïðàâî íà óêàçàííîå äåéñòâèå
3173     * @param string $access_type
3174     * @return bool
3175     */
3176    public function isUserCan($access_type){ //$access_type like "comments/delete" or "photo/edit"
3177        $inDB = cmsDatabase::getInstance();
3178        $inUser = cmsUser::getInstance();
3179        $do_access = false;
3180
3181        if ($inUser->id) {
3182            $group_id = $_SESSION['user']['group_id'];
3183            if ($inUser->is_admin){
3184                return true;
3185            }
3186            if (in_array($access_type, $_SESSION['user']['access'])){
3187                $do_access = true;
3188            }
3189        }
3190        else { $group_id = cmsUser::getGuestGroupId(); }
3191
3192        if (!$do_access) {
3193            if ($group_id > 0) {
3194                $sql = "SELECT access FROM cms_user_groups WHERE id = $group_id LIMIT 1";
3195            }
3196
3197            $result = $inDB->query($sql) ;
3198
3199            if ($inDB->num_rows($result)){
3200                $ac = $inDB->fetch_assoc($result);
3201                $access_str = $ac['access'];
3202
3203                $access = str_replace(', ', ',', $access_str);
3204                $access = explode(',', $access);
3205
3206                if (in_array($access_type, $access)){
3207                    $do_access = true;
3208                }
3209            }
3210        }
3211
3212        return $do_access;
3213    }
3214
3215    // SECURITY /////////////////////////////////////////////////////////////////////////////////////////////////////////////
3216    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3217    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3218    public function strClear($string, $strip_tags=true){
3219        $string = trim($string);
3220        //Åñëè magic_quotes_gpc = On, ñíà÷àëà óáèðàåì ýêðàíèðîâàíèå
3221        $string = (@get_magic_quotes_gpc()) ? stripslashes($string) : $string;       
3222        $string = rtrim($string, ' \\');
3223        if ($strip_tags) {
3224            $string = strip_tags($string);
3225            $string = mysql_real_escape_string($string);
3226        }
3227        return $string;
3228    }
3229    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3230    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3231    /**
3232     * Óäàëÿåò òåãè script iframe style meta
3233     * @param string $string
3234     * @return bool
3235     */
3236    public static function badTagClear($string){
3237
3238        $bad_tags = array (
3239            "'<script[^>]*?>.*?</script>'si",
3240            "'<style[^>]*?>.*?</style>'si",
3241            "'<meta[^>]*?>'si",
3242            '/<iframe.*?src=(?!"http:\/\/www\.youtube\.com\/embed\/|"http:\/\/vkontakte\.ru\/video_ext\.php\?).*?>.*?<\/iframe>/i',
3243            '/<iframe.*>.+<\/iframe>/i'
3244        );
3245
3246        $string = preg_replace($bad_tags, '', $string);
3247
3248        return $string;
3249       
3250    }
3251    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3252    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3253    /**
3254     * Ïðîâåðÿåò ñîâïàäåíèÿ êîäà êàïò÷è ñ êîäîì ââåäåííûì ïîëüçîâàòåëåì
3255     * @param string $code
3256     * @return bool
3257     */
3258    public function checkCaptchaCode($code){
3259        $sess_id        = session_id();
3260        $real_code      = $_SESSION['captcha_keystring'];
3261        unset($_SESSION['captcha_keystring']);
3262        return ($real_code == $code);
3263    }
3264
3265    // MAIL ROUTINES ////////////////////////////////////////////////////////////////////////////////////////////////////////
3266    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3267    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3268    /**
3269     * Ñîçäàåò è îòïðàâëÿåò ïèñüìî ýëåêòðîííîé ïî÷òîé
3270     * @param string $email
3271     * @param string $subject
3272     * @param string $message
3273     * @param string $content
3274     */
3275    public function mailText($email, $subject, $message, $content='text/plain'){
3276        $inConf = cmsConfig::getInstance();
3277        $headers = 'MIME-Version: 1.0' . "\r\n" .
3278                   'Content-type: '.$content.'; charset=windows-1251;' . "\r\n" .
3279                   'From: '.$inConf->sitename.' <'.$inConf->sitemail.'>' . "\r\n" .
3280                   'Reply-To: '.$inConf->sitename.' <'.$inConf->sitemail.'>' . "\r\n" .
3281                   'X-Mailer: PHP/' . phpversion();
3282        $message = wordwrap($message, 70);
3283        $this->sendMail( $inConf->sitemail, $inConf->sitename, $email, $subject, $message );
3284    }
3285
3286    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3287    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3288    private function createMail( $from='', $fromname='', $subject, $body ) {
3289        $inConf = cmsConfig::getInstance();
3290        if(!isset($inConf->mailer)) { $inConf->mailer = 'mail'; }
3291
3292        $this->includeFile('includes/phpmailer/phpmailer.php');
3293
3294        $mail = new mosPHPMailer();
3295
3296        $mail->PluginDir = PATH . '/includes/phpmailer/';
3297        $mail->SetLanguage( 'en', PATH . '/includes/phpmailer/language/' );
3298        $mail->CharSet     = 'windows-1251';
3299        $mail->IsMail();
3300        $mail->From     = $from ? $from : $inConf->sitemail;
3301        $mail->FromName = $fromname ? $fromname : $inConf->sitename;
3302        $mail->Mailer   = $inConf->mailer;
3303
3304        // Add smtp values if needed
3305        if ( $inConf->mailer == 'smtp' ) {
3306            $mail->SMTPAuth = $inConf->smtpauth;
3307            $mail->Username = $inConf->smtpuser;
3308            $mail->Password = $inConf->smtppass;
3309            $mail->Host     = $inConf->smtphost;
3310        } else
3311
3312        // Set sendmail path
3313        if ( $inConf->mailer == 'sendmail' ) {
3314            if (isset($inConf->sendmail)){
3315                $mail->Sendmail = $inConf->sendmail;
3316            } else {
3317                $mail->Sendmail = '/usr/sbin/sendmail';
3318            }
3319        } // if
3320
3321        $mail->Subject     = $subject;
3322        $mail->Body        = $body;
3323
3324        return $mail;
3325    }
3326
3327    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3328    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3329    private function sendMail( $from, $fromname, $recipient, $subject, $body, $mode=0, $cc=NULL, $bcc=NULL, $attachment=NULL, $replyto=NULL, $replytoname=NULL ) {
3330        $inConf = cmsConfig::getInstance();
3331
3332        // Allow empty $from and $fromname settings (backwards compatibility)
3333        if ($from == '') { $from = $inConf->sitemail;   }
3334        if ($fromname == '') { $fromname = $inConf->sitename; }
3335
3336        $mail = $this->createMail( $from, $fromname, $subject, $body );
3337
3338        // activate HTML formatted emails
3339        if ( $mode ) {  $mail->IsHTML(true); }
3340
3341        if (is_array( $recipient )) {
3342            foreach ($recipient as $to) {
3343                $mail->AddAddress( $to );
3344            }
3345        } else { $mail->AddAddress( $recipient ); }
3346
3347        if (isset( $cc )) {
3348            if (is_array( $cc )) {
3349                foreach ($cc as $to) {
3350                    $mail->AddCC($to);
3351                }
3352            } else { $mail->AddCC($cc); }
3353        }
3354        if (isset( $bcc )) {
3355            if (is_array( $bcc )) {
3356                foreach ($bcc as $to) {
3357                    $mail->AddBCC( $to );
3358                }
3359            } else {
3360                $mail->AddBCC( $bcc );
3361            }
3362        }
3363        if ($attachment) {
3364            if (is_array( $attachment )) {
3365                foreach ($attachment as $fname) {
3366                    $mail->AddAttachment( $fname[0], $fname[1] );
3367                }
3368            } else {
3369                $mail->AddAttachment($attachment);
3370            }
3371        }
3372        //Important for being able to use mosMail without spoofing...
3373        if ($replyto) {
3374            if (is_array( $replyto )) {
3375                reset( $replytoname );
3376                foreach ($replyto as $to) {
3377                    $toname = ((list( $key, $value ) = each( $replytoname )) ? $value : '');
3378                    $mail->AddReplyTo( $to, $toname );
3379                }
3380            } else {
3381                $mail->AddReplyTo($replyto, $replytoname);
3382            }
3383        }
3384
3385        $mailssend = $mail->Send();
3386
3387        return $mailssend;
3388    }
3389
3390    // UC SEARCH ////////////////////////////////////////////////////////////////////////////////////////////////////////////
3391    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3392    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3393    public function getUCSearchLink($cat_id, $menuid, $field_id, $text){
3394        $html='';
3395        $text = html_entity_decode($text);
3396        $text = strip_tags($text);
3397        $text = trim($text);
3398        if (!strstr($text, ',')){
3399            $html .= '<a href="/catalog/'.$cat_id.'/find/'.urlencode($text).'">'.$text.'</a>';
3400        } else {
3401            $text = str_replace(', ', ',', $text);
3402            $words = array();
3403            $words = explode(',', $text);
3404
3405            $n=0;
3406            foreach($words as $key=>$value){
3407                $n++;
3408                $value = strip_tags($value);
3409                $value = str_replace("\r", '', $value);
3410                $value = str_replace("\n", '', $value);
3411                $value = trim($value);
3412
3413                $html .= '<a href="/catalog/'.$cat_id.'/find/'.urlencode($value).'">'.$value.'</a>';
3414                if ($n<sizeof($words)) { $html .= ', '; } else { $html .= '.'; }
3415            }
3416
3417        }
3418        return $html;
3419    }
3420
3421    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3422    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3423    public function registerUploadImages($session_id, $post_id, $target){
3424        $inDB = cmsDatabase::getInstance();
3425        $sql = "UPDATE cms_upload_images SET post_id = $post_id, session_id = '' WHERE session_id = '$session_id' AND target='$target'";
3426        $inDB->query($sql);
3427        return true;
3428    }
3429
3430    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3431    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3432    public function deleteUploadImages($post_id, $target){
3433        $inDB = cmsDatabase::getInstance();
3434        $sql = "SELECT * FROM cms_upload_images WHERE post_id = '$post_id' AND target='$target'";
3435        $rs = $inDB->query($sql);
3436        if ($inDB->num_rows($rs)){
3437            while($file = $inDB->fetch_assoc($rs)){
3438                $filename = PATH.$file['fileurl'];
3439                if (file_exists($filename)){ @unlink($filename); }
3440                $inDB->query("DELETE FROM cms_upload_images WHERE id=".$file['id']);
3441            }
3442        }
3443        return true;
3444    }
3445
3446    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3447    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3448    public function parseSmiles($text, $parse_bbcode=false){
3449        if (!$parse_bbcode){
3450            //convert URLs to links
3451            $text = ereg_replace("/(?<!http:\\/\\/)(www)(\\S+)/si",'http://www\\2', $text);
3452            $text = ereg_replace("/(http:\\/\\/)(\\S+)/si",'<a href="/go/url=http://\\2" target=_blank>http://\\2</a>',$text);
3453        } else {
3454            //parse bbcode
3455            include_once PATH.'/includes/bbcode/bbcode.lib.php';
3456            $bb = new bbcode($text);
3457            $text = $bb->get_html();           
3458        }
3459
3460        //convert emoticons to smileys
3461        $smilefix = array();
3462        $smilefix[' :) '] = 'smile';
3463        $smilefix[' =) '] = 'smile';
3464        $smilefix[':-)'] = 'smile';
3465        $smilefix[' :( '] = 'sad';
3466        $smilefix[':-('] = 'sad';
3467        $smilefix[';-)'] = 'joke';
3468        $smilefix[' ;) '] = 'joke';
3469        $smilefix[' =0 '] = 'shock';
3470        $smilefix['=-0'] = 'shock';
3471        $smilefix[' Oo '] = 'shock';
3472        $smilefix[':-0'] = 'shock';
3473        $smilefix[' :D '] = 'laugh';
3474        $smilefix[':-D'] = 'laugh';
3475
3476        foreach($smilefix as $find=>$tag){
3477            $text = str_replace($find, ':'.$tag.':', $text);
3478        }
3479
3480        $tags = explode(':', $text);
3481
3482        foreach($tags as $key=>$value){
3483            if (strlen($value)<15){
3484                $file = '/images/smilies/'.$value.'.gif';
3485                if (@file_exists(PATH.$file)){
3486                    $text = str_replace(':'.$value.':', '<img src="'.$file.'" alt="'.$value.'" border="0"/>', $text);
3487                }
3488            }
3489        }
3490
3491        return $text;
3492    }
3493
3494    // PAGE CACHE   /////////////////////////////////////////////////////////////////////////////////////////////////////////
3495    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3496    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3497    /**
3498     * Ïðîâåðÿåò íàëè÷èå êýøà äëÿ óêàçàííîãî êîíòåíòà
3499     * @param string $target
3500     * @param int $target_id
3501     * @param int $cachetime
3502     * @param string $cacheint
3503     * @return bool
3504     */
3505    public function isCached($target, $target_id, $cachetime=1, $cacheint='MINUTES'){
3506        $where = "target='$target' AND target_id='$target_id' AND cachedate >= DATE_SUB(NOW(), INTERVAL $cachetime $cacheint)";
3507        $page = dbGetFields('cms_cache', $where, '*');
3508        if ($page){
3509            $cachefile = PATH.'/cache/'.$page['cachefile'];
3510            if (file_exists($cachefile)){
3511                return true;
3512            } else {
3513                return false;
3514            }
3515        } else {
3516            $this->deleteCache($target, $target_id);
3517            return false;
3518        }
3519    }
3520
3521    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3522    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3523    /**
3524     * Âîçâðàùàåò êýø óêàçàííîãî êîíòåíòà
3525     * @param string $target
3526     * @param int $target_id
3527     * @return html
3528     */
3529    public function getCache($target, $target_id){
3530            $page = dbGetFields('cms_cache', "target='$target' AND target_id='$target_id'", '*');
3531            if ($page){
3532                $cachefile = PATH.'/cache/'.$page['cachefile'];
3533                if (file_exists($cachefile)){
3534                    $cache = file_get_contents($cachefile);
3535                    if(strstr($_SERVER['QUERY_STRING'], 'show_cache')){
3536                        $cache .= '<div style="background-color:gray;color:white">Printed from cache!</div>';
3537                    }
3538                    return $cache;
3539                }
3540            }
3541        return false;
3542    }
3543
3544    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3545    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3546    /**
3547     * Ñîõðàíÿåò ïåðåäàííûé êýø óêàçàííîãî êîíòåíòà
3548     * @param string $target
3549     * @param int $target_id
3550     * @param string $html
3551     * @return bool
3552     */
3553    public function saveCache($target, $target_id, $html){
3554        $inDB = cmsDatabase::getInstance();
3555        $filename = md5($target.$target_id).'.html';
3556        $sql = "INSERT INTO cms_cache (target, target_id, cachedate, cachefile)
3557                VALUES ('$target', $target_id, NOW(), '$filename')";
3558        $inDB->query($sql) or die('ERROR CREATING CACHE: '.mysql_error());
3559        $filename = PATH.'/cache/'.$filename;
3560        file_put_contents($filename, $html);
3561        return true;
3562    }
3563
3564    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3565    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3566    /**
3567     * Óäàëÿåò êýø óêàçàííîãî êîíòåíòà
3568     * @param string $target
3569     * @param int $target_id
3570     * @return bool
3571     */
3572    public function deleteCache($target, $target_id){
3573        $inDB = cmsDatabase::getInstance();
3574        $inDB->query("DELETE FROM cms_cache WHERE target='$target' AND target_id='$target_id'");
3575        $oldcache = PATH.'/cache/'.md5($target.$target_id).'.html';
3576        if (file_exists($oldcache)) { @unlink($oldcache); }
3577        return true;
3578    }
3579
3580    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3581    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3582    /**
3583     * Âîçâðàùàåò êîä áàííåðà ñ ìèíèìàëüíûé êîëè÷åñòâîì ïîêàçîâ äëÿ óêàçàííîé ïîçèöèè
3584     * @param string $position
3585     * @return html
3586     */
3587    public function getBanner($position){
3588
3589        if (!$this->isComponentInstalled('banners')) { return false; }
3590
3591        $inDB = cmsDatabase::getInstance();
3592        $html = '';
3593
3594        $sql = "SELECT *
3595                FROM cms_banners
3596                WHERE position = '$position' AND published = 1 AND ((maxhits > hits) OR (maxhits = 0))
3597                ORDER BY RAND() ASC
3598                LIMIT 1";
3599        $rs = $inDB->query($sql);
3600
3601        if ($inDB->num_rows($rs)==1){
3602            $banner = $inDB->fetch_assoc($rs);
3603            if ($banner['typeimg']=='image'){
3604                $html = '<a href="/gobanner'.$banner['id'].'" title="'.$banner['title'].'" target="_blank"><img src="/images/banners/'.$banner['fileurl'].'" border="0" alt="'.$banner['title'].'"/></a>';
3605            }
3606            if ($banner['typeimg']=='swf'){
3607                $html = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="468" height="60">'."\n".
3608                            '<param name="movie" value="/images/banners/'.$banner['fileurl'].'?banner_id='.$banner['id'].'" />'."\n".
3609                            '<param name="quality" value="high" />'."\n".
3610                            '<param name="FlashVars" value="banner_id='.$banner['id'].'" />'."\n".
3611                            '<embed src="/images/banners/'.$banner['fileurl'].'?banner_id='.$banner['id'].'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="468" height="60">'."\n".
3612                            '</embed>'."\n".
3613                        '</object>';
3614            }
3615            if ($html) { $inDB->query("UPDATE cms_banners SET hits = hits + 1 WHERE id=".$banner['id']);        }
3616        }
3617        return $html;
3618    }
3619
3620    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3621    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3622    /**
3623     * Âîçâðàùàåò êîä áàííåðà ïî ID
3624     * @param int $id
3625     * @return html
3626     */
3627    public function getBannerById($id){
3628        $inDB = cmsDatabase::getInstance();
3629        $html = '';
3630
3631        $sql = "SELECT *
3632                FROM cms_banners
3633                WHERE id = $id
3634                LIMIT 1";
3635        $rs = $inDB->query($sql);
3636
3637        if ($inDB->num_rows($rs)==1){
3638            $banner = $inDB->fetch_assoc($rs);
3639            if ($banner['typeimg']=='image'){
3640                $html = '<a href="/gobanner'.$banner['id'].'" title="'.$banner['title'].'"><img src="/images/banners/'.$banner['fileurl'].'" border="0" alt="'.$banner['title'].'"/></a>';
3641            }
3642            if ($banner['typeimg']=='swf'){
3643                $html = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="468" height="60">'."\n".
3644                            '<param name="movie" value="/images/banners/'.$banner['fileurl'].'?banner_id='.$banner['id'].'" />'."\n".
3645                            '<param name="quality" value="high" />'."\n".
3646                            '<param name="FlashVars" value="banner_id='.$banner['id'].'" />'."\n".
3647                            '<embed src="/images/banners/'.$banner['fileurl'].'?banner_id='.$banner['id'].'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="468" height="60">'."\n".
3648                            '</embed>'."\n".
3649                        '</object>';
3650            }
3651        }
3652        return $html;
3653    }
3654
3655    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3656    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3657    static public function strToURL($str){
3658
3659        $str    = trim($str);       
3660        $str    = mb_strtolower($str, 'cp1251');
3661        $str    = str_replace(' ', '-', $str);
3662        $string = preg_replace ('/[^a-zA-Zà-ÿÀ-ß0-9\-]/i', '-', $str);
3663        $string = rtrim($string, '-');
3664
3665        while(strstr($string, '--')){ $string = str_replace('--', '-', $string); }
3666
3667        $ru_en = array(
3668                        'à'=>'a','á'=>'b','â'=>'v','ã'=>'g','ä'=>'d',
3669                        'å'=>'e','¸'=>'yo','æ'=>'zh','ç'=>'z',
3670                        'è'=>'i','é'=>'i','ê'=>'k','ë'=>'l','ì'=>'m',
3671                        'í'=>'n','î'=>'o','ï'=>'p','ð'=>'r','ñ'=>'s',
3672                        'ò'=>'t','ó'=>'u','ô'=>'f','õ'=>'h','ö'=>'c',
3673                        '÷'=>'ch','ø'=>'sh','ù'=>'sch','ú'=>'','û'=>'y',
3674                        'ü'=>'','ý'=>'ye','þ'=>'yu','ÿ'=>'ja'
3675                      );
3676
3677        foreach($ru_en as $ru=>$en){
3678            $string = preg_replace('/(['.$ru.']+)/i', $en, $string);
3679        }
3680
3681        if (!$string){ $string = 'untitled'; }
3682
3683        return $string;
3684
3685        }
3686
3687    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3688    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3689    public function halt($message=''){
3690        die($message);
3691    }
3692
3693    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3694    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3695    public function flushUpload(){
3696        $inDB = cmsDatabase::getInstance();
3697        $inDB->query("DELETE FROM cms_upload_images WHERE session_id='".session_id()."'");
3698    }
3699
3700    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3701    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3702    public function clearSessionTrash(){
3703        unset($_SESSION['bbcode']);
3704    }
3705
3706    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3707    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3708    /**
3709     * Âûâîäèò ñëîâàìè ðàçíèöó ìåæäó òåêóùåé è óêàçàííîé äàòîé
3710     * @param string $date
3711     * @return string
3712     */
3713    public static function dateDiffNow($date) {
3714
3715        $diff_str   = '';
3716
3717        $now        = time();
3718        $date       = strtotime($date);
3719
3720        if ($date == 0) { return 'íå èçâåñòíî'; }
3721
3722        $diff_sec   = $now - $date;
3723
3724        $diff_day   = (string)round($diff_sec/60/60/24);
3725        $diff_hour  = (string)round(($diff_sec/60/60) - ($diff_day*24));
3726        $diff_min   = (string)round(($diff_sec/60)-($diff_hour*60));
3727
3728        //Âûâîäèì ðàçíèöó â äíÿõ
3729        if ($diff_day > 0){
3730
3731            if ($diff_day == 11 || $diff_day == 12 || $diff_day == 13 || $diff_day == 14) {
3732                $diff_str = $diff_day. " äíåé";
3733            } elseif ($diff_day[strlen($diff_day)-1] == "2" || $diff_day[strlen($diff_day)-1] == "3" || $diff_day[strlen($diff_day)-1] == "4") {
3734                $diff_str = $diff_day." äíÿ";
3735            } elseif($diff_day[strlen($diff_day)-1] == "1") {
3736                $diff_str = $diff_day. " äåíü";
3737            } else {
3738                $diff_str = $diff_day. " äíåé";
3739            }
3740
3741            return $diff_str;
3742
3743        }
3744
3745        //Âûâîäèì ðàçíèöó â ÷àñàõ
3746        if ($diff_hour > 0){
3747
3748            if ($diff_hour == 1 || $diff_hour == 21) $diff_str = $diff_hour." ÷àñ"; else
3749            if ($diff_hour == 2 || $diff_hour == 3 or $diff_hour == 4 || $diff_hour == 22 || $diff_hour == 23) $diff_str = $diff_hour." ÷àñà";
3750            else $diff_str = $diff_hour." ÷àñîâ";
3751
3752            return $diff_str;
3753
3754        }
3755
3756        //Âûâîäèì ðàçíèöó â ìèíóòàõ
3757        if ($diff_min > 0){
3758
3759            if ($diff_min == "11" || $diff_min == "12" || $diff_min == "13" || $diff_min == "14") {
3760                $diff_str = $diff_min. " ìèíóò";
3761            } elseif ($diff_min[strlen($diff_min)-1] == "2" || $diff_min[strlen($diff_min)-1] == "3" || $diff_min[strlen($diff_min)-1] == "4") {
3762                $diff_str = $diff_min." ìèíóòû";
3763            } elseif($diff_min[strlen($diff_min)-1] == "1") {
3764                $diff_str = $diff_min. " ìèíóòó";
3765            } else {
3766                $diff_str = $diff_min. " ìèíóò";
3767            }
3768
3769            return $diff_str;
3770
3771        }
3772
3773        $diff_str = 'ìåíüøå ìèíóòû';
3774
3775        return $diff_str;
3776
3777    }
3778
3779    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3780    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3781
3782/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3783/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3784} //cmsCore
3785
3786
3787/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3788///////////////////////////////////////////////////////////////////////////////////////////////////////////////
3789function dbRowsCount($table, $where){
3790    $inDB = cmsDatabase::getInstance();
3791    return $inDB->rows_count($table, $where);
3792}
3793
3794function dbGetField($table, $where, $field){
3795    $inDB = cmsDatabase::getInstance();
3796    return $inDB->get_field($table, $where, $field);
3797}
3798
3799function dbGetFields($table, $where, $fields, $order='id ASC'){
3800    $inDB = cmsDatabase::getInstance();
3801    return $inDB->get_fields($table, $where, $fields, $order);
3802}
3803
3804function dbGetTable($table, $where='', $fields='*'){
3805    $inDB = cmsDatabase::getInstance();
3806    return $inDB->get_table($table, $where, $fields);
3807}
3808
3809function dbLastId($table){
3810    $inDB = cmsDatabase::getInstance();
3811    return $inDB->get_last_id($table);
3812}
3813
3814function dbDeleteNS($table, $id){
3815    $inCore = cmsCore::getInstance();
3816    $ns = $inCore->nestedSetsInit($table);
3817    $ns->DeleteNode($id);
3818}
3819
3820function dbDeleteListNS($table, $list){
3821    $inCore = cmsCore::getInstance();
3822    $ns = $inCore->nestedSetsInit($table);
3823    if (is_array($list)){
3824        foreach($list as $key => $value){
3825            $ns->DeleteNode($value);
3826        }
3827    }
3828}
3829
3830/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3831/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3832//
3833//Ôóíêöèè íèæå îñòàâëåíû äëÿ ñîâìåñòèìîñòè ñî ñòàðûìè øàáëîíàìè
3834//
3835
3836function cmsPrintSitename(){
3837    $inPage = cmsPage::getInstance();
3838    $inPage->printSitename();
3839}
3840
3841function cmsPrintHead(){
3842    $inPage = cmsPage::getInstance();
3843    $inPage->printHead();
3844}
3845
3846function cmsPathway($separator){
3847    $inPage = cmsPage::getInstance();
3848    $inPage->printPathway($separator);
3849}
3850
3851function cmsBody(){
3852    $inPage = cmsPage::getInstance();
3853    $inPage->printBody();
3854}
3855
3856function cmsPrintFooter(){
3857    $inPage = cmsPage::getInstance();
3858    $inPage->printFooter();
3859}
3860
3861function cmsCountModules($position){
3862    $inPage = cmsPage::getInstance();
3863    return $inPage->countModules($position);
3864}
3865
3866function cmsModule($position){
3867    $inPage = cmsPage::getInstance();
3868    $inPage->printModules($position);
3869}
3870
3871/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3872
3873function cmsGetUserLink(){
3874    $inPage = cmsPage::getInstance();
3875    return $inPage->getUserLinks();
3876}
3877
3878function cmsMenuId(){
3879   $inCore = cmsCore::getInstance();
3880   return $inCore->menuId();
3881}
3882
3883function cmsUserId(){
3884   $inUser = cmsUser::getInstance();
3885   return $inUser->id;
3886}
3887
3888function cmsLoadModuleConfig($module_id){
3889   $inCore = cmsCore::getInstance();
3890   return $inCore->loadModuleConfig($module_id);
3891}
3892
3893function cmsLoadComponentConfig($component){
3894   $inCore = cmsCore::getInstance();
3895   return $inCore->loadComponentConfig($component);
3896}
3897
3898function cmsNestedSetsInit($table){
3899   $inCore = cmsCore::getInstance();
3900   return $inCore->nestedSetsInit($table);
3901}
3902
3903function cmsUserIsAdmin(){
3904    $inUser = cmsUser::getInstance();
3905    return $inUser->is_admin;
3906}
3907
3908function cmsGuestGroup(){
3909    return cmsUser::getGuestGroupId();
3910}
3911
3912function cmsMenuSeoLink($link, $linktype, $menuid=1){
3913    $inCore = cmsCore::getInstance();
3914    return $inCore->menuSeoLink($link, $linktype, $menuid);
3915}
3916/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3917
3918function cmsSmartyComments($params){
3919
3920    if (!$params['target']) { return false; }
3921    if (!$params['target_id']) { return false; }
3922
3923    $inCore = cmsCore::getInstance();
3924    $inCore->includeComments();
3925
3926    comments($params['target'], $params['target_id'], $params['labels']);
3927
3928    return;
3929
3930}
3931
3932function cmsSmartyNoSpam($email, $filterLevel = 'normal'){
3933    $email = strrev($email);
3934    $email = preg_replace('[\.]', '/', $email, 1);
3935    $email = preg_replace('[@]', '/', $email, 1);
3936
3937    if($filterLevel == 'low')
3938    {
3939        $email = strrev($email);
3940    }
3941
3942    return $email;
3943}
3944
3945function cmsSmartyAddJS($params){
3946    $inPage = cmsPage::getInstance();
3947    $inPage->addHeadJS($params['file']);
3948}
3949
3950function cmsSmartyWysiwyg($params){
3951    $inCore = cmsCore::getInstance();
3952    ob_start();
3953    $inCore->insertEditor($params['name'], $params['value'], $params['height'], $params['width']);
3954    return ob_get_clean();
3955}
3956
3957function cmsSmartyAddCSS($params){
3958    $inPage = cmsPage::getInstance();
3959    $inPage->addHeadCSS($params['file']);
3960}
3961
3962function cmsSmartyProfileURL($params){
3963    return cmsUser::getProfileURL($params['login']);
3964}
3965
3966function usrNewMessages($user_id){
3967   $inCore = cmsCore::getInstance();
3968   return cmsUser::isNewMessages($user_id);
3969}
3970
3971/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3972/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3973
3974?>
Note: See TracBrowser for help on using the repository browser.