Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 12.62 KB | None | 0 0
  1. <?php
  2. define('YML_NAME', 'file.xml');
  3. function yandex_yml_menu() {
  4.   $items = array();
  5.   $items['yandex_yml_sorok.xml'] = array(
  6.     'title' => t('YML export'),
  7.     'page callback' => 'yandex_yml_get_xml',    
  8.     'type' => MENU_CALLBACK,
  9.     'access arguments' => array('access content'),
  10.   );
  11.   $items['admin/config/services/yandex_yml'] = array(
  12.     'title' => 'Yml export for Yandex.market',  
  13.     'page callback' => 'drupal_get_form',
  14.     'page arguments' => array('yandex_yml_admin_settings'),
  15.     'access callback' => 'user_access',
  16.     'access arguments' => array('administer site configuration'),
  17.   );
  18.   return $items;
  19. }
  20.  
  21. function yandex_yml_admin_settings() {
  22.   $form = array();
  23.  
  24.   $ctypes = commerce_product_types();
  25.  
  26.   $form['yandex_yml_types'] = array(
  27.     '#required' => TRUE,
  28.     '#type' => 'checkboxes',
  29.     '#options' => array(
  30.             $ctypes['product']['type'] => $ctypes['product']['name'],
  31.             // $ctypes['finished_product']['type'] => $ctypes['finished_product']['name']
  32.         ),
  33.     '#default_value' => variable_get('yandex_yml_types', array('product' => 'product')),
  34.     '#title' => t('Select node types for export'),
  35.   );
  36.   $instances = field_info_instances('node');
  37.  
  38.   $instance = $instances[$ctypes['product']['type']];
  39.  
  40.   $term_fields = array();
  41.   $descr_fields = array();
  42.  
  43.   foreach ($instance as $field_name => $field) {
  44.     $info = field_info_field($field_name);
  45.     if ($info['type'] == 'taxonomy_term_reference') {
  46.       $term_fields[] = $field_name;
  47.     }
  48.     if ($info['module'] == 'text') {
  49.       $descr_fields[] = $field_name;
  50.     }
  51.     if ($info['type'] == 'image') {
  52.       $img_fields[] = $field_name;
  53.     }
  54.   }
  55.  
  56.   if (count($term_fields) == 0) {
  57.     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');
  58.   } else {  
  59.     $term_fields = array_combine($term_fields, $term_fields);
  60.   }
  61.  
  62.   if (count($descr_fields) == 0) {
  63.     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');
  64.   } else {  
  65.     $descr_fields = array_combine($descr_fields, $descr_fields);
  66.   }
  67.   if (count($descr_fields) == 0) {
  68.     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');
  69.   } else {  
  70.     $img_fields = array_combine($img_fields, $img_fields);
  71.   }
  72.  
  73.   $form['yandex_yml_term_field'] = array(
  74.     '#required' => TRUE,
  75.     '#type' => 'select',
  76.     '#empty_value' => '',
  77.     '#options' => $term_fields,
  78.     '#default_value' => variable_get('yandex_yml_term_field', ''),
  79.     '#description' => t('Select product term field where primary product categories are stored'),
  80.     '#title' => t('Category field'),
  81.   );
  82.  
  83.   $form['yandex_yml_descr_field'] = array(
  84.     '#required' => TRUE,
  85.     '#type' => 'select',
  86.     '#empty_value' => '',
  87.     '#options' => $descr_fields,
  88.     '#default_value' => variable_get('yandex_yml_descr_field', ''),
  89.     '#description' => t('Select text field which will be used as product description'),
  90.     '#title' => t('Description field'),
  91.   );
  92.  
  93.   $form['yandex_yml_image_field'] = array(
  94.     '#required' => TRUE,
  95.     '#type' => 'select',
  96.     '#empty_value' => '',
  97.     '#options' => $img_fields,
  98.     '#default_value' => variable_get('yandex_yml_image_field', ''),
  99.     '#description' => t("This field will be used for images in export."),
  100.     '#title' =>t('Image field'),
  101.   );
  102.  
  103.   $form['yandex_yml_delivery'] = array(
  104.     '#type' => 'select',
  105.     '#options' => array('true' => t("true"), 'false' => t("false")),
  106.     '#title' => t('Select if delivery is enabled'),    
  107.     '#default_value' => variable_get('yandex_yml_delivery', 'true'),
  108.     '#description' => t('Yandex.Market has "delivery" field. Select if it is enabled'),
  109.   );
  110.  
  111.   $form['yandex_yml_currency'] = array(
  112.     '#type' => 'item',  
  113.     '#title' => t('Commerce currency'),    
  114.     '#markup' => variable_get('commerce_currency_code', 'BYN') . ' (' . l(t("Change"), 'admin/commerce/config/currency') . ')',
  115.     '#description' => t("Should be 'BYR' for Belarus"),
  116.   );
  117.  
  118.   $url = url('yandex_yml_sorok.xml', array('absolute' => TRUE));
  119.   $form['generated_url'] = array(
  120.     '#type' => 'item',  
  121.     '#title' => t("Generated file"),
  122.     '#markup' => $url . ' (' . l(t("View"), $url) . ')',
  123.     '#description' => t("Use this url in Yandex.Market"),
  124.   );
  125.  
  126.   $form['#submit'][] = 'yandex_yml_admin_settings_submit';
  127.  
  128.   return system_settings_form($form);
  129. }
  130.  
  131. function yandex_yml_admin_settings_submit($form, $form_state) {
  132.   $term_field = $form_state['values']['yandex_yml_term_field'];
  133.   $term_field  = field_info_field($term_field);
  134.  
  135.   $vocab = taxonomy_vocabulary_machine_name_load($term_field['settings']['allowed_values'][0]['vocabulary']);
  136.   variable_set('yandex_yml_vid', $vocab->vid);
  137. }
  138.  
  139. function yandex_yml_get_xml() {
  140.   if (variable_get('yandex_yml_vid', '') == '') {
  141.     die('Please select primary vocabulary on YML export settings page!');
  142.   }
  143.  
  144.   $ctypes = variable_get('yandex_yml_types', array('product' => 'product'));
  145.   $enabled_ctypes = array();
  146.   foreach ($ctypes as $type_name => $enabled) {
  147.     if ($enabled) {
  148.       $enabled_ctypes[$type_name] = $type_name;
  149.     }
  150.   }
  151.  
  152.   if (empty($enabled_ctypes)) {
  153.     die('Please select at least one node type on YML export settings page!');
  154.   }  
  155.  
  156.   $node_types = variable_get('yandex_yml_types', array('product' => 'product'));
  157.  
  158.   // $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();
  159.   $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();
  160.   $products = commerce_product_load_multiple($products_id);
  161.  
  162.   $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');
  163.  
  164.   //user => password
  165.     $login = "admin";
  166.     $password = "sorok";
  167.     // header('HTTP/1.0');
  168.     // print($_SERVER['PHP_AUTH_USER']);
  169.  
  170.     // if (!isset($_SERVER['PHP_AUTH_USER'])) {
  171.     //  header('Content-type: application/xhtml+xml; charset=utf-8');
  172.     //   echo theme('yml_products', array(
  173.     //     'products' => $products,
  174.     //     'categories' => $categories,
  175.     //   ));
  176.     //   exit();
  177.     // } else {
  178.     //  $auth_user = $_SERVER['PHP_AUTH_USER'];
  179.     //  $auth_pass = $_SERVER['PHP_AUTH_PW'];
  180.        
  181.     //  if (($auth_user != $login) || ($auth_pass != $password)) {
  182.     //      header('WWW-Authenticate: Basic realm="Closed Zone"');
  183.     //    header('HTTP/1.0 401 Unauthorized');
  184.     //    echo "<html><body bgcolor=white link=blue vlink=blue alink=red>","<h1>Ошибка аутентификации</h1>","<p>Обратитесь к администратору для получения логина и пароля.</p>","</body></html>";
  185.     //    exit();
  186.     //  };
  187.     // };
  188.  
  189.     header('Content-type: application/xhtml+xml; charset=utf-8');
  190.   echo theme('yml_products', array(
  191.     'products' => $products,
  192.     'categories' => $categories,
  193.   ));
  194.   exit();
  195. }
  196.  
  197. function yandex_yml_theme() {
  198.   return array(    
  199.     'yml_products' => array(
  200.       'variables' => array('nodes' => NULL, 'categories' => NULL),
  201.       'template' => 'yml_products',
  202.     ));
  203. }
  204.  
  205. // Prepare all strings so they are valid for Yandex.Market format
  206. function yml_safe($str) {
  207.   $rep = array(
  208.     '"' => '&quot;',
  209.     '&' => '&amp;',
  210.     '>' => '&gt;',
  211.     '<' => '&lt;',
  212.     "'" => '&apos;'
  213.   );
  214.  
  215.   return strtr($str, $rep);
  216. }
  217.  
  218. // Shortcut for usage in html templates
  219. function ys($str) {
  220.   return yml_safe($str);
  221. }
  222.  
  223. function yandex_yml_get_referencing_node_id($product) {
  224.   global $language;
  225.  
  226.   // Itterate thhrough fields which refer to products.
  227.   foreach (commerce_info_fields('commerce_product_reference') as $field['field_name']) {
  228.     // Build query.
  229.     $query = new EntityFieldQuery;
  230.     $query->entityCondition('entity_type', 'node', '=')
  231.       ->fieldCondition($field['field_name'], 'product_id', $product->product_id, '=')
  232.       ->propertyCondition('language', $language->language, '=')
  233.       ->range(0, 1);
  234.  
  235.     if ($result = $query->execute()) {
  236.       // Return node.
  237.       $node_id = array_shift(array_keys($result['node']));
  238.       return node_load($node_id);
  239.     }
  240.   }
  241.  
  242.   return false;
  243. }
  244.  
  245. /**
  246.  * Implements hook_cron().
  247.  */
  248. function yandex_yml_cron()
  249. {
  250.     if(variable_get('yandex_yml_queue_time',0)+60*30>time())
  251.     {
  252.         watchdog('tst','start');
  253.         yandex_yml_queue_create();
  254.     }
  255. }
  256. /**
  257.  * Создание очереди
  258.  */
  259. function yandex_yml_queue_create()
  260. {
  261.     $node_types = variable_get('yandex_yml_types', array('product' => 'product'));
  262.     $products_count= db_query("SELECT  COUNT(*)  FROM {commerce_product} WHERE type IN (:node_types) AND status=:status",
  263.         array(':node_types' => $node_types, ':status' => 1))->fetchCol();
  264.     watchdog('tst','prod='.$products_count);
  265.     $products_count=100;
  266.     if($products_count>0)
  267.     {
  268.     // Без запроса (в фоне) url() пустой. Запомним
  269.    variable_set('yandex_yml_queue_url', url('/', array('absolute' => TRUE)));
  270.  
  271.     // проверь, нужно ли проверять ...
  272.     file_unmanaged_delete(YML_NAME);
  273.  
  274.     $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');
  275.     yandex_yml_queue_header_write($categories);
  276.     // создаем очередь
  277.         $queue = DrupalQueue::get('yandex_yml_queue');
  278.         $queue->createQueue();
  279.  
  280.         for ($i = 0; $i < $products_count; $i++) {
  281.             $queue->createItem(array('start' => $i));
  282.         }
  283.         $queue->createItem(array('start' =>-1));
  284. }
  285. }
  286. function yandex_yml_queue_header_write($categories)
  287. {
  288.     watchdog('tst','header');
  289.  $data=array();
  290.  
  291.  
  292. $data[]='<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" ?>';
  293. $data[]='<!DOCTYPE yml_catalog SYSTEM "shops.dtd">';
  294. $data[]='<yml_catalog date="'.date('Y-m-d h:i').'">';
  295. $data[]='<shop>';
  296. $data[]='<name>'.variable_get('site_name', 'Drupal').'</name>';
  297. $data[]='<company>'.variable_get('site_name', 'Drupal').'</company>';
  298. $data[]='<url>'.variable_get('yandex_yml_queue_url', '/').'</url>';
  299. $data[]='<currencies>';
  300. $data[]='<currency id="BYN" rate="1" />';
  301. $data[]='</currencies>';
  302. $data[]='<categories>';
  303. foreach ($categories as $key => $category):
  304. $data[]='<category id="'.$category->tid .'" '.($category->parent?' parentId="'.$category->parent.'" ':'').'>'.ys($category->name).'</category>';
  305.  endforeach;
  306. $data[]='</categories>';
  307. $data[]='<offers>';
  308.     yandex_yml_queue_write($data);
  309. }
  310. function yandex_yml_queue_footer_write()
  311. {
  312.     watchdog('tst','footer');
  313.  $data=array();
  314. $data[]='</offers>';
  315. $data[]='</shop>';
  316. $data[]='</yml_catalog>';
  317.     yandex_yml_queue_write($data);
  318. }
  319. function yandex_yml_queue_data_write($start)
  320. {
  321.     $node_types = variable_get('yandex_yml_types', array('product' => 'product'));
  322.     $products_id = db_query("SELECT product_id FROM {commerce_product} WHERE type IN (:node_types) AND status=:status LIMIT $start, 1",
  323.         array(':node_types' => $node_types, ':status' => 1))->fetchCol();
  324.     $products = commerce_product_load($products_id);
  325.  $data=array();
  326.     watchdog('tst',$start);
  327.     $data[]='prod='.$products_id;
  328. // тут перемести продукт
  329.     yandex_yml_queue_write($data);
  330. }
  331. /**
  332.  * Implements hook_cron_queue_info().
  333.  */
  334. function sy_catalog_cron_queue_info()
  335. {
  336.     $queues = array();
  337.     $queues['yandex_yml_queue'] = array(
  338.         'worker callback' => 'yandex_yml_queue_proc',
  339.         'time' => 10,
  340.     );
  341.     return $queues;
  342. }
  343.  
  344. /*
  345.  * функция обработки задачь из очереди
  346.  */
  347. function yandex_yml_queue_proc($data)
  348. {
  349.     if (!empty($data)) {
  350.         if (isset($data['op'])) {
  351.             if ($data['op'] <0 ) yandex_yml_queue_footer_write();
  352.             else{
  353.                 yandex_yml_queue_data_write($data['op']);
  354.             }
  355.         }
  356.     }
  357. }
  358.  
  359. /*
  360.  * Запись в файл
  361.  */
  362. function yandex_yml_queue_write($data)
  363. {
  364.     $fh = fopen(YML_NAME, 'a+');
  365.     foreach ($data as $line) {
  366.         $string = $line . "\n";
  367.         fwrite($fh, $string);
  368.     }
  369.     fclose($fh);
  370. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement