install proxmox in new server\vps

Load RESCUE

(load last version)

connect server+proxy port

ssh -L 8888:127.0.0.1:5901 root@IP.SE.RV.ER

wget http://download.proxmox.com/iso/proxmox-ve_8.2-1.iso

lsblk
(replace nvme0n1 nvme0n0 on your disk)

qemu-system-x86_64 -smp 4 -m 4096 -boot d -cdrom ./proxmox-ve_8.2-1.iso -drive file=/dev/nvme1n1,format=raw,media=disk -drive file=/dev/nvme0n1,format=raw,media=disk -vnc 127.0.0.1:1

connect from vnc 127.0.0.1:8888
install server
shutdown

disconect qemu-system-x86_64
connect without cd

qemu-system-x86_64 -smp 4 -m 4096 -boot d file=/dev/nvme1n1,format=raw,media=disk -drive file=/dev/nvme0n1,format=raw,media=disk -vnc 127.0.0.1:1

change networck
nano /etc/network/inetrface

proxmox setup network

proxmox backup add CIFS

create an access file

nano /etc/samba/credentials

username=****
password=****

ctrl+s
ctrl+x
chmod 600 /etc/samba/credentials

mount the disk

mount.cifs -o cache=none,credentials=/etc/samba/credentials,noperm,vers=3.0,gid=1000,iocharset=utf8,sec=ntlmssp,file_mode=0770,dir_mode=0770 //****.your-storagebox.de/backup /mnt/pve/****.your-storagebox.de

proxmox-backup-manager datastore create CIFS_REPO /mnt/pve/****.your-storagebox.de/synctumbackup --comment 'Backups directory via cifs'


nano /etc/network/interfaces
add mount

auto ens18
iface ens18 inet static
	address 10.5.0.250/24
	gateway 10.5.0.1

	post-up mount.cifs -o cache=none,credentials=/etc/samba/credentials,noperm,vers=3.0,gid=1000,iocharset=utf8,sec=ntlmssp,file_mode=0770,dir_mode=0770 //u411724.your-storagebox.de/backup /mnt/pve/u411724.your-storagebox.de

proxmox setup network

ip route
default via 116.***.***.129 dev eth0
116.***.***.128/26 via 116.***.***.129 dev eth0
116.***.***.129 dev eth0 scope link

# get corectly name
ip link show
cat /etc/network/interfaces
# network interface settings; autogenerated
# Please do NOT modify this file directly, unless you know what
# you're doing.
#
# If you want to manage parts of the network configuration manually,
# please utilize the 'source' or 'source-directory' directives to do
# so.
# PVE will preserve these directives, but will NOT read its network
# configuration from sourced files, so do not attempt to move any of
# the PVE managed interfaces into external files!

auto lo
iface lo inet loopback

auto enp0s31f6
iface enp0s31f6 inet static
address 116.***.***.149/26
gateway 116.***.***.129
dns-nameservers 1.1.1.1 8.8.8.8
post-up iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o enp0s31f6 -j MASQUERADE

auto vmbr0
iface vmbr0 inet static
address 10.0.0.1/24
bridge-ports none
bridge-stp off
bridge-fd 0
bridge-vlan-aware yes
bridge-vids 2-4094

source /etc/network/interfaces.d/*

auto snapshot

apt install zfs-auto-snapshot

Drupal 8 commerce2 add custom field checkout


https://www.drupal.org/project/commerce_checkout_order_fields. Just enable it, go to /admin/commerce/config/order-types/default/edit/form-display, scroll down, enable 'Checkout' view, drag/drop fields on the Checkout view, and then go to /admin/commerce/config/checkout-flows/manage/default and add 'Order Fields: Checkout' pane to a step you want. Enjoy

Некие команды для ./occ

Выполнять от юзера www-data

docker exec -it -u 82 dockername /bin/sh

./occ upgrade - обновляет базу

./occ files:scan --all

./occ files:scan grenuy
./occ files:scan --path "grenuy/files/Share uWorld"
sudo -u www-data php occ files:scan --help
  Usage:
  files:scan [-p|--path="..."] [-q|--quiet] [-v|vv|vvv --verbose] [--all]
  [user_id1] ... [user_idN]

Arguments:
  user_id               will rescan all files of the given user(s)

Options:
  --path                limit rescan to the user/path given
  --all                 will rescan all files of all known users
  --quiet               suppress any output
  --verbose             files and directories being processed are shown
                        additionally during scanning
  --unscanned           scan only previously unscanned files

Index column size too large. The maximum column size is 767 bytes.

Проблема много где описана, но решается на уровне рута и настройки базы данных

mysql

set global innodb_file_format = BARRACUDA;

set global innodb_large_prefix = ON;

SET GLOBAL innodb_default_row_format = DYNAMIC;

mount USB media in wls(windows linux)

Good news, it is now possible to mount USB media (including FAT formated) and network shares with drvfs on Windows 10:

Mount removable media: (e.g. D:)

$ sudo mkdir /mnt/d
$ sudo mount -t drvfs D: /mnt/d

To safely unmount

$ sudo umount /mnt/d

You can also mount network shares without smbfs:

$ sudo mount -t drvfs '\\server\share' /mnt/share

You need at least Build 16176 so you might have to opt-in to the Windows Insider programm and then update Windows. Source: https://blogs.msdn.microsoft.com/wsl/2017/04/18/file-system-improvements-to-the-windows-subsystem-for-linux/

Новые бэкапы ISPtar в ISPmanager

Компания ISPsystem в панелях ISPmanager начиная с версии 5.51 выпустила новую версию бэкапов.
Называются ISPtar.
Сюда буду писать интересные фичи и ошибки.

Бэкап обного пользователя

ISPmanager 5 Lite
sbin/backup2 имя_пользователя

ISPmanager 5 Business
sbin/backup2_pro имя_пользователя

Если бэкап за сегодня есть а потестить надо, то указываем фэйковую дату:
bin/backup2_pro    user  --date 2016-04-01

Ошибка:
backup ERROR isptar finished with error 1. Output: No header found
Проблема в бинарнике ISPtar? бэкапим старый, ставим новый:
Можно командой
Centos 6 Centos 7
Debinan 7 Debian 8
wget -O /usr/local/mgr5/sbin/isptar http://sis-admin.su/wp-content/uploads/2016/01/ваша_версия_tar

Распаковка бэкапов вручную

Переходим в папку с бэкапом:

/usr/local/mgr5/sbin/isptar -x F2016-10-18.user.tgz data/www/dipris.ru/ -R /var/www/user/site.ru

Где

F2016-10-18.user.tgz — название бэкапа, берётся из файла F2016-10-18.user.tgz.part1 Такого файла нет.

data/www/dipris.ru/ — Файлы какого сайта необходимо восстановить

/var/www/user/site.ru — Куда восстановить данные

Базы лежат в папке .system/

Пример распаковки базы base:

/usr/local/mgr5/sbin/isptar -x F2016-10-18.user.tgz .system/db.mysql.base -R /var/www/user/site.ru

Полная документация разработчика

Удаление 5 миллионов файлов

Обычно предлагается удалять через find и рабочий вариант, но в моем случаи 1.5млн удаляло часов 10 что недопустимо долго так перебирать пошел другим путем через цыклы и маски

for i in {a..z}
  do 
	rm /var/www/*/data/www/*/system/sessions/sess_$i[a-c]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[d-g]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[h-k]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[l-n]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[p-r]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[s-v]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[w-y]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[y-z]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[0-2]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[3-5]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[6-8]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[8-9]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i*
 done



 for i in {0..9}
  do 
	rm /var/www/*/data/www/*/system/sessions/sess_$i[a-c]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[d-g]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[h-k]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[l-n]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[p-r]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[s-v]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[w-y]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[y-z]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[0-2]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[3-5]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[6-8]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i[8-9]*
	rm /var/www/*/data/www/*/system/sessions/sess_$i*
 done

Или удалить файлы, которые старше семи дней:

for f in /tmp/logs/*.log
do
  find $f -mtime +7 -exec rm {} \;
done

Удаление заняло несколько минут времени.

Windows 10 subsystem ubuntu apache2 + mysql

sudo su

apt update

apt install apache2 mysql

nano /etc/apache2/sites-available/sites.loc.conf

# Place any notes or comments you have here
# It will make any customisation easier to understand in the weeks to come

# domain: domain1.com
# public: /home/demo/public_html/domain1.com/

<VirtualHost *:80>

  # Admin email, Server Name (domain name) and any aliases
  ServerAdmin webmaster@domain1.com
  ServerName  sites.loc
  ServerAlias www.sites.loc


  # Index file and Document Root (where the public files are located)
  DirectoryIndex index.php
  DocumentRoot /mnt/c/work/website/sites.loc/html


  # Custom log file locations
  LogLevel warn
  ErrorLog /var/log/apache2/error-mydomainname.com.log
  CustomLog /var/log/apache2/access-mydomainname.com.log combined

</VirtualHost>

add in

nano /etc/apache2/apache2.conf

<Directory /mnt/c/work/website/*>                                                                                                      Options Indexes FollowSymLinks MultiViews                                                                               AllowOverride All                                                                                                       Order allow,deny                                                                                                        allow from all                                                                                                          Require all granted                                                                                              </Directory>   

a2ensite sites.loc

service apache2 restart

add in c:\Windows\System32\drivers\etc\hosts

127.0.0.1 cprice.loc

a2enmod rewrite

service apache2 restart

Find the php.ini on your server. In wamp you click on the toolbar icon -> select PHP -> select php.ini

Push ctrl+ f and find "realpath_cache_size" . Remove the semi-colon at the beginning of the line and make it =16M instead of 16k .

This all

Что бы скачать с googledrive любые по размеру файлы без вопросов нужно подменить FILEID

wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=FILEID' -O- | sed -rn 's/.confirm=([0-9A-Za-z_]+)./\1\n/p')&id=FILEID" -O FILENAME && rm -rf /tmp/cookies.txt

Commit in arhive

На одном из проектов нужно было давать архив всех измененых файлов с каталогами. Причем именно архив. Первая мысль git но блин на сервере у клиента нельзя установить гит, а его админ доступов не дает, и только архив с изменениями хочет. Нашел выход достаточно простой который решил мои проблемы

git diff-tree -r --no-commit-id --name-only --diff-filter=ACMRT idCommit | tar -czf file.tgz -T -

idCommit - наш индификатор коммита

Установка Drupal через drush

Установить друпал можно через командную строку в одну строку!!!! Ну если быть точнее через две.

#Первая строка скачивает drupal
drush dl drupal

#установка друпалла
drush site-install standard --account-name=LoginAdmin --account-pass=passwordAdmin --db-url=mysql://UserDB:PasswordDB@localhost/NameDB

Больше команд можно почитать здесь

Попытка получить тиц 10

Первый шаг, попытаюсь зарегаться на сайте dir.ikernel.org, они очень просили опубликовать обратную ссылку, вот и опубликую здесь 🙂

Глобальный каталог сайтов

Drush worck shop

1. Установка друпал

#скачать ядро
drush dl drupal-7

#перенести файлы в корень
mv drupal-7.x-dev/{.,*}* .
#удалить пустую папку
rm -r drupal-7.x-dev/

#фикс прав
find * -type d -exec chmod 755 {} \;
find * -type f -exec chmod 644 {} \;

#установка друпалла
drush site-install standard --account-name=LoginAdmin --account-pass=passwordAdmin --db-url=mysql://UserDB:PasswordDB@localhost/NameDB

#отключаем 2 лишние модули
drush dis dashboard overlay shortcut toolbar

#качаем и включаем нужные моддули (можно сначала скачать через dl)

#пример с зависимостями
drush en views webform module_filter

#установка выбраной версии
drush dl og-1.3 # shortcut for pm-download
drush -y en og # shortcut for pm-enable

# отключаем с зависимостями (можно глянуть на модуль i18n)
drush dis ctools

#устанавливаем набор модулей к примеру

drush en admin_menu admin_menu_toolbar l10n_update module_filter page_manager views_content ctools_custom_content ctools views views_ui transliteration token pathauto rules rules_admin entity devel basic wysiwyg wysiwyg_filter lightbox2 plupload libraries filefield_sources filefield_sources_plupload ocupload views_bulk_operations admin_views i18n

-- добавляем языка включения отключения и тёдё
drush language-add ru de

drush language-disable de ru

drush language-enable ru

drush language-default ru

#подкачка языка
drush l10n-update-status
drush l10n-update-refresh
drush l10n-update --languages=ru

другие команды
drush core-cron
drush up
drush ccй

drush ard — создание бэкапа сайта. Делает бэкап как самого сайта, так и базы данных, все это сохраняется в tar.gz архиве. Невероятно удобная вещь.
drush arr path — восстановление бекапа созданного командой drush ard. Заместо path нужно

#пробежаться и обновит все

for i in /home/www/grenuy/data/www/*/sites/.. ; do cd "$i"; drush updb; drush en update; yes | drush pm-update

DRUSH

drush up — обновление ядра и модулей Drupal.
drush cc all — очистка всего кеша сайта.
drush pm-list — список всех модулей и тем установленных на сайте, а также их версии и статус активности.
drush dl module — загружает модуль или тему. Несколько значений пишится через пробел.
drush en module — включает указанный модуль или тему.
drush dis module — выключает указанный модуль или тему.
drush ard — создание бэкапа сайта. Делает бэкап как самого сайта, так и базы данных, все это сохраняется в tar.gz архиве. Невероятно удобная вещь.
drush arr path — восстановление бекапа созданного командой drush ard. Заместо path нужно указать путь до архива, включая его название и расширение.

Установка drupall

drush dl drupal-7.x
drush site-install standard --account-name=admin --account-pass=admin --db-url=mysql://YourMySQLUser:RandomPassword@localhost/YourMySQLDatabase

Розпаковка архива на другой сервер
drush arr nivea.20150415_200549.tar.gz --db-url=mysql://root@localhost:3306/nivea

drush uli - получить разовую ссылку на вход для админа
drush upwd admin --password="newpassword" - сбросить пароль для пользователя

cinst chocolatey.org apt-get для Windows

Не так давно открыл для себя прелестную возможность у Windows того что очень не хватало, и одно из того чем очень сильно привлекает linux, это установка приложений из командной строки а так же обновления всех приложений одной командой
Очень клево будте для различных админов или "настройщиков" Windows
можно установить 90% всех необходимых программ(а то и все 100%) просто выполнив в cmd
cinst flashplayerplugin flashplayeractivex notepadplusplus sublimetext2 7zip GoogleChrome javaruntime Firefox flashplayerplugin adobereader ccleaner sysinternals putty filezilla dropbox skype paint.net virtualbox DotNet4.5 Wget ConEmu libreoffice PDFCreator teamviewer wuinstall.run
Все происходит с помощью "тихой установки" не задавая лишних вопросов и что важно не устанавливая лишние программы )
Что бы работала такая установка всего то нужно выполнить в командной строке

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin

Возможные пакеты можно глянуть на сайте
chocolatey.org

Массовое применение patch drupal 7.32

Для того что применить к всем пользователям патч нужно создать файл на сервере (к примеру в корне) с именем к примеру
pathc.patch. Текст в файле, в нашем случаи можно взять, здесь https://www.drupal.org/files/issues/SA-CORE-2014-005-D7.patch

И зайдя через SSH выполнить команду

for i in /home/www/*/data/www/* ; do cd "$i"; echo "$i"; patch -p1 < /patch.patch; done

Путь конечно же под ваш сервер, у меня первая звездочка это пользователи на сервере, вторая сайты.

Анимация css

Пример анимации на CSS очень прикольно! 🙂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
.uwloader{
	background: url(http://my-opinions.info/wp-content/uploads/2014/09/preloader.png) no-repeat;
	background-size: 80px 80px;
	position: fixed;
	top: 50%;
	left: 50%;
	margin-left: -30px;
	margin-top: -30px;
	width: 80px;
	height: 80px;
	-webkit-animation: rotateplane 2s infinite ease-in-out;
	animation: rotateplane 2s infinite ease-in-out;
}
@-webkit-keyframes rotateplane {
    0% {
    -webkit-transform: perspective(120px) rotateX(0deg) rotateY(0deg)
	}
	25% {
	    -webkit-transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg)
	}
	50% {
	    -webkit-transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg)
	}
	75% {
	    -webkit-transform: perspective(120px) rotateX(0deg) rotateY(-179.9deg)
	} <a href="http://my-opinions.info/en/programing/css/animaciya-css#more-266" class="more-link">Continue reading <span class="screen-reader-text">Анимация css</span></a>

 

Дробное количество ubercart 3

ubercard 3.5 нашел решения с некоторыми коректировками
// making the product quantities FLOAT instead INTEGER Drupal 7, Ubercart 3.1
//// DATABASE CHANGES Four ubercart tables alterations are made from sql terminal (mysql -u ADMIN_USER -p , use DATABASE_NAME )
1) The UC_CART_PRODUCTS table intersect the UC_CARTS table and the UC_PRODUCTS table. The column ц╒Б┌╛е⌠qtyц╒Б┌╛б² is the one to ajust. Here is the MySQL statement that will modify the column to a FLOAT data type:

ALTER TABLE `uc_cart_products` MODIFY COLUMN `qty` FLOAT(6,2) UNSIGNED NOT NULL DEFAULT 0;

2) The UC_ORDERS table holds all the orders created. The column to adjust is ц╒Б┌╛е⌠product_countц╒Б┌╛б².

ALTER TABLE `uc_orders` MODIFY COLUMN `product_count` FLOAT(6,2) UNSIGNED NOT NULL DEFAULT 0; 3) The UC_PRODUCTS table contains a

default_qty field. This value gets inserted into both the product edit page and the product view page (for the customer). I think it would be a good idea to show the customer how many decimal places one may use.

ALTER TABLE `uc_products` MODIFY COLUMN `default_qty` FLOAT(6,2) UNSIGNED NOT NULL DEFAULT 1.00;

4) The UC_ORDER_PRODUCTS table intersects the UC_ORDERS table and the UC_PRODUCTS table. The column to adjust is the ц╒Б┌╛е⌠qtyц╒Б┌╛б² column. Here is the MySQL statement that will modify the column to a FLOAT data type:

ALTER TABLE `uc_order_products` MODIFY COLUMN `qty` FLOAT(6,2) UNSIGNED NOT NULL DEFAULT 0;

//// CODE CHANGES // FIRST uc_order -> uc_order.install //Change array elements in function to: /** * Increase maximum order item quantity. */

function uc_order_update_7003() {
db_change_field('uc_order_products', 'qty', 'qty', array(
'description' => 'The number of the same product ordered.',
'type' => 'float',
'precision' => 6,
'scale' => 1,
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 1.0,
));
}

// SECOND


uc_order
->
uc_order.install

In $schema['uc_order_products'] change:

'qty' => array(
'description' => 'The number of the same product ordered.',
'type' => 'int',
'size' => 'small',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
),

To:


'qty' => array(
'description' => 'The number of the same product ordered.',
'type' => 'float',
'precision' => 6,
'scale' => 1,
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 1.0,
),

// THIRD uc_product -> uc_product.module //For possibility of using 0.00 to 1.00 quantites in function uc_product_uc_update_cart_item change: (string 1052) p.s. С новыми версиями функция поменялась, я сменил на функцию на старую версию, пока все ок 🙂

</pre>
<pre class="php"><code><span class="php-keyword">function</span> <span class="php-function-or-constant"><a class="local active" title="Implements hook_uc_update_cart_item()." href="http://drupalcontrib.org/api/drupal/contributions%21ubercart%21uc_product%21uc_product.module/function/uc_product_uc_update_cart_item/7">uc_product_uc_update_cart_item</a></span>(<span class="php-variable">$nid</span>, <span class="php-variable">$data</span> = <span class="php-keyword">array</span>(), <span class="php-variable">$qty</span>, <span class="php-variable">$cid</span> = <span class="php-function-or-constant">NULL</span>) {
  <span class="php-keyword">if</span> (!<span class="php-variable">$nid</span>) {
    <span class="php-keyword">return</span> <span class="php-function-or-constant">NULL</span>;
  }
  <span class="php-variable">$cid</span> = !(<span class="php-function-or-constant">is_null</span>(<span class="php-variable">$cid</span>) || <span class="php-keyword">empty</span>(<span class="php-variable">$cid</span>)) ? <span class="php-variable">$cid</span> : <span class="php-function-or-constant"><a class="local" title="Returns the unique cart_id of the user." href="http://drupalcontrib.org/api/drupal/contributions%21ubercart%21uc_cart%21uc_cart.module/function/uc_cart_get_id/7">uc_cart_get_id</a></span>();
  <span class="php-keyword">if</span> (<span class="php-variable">$qty</span> < <span class="php-constant">1</span>) {
    <span class="php-function-or-constant"><a class="local" title="Removes an item from the cart." href="http://drupalcontrib.org/api/drupal/contributions%21ubercart%21uc_cart%21uc_cart.module/function/uc_cart_remove_item/7">uc_cart_remove_item</a></span>(<span class="php-variable">$nid</span>, <span class="php-variable">$cid</span>, <span class="php-variable">$data</span>);
  }
  <span class="php-keyword">else</span> {
    <span class="php-function-or-constant"><a class="local" title="Returns a new UpdateQuery object for the active database." href="http://drupalcontrib.org/api/drupal/drupal%21includes%21database%21database.inc/function/db_update/7">db_update</a></span>(<span class="php-string">'uc_cart_products'</span>)
      -><span class="php-function-or-constant"><a class="local" title="Multiple implementations exist." href="http://drupalcontrib.org/api/search/7/fields">fields</a></span>(<span class="php-keyword">array</span>(
      <span class="php-string">'qty'</span> => <span class="php-variable">$qty</span>, 
      <span class="php-string">'changed'</span> => <span class="php-function-or-constant"><a class="local" title="Time of the current request in seconds elapsed since the Unix Epoch." href="http://drupalcontrib.org/api/drupal/drupal%21includes%21bootstrap.inc/constant/REQUEST_TIME/7">REQUEST_TIME</a></span>,
    ))
      -><span class="php-function-or-constant"><a class="local" title="Multiple implementations exist." href="http://drupalcontrib.org/api/search/7/condition">condition</a></span>(<span class="php-string">'nid'</span>, <span class="php-variable">$nid</span>)
      -><span class="php-function-or-constant"><a class="local" title="Multiple implementations exist." href="http://drupalcontrib.org/api/search/7/condition">condition</a></span>(<span class="php-string">'cart_id'</span>, <span class="php-variable">$cid</span>)
      -><span class="php-function-or-constant"><a class="local" title="Multiple implementations exist." href="http://drupalcontrib.org/api/search/7/condition">condition</a></span>(<span class="php-string">'data'</span>, <span class="php-function-or-constant">serialize</span>(<span class="php-variable">$data</span>))
      -><span class="php-function-or-constant"><a class="local" title="Multiple implementations exist." href="http://drupalcontrib.org/api/search/7/execute">execute</a></span>();
  }
}


 


if ($qty < 1) {

 

CHANGE TO:


if ($qty == 0) {

// FOURTH uc_order -> uc_order.admin.inc //Not sure if it's necessary but just in case (string 1125)

if (!isset($product['remove']) && intval($product['qty']) > 0) {

CHANGE TO:


if (!isset($product['remove']) && ($product['qty']) > 0) {

//FIFTH uc_cart -> uc_cart.install //Not sure if it's necessary but just in case CHANGE TO FLOATS: (string 37)


'qty' => array(
'description' => 'The number of this product in the cart.',
'type' => 'float',
'precision' => 6,
'scale' => 1,
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 1.0,

AND (string 126)


function uc_cart_update_7001() {
db_change_field('uc_cart_products', 'qty', 'qty', array(
'description' => 'The number of this product in the cart.',
'type' => 'float',
'precision' => 6,
'scale' => 1,
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 1.0,
));
}

/*uc_store\uc_store.module*/ /*chenge */


function uc_store_validate_uc_quantity(&$element, &$form_state) {
if (!preg_match('/^\d+$/', $element['#value'])) {
form_error($element, t('The quantity must be a number.'));
}
elseif (empty($element['#allow_zero']) && !$element['#value']) {
form_error($element, t('The quantity cannot be zero.'));
}
}

/*on*/


function uc_store_validate_uc_quantity(&$element, &$form_state) {
if (!preg_match("/([0-9\.-]+)/", $element['#value'])) {
form_error($element, t('The quantity must be a number.'));
}
elseif (empty($element['#allow_zero']) && !$element['#value']) {
form_error($element, t('The quantity cannot be zero.'));
}
}

Drush update all module and drupal automatic more site

Как всегда не буду тянуть заходим в SSH и вводим такую вот строчку

for i in /home/www/grenuy/data/www/*/sites/.. ; do cd "$i"; drush updb; drush en update; yes | drush pm-update ; drush up drupal ; drush updb ; done

 

grenuy это имя пользователя путь может быть немного видоизмененным в зависимости от сервера.

Скрипт может давать сбои и error, при сбои создается папка с именем drupal-7.** перенеся от туда файлы в корень сайта восстановиться сайт.

обновляет как и 7-ку так и 6-ку в построчечный режим выполнения команд такой(в корне сайта выполняться)

drush en update
drush pm-update
drush up drupal
drush updb

Вложеный запрос в codeignator

Как всегда мало водного текста, сразу код, ниже немного разъяснения по нему

1
2
3
4
5
6
7
8
9
10
11
    $this->db->select("*")
            ->from("schedule")
            ->order_by("schedule.dayofweek", "asc")
            ->order_by("schedule.lesson_number", "asc")
            ->order_by("date_approve", "desc");
    $s = $this->db->_compile_select();
    $this->db->_reset_select();
    $dbprefix = $this->db->dbprefix;
    $this->db->set_dbprefix('');
    $this->db->select("*")
            ->from('(' . $s . ') as ' . $this->db->dbprefix . 'schedule_tmp'); <a href="http://my-opinions.info/codeigniter/vlozhenyj-zapros-v-codeignator#more-171" class="more-link">Читать далее <span class="screen-reader-text">Вложеный запрос в codeignator</span></a>

В результате получим вот такой вот запрос

1
2
3
4
5
6
7
8
9
      SELECT * FROM (
      SELECT * FROM `uw_schedule` ORDER BY  `uw_schedule`.`dayofweek` ASC, `uw_schedule`.`lesson_number` ASC, `uw_schedule`.`date_approve` DESC
      ) AS uw_schedule_tmp
 
      LEFT JOIN `uw_lessons` ON `uw_lessons`.`lesson_id` = `uw_schedule_tmp`.`lesson_id`
      LEFT JOIN `uw_students` ON `uw_schedule_tmp`.`class_id` = `uw_students`.`class_id`
      WHERE `uw_schedule_tmp`.`class_id` = 0
      AND `uw_schedule_tmp`.`date_approve` < '2012-06-29 14:59:00'
      GROUP BY uw_schedule_tmp.dayofweek, uw_schedule_tmp.lesson_number

Скорее всего вы столкнетесь с проблемой что методы
_compile_select();
_reset_select();
protected, а соответственно их можно использовать только в нутри класса, честно говоря не разберался как обойти эту ситуацию и просто поменял их в ядре на public, если кто разберется, напишите пожалуйста, исправлю статью, и себе на заметку.. )

И так теперь по коду,
$this->db->dbprefix Получает текущий префикс, если Вам он не нужен то можно пропустить использования этого метода
_compile_select() Возращает запрос в переменую
_reset_select();

What I was now # 1

I had a task to be empathetic and active today.
To start today was the day Badi, and naturally thought as the Badi to please, and it turned out, now I will take her agruz, plum, cherry, with its own garden.
Next, the team has helped with the designer, but I realized that the initiative is punishable began vylazit with "small requests" on its head, had the strength and courage to begin to speak what is not, that would be not to let those people who have been laid out time after the conversation with Badi, went crown, where he received offers to go to the movies on companion proposals received. After I went to the designer, it is on its last zhaluvalas Unfortunately, she asked me to ride her horses to ride on Monday and for one and rolled himself with his girlfriend, which she certainly received a positive response.
After I went to the girl, took her, wooed her, massage, teas, etc. In short, announced DAY YOUR desires. And dutifully performed ... It was funny and fun ...
After the movie was on the way hooked up the theme work, and then Sosyk home ...
Now try to lay down at night hoping to get the printer ... and will not spare parts. So I spent the day ...
By the way the girl said she was caring and gentle. So mission accomplished more than

LP program in the agency “Development”

That was not long ago I was drawn into the agency "Development" on-course. First, in the first stage, then decided to go to LP.
This level courses I do not know the first step even so-so, of course cool but still it is not as much as you expected, there were some exercises that will allow to dig into the past, go to, but much like that to no avail.
And yet, I decided to go ahead in leadership, LProgrammu.
Leadership share on weekends, that's held the first weekend that I can tell, it's just PPV!! Received 5 times more than I expected, I heard and took it on himself that he could not accept for many years, and believed that this is not about me, although frequently mentioned. Very much negativity is gone. Learned to look at life differently, the experience began to emerge THIS, team play, one of the interesting points in the first day of each chooses "Badi", is a man who often sold articles you furious, and with that in life you just have not spoken to but with training, learn and work with ...
The world begins to look quite different, as it "really" what-if, by training, I remember how truly feel happy, more uchat switch, and draw conclusions.
But even after the end of the first weekend, do not give a descent, appointed captain, and begin to control what would you have acted on their own words. And really begin to work more effectively and try and do more ....
Here is their website http://razvitie.od.ua/.

XML -> PHP

It's no longer the post as well primetka for myself that would not have forgotten

simplexml_load_file("file.xml");
simplexml_load_string($xml_string);

At output you get an object with a pre-packaged xml. That's super easy and super convenient.
The only thing that should probably be noted that this method requires php5 and I understand some module, well, I have gone without a shaman. If that is not the path to the php.ini file
For example, you can write here is a simple file

$xml="<request>      
<version>1.2</version>
<result_url>http://ulove.ua//buy/</result_url>
<server_url>http://ulove.ua//buy/resultliqpay/</server_url>
<merchant_id>i4927007979</merchant_id>
<order_id>128</order_id>
<amount>12</amount>
<currency>USD</currency>
<description>uLove</description>
<default_phone>+380938729936</default_phone>
<pay_way>card</pay_way> 
</request>";
$xml=simplexml_load_string($xml);
print_r($xml);
echo $xml->order_id;

On the screen we

SimpleXMLElement Object
(
    [version] => 1.2
    [result_url] => http://ulove.ua//buy/
    [server_url] => http://ulove.ua//buy/resultliqpay/
    [merchant_id] => i4927007979
    [order_id] => 128
    [amount] => 12
    [currency] => USD
    [description] => uLove
    [default_phone] => +380938729936
    [pay_way] => card
)
128

My opinion, this is the easiest option, who will offer easier listen.

Alcoholism part 2

Since the beginning of this article you can find by clicking on the link
In this part, would like to talk, why, still, as promoted by alcohol, and other degraded product in Ukraine.
In fact, all very trite, prosaic and transparent.
I will bring a simple example of how to think, easier to convince someone that, for example, the earth is square, or that the color blue in the sky, in fact, in the form of jelly ... or other garbage, which generally does not get on with reality?The answer is obvious ...
Here, I can hear the cues, such as it is because of inexperience, alright I will agree, the way it is ... But what do you say if we take the example of the more interesting for us, who easily made to work for the ice cream? Easier to convince someone that is boring and hard work, interesting and exciting? OF COURSE children ...
Easier to manage those who do not soar, who are willing to work for food, literally. Those who believe a salary of $ 500 per month salary space, and if you get 4000 UAH. (Equivalent to $ 500), then you must be a happy person and consider myself a secured ... What a delusion! 3-bedroom apartment in Odessa is 60 000 $, that is, it's 10 years of work, with both titles, an excellent salary, while all that may have no clothes, and generally do not spend a penny that is not realistic, and at best is 20 years, and yet still want to buy a car, not Cossack ... And it's not the last money, and not in 60 years ... So my opinion is that it is necessary to develop learning and earning her head.
Is over, immediately not get to go against all, and smart book to learn, it does not unload the car ... I do not want to offend anyone, and do not unloaded one car ... But physical work really hard to earn more, and most likely $ 500 is not raised the amount of for this kind of work ...
As Caesar said Yu. "The bread earning his hands on the canvas - his head" ... So I urge all not become blunt, and not be, especially if the society will degrade, the professionals who require mental capacity will be increasingly in short supply, and accordingly , and the price ...
When we begin to somehow work it hard to get on their feet walking on the intellectual path of earnings. First, the options for less. Secondly, the initial rate and payment for physical labor, usually above ... So fall into the trap ... But we have to have perseverance ...
By the way about perseverance and alcoholism , is not it punning sounds, if these words are next to each other?Think about it, begin to lead a sober lifestyle!
Since the beginning of this article you can find by clicking on the link Continue reading Alcoholism part 2

Better than waking up to sleep

How do you want to sleep in the morning, as I do not want to get up. But if you wake up, you need to learn is to get up, except perhaps in those cases, if awakened by the noise / poor sleep, because the time to fill up that still does not add power, but simply take away the time ...
Work freelancing usually allows sleep all you want, and go in as you want. Do not think that we (freelancers) and only do what we sleep, in fact, be a freelancer is often much harder than working in an office. And often less pribelno about frilastvo it has its advantages, namely
1. Develop along the chosen direction
2. Healthy sleep (usually)
3. Relatively high earnings, if live in a small town
There are many more, but I think I'm not the first one lists the pros and cons, by the way of cons:
1. Relatively low salary, if you live in a big city
2. Required enormous self-control / determination / desire that would work
3. Hard razvinutsya career
4. Sots.paketa absence, paid leave
But then I went away, saying we are not on the + and - frilanstva. And the fact that the need to wake up immediately after wake up and do not fill up those hours ... Since the forces they do not dodadut. Maybe I'm wrong, and the scientific evidence I was not looking, but still my opinion is the following.
Waiting komentov and your opinion !

Began studying CodeIgniter

Began studying CodeIgniter, very Kulnev ferymvork, according to the author of the fastest of the existing framework. So wait for new articles on the CodeIgniter. What good is a very good documentation, and start simply enough ... By the way Russian docks on CodeIgniter version 2.0.0 can be found here http://whitepiano.ru/user_guide/ so happy to delve into all this beautiful framework

Drupal BuEditor разметка php css html c++ и т.д.

Все очень просто заходим в раздел настройки bueditor-a
http://*****/admin/settings/bueditor
Возле желаймого редактора тыкаем изменить, получаем следующее

Вставив код в ячейку кода

[PHP]js: E.tagChooser([
<%%KEEPWHITESPACE%%> ['code', 'Bash', {'class': 'bash'}],
<%%KEEPWHITESPACE%%> ['code', 'C', {'class': 'c'}],
<%%KEEPWHITESPACE%%> ['code', 'C++', {'class': 'cpp'}],
<%%KEEPWHITESPACE%%> ['code', 'C#', {'class': 'csharp'}],
<%%KEEPWHITESPACE%%> ['code', 'Pascal', {'class': 'pascal'}],
<%%KEEPWHITESPACE%%> ['code', 'Php', {'class': 'php'}],
<%%KEEPWHITESPACE%%> ['code', 'Css', {'class': 'css'}],
<%%KEEPWHITESPACE%%> ['code', 'html', {'class': 'html4strict'}],
<%%KEEPWHITESPACE%%> ['code', 'Brainfuck', {'class': 'bf'}],
<%%KEEPWHITESPACE%%> ]);[/PHP]

Нажали сохранить мы получим обновленный редактор

 

views nivo slider how to do that would slide shows in order, randomly, and the first slide was also randomly

Can anyone come in handy, did a little bit perverted, but it works, sort, and finally finished the pattern

if(drupal_is_front_page()){
$sql = "SELECT nid FROM node WHERE TYPE =  'image_slider'";
$result = db_query($sql); 
while ($n = db_fetch_object($result)) {
db_query("UPDATE  `node` SET  `title` =  '".rand(1,100500)."' WHERE `nid` ='".$n->nid."';");
}}

the essence of all that the name node, which is sorted, renamed when visiting the home page. Accordingly, when sorting each time a new order will

Variables in the subject Drupal

page.tpl.php

Basic template for a page.Accessible variables:

  • $head_title is a header of page
  • $head is all information in head
  • $styles are styles
  • $scripts are scripts
  • $classes are classes for body
  • $header is a cap which we took away in a separate template
  • $REGION_NAME are variables with the names of regions
  • $messages are system reports
  • $tabs - табы
  • $content is content
  • $feed_icons are icons of RSS
  • $footer is basement which we took away in a separate template
  • $base_path is a base path of site
  • $is_front is a main page or no
  • $logged_in is whether a залогинен user
  • $is_admin - admin or no
  • $language is an object, containing data about a current language
  • $node - нода
  • $front_page is a pointer to main
  • $logo is a logotype
  • $site_name is the name of site
  • $site_slogan is a slogan of site
  • $mission is a mission of site
  • $search_box is a block of search
  • $closure - a variable is inserted before the closing tag /of body, in it some modules write scripts. Thank you хабраюзеру juliv/ Continue reading Variables in the subject Drupal

Alcoholism Part 1

I'm shocked how much solder is now the people in Ukraine and Russia.
brazenly promotes "normal" use, while still splurge supposedly struggling against it all!
In addition to already people there is a perception about what 1 glass of wine a day is helpful , so that there people, half if not more, attendants say! Yes it is! DELUSION THAT'S IT! Continue reading Alcoholism Part 1

Rebuild $content $vars[‘content’] Drupal

That is needed to rebuild the $ content variable in taksomanii,
Link taksomanii was such a
taxonomy/term/1
the output was supposed to get here this html one record

<div class="news-item">
				  <div class="date"><i>04</i>апр</div>
				  <div class="news-block">
					<p class="title"><a href="node/7">программирования с помощью метода эллипсоидов. С самого начала большое внимание будет уделяться связи линейного программирования с теорией целочисленного программирования, комбинаторикой и оптимизацией.
				</p>
					<p class="more"><a "="" href="node/7">Читать далее</a></p>
				  <div class="line"></div>
				</div>
				</div>

Continue reading Rebuild $content $vars[‘content’] Drupal

Home in Drupal (home page of drupal)

In order that would make the home page you can create a unique file in the template with the name of page-front.tpl.php, but if you create a template and you simply need to determine a home page or not, you can use drupal_is_front_page. If the current home page - TRUE, otherwise - FALSE. So we can write

<?php
if(drupal_is_front_page())
echo "Это главная страница";
else "Не главная страница";
?>

Настройка PhpMyAdmin для локал хоста

Вот как то долго не настраивал PhpMyAdmin, а потом взял и настроил! ) создаем в корне папки PhpMyAdmin файл config.inc.php и вставляем туда вот такое Continue reading Настройка PhpMyAdmin для локал хоста

Withdrawal of certain categories of positions

Zadachka needed in the template display the latest news of a certain category on the home. Well established in the template file home.php. And place prescribed

1
2
3
4
5
6
<?php
query_posts($query_string.'&amp;cat=26');//Делаем запрос в базу который выберет нужные нам посты
have_posts();//выбрать посты
the_post();//выбрать первый пост
the_excerpt();//вывод краткой новости
?>