Пример #1
0
function translateOneNode($currentNodeID, $to_languages, $content_type)
{
    global $db, $XMLarray, $error_log;
    $separator = "7543545165934149";
    // Fetch a node from Drupal if a copy does not already exist in sources dir.
    //  $xml_MASTER is the original English-language version
    //  $xml is the copy that will be translated
    $fn = getcwd() . "/sources/SOURCE_" . $currentNodeID . ".XML";
    if (file_exists($fn)) {
        $xml_MASTER = file_get_contents($fn);
        if ($content_type == "page") {
            // Remove <teaser> from "page". The "teaser" is created by truncating the <body>, resulting in invalid XML
            $xml_MASTER = preg_replace("|<teaser>.*?</teaser>|us", "<teaser></teaser>", $xml_MASTER);
        }
    } else {
        $xml_MASTER = fetchOneNode($currentNodeID);
        if ($content_type == "page") {
            $xml_MASTER = preg_replace("|<teaser>.*?</teaser>|us", "<teaser></teaser>", $xml_MASTER);
        }
        $fh = fopen($fn, "w");
        fwrite($fh, $xml_MASTER);
        fclose($fh);
    }
    foreach ($to_languages as $to_language) {
        $query = "select drupal_code from sovee.languages where sovee_code = '" . $to_language . "'";
        $result = mysql_query($query, $db);
        while ($row = mysql_fetch_assoc($result)) {
            $drupalLanguageCode = $row['drupal_code'];
        }
        mysql_free_result($result);
        echo "\n=====================================================================================\n==========                                                                 ==========\n. . . Translating node {$currentNodeID} ({$content_type}) into {$to_language}  . . . \n";
        $error_IncompleteNodeFlag = 0;
        $xml = $xml_MASTER;
        // Create a copy of the master, to be translated
        // Convert XML to array
        $XMLarray = XML2Array::createArray($xml);
        // Get info about the node
        //      Requested info is placed in the $requestedTags array
        //      and returned in the assoc. array info()
        $requestedTags = array("type", "tnid");
        $info = getXMLinfo($xml, $requestedTags);
        $derivedContentType = $info['type'];
        // Build list of containers to parse for the given content_type.
        $query = "select DISTINCT sovee.node_fields.name from sovee.content_type \nLEFT JOIN sovee.field_map ON sovee.content_type.id = sovee.field_map.content_id\nLEFT JOIN sovee.node_fields ON sovee.node_fields.id = sovee.field_map.field_id\nWHERE sovee.content_type.name = '" . $derivedContentType . "'";
        $result = mysql_query($query, $db);
        while ($row = mysql_fetch_assoc($result)) {
            $containerArrayTemplate[] = $row['name'];
        }
        mysql_free_result($result);
        // Walk throught the array, extract the specified containers, translate
        // and replace in the array
        // All array elements are assumed to be in the [node_export][node] array
        //  $containerArrayTemplate = array("body", "title", "teaser", "field_product_subtitle|n*|value", "field_warranty|n*|value", "field_product_education|n*|value",
        // 		 	"field_prod_man_docs_link|n*|title",
        //                       "field_did_you_know|n*|value", "field_product_benefits|n*|value",  "nodewords|copyright|value", "nodewords|dcterms.contributor|value",
        //		        "nodewords|dcterms.title|value", "nodewords|description|value", "nodewords|keywords|value" );
        $containerArray = expandTemplate($containerArrayTemplate);
        $allContainers = "<div>{$separator}";
        foreach ($containerArray as $oneContainer) {
            echo "\nProcessing container {$oneContainer}\n";
            $parents = explode("|", $oneContainer);
            array_unshift($parents, "node_export", "node");
            #echo "Parents: ";
            #print_r($parents);
            $XMLfragment = drupal_array_get_nested_value($XMLarray, $parents);
            if (is_array($XMLfragment)) {
                $XMLfragment = "";
            }
            $translatedFragment = "";
            $patterns = array("|^<div>|us", "|</div>\$|us");
            // The "|u" flag enables multibyte support
            $replacements = array("", "");
            if (strlen(trim($XMLfragment)) > 0 and !is_array($XMLfragment)) {
                $XMLfragment = "<div>" . $XMLfragment . "</div>";
                // Encapsulate in dummy <div> to satisfy Sovee translator
                // echo "ORIGINAL Fragment = |$XMLfragment|\n";
            } else {
                echo "Original Fragment |{$XMLfragment}| is empty -- skipping.\n";
            }
            $allContainers .= $XMLfragment . $separator;
            // Add at the end of each container to faciliate preg_split
        }
        //   -------  End of foreach($containerArray as $oneContainer)
        $allContainers .= "</div>";
        // Translate the entire node if target language is not English
        echo "TO_LANGUAGE = {$to_language}\n";
        $xxx = substr($to_language, 0, 2);
        echo "SUBSTR = |{$xxx}|\n";
        $sovee_to_language = $to_language;
        if (substr($to_language, 0, 2) != "en") {
            if ($to_language == "es-419") {
                $sovee_to_language = "es-es";
            }
            // Use standard Spanish for Latin America
            echo "Sending strings to Sovee . . . \n";
            $translatedFragmentAry = translateFrag($allContainers, $currentNodeID, "FULL NODE", $to_language);
            // Perform the translation
            $translatedFragment = $translatedFragmentAry['content'];
            $translatedFragmentError = $translatedFragmentAry['error_count'];
            // Count of translation errors.  0 = success
            $error_IncompleteNodeFlag += $translatedFragmentError;
        } else {
            echo "English-to-English: No translation needed.\n";
            $translatedFragment = $allContainers;
            $translatedFragmentError = 0;
        }
        // print_r($translatedFragmentAry);
        $separatorPattern = "/{$separator}/u";
        $translatedNodeAry = preg_split($separatorPattern, $translatedFragment);
        // print_r($translatedNodeAry);
        $translatedContentPointer = 1;
        reset($containerArray);
        foreach ($containerArray as $oneContainer) {
            $parents = explode("|", $oneContainer);
            array_unshift($parents, "node_export", "node");
            $stripped = trim(preg_replace($patterns, $replacements, $translatedNodeAry[$translatedContentPointer]));
            // Remove the leading and trailing <div>s from the node fragments
            // Special handling for page_title, which can be a string or an array
            if ($oneContainer == "page_title" and $stripped == "Array") {
                $pageTitleParents1 = array('node_export', 'node', 'page_title', 'value');
                $pageTitleParents2 = array('node_export', 'node', 'page_title', 'attributes', 'type');
                drupal_array_set_nested_value($XMLarray, $pageTitleParents1, "FALSE");
                drupal_array_set_nested_value($XMLarray, $pageTitleParents2, "boolean");
            } else {
                if (strlen($stripped) > 0) {
                    drupal_array_set_nested_value($XMLarray, $parents, $stripped);
                }
            }
            $translatedContentPointer++;
        }
        // HTML-Encode any info in the <data> container
        // $dataParents = array('node_export', 'node', 'data');
        // $dataFragment =  htmlentities(drupal_array_get_nested_value($XMLarray, $dataParents));
        // drupal_array_set_nested_value($XMLarray, $dataParents, $dataFragment);
        #echo "TRANSLATED XML ARRAY:";
        #print_r($XMLarray);
        // Does an older version of this translated node exist?
        //	If yes, return the node# and alias in an array
        //	otherwise, $oldNodeID_ary['number'] == ''
        $oldNodeID_ary = findOldTranslation($currentNodeID, $to_language);
        $oldNodeID = $oldNodeID_ary['number'];
        $oldNodeIDalias = $oldNodeID_ary['url_alias'];
        if ($oldNodeID != "") {
            echo "\nFound old node number -- old={$oldNodeID}\n";
        }
        if ($oldNodeIDalias != "") {
            echo "\nFound old node number alias -- old={$oldNodeIDalias}\n";
        }
        // Update the nid and tnid fields
        //    For new nodes, nid=''
        //    and tnid = the current nid value
        $XMLarray['node_export']['node']['tnid'] = $currentNodeID;
        $XMLarray['node_export']['node']['nid'] = $oldNodeID;
        // $XMLarray['node_export']['node']['language'] = $oldNodeID['drupal_lang_code'];
        $XMLarray['node_export']['node']['language'] = $drupalLanguageCode;
        // // // $XMLarray['node_export']['node']['path'] = $oldNodeID['url_alias'];
        if (isset($XMLarray['node_export']['node']['xmlsitemap']['language'])) {
            //	$XMLarray['node_export']['node']['xmlsitemap']['language'] = $oldNodeID['drupal_lang_code'];
            $XMLarray['node_export']['node']['xmlsitemap']['language'] = $drupalLanguageCode;
        }
        //echo "XMLARRAY = \n";
        //print_r($XMLarray);
        $FOO = $XMLarray['node_export']['node']['nodewords']['location']['latitude'];
        $BAR = $XMLarray['node_export']['node']['nodewords']['location']['longitude'];
        echo "FOO = {$FOO}\nBAR = {$BAR}\n";
        // If lat or long > 8 chars, set to zero, otherwise node will not import
        if (isset($XMLarray['node_export']['node']['nodewords']['location']['latitude'])) {
            if (strlen($XMLarray['node_export']['node']['nodewords']['location']['latitude']) > 8) {
                $XMLarray['node_export']['node']['nodewords']['location']['latitude'] = 0;
            }
        }
        if (isset($XMLarray['node_export']['node']['nodewords']['location']['longitude'])) {
            if (strlen($XMLarray['node_export']['node']['nodewords']['location']['longitude']) > 8) {
                $XMLarray['node_export']['node']['nodewords']['location']['longitude'] = 0;
            }
        }
        // Adjust the menu references
        $this_plid = $XMLarray['node_export']['node']['menu']['plid'];
        $this_menu_name = $XMLarray['node_export']['node']['menu']['menu_name'];
        if ($this_menu_name == "primary-links") {
            $mquery = "SELECT t_menuid from sovee.menus LEFT JOIN sovee.languages on sovee.menus.language_code = sovee.languages.id  WHERE drupal_code = \"" . $drupalLanguageCode . "\" and Eng_menuid = \"" . $this_plid . "\"";
            echo "MQ = {$mquery}\n";
            $rmquery = mysql_query($mquery, $db);
            $err_msg = trim(mysql_error($db));
            if (strlen($err_msg) > 0) {
                echo "{$mquery}\n{$err_msg}\n\n\n";
            }
            while ($m1 = mysql_fetch_assoc($rmquery)) {
                $newPlid = $m1['t_menuid'];
                $XMLarray['node_export']['node']['menu']['plid'] = $newPlid;
            }
            mysql_free_result($rmquery);
        }
        // Convert array back to XML
        $encoding = "UTF-8";
        $xmlVersion = "1.0";
        Array2XML::init($xmlVersion, $encoding);
        $xmlobj = Array2XML::createXML('DELETE_ME', $XMLarray);
        // Convert a PHP array to XML, using 'DELETE_ME' as the root_node_name
        $translated_xml = $xmlobj->saveXML();
        //  Returned object is of type DOMDocument
        $translated_xml = preg_replace("/<[\\/]?DELETE_ME>[\n]/u", "", $translated_xml);
        $fn = getcwd() . "/TRANSLATED_" . $drupalLanguageCode . "_" . $currentNodeID . ".XML";
        echo "WRITING {$fn}\n";
        $fh = fopen($fn, "w");
        fwrite($fh, $translated_xml);
        fclose($fh);
        // If node translation was successful,
        // import the translated node back into Drupal
        if ($error_IncompleteNodeFlag == 0) {
            $cmd = "/usr/bin/drush --root=/var/www/pressflow node-export-import --file={$fn}";
            echo "COMMAND = {$cmd}\n";
            $success = `{$cmd}`;
            $error = "DRUSH IMPORT RESULTS: {$success}\n";
            echo $error;
            fwrite($error_log, $error);
            $cmd = "/bin/rm {$fn}";
            #$success = `$cmd`;
            $q1 = "INSERT INTO sovee.progress (node, status, type, language) VALUES(\"" . $currentNodeID . "\", \"1\", \"" . $derivedContentType . "\", \"" . $to_language . "\") ON DUPLICATE KEY UPDATE status=VALUES(status)";
            echo "Q1={$q1}\n";
            $r1 = mysql_query($q1, $db);
        } else {
            $error = "Node {$currentNodeID} ({$content_type}) not completely translated. Not importing into Drupal.\n";
            echo $error;
            $q1 = "INSERT INTO sovee.progress (node, status, type, language) VALUES(\"" . $currentNodeID . "\", \"0\", \"" . $derivedContentType . "\", \"" . $to_language . "\")  ON DUPLICATE KEY UPDATE status=VALUES(status)";
            $r1 = mysql_query($q1, $db);
            $err_msg = trim(mysql_error($db));
            if (strlen($err_msg) > 0) {
                echo "{$q1}\n{$err_msg}\n\n\n";
            }
            fwrite($error_log, $error);
        }
        echo "==========                                                                 ==========\n=====================================================================================\n";
    }
    $translated_xml_array = array('status' => $error_IncompleteNodeFlag, 'translated_xml' => $translated_xml);
    return $translated_xml_array;
}
Пример #2
0
 /**
  * {@inheritdoc}
  */
 public function postBuild(array &$build, \Drupal\openlayers\Types\ObjectInterface $context = NULL)
 {
     $component = array('#type' => 'fieldset', '#title' => 'Geofield component', '#attributes' => array('id' => 'geofield-' . $context->getId()));
     $action_feature = $type_of_feature = $this->getOption('actionFeature');
     if (count($action_feature) > 1) {
         $component['actionFeature'] = array('#type' => 'select', '#title' => 'Type of interaction', '#options' => array_intersect_key(array('draw' => t('Draw'), 'modify' => t('Modify')), $action_feature), '#attributes' => array('class' => array('action-feature')));
     } else {
         $component['actionFeature'] = array('#type' => 'hidden', '#default_value' => reset($action_feature), '#attributes' => array('class' => array('action-feature')));
     }
     $data_type = $this->getOption('dataType');
     if (count($data_type) > 1) {
         $component['dataType'] = array('#type' => 'select', '#title' => 'Data type', '#options' => array_intersect_key(array('GeoJSON' => 'GeoJSON', 'KML' => 'KML', 'GPX' => 'GPX', 'WKT' => 'WKT'), $data_type), '#attributes' => array('class' => array('data-type')));
     } else {
         $component['dataType'] = array('#type' => 'hidden', '#default_value' => reset($data_type), '#value' => reset($data_type), '#attributes' => array('class' => array('data-type')));
     }
     $type_of_feature = $this->getOption('typeOfFeature');
     if (count($type_of_feature) > 1) {
         $component['typeOfFeature'] = array('#type' => 'select', '#title' => 'Geometry type', '#options' => array_intersect_key(array('Point' => t('Point'), 'LineString' => t('LineString'), 'Polygon' => t('Polygon')), $type_of_feature), '#attributes' => array('id' => 'typeOfFeature', 'class' => array('type-of-feature')));
     } else {
         $component['typeOfFeature'] = array('#type' => 'hidden', '#default_value' => reset($type_of_feature), '#value' => reset($type_of_feature), '#attributes' => array('class' => array('type-of-feature')));
     }
     $component['clearmap'] = array('#markup' => '<a href="#" class="clearmap">' . t('Clear the map') . '</a>');
     $component['data'] = array('#type' => $this->getOption('showInputField') ? 'textarea' : 'hidden', '#title' => 'Data', '#attributes' => array('class' => array('openlayers-geofield-data')), '#default_value' => $this->getOption('initialData'), '#value' => $this->getOption('initialData'));
     // Now add the component into the build array. This is a bit complex due
     // the fact that we want to support form nesting.
     $build = array('map' => $build);
     $parents = array('geofield', 'component');
     $data_input_field_name = $this->getOption('inputFieldName');
     if (!empty($data_input_field_name)) {
         $data_input_field_name = preg_replace('/(^\\[|\\]$)/', '', $data_input_field_name);
         $levels = explode('][', $data_input_field_name);
         $parents = array_slice(explode('][', $data_input_field_name), 0, count($levels) - 1);
         // Ensure the requested name for the input data field is set.
         $component[end($levels)] = $component['data'];
         unset($component['data']);
     }
     if (!empty($parents)) {
         drupal_array_set_nested_value($build, $parents, $component);
     } else {
         $build += $component;
     }
 }
Пример #3
0
 /**
  * {@inheritdoc}
  */
 public function postBuild(array &$build, ObjectInterface $context = NULL)
 {
     $component = array('#type' => 'container', '#attributes' => array('id' => 'openlayers-geofield-' . $context->getId()));
     $data_type = $this->getOption('dataType', array('WKT' => 'WKT'));
     if (count($data_type) > 1) {
         $component['dataType'] = array('#type' => 'select', '#title' => 'Data type', '#options' => array_intersect_key(array('WKT' => 'WKT', 'GeoJSON' => 'GeoJSON', 'KML' => 'KML', 'GPX' => 'GPX'), $data_type), '#attributes' => array('class' => array('data-type')), '#default_value' => $data_type);
     } else {
         $component['dataType'] = array('#type' => 'hidden', '#default_value' => reset($data_type), '#value' => reset($data_type), '#attributes' => array('class' => array('data-type')));
     }
     $geom = $this->initialDataToGeomFeatures();
     $wkt = '';
     if (!empty($geom['geom'])) {
         $wkt = $geom['geom']->out('wkt');
     }
     $component['data'] = array('#type' => $this->getOption('showInputField') ? 'textarea' : 'hidden', '#title' => 'Data', '#attributes' => array('class' => array('openlayers-geofield-data')), '#default_value' => $wkt, '#value' => $wkt);
     // Now add the component into the build array. This is a bit complex due
     // the fact that we want to support form nesting.
     $parents = array('geofield', 'component');
     $data_input_field_name = $this->getOption('inputFieldName');
     if (!empty($data_input_field_name)) {
         $data_input_field_name = preg_replace('/(^\\[|\\]$)/', '', $data_input_field_name);
         $levels = explode('][', $data_input_field_name);
         $parents = array_slice(explode('][', $data_input_field_name), 0, count($levels) - 1);
         // Ensure the requested name for the input data field is set.
         $component[end($levels)] = $component['data'];
         unset($component['data']);
     }
     if (!empty($parents)) {
         drupal_array_set_nested_value($build, $parents, $component);
     } else {
         $build += $component;
     }
 }
Пример #4
0
/**
 * Perform alterations on the field form elements provide by a field module.
 *
 * Modules can implement hook_commerce_bpc_MODULE_NAME_form_element_alter()
 * to act only on the form elements provided by field types defined by a
 * specific module, rather than implementing
 * hook_commerce_bpc_form_element_alter() and checking the field type, or
 * using long switch statements to alter form elements of multiple field
 * types.
 *
 * This hook is particularly useful in case the field-defining module
 * defines several similar field type which essentially are to be
 * treated identically during bulk creation (such as core's list.module),
 * which would require multiple identical implementations of
 * hook_commerce_bpc_FIELD_TYPE_form_element_alter().
 *
 * @param array $form
 *   Nested array of form elements that comprise the bulk creation form.
 * @param array $form_state
 *   A keyed array containing the current state of the form.
 * @param array $path
 *   An array of keys specifying where in the form the current element
 *   is to be found. This should be reset if the element is moved.
 *
 * @see hook_commerce_bpc_form_element_alter()
 * @see hook_commerce_bpc_FIELD_TYPE_form_element_alter()
 */
function hook_commerce_bpc_MODULE_NAME_form_element_alter(&$form, &$form_state, $path)
{
    // Modification for form elements related to field types defined by a
    // specific module go here. For example, MODULE_NAME is "list" this code will
    // run only on fields of type "list_text", "list_integer", "list_float" and
    // "list_boolean".
    $element = drupal_array_get_nested_value($form, $path);
    $lang = $element['#language'];
    $field_name = $element[$lang]['#field_name'];
    $instance = field_info_instance('commerce_product', $field_name, $form['product_type']['#value']);
    if (commerce_bpc_commerce_bpc_is_combination_field($instance)) {
        $element[$lang]['#type'] = 'checkboxes';
        // Get rid of 'none' option---user can just not pick any.
        unset($element[$lang]['#options']['_none']);
        // Move to comibinations-fieldset.
        $form['combinations'][$field_name] = $element;
        drupal_array_set_nested_value($form, $path, NULL);
        // Change path to allow subsequent hooks operate on the form element.
        $path = array('combinations', $field_name);
        if (empty($form_state['commerce_bpc']['list']['combination_fields']) || !in_array($field_name, $form_state['commerce_bpc']['list']['combination_fields'])) {
            // Record what we have done. As this hook may be run multiple times
            // due to form rebuilds, we need to make sure that we record each field
            // only once.
            $form_state['commerce_bpc']['list']['combination_fields'][] = $field_name;
        }
    }
}