Skip to content

Instantly share code, notes, and snippets.

@ig0r74 ig0r74/packages.php forked from govza/settings.php
Last active May 29, 2018

Embed
What would you like to do?
Быстрая настройка MODX
<?php
/*
Скрипт надо запускать от юзера - владельца сайта, чтобы созданные файлы пакетов не принадлежали юзеру root
$ sudo -u USERNAME php /var/www/USERNAME/packages.php /var/www/USERNAME/www/
Или от root, а после выставить владельца:
$ php /root/scripts/modx/packages.php /var/www/USERNAME/www/ && /var/www/USERNAME/chmod
Чтобы запустить из веба, просто положите скрипт в корень или куда-нибудь глубже и вызовите по HTTP
*/
// >> Список репозиториев с компонентами для установки
$providers = array(
array(
'name' => 'modx.com',
'service_url' => 'http://rest.modx.com/extras/',
'username' => '',
'api_key' => '',
'packages' => array(
'formit',
'translit',
'TinyMCE Rich Text Editor',
'ClientConfig',
//'pThumb',
//'MIGX',
//'console',
),
),
array(
'name' => 'Modstore',
'service_url' => 'https://modstore.pro/extras/',
'username' => '',
'api_key' => '',
'packages' => array(
'ace',
'pdotools',
'AjaxForm',
//'minifyx',
//'theme.bootstrap',
//'minishop2',
),
),
);
// << Список репозиториев с компонентами для установки
$countInstalled = 0;
$console = !empty($argv) ? true : false; // Узнаём из консоли запустили или из веба
if( $console )
{
if( !empty($argv[1]) && file_exists( $argv[1] .'index.php' ) )
{
$current_dir = $argv[1];
}
}
// >> Подключаем
define('MODX_API_MODE', true);
$current_dir = !empty($current_dir) ? $current_dir : dirname(__FILE__) .'/';
$index_php = $current_dir .'index.php';
$i=0;
while( !file_exists( $index_php ) && $i < 9 )
{
$current_dir = dirname(dirname($index_php)) .'/';
$index_php = $current_dir .'index.php';
$i++;
}
if( file_exists($index_php) )
{
require_once $index_php;
}
if( !is_object($modx) )
{
_print('ERROR: Не удалось подгрузить MODX');
die;
}
// << Подключаем
// >> Включаем обработку ошибок
$modx->getService('error','error.modError');
$modx->setLogLevel(modX::LOG_LEVEL_ERROR);
$modx->setLogTarget(XPDO_CLI_MODE ? 'ECHO' : 'HTML');
// << Включаем обработку ошибок
$modx->switchContext('mgr');
$modx->addPackage('modx.transport', MODX_CORE_PATH .'model/');
$modx->getVersionData();
$productVersion = $modx->version['code_name'] .'-'. $modx->version['full_version'];
foreach( $providers as $prov )
{
if( !$provider = $modx->getObject('transport.modTransportProvider', array('service_url' => $prov['service_url']) ) )
{
$provider = $modx->newObject('transport.modTransportProvider');
$provider->fromArray($prov);
$provider->save();
}
$provider->getClient();
foreach( $prov['packages'] as $packageName )
{
$response = $provider->request('package', 'GET',
array(
'query' => $packageName
));
if( !empty($response) )
{
$foundPackages = simplexml_load_string($response->response);
if( $foundPackages['total'] > 0 )
{
foreach( $foundPackages as $foundPackage )
{
if( strtolower((string)$foundPackage->name) == strtolower($packageName) )
{
if( !$modx->getCount('transport.modTransportPackage', array('signature' => (string)$foundPackage->signature)) )
{
$sig = explode('-', $foundPackage->signature);
$versionSignature = explode('.', $sig[1]);
file_put_contents( MODX_CORE_PATH .'packages/'. $foundPackage->signature .'.transport.zip', file_get_contents($foundPackage->location) );
$package = $modx->newObject('transport.modTransportPackage');
$package->set('signature', $foundPackage->signature);
$package->fromArray(
array(
'created' => date('Y-m-d h:i:s'),
'updated' => null,
'state' => 1,
'workspace' => 1,
'provider' => $provider->id,
'source' => $foundPackage->signature .'.transport.zip',
'package_name' => (string)$foundPackage->name,
'version_major' => $versionSignature[0],
'version_minor' => !empty($versionSignature[1]) ? $versionSignature[1] : 0,
'version_patch' => !empty($versionSignature[2]) ? $versionSignature[2] : 0,
));
if( !empty($sig[2]) )
{
$r = preg_split('/([0-9]+)/', $sig[2], -1, PREG_SPLIT_DELIM_CAPTURE);
if( is_array($r) && !empty($r) )
{
$package->set('release', $r[0]);
$package->set('release_index', (isset($r[1]) ? $r[1] : '0'));
}
else {
$package->set('release', $sig[2]);
}
if( $success = $package->save() )
{
$package->install();
_print('Installed: "'. (string)$foundPackage->name .'"');
$countInstalled++;
}
else {
_print('Could not save: "'. (string)$foundPackage->name .'"');
}
}
}
else {
_print('Already exists: "'. (string)$foundPackage->name .'"');
}
}
}
}
else {
_print('Not found: "'. $packageName .'"');
}
}
}
}
if( $countInstalled > 0 )
{
_print('Done!', 0);
}
/* >> Функция принта для консоли и веба */
function _print( $str='', $br=true )
{
global $console;
if( empty($str) ) {return;}
if( $console )
{
fwrite(STDOUT, $str . ($br ? "\n" : ""));
}
else {
print $str . ($br ? "<br />" : "");
}
}
/* << */
exit;
<?php
require_once dirname(__FILE__).'/config.core.php';
include_once MODX_CORE_PATH . 'model/modx/modx.class.php';
$modx= new modX();
$modx->initialize('mgr');
$modx->setLogLevel(modX::LOG_LEVEL_INFO);
$modx->setLogTarget(XPDO_CLI_MODE ? 'ECHO' : 'HTML');
header("Content-type: text/plain");
// Settings
$settings = array(
'cultureKey' => 'ru'
, 'fe_editor_lang' => 'ru'
, 'publish_default' => 1
, 'tvs_below_content' => 1
, 'upload_maxsize' => '10485760'
, 'manager_lang_attribute' => 'ru'
, 'manager_language' => 'ru'
, 'editor_css_path' => '/tpl/css/styles.css'
, 'send_poweredby_header' => 0
, 'resource_tree_node_name' => 'menutitle'
//url
, 'automatic_alias' => 1
, 'friendly_urls' => 1
, 'use_alias_path' => 1
, 'container_suffix' => '/'
, 'friendly_alias_translit' => 'russian'
, 'friendly_alias_restrict_chars' => 'alphanumeric'
//mail
, 'mail_smtp_auth' => 1
, 'mail_smtp_port' => 465
, 'mail_smtp_prefix' => 'ssl'
, 'mail_smtp_hosts' => 'smtp.yandex.ru'
/*after packages install */
, 'pdotools_fenom_parser' => 1
//, 'tinymcerte.valid_elements' => 'img[src|class|id|alt]'
//, 'typo.css_selectors' => 'Таблица=site_table;Подзаголовок табл=subth;'
//, 'typo.custom_buttons1' => 'undo,redo,selectall,separator,pastetext,pasteword,separator,search,replace,separator,image,modxlink,unlink,anchor,media,separator,cleanup,removeformat,separator,fontselect,fontsizeselect,separator,forecolor,backcolor'
//, 'typo.custom_buttons2' => 'bold,italic,underline,strikethrough,sub,sup,separator,bullist,numlist,outdent,indent,blockquote,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,styleselect,formatselect,separator,styleprops'
//, 'typo.custom_buttons3' => 'tablecontrols,separator,visualaid,nonbreaking,hr,charmap,separator,fullscreen,print,code,help'
//, 'typo.custom_plugins' => 'style,advimage,advlink,modxlink,searchreplace,print,contextmenu,paste,fullscreen,noneditable,nonbreaking,xhtmlxtras,visualchars,media,table'
//, 'typo.skin' => 'default'
);
foreach ($settings as $k => $v) {
$opt = $modx->getObject('modSystemSetting', array('key' => $k));
if (!empty($opt)){
$opt->set('value', $v);
$opt->save();
echo 'edited '.$k.' = '.$v."\n";
} else {
$newOpt = $modx->newObject('modSystemSetting');
$newOpt->set('key', $k);
$newOpt->set('value', $v);
$newOpt->save();
echo 'added '.$k.' = '.$v."\n";
}
}
// Resources
$resources = array(
array('pagetitle' => 'О компании',
'template' => 1,
'published' => 1,
'hidemenu' => 0,
'alias' => 'about',
'content_type' => 1,
'richtext' => 1,
'content' => 'Информация о компании'
)
, array('pagetitle' => 'Контакты',
'template' => 1,
'published' => 1,
'hidemenu' => 0,
'alias' => 'contacts',
'content_type' => 1,
'richtext' => 1,
'content' => '<table border="0" cellpadding="5"><tbody><tr><td><strong>Тел.: </strong></td><td>+7 </td></tr><tr><td><strong>Email: </strong></td><td></td></tr></tbody></table>'
)
, array('pagetitle' => 'sitemap',
'template' => 0,
'published' => 1,
'hidemenu' => 1,
'alias' => 'sitemap'
,'content_type' => 2,
'richtext' => 0,
'searchable' => 0,
'content' =>'[[pdoSitemap?
&showHidden=`1`
]]'
)
, array('pagetitle' => 'robots',
'template' => 0,
'published' => 1,
'hidemenu' => 1,
'alias' => 'robots',
'content_type' => 3,
'richtext' => 0,
'searchable' => 0,
'content' => 'User-agent: *
Disallow: /manager/
Disallow: /assets/components/
Allow: /assets/uploads/
Disallow: /core/
Disallow: /connectors/
Disallow: /index.php
Disallow: /search
Disallow: /profile/
Disallow: *?
Host: [[++site_url]]
Sitemap: [[++site_url]]sitemap.xml'
)
);
foreach ($resources as $attr) {
// $modx->error->reset();
$response = $modx->runProcessor('resource/create', $attr);
}
// chunks
$chunks = array(
array('name' => 'childs',
'description' => '',
'snippet' => '<div class="childs">[[pdoMenu? &parents=`[[*id]]` &level=`1`]]</div>'
)
, array('name' => 'contactEmailTpl',
'description' => '',
'snippet' => '<b>ФИО</b>: [[+name]]<br>
<b>E-mail</b>: [[+email]]<br>
<b>Сообщение</b>:<br> [[+message]]<br>'
)
, array('name' => 'contactFormTpl',
'description' => '',
'snippet' => '<form action="" method="post" class="ajax_form">
<input type="text" class="form-control" placeholder="Lnk" id="af_link" name="link" value="[[+fi.link]]">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="Имя" id="af_name" name="name" value="[[+fi.name]]">
<span class="error_name">[[+fi.error.name]]</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="Email" id="af_email" name="email" value="[[+fi.email]]">
<span class="error_email">[[+fi.error.email]]</span>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea id="af_message" name="message" class="form-control" id="" cols="30" rows="7" placeholder="Сообщение">[[+fi.message]]</textarea>
<span class="error_message">[[+fi.error.message]]</span>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="submit" name="contact" value="Отправить Сообщение" class="btn btn-primary">
</div>
</div>
</div>
[[+fi.success:is=`1`:then=`
<div class="alert alert-success">[[+fi.successMessage]]</div>
`]]
[[+fi.validation_error:is=`1`:then=`
<div class="alert alert-danger">[[+fi.validation_error_message]]</div>
`]]
</form>'
)
, array('name' => 'pdoResources.tpl',
'description' => '',
'snippet' => '<div class="media">
<div class="pull-left">
<a class="thumbnail" href="{$uri}">
<img class="media-object" src="{$_modx->runSnippet("pthumb", [ \'input\' => $_pls[\'tv.img\'] ?: \'tpl/upload/imgtmp01.jpg\', \'options\' => \'w=90&h=90&zc=1&q=90\', \'useResizer\' => 1, ])}" alt="txt">
</a>
</div>
<div class="media-body">
<h4 class="media-heading"><a href="{$uri}">{$pagetitle}</a></h4>
{$introtext}
</div>
</div>'
)
);
foreach ($chunks as $attr) {
// $modx->error->reset();
$response = $modx->runProcessor('element/chunk/create', $attr);
}
// $modx->error->reset();
$crttv = $modx->runProcessor('element/tv/create', array(
'name' => 'childstv',
'caption' => 'Выводить списком',
'type' => 'checkbox',
'els' => 'Да==@CHUNK childs'
));
$crttpl = $modx->runProcessor('element/template/create', array(
'templatename' => 'Главная',
'description' => '',
'icon' => 'icon icon-home',
'content' => ' {extends \'template:1\'}
<title>{$_modx->resource.longtitle ?: $_modx->resource.pagetitle} | {$_modx->config.site_name}</title>
<meta name="description" content="{$_modx->resource.description}" />
<base href="{$_modx->config.site_url}">
<a href="{$_modx->config.site_url}"><img src="tpl/i/logo.png" alt="{$_modx->config.site_name}" id="logo"></a>
<address>{$_modx->config.address}</address>
<div id="topphone">{$_modx->config.phone}</div>
<!-- МЕНЮ -->
{$_modx->runSnippet(\'pdoMenu\', [
\'parents\' => 0,
\'level\' => 1,
\'outerClass\' => \'nav navbar-nav\',
])}
<h1>{$_modx->resource.pagetitle}</h1>
{$_modx->resource.content}
{$_modx->resource.childstv}
<!-- MIGX с ограничением кол-ва результатов -->
{set $rows = json_decode($_modx->resource.home_blocks, true)}
{set $i = 0}
{foreach $rows as $row}
{foreach json_decode($_modx->resource.home_blocks, true) as $row} {* Или сразу так *}
<a href="{$row.link}" class="sidebartopic">
<img src="{$_modx->runSnippet("pthumb", [ \'input\' => $row.image, \'options\' => \'w=350&h=180&zc=1&q=90\', \'useResizer\' => 1, ])}" alt="{$row.title}">
<span>{$row.title}</span>
</a>
{if ++$i == 3} {break} {/if}
{/foreach}
<!-- AjaxForm -->
{\'!AjaxForm\' | snippet : [
\'snippet\' => \'FormIt\',
\'form\' => \'contactFormTpl\',
\'emailTpl\' => \'contactEmailTpl\',
\'hooks\' => \'email\',
\'emailFrom\' => $_modx->config.emailsender,
\'emailFromName\' => $_modx->config.site_name,
\'emailSubject\' => \'Сообщение с сайта \' ~ $_modx->config.site_name,
\'emailTo\' => $_modx->config.emailsender,
\'validate\' => \'email:required,link:blank\',
\'validationErrorMessage\' => \'В форме содержатся ошибки!\',
\'successMessage\' => \'Сообщение успешно отправлено\',
]}'
));
// $modx->cacheManager->refresh();
$modx->runProcessor('system/clearcache');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.