Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- define('YML_NAME', 'file.xml');
- function yandex_yml_menu() {
- $items = array();
- $items['yandex_yml_sorok.xml'] = array(
- 'title' => t('YML export'),
- 'page callback' => 'yandex_yml_get_xml',
- 'type' => MENU_CALLBACK,
- 'access arguments' => array('access content'),
- );
- $items['admin/config/services/yandex_yml'] = array(
- 'title' => 'Yml export for Yandex.market',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('yandex_yml_admin_settings'),
- 'access callback' => 'user_access',
- 'access arguments' => array('administer site configuration'),
- );
- return $items;
- }
- function yandex_yml_admin_settings() {
- $form = array();
- $ctypes = commerce_product_types();
- $form['yandex_yml_types'] = array(
- '#required' => TRUE,
- '#type' => 'checkboxes',
- '#options' => array(
- $ctypes['product']['type'] => $ctypes['product']['name'],
- // $ctypes['finished_product']['type'] => $ctypes['finished_product']['name']
- ),
- '#default_value' => variable_get('yandex_yml_types', array('product' => 'product')),
- '#title' => t('Select node types for export'),
- );
- $instances = field_info_instances('node');
- $instance = $instances[$ctypes['product']['type']];
- $term_fields = array();
- $descr_fields = array();
- foreach ($instance as $field_name => $field) {
- $info = field_info_field($field_name);
- if ($info['type'] == 'taxonomy_term_reference') {
- $term_fields[] = $field_name;
- }
- if ($info['module'] == 'text') {
- $descr_fields[] = $field_name;
- }
- if ($info['type'] == 'image') {
- $img_fields[] = $field_name;
- }
- }
- if (count($term_fields) == 0) {
- drupal_set_message(t("No term fields attached to product node! Export can't work properly. Please create at least one taxonomy vocabulary and use it for your products."), 'warning');
- } else {
- $term_fields = array_combine($term_fields, $term_fields);
- }
- if (count($descr_fields) == 0) {
- drupal_set_message(t("No text fields attached to product node! Export can't work properly. Please create at least one text field and use it for your products."), 'warning');
- } else {
- $descr_fields = array_combine($descr_fields, $descr_fields);
- }
- if (count($descr_fields) == 0) {
- drupal_set_message(t("No text fields attached to product node! Export can't work properly. Please create at least one image field and use it for your products."), 'warning');
- } else {
- $img_fields = array_combine($img_fields, $img_fields);
- }
- $form['yandex_yml_term_field'] = array(
- '#required' => TRUE,
- '#type' => 'select',
- '#empty_value' => '',
- '#options' => $term_fields,
- '#default_value' => variable_get('yandex_yml_term_field', ''),
- '#description' => t('Select product term field where primary product categories are stored'),
- '#title' => t('Category field'),
- );
- $form['yandex_yml_descr_field'] = array(
- '#required' => TRUE,
- '#type' => 'select',
- '#empty_value' => '',
- '#options' => $descr_fields,
- '#default_value' => variable_get('yandex_yml_descr_field', ''),
- '#description' => t('Select text field which will be used as product description'),
- '#title' => t('Description field'),
- );
- $form['yandex_yml_image_field'] = array(
- '#required' => TRUE,
- '#type' => 'select',
- '#empty_value' => '',
- '#options' => $img_fields,
- '#default_value' => variable_get('yandex_yml_image_field', ''),
- '#description' => t("This field will be used for images in export."),
- '#title' =>t('Image field'),
- );
- $form['yandex_yml_delivery'] = array(
- '#type' => 'select',
- '#options' => array('true' => t("true"), 'false' => t("false")),
- '#title' => t('Select if delivery is enabled'),
- '#default_value' => variable_get('yandex_yml_delivery', 'true'),
- '#description' => t('Yandex.Market has "delivery" field. Select if it is enabled'),
- );
- $form['yandex_yml_currency'] = array(
- '#type' => 'item',
- '#title' => t('Commerce currency'),
- '#markup' => variable_get('commerce_currency_code', 'BYN') . ' (' . l(t("Change"), 'admin/commerce/config/currency') . ')',
- '#description' => t("Should be 'BYR' for Belarus"),
- );
- $url = url('yandex_yml_sorok.xml', array('absolute' => TRUE));
- $form['generated_url'] = array(
- '#type' => 'item',
- '#title' => t("Generated file"),
- '#markup' => $url . ' (' . l(t("View"), $url) . ')',
- '#description' => t("Use this url in Yandex.Market"),
- );
- $form['#submit'][] = 'yandex_yml_admin_settings_submit';
- return system_settings_form($form);
- }
- function yandex_yml_admin_settings_submit($form, $form_state) {
- $term_field = $form_state['values']['yandex_yml_term_field'];
- $term_field = field_info_field($term_field);
- $vocab = taxonomy_vocabulary_machine_name_load($term_field['settings']['allowed_values'][0]['vocabulary']);
- variable_set('yandex_yml_vid', $vocab->vid);
- }
- function yandex_yml_get_xml() {
- if (variable_get('yandex_yml_vid', '') == '') {
- die('Please select primary vocabulary on YML export settings page!');
- }
- $ctypes = variable_get('yandex_yml_types', array('product' => 'product'));
- $enabled_ctypes = array();
- foreach ($ctypes as $type_name => $enabled) {
- if ($enabled) {
- $enabled_ctypes[$type_name] = $type_name;
- }
- }
- if (empty($enabled_ctypes)) {
- die('Please select at least one node type on YML export settings page!');
- }
- $node_types = variable_get('yandex_yml_types', array('product' => 'product'));
- // $products_id = db_query("SELECT product_id FROM {commerce_product} WHERE type IN (:node_types) AND status=:status LIMIT 0, 10", array(':node_types' => $node_types, ':status' => 1))->fetchCol();
- $products_id = db_query("SELECT product_id FROM {commerce_product} WHERE type IN (:node_types) AND status=:status LIMIT 0, 400", array(':node_types' => $node_types, ':status' => 1))->fetchCol();
- $products = commerce_product_load_multiple($products_id);
- $categories = db_query("SELECT d.tid, d.name, h.* FROM {taxonomy_term_data} d LEFT JOIN {taxonomy_term_hierarchy} h USING(tid) WHERE d.vid=:vid", array(':vid' => variable_get('yandex_yml_vid', '')))->fetchAllAssoc('tid');
- //user => password
- $login = "admin";
- $password = "sorok";
- // header('HTTP/1.0');
- // print($_SERVER['PHP_AUTH_USER']);
- // if (!isset($_SERVER['PHP_AUTH_USER'])) {
- // header('Content-type: application/xhtml+xml; charset=utf-8');
- // echo theme('yml_products', array(
- // 'products' => $products,
- // 'categories' => $categories,
- // ));
- // exit();
- // } else {
- // $auth_user = $_SERVER['PHP_AUTH_USER'];
- // $auth_pass = $_SERVER['PHP_AUTH_PW'];
- // if (($auth_user != $login) || ($auth_pass != $password)) {
- // header('WWW-Authenticate: Basic realm="Closed Zone"');
- // header('HTTP/1.0 401 Unauthorized');
- // echo "<html><body bgcolor=white link=blue vlink=blue alink=red>","<h1>Ошибка аутентификации</h1>","<p>Обратитесь к администратору для получения логина и пароля.</p>","</body></html>";
- // exit();
- // };
- // };
- header('Content-type: application/xhtml+xml; charset=utf-8');
- echo theme('yml_products', array(
- 'products' => $products,
- 'categories' => $categories,
- ));
- exit();
- }
- function yandex_yml_theme() {
- return array(
- 'yml_products' => array(
- 'variables' => array('nodes' => NULL, 'categories' => NULL),
- 'template' => 'yml_products',
- ));
- }
- // Prepare all strings so they are valid for Yandex.Market format
- function yml_safe($str) {
- $rep = array(
- '"' => '"',
- '&' => '&',
- '>' => '>',
- '<' => '<',
- "'" => '''
- );
- return strtr($str, $rep);
- }
- // Shortcut for usage in html templates
- function ys($str) {
- return yml_safe($str);
- }
- function yandex_yml_get_referencing_node_id($product) {
- global $language;
- // Itterate thhrough fields which refer to products.
- foreach (commerce_info_fields('commerce_product_reference') as $field['field_name']) {
- // Build query.
- $query = new EntityFieldQuery;
- $query->entityCondition('entity_type', 'node', '=')
- ->fieldCondition($field['field_name'], 'product_id', $product->product_id, '=')
- ->propertyCondition('language', $language->language, '=')
- ->range(0, 1);
- if ($result = $query->execute()) {
- // Return node.
- $node_id = array_shift(array_keys($result['node']));
- return node_load($node_id);
- }
- }
- return false;
- }
- /**
- * Implements hook_cron().
- */
- function yandex_yml_cron()
- {
- if(variable_get('yandex_yml_queue_time',0)+60*30>time())
- {
- watchdog('tst','start');
- yandex_yml_queue_create();
- }
- }
- /**
- * Создание очереди
- */
- function yandex_yml_queue_create()
- {
- $node_types = variable_get('yandex_yml_types', array('product' => 'product'));
- $products_count= db_query("SELECT COUNT(*) FROM {commerce_product} WHERE type IN (:node_types) AND status=:status",
- array(':node_types' => $node_types, ':status' => 1))->fetchCol();
- watchdog('tst','prod='.$products_count);
- $products_count=100;
- if($products_count>0)
- {
- // Без запроса (в фоне) url() пустой. Запомним
- variable_set('yandex_yml_queue_url', url('/', array('absolute' => TRUE)));
- // проверь, нужно ли проверять ...
- file_unmanaged_delete(YML_NAME);
- $categories = db_query("SELECT d.tid, d.name, h.* FROM {taxonomy_term_data} d LEFT JOIN {taxonomy_term_hierarchy} h USING(tid) WHERE d.vid=:vid", array(':vid' => variable_get('yandex_yml_vid', '')))->fetchAllAssoc('tid');
- yandex_yml_queue_header_write($categories);
- // создаем очередь
- $queue = DrupalQueue::get('yandex_yml_queue');
- $queue->createQueue();
- for ($i = 0; $i < $products_count; $i++) {
- $queue->createItem(array('start' => $i));
- }
- $queue->createItem(array('start' =>-1));
- }
- }
- function yandex_yml_queue_header_write($categories)
- {
- watchdog('tst','header');
- $data=array();
- $data[]='<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" ?>';
- $data[]='<!DOCTYPE yml_catalog SYSTEM "shops.dtd">';
- $data[]='<yml_catalog date="'.date('Y-m-d h:i').'">';
- $data[]='<shop>';
- $data[]='<name>'.variable_get('site_name', 'Drupal').'</name>';
- $data[]='<company>'.variable_get('site_name', 'Drupal').'</company>';
- $data[]='<url>'.variable_get('yandex_yml_queue_url', '/').'</url>';
- $data[]='<currencies>';
- $data[]='<currency id="BYN" rate="1" />';
- $data[]='</currencies>';
- $data[]='<categories>';
- foreach ($categories as $key => $category):
- $data[]='<category id="'.$category->tid .'" '.($category->parent?' parentId="'.$category->parent.'" ':'').'>'.ys($category->name).'</category>';
- endforeach;
- $data[]='</categories>';
- $data[]='<offers>';
- yandex_yml_queue_write($data);
- }
- function yandex_yml_queue_footer_write()
- {
- watchdog('tst','footer');
- $data=array();
- $data[]='</offers>';
- $data[]='</shop>';
- $data[]='</yml_catalog>';
- yandex_yml_queue_write($data);
- }
- function yandex_yml_queue_data_write($start)
- {
- $node_types = variable_get('yandex_yml_types', array('product' => 'product'));
- $products_id = db_query("SELECT product_id FROM {commerce_product} WHERE type IN (:node_types) AND status=:status LIMIT $start, 1",
- array(':node_types' => $node_types, ':status' => 1))->fetchCol();
- $products = commerce_product_load($products_id);
- $data=array();
- watchdog('tst',$start);
- $data[]='prod='.$products_id;
- // тут перемести продукт
- yandex_yml_queue_write($data);
- }
- /**
- * Implements hook_cron_queue_info().
- */
- function sy_catalog_cron_queue_info()
- {
- $queues = array();
- $queues['yandex_yml_queue'] = array(
- 'worker callback' => 'yandex_yml_queue_proc',
- 'time' => 10,
- );
- return $queues;
- }
- /*
- * функция обработки задачь из очереди
- */
- function yandex_yml_queue_proc($data)
- {
- if (!empty($data)) {
- if (isset($data['op'])) {
- if ($data['op'] <0 ) yandex_yml_queue_footer_write();
- else{
- yandex_yml_queue_data_write($data['op']);
- }
- }
- }
- }
- /*
- * Запись в файл
- */
- function yandex_yml_queue_write($data)
- {
- $fh = fopen(YML_NAME, 'a+');
- foreach ($data as $line) {
- $string = $line . "\n";
- fwrite($fh, $string);
- }
- fclose($fh);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement