Completed
Push — master ( 0591a9...8e0116 )
by Agel_Nash
02:58
created

modResource::childrens()   B

Complexity

Conditions 8
Paths 4

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 11
nc 4
nop 2
dl 0
loc 16
rs 7.7777
c 0
b 0
f 0
1
<?php
2
require_once('MODx.php');
3
4
class modResource extends MODxAPI
5
{
6
    protected $mode = null;
7
    protected $default_field = array(
8
        'type' => 'document',
9
        'contentType' => 'text/html',
10
        'pagetitle' => 'New document',
11
        'longtitle' => '',
12
        'description' => '',
13
        'alias' => '',
14
        'link_attributes' => '',
15
        'published' => 1,
16
        'pub_date' => 0,
17
        'unpub_date' => 0,
18
        'parent' => 0,
19
        'isfolder' => 0,
20
        'introtext' => '',
21
        'content' => '',
22
        'richtext' => 1,
23
        'template' => 0,
24
        'menuindex' => 0,
25
        'searchable' => 1,
26
        'cacheable' => 1,
27
        'createdon' => 0,
28
        'createdby' => 0,
29
        'editedon' => 0,
30
        'editedby' => 0,
31
        'deleted' => 0,
32
        'deletedon' => 0,
33
        'deletedby' => 0,
34
        'publishedon' => 0,
35
        'publishedby' => 0,
36
        'menutitle' => '',
37
        'donthit' => 0,
38
        'haskeywords' => 0,
39
        'hasmetatags' => 0,
40
        'privateweb' => 0,
41
        'privatemgr' => 0,
42
        'content_dispo' => 0,
43
        'hidemenu' => 0,
44
        'alias_visible' => 1
45
    );
46
    private $table = array('"' => '_', "'" => '_', ' ' => '_', '.' => '_', ',' => '_', 'а' => 'a', 'б' => 'b', 'в' => 'v',
47
        'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k',
48
        'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u',
49
        'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch', 'ь' => '', 'ы' => 'y', 'ъ' => '',
50
        'э' => 'e', 'ю' => 'yu', 'я' => 'ya', 'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E',
51
        'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z', 'И' => 'I', 'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N',
52
        'О' => 'O', 'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C',
53
        'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sch', 'Ь' => '', 'Ы' => 'Y', 'Ъ' => '', 'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya',
54
    );
55
    /**
56
     * @var array массив ТВшек где name это ключ массива, а ID это значение
57
     */
58
    private $tv = array();
59
    /**
60
     * @var array массив ТВшек где ID это ключ массива, а name это значение
61
     */
62
    private $tvid = array();
63
    /**
64
     * @var array значения по умолчанию для ТВ параметров
65
     */
66
    private $tvd = array();
67
68
    /** @var array связи ТВ и шаблонов */
69
    private $tvTpl = array();
70
71
    /**
72
     * Массив администраторов
73
     * @var DLCollection
74
     */
75
    private $managerUsers = null;
76
77
    public function __construct($modx, $debug = false)
78
    {
79
        parent::__construct($modx, $debug);
80
        $this->get_TV();
81
        $uTable = $this->makeTable("manager_users");
82
        $aTable = $this->makeTable("user_attributes");
83
        $query = "SELECT `u`.`id`, `a`.`email`, `u`.`username`  FROM ".$aTable." as `a` LEFT JOIN ".$uTable." as `u` ON `u`.`id`=`a`.`internalKey`";
84
        $this->managerUsers = new DLCollection($modx, $this->query($query));
85
    }
86
87
    public function toArrayMain()
88
    {
89
        $out = array_intersect_key(parent::toArray(), $this->default_field);
90
        return $out;
91
    }
92
93
    public function toArrayTV($render = false)
94
    {
95
        $out = array_diff_key(parent::toArray(), $this->default_field);
96
        $tpl = $this->get('template');
97
        $tvTPL = APIHelpers::getkey($this->tvTpl, $tpl, array());
98
        foreach($tvTPL as $item){
99
            if(isset($this->tvid[$item]) && !array_key_exists($this->tvid[$item], $out)){
100
                $out[$this->tvid[$item]] = $this->get($this->tvid[$item]);
101
            }
102
        }
103
        if($render){
104
            foreach($out as $key => $val){
105
                $out[$key] = $this->renderTV($key);
106
            }
107
        }
108
        return $out;
109
    }
110
111
    public function toArray($prefix = '', $suffix = '', $sep = '_', $render = true){
112
        $out = array_merge(
113
            $this->toArrayMain(),
114
            $this->toArrayTV($render),
115
            array($this->fieldPKName() => $this->getID())
116
        );
117
        return \APIhelpers::renameKeyArr($out, $prefix, $suffix, $sep);
118
    }
119
	public function getUrl(){
120
		$out = null;
121
		$id = (int)$this->getID();
122
		if(!empty($id)){
123
			$out = $this->modx->makeUrl($id);
124
		}
125
		return $out;
126
	}
127
	public function getTitle($main = 'menutitle', $second = 'pagetitle'){
128
		$title = $this->get($main);
129
		if(empty($title) && $title !== '0'){
130
			$title = $this->get($second);
131
		}
132
		return $title;
133
	}
134
	
135
    public function isWebShow()
136
    {
137
        $pub = ($this->get('publishedon') < time() && $this->get('published'));
138
        $unpub = ($this->get('unpub_date') == 0 || $this->get('unpub_date') > time());
139
        $del = ($this->get('deleted') == 0 && ($this->get('deletedon') == 0 || $this->get('deletedon') > time()));
140
        return ($pub && $unpub && $del);
141
    }
142
    public function touch(){
143
        $this->set('editedon', time());
144
        return $this;
145
    }
146
147
    public function renderTV($tvname){
148
        $out = null;
149
        if($this->getID() > 0){
150
            include_once MODX_MANAGER_PATH . "includes/tmplvars.format.inc.php";
151
            include_once MODX_MANAGER_PATH . "includes/tmplvars.commands.inc.php";
152
            $tvval = $this->get($tvname);
153
            $param = APIHelpers::getkey($this->tvd, $tvname, array());
154
            $display = APIHelpers::getkey($param, 'display', '');
155
            $display_params = APIHelpers::getkey($param, 'display_params', '');
156
            $type = APIHelpers::getkey($param, 'type', '');
157
            $out = getTVDisplayFormat($tvname, $tvval, $display, $display_params, $type, $this->getID(), '');
158
        }
159
        return $out;
160
    }
161
162
    public function get($key){
163
        $out = parent::get($key);
164
        if(isset($this->tv[$key])){
165
            $tpl = $this->get('template');
166
            $tvTPL = APIHelpers::getkey($this->tvTpl, $tpl, array());
167
            $tvID = APIHelpers::getkey($this->tv, $key, 0);
168
            if(in_array($tvID, $tvTPL) && is_null($out)){
169
                $out = APIHelpers::getkey($this->tvd[$key], 'value', null);
170
            }
171
        }
172
        return $out;
173
    }
174
175
    public function set($key, $value)
176
    {
177
        if (is_scalar($value) && is_scalar($key) && !empty($key)) {
178
            switch ($key) {
179
                case 'parent':
180
                    $value = (int)$value;
181
                    break;
182
                case 'template':
183
                    $value = trim($value);
184
                    $value = $this->setTemplate($value);
185
                    break;
186 View Code Duplication
                case 'published':
187
                    $value = (int)((bool)$value);
188
                    if($value){
189
                        $this->field['publishedon'] = time() + $this->modxConfig('server_offset_time');
190
                    }
191
                    break;
192 View Code Duplication
                case 'pub_date':
193
                    $value = $this->getTime($value);
194
                    if($value > 0 && time() + $this->modxConfig('server_offset_time') > $value){
195
                        $this->field['published'] = 1;
196
                        $this->field['publishedon'] = $value;
197
                    }
198
                    break;
199 View Code Duplication
                case 'unpub_date':
200
                    $value = $this->getTime($value);
201
                    if($value > 0 && time() + $this->modxConfig('server_offset_time') > $value){
202
                        $this->field['published'] = 0;
203
                        $this->field['publishedon'] = 0;
204
                    }
205
                    break;
206 View Code Duplication
                case 'deleted':
207
                    $value = (int)((bool)$value);
208
                    if($value){
209
                        $this->field['deletedon'] = time() + $this->modxConfig('server_offset_time');
210
                    }else{
211
                        $this->field['deletedon'] = 0;
212
                    }
213
                    break;
214 View Code Duplication
                case 'deletedon':
215
                    $value = $this->getTime($value);
216
                    if($value > 0 && time() + $this->modxConfig('server_offset_time') < $value){
217
                        $value = 0;
218
                    }
219
                    if($value){
220
                        $this->field['deleted'] = 1;
221
                    }
222
                    break;
223
                case 'editedon':
224
                case 'createdon':
225
                case 'publishedon':
226
                    $value = $this->getTime($value);
227
                    break;
228
                case 'publishedby':
229
                case 'editedby':
230
                case 'createdby':
231
                case 'deletedby':
232
                    $value = $this->getUser($value, $this->default_field[$key]);
233
                    break;
234
            }
235
            $this->field[$key] = $value;
236
        }
237
        return $this;
238
    }
239
240
    protected function getUser($value, $default = 0){
241
        $currentAdmin = APIHelpers::getkey($_SESSION, 'mgrInternalKey', 0);
242
        $value = (int)$value;
243
        if(!empty($value)){
244
            $by = $this->findUserBy($value);
245
            $exists = $this->managerUsers->exists(function($key, $val) use ($by, $value){
246
                return ($val->containsKey($by) && $val->get($by) === (string)$value);
247
            });
248
            if(!$exists){
249
                $value = 0;
250
            }
251
        }
252
        if(empty($value)){
253
            $value = empty($currentAdmin) ? $default : $currentAdmin;
254
        }
255
        return $value;
256
    }
257
258 View Code Duplication
    protected function findUserBy($data)
259
    {
260
        switch (true) {
261
            case (is_int($data) || ((int)$data > 0 && (string)intval($data) === $data)):
262
                $find = 'id';
263
                break;
264
            case filter_var($data, FILTER_VALIDATE_EMAIL):
265
                $find = 'email';
266
                break;
267
            case is_scalar($data):
268
                $find = 'username';
269
                break;
270
            default:
271
                $find = false;
272
        }
273
        return $find;
274
    }
275
276
    protected function getTime($value){
277
        $value = trim($value);
278
        if(!empty($value)){
279
            if(!is_numeric($value)){
280
                $value = (int)strtotime($value);
281
            }
282
            if(!empty($value)){
283
                $value += $this->modxConfig('server_offset_time');
284
            }
285
        }
286
        return $value;
287
    }
288
    public function create($data = array())
289
    {
290
        parent::create($data);
291
        $this->set('createdby', null)
292
            ->set('editedby', null)
293
            ->set('createdon', time())
294
            ->touch();
295
        return $this;
296
    }
297
298
    public function edit($id)
299
    {
300
        $id = is_scalar($id) ? trim($id) : '';
301
        if ($this->getID() != $id) {
302
            $this->close();
303
            $this->newDoc = false;
304
305
            $result = $this->query("SELECT * from {$this->makeTable('site_content')} where `id`=" . (int)$id);
306
            $this->fromArray($this->modx->db->getRow($result));
307
            $result = $this->query("SELECT * from {$this->makeTable('site_tmplvar_contentvalues')} where `contentid`=" . (int)$id);
308
            while ($row = $this->modx->db->getRow($result)) {
309
                $this->field[$this->tvid[$row['tmplvarid']]] = $row['value'];
310
            }
311
            if (empty($this->field['id'])) {
312
                $this->id = null;
313
            } else {
314
                $this->id = $this->field['id'];
315
                $this->set('editedby', null)->touch();
316
            }
317
            unset($this->field['id']);
318
        }
319
        return $this;
320
    }
321
322
    public function save($fire_events = null, $clearCache = false)
323
    {
324
        $parent = null;
325
        if ($this->field['pagetitle'] == '') {
326
            $this->log['emptyPagetitle'] = 'Pagetitle is empty in <pre>' . print_r($this->field, true) . '</pre>';
327
            return false;
328
        }
329
330
        $this->set('alias', $this->getAlias());
331
332
        $this->invokeEvent('OnBeforeDocFormSave', array(
333
            'mode'  => $this->newDoc ? "new" : "upd",
334
            'id'    => $this->id ? $this->id : '',
335
            'doc'   => $this->toArray(),
336
            'docObj'=> $this
337
        ), $fire_events);
338
339
        $fld = $this->toArray(null, null, null, false);
340
        foreach ($this->default_field as $key => $value) {
341
            $tmp = $this->get($key);
342
            if ($this->newDoc && ( !is_int($tmp) && $tmp=='')) {
343
                if($tmp == $value){
344
                    switch ($key) {
345
                        case 'cacheable':
346
                            $value = $this->modxConfig('cache_default');
347
                            break;
348
                        case 'template':
349
                            $value = $value = $this->modxConfig('default_template');
350
                            break;
351
                        case 'published':
352
                            $value = $this->modxConfig('publish_default');
353
                            break;
354
                        case 'searchable':
355
                            $value = $this->modxConfig('search_default');
356
                            break;
357
                        case 'donthit':
358
                            $value = $this->modxConfig('track_visitors');
359
                            break;
360
                    }
361
                }
362
                $this->field[$key] = $value;
363
            }
364
            switch(true){
365
                case $key == 'parent':
366
                    $parent = (int)$this->get($key);
367
                    $q = $this->query("SELECT count(`id`) FROM {$this->makeTable('site_content')} WHERE `id`='{$parent}'");
368
                    if($this->modx->db->getValue($q)!=1){
369
                        $parent = $value;
370
                    }
371
                    $this->field[$key] = $parent;
372
                    $this->Uset($key);
373
                    break;
374
                case ($key == 'alias_visible' && !$this->checkVersion('1.0.10', true)):
375
                    $this->eraseField('alias_visible');
376
                    break;
377
                default:
378
                    $this->Uset($key);
379
            }
380
            unset($fld[$key]);
381
        }
382
383
        if (!empty($this->set)) {
384 View Code Duplication
            if ($this->newDoc) {
385
                $SQL = "INSERT into {$this->makeTable('site_content')} SET " . implode(', ', $this->set);
386
            } else {
387
                $SQL = "UPDATE {$this->makeTable('site_content')} SET " . implode(', ', $this->set) . " WHERE `id` = " . $this->id;
388
            }
389
            $this->query($SQL);
390
391
            if ($this->newDoc) {
392
                $this->id = $this->modx->db->getInsertId();
393
            }
394
395
            if ($parent > 0) {
396
                $this->query("UPDATE {$this->makeTable('site_content')} SET `isfolder`='1' WHERE `id`='{$parent}'");
397
            }
398
        }
399
400
        foreach ($fld as $key => $value) {
401
            if (empty($this->tv[$key])) continue;
402
            if ($value === '') {
403
                $this->query("DELETE FROM {$this->makeTable('site_tmplvar_contentvalues')} WHERE `contentid` = '{$this->id}' AND `tmplvarid` = '{$this->tv[$key]}'");
404
            } else {
405
                $value = $this->escape($value);
406
                $result = $this->query("SELECT `value` FROM {$this->makeTable('site_tmplvar_contentvalues')} WHERE `contentid` = '{$this->id}' AND `tmplvarid` = '{$this->tv[$key]}'");
407
                if ($this->modx->db->getRecordCount($result) > 0) {
408
                    $this->query("UPDATE {$this->makeTable('site_tmplvar_contentvalues')} SET `value` = '{$value}' WHERE `contentid` = '{$this->id}' AND `tmplvarid` = '{$this->tv[$key]}';");
409
                } else {
410
                    $this->query("INSERT into {$this->makeTable('site_tmplvar_contentvalues')} SET `contentid` = {$this->id},`tmplvarid` = {$this->tv[$key]},`value` = '{$value}';");
411
                }
412
            }
413
        }
414
        if (!isset($this->mode)) {
415
            $this->mode = $this->newDoc ? "new" : "upd";
416
            $this->newDoc = false;
417
        }
418
        $this->invokeEvent('OnDocFormSave', array(
419
            'mode'  => $this->mode,
420
            'id'    => $this->id,
421
            'doc'   => $this->toArray(),
422
            'docObj'=> $this
423
        ), $fire_events);
424
425
        if ($clearCache) {
426
            $this->clearCache($fire_events);
427
        }
428
        return $this->id;
429
    }
430
431
    public function toTrash($ids){
432
        $ignore = $this->systemID();
433
        $_ids = $this->cleanIDs($ids, ',', $ignore);
434
        if (is_array($_ids) && $_ids != array()) {
435
        	$id = $this->sanitarIn($_ids);
436
            $this->query("UPDATE {$this->makeTable('site_content')} SET `deleted`='1' WHERE `id` IN ({$id})");
437 View Code Duplication
		} else throw new Exception('Invalid IDs list for mark trash: <pre>' . print_r($ids, 1) . '</pre> please, check ignore list: <pre>' . print_r($ignore, 1) . '</pre>');
438
        return $this;
439
    }
440
    public function clearTrash($fire_events = null){
441
        $q = $this->query("SELECT `id` FROM {$this->makeTable('site_content')} WHERE `deleted`='1'");
442
        $q = $this->modx->makeArray($q);
443
        $_ids = array();
444
        foreach($q as $item){
445
              $_ids[] = $item['id'];
446
        }
447
        if (is_array($_ids) && $_ids != array()) {
448
            $this->invokeEvent('OnBeforeEmptyTrash', array(
449
                "ids" => $_ids
450
            ), $fire_events);
451
452
            $id = $this->sanitarIn($_ids);
453
            $this->query("DELETE from {$this->makeTable('site_content')} where `id` IN ({$id})");
454
            $this->query("DELETE from {$this->makeTable('site_tmplvar_contentvalues')} where `contentid` IN ({$id})");
455
456
            $this->invokeEvent('OnEmptyTrash', array(
457
                "ids" => $_ids
458
            ), $fire_events);
459
        }
460
        return $this;
461
    }
462
463
    public function childrens($ids, $depth = 0)
464
    {
465
        $_ids = $this->cleanIDs($ids, ',');
466
        if (is_array($_ids) && $_ids != array()) {
467
            $id = $this->sanitarIn($_ids);
468
            if(!empty($id)) {
469
                $q = $this->query("SELECT `id` FROM {$this->makeTable('site_content')} where `parent` IN ({$id})");
470
                $id = $this->modx->db->getColumn('id', $q);
471
                if($depth > 0 || (is_bool($depth) && $depth == true)){
472
                    $id = $this->childrens($id, is_bool($depth) ? $depth : ($depth - 1));
0 ignored issues
show
Bug introduced by
It seems like is_bool($depth) ? $depth : $depth - 1 can also be of type boolean; however, modResource::childrens() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
473
                }
474
                $_ids = array_merge($_ids, $id);
475
            }
476
        }
477
        return $_ids;
478
    }
479
480
    public function delete($ids, $fire_events = null)
481
    {
482
        $ids = $this->childrens($ids, true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
483
        $_ids = $this->cleanIDs($ids, ',', $this->systemID());
484
        if (is_array($_ids) && $_ids != array()) {
485
        	$this->invokeEvent('OnBeforeEmptyTrash', array(
486
            	"ids" => $_ids
487
			), $fire_events);
488
489
			$id = $this->sanitarIn($_ids);
490
			if(!empty($id)){
491
				$this->query("DELETE from {$this->makeTable('site_content')} where `id` IN ({$id})");
492
				$this->query("DELETE from {$this->makeTable('site_tmplvar_contentvalues')} where `contentid` IN ({$id})");
493
				$this->invokeEvent('OnEmptyTrash', array(
494
					"ids" => $_ids
495
				), $fire_events);
496
			}
497 View Code Duplication
		} else throw new Exception('Invalid IDs list for delete: <pre>' . print_r($ids, 1) . '</pre> please, check ignore list: <pre>' . print_r($ignore, 1) . '</pre>');
498
499
        return $this;
500
    }
501
502
    private function systemID()
503
    {
504
        $ignore = array(
505
            0, //empty document
506
            (int)$this->modxConfig('site_start'),
507
            (int)$this->modxConfig('error_page'),
508
            (int)$this->modxConfig('unauthorized_page'),
509
            (int)$this->modxConfig('site_unavailable_page')
510
        );
511
        $data = $this->query("SELECT DISTINCT setting_value FROM {$this->makeTable('web_user_settings')} WHERE `setting_name`='login_home' AND `setting_value`!=''");
512
        $data = $this->modx->db->makeArray($data);
513
        foreach ($data as $item) {
514
            $ignore[] = (int)$item['setting_value'];
515
        }
516
        return array_unique($ignore);
517
518
    }
519
520
    private function checkAlias($alias)
521
    {
522
        $alias = strtolower($alias);
523
        if ($this->modxConfig('friendly_urls')) {
524
            $_alias = $this->escape($alias);
525
            if ((!$this->modxConfig('allow_duplicate_alias') && !$this->modxConfig('use_alias_path')) || ($this->modxConfig('allow_duplicate_alias') && $this->modxConfig('use_alias_path'))) {
526
                $flag = $this->modx->db->getValue($this->query("SELECT `id` FROM {$this->makeTable('site_content')} WHERE `alias`='{$_alias}' AND `parent`={$this->get('parent')} LIMIT 1"));
527
            } else {
528
                $flag = $this->modx->db->getValue($this->query("SELECT `id` FROM {$this->makeTable('site_content')} WHERE `alias`='{$_alias}' LIMIT 1"));
529
            }
530
            if (($flag && $this->newDoc) || (!$this->newDoc && $flag && $this->id != $flag)) {
531
                $suffix = substr($alias, -2);
532
                if (preg_match('/-(\d+)/', $suffix, $tmp) && isset($tmp[1]) && (int)$tmp[1] > 1) {
533
                    $suffix = (int)$tmp[1] + 1;
534
                    $alias = substr($alias, 0, -2) . '-' . $suffix;
535
                } else {
536
                    $alias .= '-2';
537
                }
538
                $alias = $this->checkAlias($alias);
539
            }
540
        }
541
        return $alias;
542
    }
543
544
    public function issetField($key)
545
    {
546
        return (array_key_exists($key, $this->default_field) || array_key_exists($key, $this->tv));
547
    }
548
549
    protected function get_TV($reload = false)
550
    {
551
        if (empty($this->modx->_TVnames) || $reload) {
552
            $result = $this->query('SELECT `id`,`name` FROM ' . $this->makeTable('site_tmplvars'));
553
            while ($row = $this->modx->db->GetRow($result)) {
554
                $this->modx->_TVnames[$row['name']] = $row['id'];
555
            }
556
        }
557
        foreach($this->modx->_TVnames as $name => $id){
558
            $this->tvid[$id] = $name;
559
            $this->tv[$name] = $id;
560
        }
561
        $this->loadTVTemplate()->loadTVDefault(array_values($this->tv));
562
        return $this;
563
    }
564
    protected function loadTVTemplate(){
565
        $q = $this->query("SELECT `tmplvarid`, `templateid` FROM ".$this->makeTable('site_tmplvar_templates'));
566
        $q = $this->modx->db->makeArray($q);
567
        $this->tvTpl = array();
568
        foreach($q as $item){
569
            $this->tvTpl[$item['templateid']][] = $item['tmplvarid'];
570
        }
571
        return $this;
572
    }
573
    protected function loadTVDefault(array $tvId = array())
574
    {
575
        if(is_array($tvId) && !empty($tvId)){
576
            $tbl_site_tmplvars = $this->makeTable('site_tmplvars');
577
            $fields = 'id,name,default_text as value,display,display_params,type';
578
            $implodeTvId = implode(',', $tvId);
579
            $rs = $this->query("SELECT {$fields} FROM {$tbl_site_tmplvars} WHERE id IN({$implodeTvId})");
580
            $rows = $this->modx->db->makeArray($rs);
581
            $this->tvd = array();
582
            foreach ($rows as $item) {
583
                $this->tvd[$item['name']] = $item;
584
            }
585
        }
586
        return $this;
587
    }
588
    public function setTemplate($tpl)
589
    {
590
        if (!is_numeric($tpl) || $tpl != (int)$tpl) {
591
            if (is_scalar($tpl)) {
592
            	$sql = "SELECT `id` FROM {$this->makeTable('site_templates')} WHERE `templatename` = '".$this->escape($tpl)."'";
593
				$rs = $this->query($sql);
594
				if (!$rs || $this->modx->db->getRecordCount($rs) <= 0) throw new Exception("Template {$tpl} is not exists");
595
				$tpl = $this->modx->db->getValue($rs);
596
			} else {
597
				throw new Exception("Invalid template name: " . print_r($tpl, 1));
598
			}
599
        }
600
        return (int)$tpl;
601
    }
602
603
    private function getAlias()
604
    {
605
        if ($this->modxConfig('friendly_urls') && $this->modxConfig('automatic_alias') && $this->get('alias') == '') {
606
            $alias = strtr($this->get('pagetitle'), $this->table);
607
        } else {
608
            if ($this->get('alias') != '') {
609
                $alias = $this->get('alias');
610
            } else {
611
                $alias = '';
612
            }
613
        }
614
        $alias = $this->modx->stripAlias($alias);
615
        return $this->checkAlias($alias);
616
    }
617
}
618