Guest User

Untitled

a guest
Apr 17th, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 30.13 KB | None | 0 0
  1. #!/usr/bin/php
  2. <?php
  3. /**
  4.  * На голой бд сначала запустить import - импортировать гуиды терминов.
  5.  * Затем запустить import_fields - импортировать гуиды названий полей.
  6.  * после import_logical_fields
  7.  * На крон вешать ./integration --cmd=load
  8.  */
  9. //error_reporting(E_ALL | ~E_WARNING);
  10. //setup global $_SERVER variables to keep WP from trying to redirect
  11. $_SERVER = array(
  12.     "HTTP_HOST" => "http://ordo.local:81",
  13.     "SERVER_NAME" => "http://ordo.local:81",
  14.     "REQUEST_URI" => "/",
  15.     "REQUEST_METHOD" => "GET"
  16. );
  17.  
  18. $username = 'CrmIntegration';
  19. $password = 'crmordogroup';
  20. $serviceUrl = 'https://ordoag.bpmonline.com/0/ServiceModel/EntityDataService.svc/';
  21. $pageSize = 40;
  22. define('ANS_YES', 'да');
  23. define('ANS_NO', 'нет');
  24. define('DEV', false);
  25. ini_set('memory_limit', '512M');
  26.  
  27.  
  28. $DOCUMENT_ROOT = dirname(__FILE__);
  29. //require the WP bootstrap
  30. require_once(dirname(__FILE__).'/wp-load.php');
  31. $timestamp = get_option('update_timestamp');
  32.  
  33. $lastUpdate = date('Y-m-d\TH:i:s', $timestamp);
  34.  
  35.  
  36.  
  37.  
  38.  
  39. function load_handbooks()
  40. {
  41.     global $pageSize,$lastUpdate;
  42.     $listings = array(
  43.         'property-status' => 'https://ordoag.bpmonline.com/0/ServiceModel/EntityDataService.svc/VwListingTypeCollection',
  44.         'agents' => 'https://ordoag.bpmonline.com/0/ServiceModel/EntityDataService.svc/VwOwnerCollection',
  45.         'currencies' => 'https://ordoag.bpmonline.com/0/ServiceModel/EntityDataService.svc/VwCurrencyCollection',
  46.         'property-type' => 'https://ordoag.bpmonline.com/0/ServiceModel/EntityDataService.svc/VwPropertyCategoryCollection',
  47.         'property-city' => 'https://ordoag.bpmonline.com/0/ServiceModel/EntityDataService.svc/VwCityCollection',
  48.         'property-country' => 'https://ordoag.bpmonline.com/0/ServiceModel/EntityDataService.svc/VwCountryCollection',
  49.         'property-new' => 'https://ordoag.bpmonline.com/0/ServiceModel/EntityDataService.svc/VwRealtySaleTypeCollection',
  50.     );
  51.     $currencies_name = array(
  52.         'RUR' => 'Рубль',
  53.         'EUR' => 'Евро',
  54.         'USD' => 'Доллар',
  55.         'CHF' => 'Швейцарский франк',
  56.         'GBP' => 'Фунт стерлингов',
  57.     );
  58.     foreach ($listings as $key => $url) {
  59.         $page = 0;
  60.         do {
  61.             $next = false;
  62.             $method = $url . '?$top=' . $pageSize . '&$skip=' . $page * $pageSize;
  63.             $method .= '&$filter=ModifiedOn%20gt%20DateTime\'' . $lastUpdate . '\'';
  64.             $xml = get_result($method);
  65.             foreach ($xml->children() as $child) {
  66.                 if ($child->getName() != 'entry') {
  67.                     continue;
  68.                 } else {
  69.                     $next = true;
  70.                 }
  71.                 $id = null;
  72.                 $properties = $child->content->children('m', true)->children('d', true);
  73.                 $guid = (string)$properties->Id;
  74.                 $name = (string)$properties->Name;
  75.                 if ($option = get_option($guid)) {
  76.                     $data = unserialize($option);
  77.                     $term = get_term_by('id', $data['id'], $data['taxonomy']);
  78.                     if ($term->name != $name) {
  79.                         wp_update_term($data['id'], $data['taxonomy'], array('name' => $name));
  80.                     }
  81.                 } elseif ($key == 'agents') {
  82.                     // Создаём объект записи
  83.                     $my_post = array(
  84.                         'post_title' => $name,
  85.                         'post_content' => '',
  86.                         'post_type' => 'agent',
  87.                         'post_status' => 'publish',
  88.                         'post_author' => 1,
  89.                     );
  90.                     // Вставляем запись в базу данных
  91.                     $id = wp_insert_post($my_post);
  92.                 } elseif ($key != 'currencies') {
  93.                     $term = wp_insert_term($name, $key);
  94.  
  95.                     if (!$term instanceof WP_Error) {
  96.                         $id = $term['term_id'];
  97.                     } else {
  98.                         $errors = $term->errors;
  99.                         if (array_key_exists('term_exists', $errors)) {
  100.                             $term = get_term_by('name', $name, $key);
  101.                             $id = $term->term_id;
  102.                         } else {
  103.                             print_r($name . ' error' . "\n");
  104.                             print_r($term->errors);
  105.                         }
  106.                     }
  107.                 } else {
  108.                     if (($cur = array_search($name, $currencies_name)) !== false) {
  109.                         $id = $cur;
  110.                     }
  111.                 }
  112.                 if (!empty($id)) {
  113.                     $data = serialize(array('taxonomy' => $key, 'id' => $id));
  114.                     update_option('guid_' . $key . $id, $guid);
  115.                     update_option($guid, $data);
  116.                 }
  117.             }
  118.             unset($xml);
  119.             $page++;
  120.         } while($next);
  121.     }
  122. }
  123.  
  124. function load_gallery()
  125. {
  126.     $url = 'https://ordoag.bpmonline.com/0/ServiceModel/EntityDataService.svc/VwListingGalleryImageCollection';
  127.     global $username, $password, $serviceUrl, $pageSize, $lastUpdate;
  128.  
  129.     $context = stream_context_create(array(
  130.         'http' => array(
  131.             'header'  => "Authorization: Basic " . base64_encode("$username:$password")
  132.         )
  133.     ));
  134.     $uploads = wp_upload_dir();
  135.     if (!is_dir($uploads['path'])) {
  136.         wp_mkdir_p($uploads['path']);
  137.     }
  138.     $postsGallery = array();
  139.     $page = 0;
  140.     do {
  141.         $next = false;
  142.         $method = $url . '?$top=' . $pageSize . '&$skip=' . $page * $pageSize;
  143.         $method .= '&$filter=ModifiedOn%20gt%20DateTime\'' . $lastUpdate . '\'';
  144.         print_r($method . "\n");
  145.         $xml = get_result($method);
  146.         foreach ($xml->children() as $child) {
  147.             try {
  148.                 if ($child->getName() != 'entry') {
  149.                     continue;
  150.                 } else {
  151.                     $next = true;
  152.                 }
  153.  
  154.                 $properties = $child->content->children('m', true)->children('d', true);
  155.                 $href = null;
  156.                 foreach ($child->children() as $field) {
  157.                     if ($field->getName() == 'link' && $field->attributes()->title == 'Data') {
  158.                          $href = $serviceUrl . $field->attributes()->href;
  159.                     }
  160.                 }
  161.  
  162.                 if (!$href) {
  163.                     continue;
  164.                 }
  165.  
  166.                 $fileContent = file_get_contents($href, false, $context);
  167.                 $imageName = (string) $properties->Name;
  168.                 $imageName = !empty($imageName) ? time() . '_' . $imageName : md5((string) $properties->Id . time()) . '.jpg';
  169.                 $imagePath = $uploads['path'] . '/' . $imageName;
  170.                 file_put_contents($imagePath, $fileContent);
  171.                 unset($fileContent);
  172.                 $objectId = (string) $properties->ListingId;
  173.                 $position = (int) $properties->Position;
  174.                 $data = unserialize(get_option($objectId));
  175.                 if (!is_array($data) || empty($data['taxonomy']) || $data['taxonomy'] != 'property') {
  176.                     continue;
  177.                 }
  178.                 $galleryData = unserialize(get_option((string) $properties->Id));
  179.                 $gallery = get_post_meta($data['id'], 'REAL_HOMES_property_images');
  180.  
  181.                 //удаляем изображения не из crm
  182.                 foreach ($gallery as $key => $imageId) {
  183.                     if (!($img = get_option('guid_gallery' . $imageId))) {
  184.                         wp_delete_attachment($imageId, true);
  185.                         unset($gallery[$key]);
  186.                     }
  187.                 }
  188.                 if ( ($key = array_search($galleryData['id'], $gallery)) !== false) {
  189.                     unset($gallery[$key]);
  190.                     wp_delete_attachment($galleryData['id'], true);
  191.                     delete_option('guid_gallery' . $galleryData['id']);
  192.                     delete_option((string) $properties->Id);
  193.                 }
  194.                 delete_post_meta($data['id'], 'REAL_HOMES_property_images');
  195.  
  196.                 foreach ($gallery as $imageId) {
  197.                     add_post_meta($data['id'], 'REAL_HOMES_property_images', $imageId);
  198.                 }
  199.                 $attachment = array(
  200.                     'guid' => $imagePath,
  201.                     'post_mime_type' => 'image/jpeg',
  202.                     'post_title' => preg_replace('/\.[^.]+$/', '', $imageName),
  203.                     'post_content' => '',
  204.                     'post_status' => 'inherit'
  205.                 );
  206.                 $imageId = wp_insert_attachment($attachment, $imagePath, $data['id']);
  207.                 update_post_meta($imageId, 'sort', $position);
  208.                 if (!isset($postsGallery[$data['id']]) && $position == 0) {
  209.                     $postsGallery[$data['id']] = array(
  210.                         'id' => $imageId,
  211.                         'path' => $imagePath,
  212.                     );
  213.                 }
  214.                 add_post_meta($data['id'], 'REAL_HOMES_property_images', $imageId);
  215.                 update_option('guid_gallery' . $imageId, (string)$properties->Id);
  216.                 $data = serialize(array('type' => 'gallery', 'id' => $imageId, 'post_id' => $data['id']));
  217.                 update_option((string)$properties->Id, $data);
  218.  
  219.             } catch (Exception $e) {
  220.                 print_r($e->getMessage());
  221.             }
  222.         }
  223.         unset($xml);
  224.         $page++;
  225.     } while($next);
  226.     echo "gallery images: \n";
  227.     print_r($postsGallery);
  228.     foreach ($postsGallery as $post_id => $image) {
  229.         if (!empty($image['id']) && !empty($image['path'])) {
  230.             set_object_thumbnail($post_id, $image['id'], $image['path']);
  231.         }
  232.     }
  233. }
  234.  
  235.  
  236. function load_files()
  237. {
  238.     $url = 'https://ordoag.bpmonline.com/0/ServiceModel/EntityDataService.svc/VwListingFileCollection';
  239.     global $username, $password, $serviceUrl, $pageSize, $lastUpdate;
  240.     $context = stream_context_create(array(
  241.         'http' => array(
  242.             'header'  => "Authorization: Basic " . base64_encode("$username:$password")
  243.         )
  244.     ));
  245.     $uploads = wp_upload_dir();
  246.     if (!is_dir($uploads['path'])) {
  247.         wp_mkdir_p($uploads['path']);
  248.     }
  249.     $page = 0;
  250.     do {
  251.         $next = false;
  252.         $method = $url . '?$top=' . $pageSize . '&$skip=' . $page * $pageSize;
  253.         $method .= '&$filter=ModifiedOn%20gt%20DateTime\'' . $lastUpdate . '\'';
  254.         $xml = get_result($method);
  255.         foreach ($xml->children() as $child) {
  256.             if ($child->getName() != 'entry') {
  257.                 continue;
  258.             } else {
  259.                 $next = true;
  260.             }
  261.  
  262.             $properties = $child->content->children('m', true)->children('d', true);
  263.             $href = null;
  264.             foreach ($child->children() as $field) {
  265.                 if ($field->getName() == 'link' && $field->attributes()->title == 'Data') {
  266.                     $href = $serviceUrl . $field->attributes()->href;
  267.                 }
  268.             }
  269.             if (!$href) {
  270.                 continue;
  271.             }
  272.             $objectId = (string) $properties->ListingId;
  273.             $data = unserialize(get_option($objectId));
  274.             if (!is_array($data) || empty($data['taxonomy']) || $data['taxonomy'] != 'property') {
  275.                 continue;
  276.             }
  277.             $fileContent = file_get_contents($href, false, $context);
  278.             $fileName = time() . $properties->Name;
  279.             $filePath = $uploads['path'] . '/' . $fileName;
  280.             file_put_contents($filePath, $fileContent);
  281.             unset($fileContent);
  282.  
  283.             $attachmentData = unserialize(get_option((string) $properties->Id));
  284.             $attachments = get_post_meta($data['id'], 'REAL_HOMES_attachments');
  285.  
  286.             foreach ($attachments as $key => $fileId) {
  287.                 if (!($img = get_option('guid_attachment' . $fileId))) {
  288.                     wp_delete_attachment($fileId, true);
  289.                     unset($attachments[$key]);
  290.                 }
  291.             }
  292.             if ( ($key = array_search($attachmentData['id'], $attachments)) !== false) {
  293.                 unset($attachments[$key]);
  294.                 wp_delete_attachment($attachmentData['id'], true);
  295.                 delete_option('guid_attachment' . $attachmentData['id']);
  296.                 delete_option((string) $properties->Id);
  297.             }
  298.             delete_post_meta($data['id'], 'REAL_HOMES_attachments');
  299.  
  300.             foreach ($attachments as $fileId) {
  301.                 add_post_meta($data['id'], 'REAL_HOMES_attachments', $fileId);
  302.             }
  303.             $type = @mime_content_type($filePath);
  304.  
  305.             $attachment = array(
  306.                 'guid' => $filePath,
  307.                 'post_mime_type' => $type,
  308.                 'post_title' => preg_replace('/\.[^.]+$/', '', $fileName),
  309.                 'post_content' => '',
  310.                 'post_status' => 'inherit'
  311.             );
  312.             $fileId = wp_insert_attachment($attachment, $filePath, $data['id']);
  313.             add_post_meta($data['id'], 'REAL_HOMES_attachments', $fileId);
  314.             update_option('guid_attachment' . $fileId, (string)$properties->Id);
  315.             $data = serialize(array('type' => 'attachment', 'id' => $fileId, 'post_id' => $data['id']));
  316.             update_option((string)$properties->Id, $data);
  317.         }
  318.         unset($xml);
  319.         $page++;
  320.     } while($next);
  321. }
  322.  
  323. function load_objects_amenity()
  324. {
  325.     global $pageSize, $lastUpdate, $serviceUrl;
  326.     $url = 'https://ordoag.bpmonline.com/0/ServiceModel/EntityDataService.svc/VwAmenityInObjectCollection';
  327.     $page = 0;
  328.     $arrayToSave = array();
  329.     $notFoundFields = array();
  330.     $notFoundObjects = array();
  331.     do {
  332.         $next = false;
  333.         $method = $url . '?$top=' . $pageSize . '&$skip=' . $page * $pageSize;
  334.         $method .= '&$filter=ModifiedOn%20gt%20DateTime\'' . $lastUpdate . '\'';
  335.         print_r($method . "\n");
  336.         $xml = get_result($method);
  337.         foreach ($xml->children() as $child) {
  338.             if ($child->getName() != 'entry') {
  339.                 continue;
  340.             } else {
  341.                 $next = true;
  342.             }
  343.             $id = null;
  344.             $properties = $child->content->children('m', true)->children('d', true);
  345.             $objectGuid = (string) $properties->ListingId;
  346.             $fieldGuid = (string) $properties->AmenityId;
  347.             $value  = (string) $properties->Value;
  348.             $lookupValue  = (string) $properties->LookupValueId;
  349.             $objectSerialized = get_option($objectGuid);
  350.             $objectData = unserialize($objectSerialized);
  351.  
  352.             if (!is_array($objectData) || !isset($objectData['id'])) {
  353.                 print_r($objectGuid . " object not found \n");
  354.                 print_r($objectData);
  355.                 if (!in_array($objectGuid, $notFoundObjects)) {
  356.                     $notFoundObjects[] = $objectGuid;
  357.                 }
  358.                 continue;
  359.             }
  360.  
  361.             $fieldSerialized = get_option($fieldGuid);
  362.             $fieldData = unserialize($fieldSerialized);
  363.             if (!is_array($fieldData)) {
  364.                 print_r($fieldData." | " .$fieldSerialized. " field not found \n");
  365.                 print_r($fieldGuid . " field not found \n");
  366.                 if (!in_array($fieldGuid, $notFoundFields)) {
  367.                     $notFoundFields[] = $fieldGuid;
  368.                 }
  369.                 continue;
  370.             }
  371.  
  372.             //Текстовые свойства сразу сохраняем
  373.             if (isset($fieldData['type']) && $fieldData['type'] == 'field') {
  374.                 if($fieldGuid == "3db05362-e6e3-4b3f-9c6a-42c3d9b9dbd0"
  375.                         || $fieldGuid == "ADCADD5A-A83E-407D-AAB7-90970CD3E795"){
  376.                     $valueIn = get_post_meta($objectData['id'], $fieldData['name'], true);
  377.                     print_r("sq: ".$valueIn);
  378.                     if($value != "" && $value != $valueIn){
  379.                        update_post_meta($objectData['id'], $fieldData['name'], $value);
  380.                     }
  381.                 }else{
  382.                     update_post_meta($objectData['id'], $fieldData['name'], $value);
  383.                 }
  384.                
  385.             } elseif (isset($fieldData['type']) && $fieldData['type'] == 'taxonomy' && !isGuidEmpty($lookupValue)) {
  386.                 $termSerialized = get_option($lookupValue);
  387.                 $termData = unserialize($termSerialized);
  388.                 if (is_array($termData)){
  389.                     $arrayToSave[$objectData['id']][$fieldData['name']][] = $termData['id'];
  390.                 } else {
  391.                     $href = null;
  392.                     foreach ($child->children() as $field) {
  393.                         if ($field->getName() == 'link' && $field->attributes()->title == 'LookupValue') {
  394.                             $href = $serviceUrl . $field->attributes()->href;
  395.                         }
  396.                     }
  397.                     if (!$href) {
  398.                         continue;
  399.                     }
  400.                     $term_id  = add_new_taxonomy_term($fieldData['name'], $href);
  401.                     if (!is_null($term_id)) {
  402.                         $arrayToSave[$objectData['id']][$fieldData['name']][] = $term_id;
  403.                     }
  404.                 }
  405.             } elseif (isset($fieldData['taxonomy']) && !empty($fieldData['id'])) {
  406.                 if ($value == ANS_YES) {
  407.                     $arrayToSave[$objectData['id']][$fieldData['taxonomy']][] = $fieldData['id'];
  408.                 } elseif (!isset($arrayToSave[$objectData['id']][$fieldData['taxonomy']])) {
  409.                     $arrayToSave[$objectData['id']][$fieldData['taxonomy']] = array();
  410.                 }
  411.             }
  412.         }
  413.         unset($xml);
  414.         $page++;
  415.     } while($next);
  416.     print_r("array to save: \n");
  417.     print_r($arrayToSave);
  418.     print_r("not found objects: \n");
  419.     print_r($notFoundObjects);
  420.     print_r("not found fields: \n");
  421.     print_r($notFoundFields);
  422.     foreach ($arrayToSave as $objectId => $taxonomies) {
  423.         foreach ($taxonomies as $taxonomy => $terms) {
  424.             wp_set_post_terms($objectId, $terms, $taxonomy);
  425.         }
  426.     }
  427. }
  428.  
  429.  
  430. /**
  431.  * @deprecated
  432.  * @param $objectId
  433.  * @param $xml
  434.  * @return bool
  435.  */
  436. function load_object_thumbnail($objectId, $xml)
  437. {
  438.     global $username, $password, $serviceUrl;
  439.     $context = stream_context_create(array(
  440.         'http' => array(
  441.             'header'  => "Authorization: Basic " . base64_encode("$username:$password")
  442.         )
  443.     ));
  444.     $href = null;
  445.     foreach ($xml->children() as $field) {
  446.         if ($field->getName() == 'link' && $field->attributes()->title == 'Photo') {
  447.             $href = $serviceUrl . $field->attributes()->href;
  448.         }
  449.     }
  450.  
  451.     if (!$href) {
  452.         return false;
  453.     }
  454.     $photoXml = get_result($href);
  455.     $photoHref = null;
  456.     foreach ($photoXml->children() as $field) {
  457.         if ($field->getName() == 'link' && $field->attributes()->title == 'Data') {
  458.  
  459.             $photoHref = $serviceUrl . $field->attributes()->href;
  460.  
  461.  
  462.         }
  463.     }
  464.  
  465.     if (!$photoHref) {
  466.         return false;
  467.     }
  468.     $uploads = wp_upload_dir();
  469.     $properties = $photoXml->content->children('m', true)->children('d', true);
  470.     $fileContent = file_get_contents($photoHref, false, $context);
  471.     if (empty($fileContent)) {
  472.         print_r($photoHref . " preview is empty\n");
  473.         return false;
  474.     }
  475.  
  476.     $imageName = md5((string) $properties->Id . time()) . '.jpg';
  477.     $imagePath = $uploads['path'] . '/' . $imageName;
  478.     file_put_contents($imagePath, $fileContent);
  479.     unset($fileContent);
  480.  
  481.     $attachment = array(
  482.         'guid' => $imagePath,
  483.         'post_mime_type' => 'image/jpeg',
  484.         'post_title' => preg_replace('/\.[^.]+$/', '', $imageName),
  485.         'post_content' => '',
  486.         'post_status' => 'inherit'
  487.     );
  488.     $attach_id = wp_insert_attachment( $attachment, $imagePath, $objectId );
  489.     require_once(ABSPATH . 'wp-admin/includes/image.php');
  490.     $attach_data = wp_generate_attachment_metadata( $attach_id, $imagePath );
  491.     wp_update_attachment_metadata( $attach_id, $attach_data );
  492.  
  493.     set_post_thumbnail( $objectId, $attach_id );
  494.     return true;
  495. }
  496.  
  497. /**
  498.  * Получает изменения с момента $lastUpdate
  499.  */
  500. function load_posts()
  501. {
  502.     mail("zhirnovvlad@gmail.com,irina.sorokina@ordogroup.ru", "ordogroup.ru: Началось обнолвение объектов.", "");
  503.     clearTmpImportIds();
  504.     $time_start = time();
  505.     global $pageSize, $lastUpdate;
  506.     load_handbooks();
  507.     print_r($lastUpdate . "\n");
  508.  
  509.     echo "handbooks ready\n";
  510.     $url = 'https://ordoag.bpmonline.com/0/ServiceModel/EntityDataService.svc/VwListingExportCollection';
  511.     $siteCurrencies = currencies_array();
  512.     $page = 0;
  513.     do {
  514.         $next = false;
  515.         $method = $url . '?$top=' . $pageSize . '&$skip=' . $page * $pageSize;
  516.         $method .= '&$filter=ModifiedOn%20gt%20DateTime\'' . $lastUpdate . '\'';
  517.         $xml = get_result($method);
  518.         try {
  519.             if(is_object($xml) && is_object($xml->children())){
  520.               foreach ($xml->children() as $child) {
  521.             try {
  522.                 if ($child->getName() != 'entry') {
  523.                     continue;
  524.                 } else {
  525.                     $next = true;
  526.                 }
  527.                 $postId = null;
  528.                 $properties = $child->content->children('m', true)->children('d', true);
  529.                 if (!isGuidEmpty((string) $properties->Id) && $data = get_option((string) $properties->Id)) {
  530.                     $data = unserialize($data);
  531.                     if ($data['taxonomy'] == 'property') {
  532.                         $postId = $data['id'];
  533.                     }
  534.                 }
  535.                 $id = (string) $properties->UsrNumberOfListing;
  536.                 insertTmpImportId($id);
  537.                 $load = (string) $properties->IsExportOnSite;
  538.                 $status = $load == 'true' ? 'publish' : 'draft';
  539.                
  540.                 $post = null;
  541.                 if (!empty($postId)) {
  542.                     $post = get_post($postId);
  543.                 }
  544.                 $new = false;
  545.                
  546.                 if (!$post instanceof WP_Post) {
  547.                         $args = array(
  548.                             'post_type' => 'property',
  549.                             'posts_per_page' => -1,
  550.                             'meta_query' => array(
  551.                                 array(
  552.                                     'key' => 'REAL_HOMES_property_id',
  553.                                     'value' => $id,
  554.                                     'compare' => '=',
  555.                                 )
  556.                             )
  557.                         );
  558.                         $query = new WP_Query($args);
  559.  
  560.                         if ($query->have_posts()) {
  561.                             $post = $query->post;
  562.                         } else {
  563.                             if ($status == "draft") {
  564.                                     continue;
  565.                                 }
  566.                             $my_post = array(
  567.                                 'post_title' => (string)$properties->Name,
  568.                                 'post_content' => (string)$properties->Description,
  569.                                 'post_type' => 'property',
  570.                                 'post_status' => $status,
  571.                                 'post_author' => 1,
  572.                             );
  573.                             // Вставляем запись в базу данных
  574.                             $postId = wp_insert_post($my_post);
  575.                             if (!($postId instanceof WP_Error)) {
  576.                                 $post = get_post($postId);
  577.                                 echo "NEW: ".$id;
  578.                             } else {
  579.                                 echo "Error adding post: ".$id." - ".$postId->get_error_message();
  580.                                 continue;
  581.                             }
  582.                             $new = true;
  583.                         }
  584.                     }
  585.                
  586.                
  587.                     update_option('guid_property' . $post->ID, (string) $properties->Id);
  588.                     $data = serialize(array('taxonomy' => 'property', 'id' => $post->ID));
  589.                     update_option((string) $properties->Id, $data);
  590.                     $post->post_title = (string) $properties->Name;
  591.                     $post->post_content = (string) $properties->Description;
  592.                     $post->post_status = $status;
  593.                     update_post_option($post->ID, (string) $properties->PropertyCategoryId);
  594.                     update_post_option($post->ID, (string) $properties->ListingTypeId);
  595.                     update_post_option($post->ID, (string) $properties->CityId);
  596.                     update_post_option($post->ID, (string) $properties->CountryId);
  597.                     update_post_option($post->ID, (string) $properties->UsrRealtySaleTypeId);
  598.                     update_post_option($post->ID, (string) $properties->OwnerId);
  599.                     update_post_meta($post->ID, 'REAL_HOMES_property_address', (string) $properties->Address);
  600.                     update_post_meta($post->ID, 'REAL_HOMES_property_card_legend', (string) $properties->UsrDescription2);
  601.                     update_post_meta($post->ID, 'REAL_HOMES_price_request', ((string) $properties->IsRequestPrice == 'true'));
  602.                     update_post_meta($post->ID, 'REAL_HOMES_show_on_main', ((string) $properties->IsShowOnMain == 'true'));
  603.                     update_post_meta($post->ID, 'REAL_HOMES_property_location', (string) $properties->Latitude . ',' . (string) $properties->Longitude);
  604.                     update_post_meta($post->ID, 'REAL_HOMES_property_id', $id);
  605.                     $curr = (string) $properties->CurrencyId;
  606.                     if ($new) {
  607.                         update_post_meta($post->ID, 'REAL_HOMES_gallery_slider_type', 'thumb-on-bottom');
  608.                     }
  609.                     if (!isGuidEmpty($curr) && $currencyData = get_option($curr)) {
  610.                         $currencyData = unserialize($currencyData);
  611.                         if ($currencyData['taxonomy'] == 'currencies') {
  612.                             $main_currency = $currencyData['id'];
  613.                             $id = array_search($main_currency, $siteCurrencies);
  614.                             if ($id !== false && $main_currency) {
  615.                                 update_post_meta($post->ID, 'REAL_HOMES_property_main_currency', $id);
  616.                                 update_post_meta($post->ID, 'REAL_HOMES_property_' . strtolower($main_currency) . '_price', (string) $properties->Price);
  617.                             }
  618.                         }
  619.                     }
  620.                     wp_update_post($post);
  621.                     if ($new) {
  622.                         print_r($post->ID . " created, guid: " . (string) $properties->Id . " \n");
  623.                     } else {
  624.                         print_r($post->ID . " updated, guid: " . (string) $properties->Id . " \n");
  625.                     }
  626.                
  627.             } catch (Exception $e) {
  628.                 print_r($e->getMessage());
  629.             }
  630.         }
  631.             }
  632.         } catch (Exception $exc) {
  633.         echo $exc->getTraceAsString ();
  634.         }
  635.  
  636.        
  637.        
  638.         unset($xml);
  639.         $page++;
  640.     } while($next);
  641.     //die();
  642.  
  643.     load_objects_amenity();
  644.     if(!DEV){
  645.       load_gallery();
  646.       mail("zhirnovvlad@gmail.com", "ordogroup.ru: Выгрузка завершена галерея.", "");
  647.    
  648.       load_files();
  649.     }
  650.     mail("zhirnovvlad@gmail.com", "ordogroup.ru: Выгрузка завершена.", "");
  651.    
  652.     update_option('update_timestamp', $time_start);
  653. }
  654.  
  655. function get_result($url) {
  656.     global $username, $password;
  657.     if ($ch = curl_init($url)) {
  658.         curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
  659.         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
  660.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  661.         $result = curl_exec($ch);
  662.         curl_close($ch);
  663.         $result  = preg_replace('/&#x[0-1]?[0-9A-E]/', ' ', $result);
  664.         return simplexml_load_string(stripInvalidXml($result));
  665.     }
  666.     return false;
  667. }
  668.  
  669. function stripInvalidXml($value)
  670. {
  671.     $ret = "";
  672.     $current;
  673.     if (empty($value))
  674.     {
  675.         return $ret;
  676.     }
  677.  
  678.     $length = strlen($value);
  679.     for ($i=0; $i < $length; $i++)
  680.     {
  681.         $current = ord($value{$i});
  682.         if (($current == 0x9) ||
  683.             ($current == 0xA) ||
  684.             ($current == 0xD) ||
  685.             (($current >= 0x20) && ($current <= 0xD7FF)) ||
  686.             (($current >= 0xE000) && ($current <= 0xFFFD)) ||
  687.             (($current >= 0x10000) && ($current <= 0x10FFFF)))
  688.         {
  689.             $ret .= chr($current);
  690.         }
  691.         else
  692.         {
  693.             $ret .= " ";
  694.         }
  695.     }
  696.     return $ret;
  697. }
  698.  
  699.  
  700. $args = parseArgs($argv);
  701. $importer = new WP_Command_Line();
  702. $importer->main($args);
  703.  
  704. function parseArgs($argv){
  705.     array_shift($argv);
  706.     $out = array();
  707.     foreach ($argv as $arg){
  708.         if (substr($arg,0,2) == '--'){
  709.             $eqPos = strpos($arg,'=');
  710.             if ($eqPos === false){
  711.                 $key = substr($arg,2);
  712.                 $out[$key] = isset($out[$key]) ? $out[$key] : true;
  713.             } else {
  714.                 $key = substr($arg,2,$eqPos-2);
  715.                 $out[$key] = substr($arg,$eqPos+1);
  716.             }
  717.         } else if (substr($arg,0,1) == '-'){
  718.             if (substr($arg,2,1) == '='){
  719.                 $key = substr($arg,1,1);
  720.                 $out[$key] = substr($arg,3);
  721.             } else {
  722.                 $chars = str_split(substr($arg,1));
  723.                 foreach ($chars as $char){
  724.                     $key = $char;
  725.                     $out[$key] = isset($out[$key]) ? $out[$key] : true;
  726.                 }
  727.             }
  728.         } else {
  729.             $out[] = $arg;
  730.         }
  731.     }
  732.     return $out;
  733. }
Add Comment
Please, Sign In to add comment