Example #1
0
 public function unformatField($formattedField, $vardef)
 {
     if ($formattedField === '' || $formattedField === NULL) {
         return null;
     }
     return (double) unformat_number($formattedField);
 }
Example #2
0
 public function unformatField($formattedField, $vardef)
 {
     if ($formattedField === '' || $formattedField === NULL) {
         return '';
     }
     return (int) unformat_number($formattedField);
 }
Example #3
0
 function saveListItems()
 {
     require_once 'modules/AOS_Products_Quotes/AOS_Products_Quotes.php';
     $productQuote = new AOS_Products_Quotes();
     $product = array('id' => $_POST['product_quote_id'], 'product_id' => $_POST['product_id'], 'product_name' => $_POST['product_name'], 'product_qty' => $_POST['product_qty'], 'vat' => $_POST['vat'], 'vat_amt' => $_POST['vat_amt'], 'product_list_price' => $_POST['product_list_price'], 'product_unit_price' => $_POST['product_unit_price'], 'product_total_price' => $_POST['product_total_price'], 'product_note' => $_POST['product_note'], 'deleted' => $_POST['deleted']);
     $productLineCount = count($product['product_id']);
     for ($i = 0; $i < $productLineCount; $i++) {
         $productQuote->id = $product['id'][$i];
         $productQuote->parent_id = $this->id;
         $productQuote->parent_type = 'AOS_Invoices';
         $productQuote->product_id = $product['product_id'][$i];
         $productQuote->name = $product['product_name'][$i];
         $productQuote->product_qty = $product['product_qty'][$i];
         $productQuote->product_list_price = unformat_number($product['product_list_price'][$i]);
         $productQuote->product_unit_price = unformat_number($product['product_unit_price'][$i]);
         $productQuote->vat = $product['vat'][$i];
         $productQuote->vat_amt = unformat_number($product['vat_amt'][$i]);
         $productQuote->product_total_price = unformat_number($product['product_total_price'][$i]);
         $productQuote->description = $product['product_note'][$i];
         $productQuote->deleted = $product['deleted'][$i];
         if ($productQuote->deleted == 1) {
             $productQuote->mark_deleted($productQuote->id);
         } else {
             if (trim($productQuote->product_id) != '') {
                 $productQuote->save();
             }
         }
     }
 }
 function ReadData($targetstring, &$map, &$item)
 {
     $data[IN] = NULL;
     $data[OUT] = NULL;
     $data_time = 0;
     $itemname = $item->name;
     $matches = 0;
     $fd = fopen($targetstring, "r");
     if ($fd) {
         while (!feof($fd)) {
             $buffer = fgets($fd, 4096);
             # strip out any Windows line-endings that have gotten in here
             $buffer = str_replace("\r", "", $buffer);
             if (preg_match("/^{$itemname}\t(\\d+\\.?\\d*[KMGT]*)\t(\\d+\\.?\\d*[KMGT]*)/", $buffer, $matches)) {
                 $data[IN] = unformat_number($matches[1]);
                 $data[OUT] = unformat_number($matches[2]);
             }
         }
         $stats = stat($targetstring);
         $data_time = $stats['mtime'];
     } else {
         // some error code to go in here
         debug("TabText ReadData: Couldn't open ({$targetstring}). \n");
     }
     debug("TabText ReadData: Returning (" . ($data[IN] === NULL ? 'NULL' : $data[IN]) . "," . ($data[OUT] === NULL ? 'NULL' : $data[OUT]) . ",{$data_time})\n");
     return array($data[IN], $data[OUT], $data_time);
 }
Example #5
0
function perform_save(&$focus)
{
    //US DOLLAR
    if (isset($focus->amount) && !number_empty($focus->amount)) {
        $currency = new Currency();
        $currency->retrieve($focus->currency_id);
        $focus->amount_usdollar = $currency->convertToDollar(unformat_number($focus->amount));
    }
}
function perform_save(&$focus)
{
    require_once 'modules/Currencies/Currency.php';
    //US DOLLAR
    if (isset($focus->price) && !number_empty($focus->price)) {
        $currency = new Currency();
        $currency->retrieve($focus->currency_id);
        $focus->price_usdollar = $currency->convertToDollar(unformat_number($focus->price));
    }
}
Example #7
0
 public function unformatField($formattedField, $vardef)
 {
     if ($formattedField === '' || $formattedField === NULL) {
         return '';
     }
     if (is_array($formattedField)) {
         $formattedField = array_shift($formattedField);
     }
     return (double) unformat_number($formattedField);
 }
 function save($df)
 {
     //the currency field
     $this->default = unformat_number($this->default);
     $this->default_value = $this->default;
     parent::save($df);
     //currency id
     $currency_id = new TemplateCurrencyId();
     $currency_id->name = 'currency_id';
     $currency_id->vname = 'LBL_CURRENCY';
     $currency_id->label = $currency_id->vname;
     $currency_id->save($df);
     //$df->addLabel($currency_id->vname);
 }
Example #9
0
/**
 * Products, Quotations & Invoices modules.
 * Extensions to SugarCRM
 * @package Advanced OpenSales for SugarCRM
 * @subpackage Products
 * @copyright SalesAgility Ltd http://www.salesagility.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with this program; if not, see http://www.gnu.org/licenses
 * or write to the Free Software Foundation,Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301  USA
 *
 * @author Salesagility Ltd <*****@*****.**>
 */
function perform_aos_save($focus)
{
    foreach ($focus->field_defs as $field) {
        $fieldName = $field['name'];
        $fieldNameDollar = $field['name'] . '_usdollar';
        if (isset($focus->field_defs[$fieldNameDollar])) {
            $focus->{$fieldNameDollar} = '';
            if (!number_empty($focus->field_defs[$field['name']])) {
                $currency = new Currency();
                $currency->retrieve($focus->currency_id);
                $focus->{$fieldNameDollar} = $currency->convertToDollar(unformat_number($fieldName));
            }
        }
    }
}
Example #10
0
 public function testUnformatNumber()
 {
     global $current_user;
     $testValue = "\$100,000.50";
     $unformattedValue = unformat_number($testValue);
     $this->assertEquals($unformattedValue, 100000.5, "Assert that \$100,000.50 becomes 100000.50. Formatted value is: " . $unformattedValue);
     //Switch the num_grp_sep and dec_sep values
     $current_user->setPreference('num_grp_sep', '.');
     $current_user->setPreference('dec_sep', ',');
     $current_user->save();
     //Force reset on dec_sep and num_grp_sep because the dec_sep and num_grp_sep values are stored as static variables
     get_number_seperators(true);
     $testValue = "\$100.000,50";
     $unformattedValue = unformat_number($testValue);
     $this->assertEquals($unformattedValue, 100000.5, "Assert that \$100.000,50 becomes 100000.50. Formatted value is: " . $unformattedValue);
 }
Example #11
0
 public function save($df)
 {
     //the currency field
     $this->default = unformat_number($this->default);
     $this->default_value = $this->default;
     $this->related_fields = array('currency_id', 'base_rate');
     parent::save($df);
     $df->addLabel('LBL_CURRENCY');
     //currency id
     $currency_id = new TemplateCurrencyId();
     $currency_id->name = 'currency_id';
     $currency_id->save($df);
     //base_rate
     $base_rate = new TemplateCurrencyBaseRate();
     $base_rate->name = 'base_rate';
     $base_rate->label = 'LBL_CURRENCY_RATE';
     $base_rate->save($df);
 }
 function ReadData($targetstring, &$map, &$item)
 {
     $inbw = NULL;
     $outbw = NULL;
     $data_time = 0;
     if (preg_match("/^static:(\\-?\\d+\\.?\\d*[KMGT]*):(\\-?\\d+\\.?\\d*[KMGT]*)\$/", $targetstring, $matches)) {
         $inbw = unformat_number($matches[1], $map->kilo);
         $outbw = unformat_number($matches[2], $map->kilo);
         $data_time = time();
     }
     if (preg_match("/^static:(\\-?\\d+\\.?\\d*[KMGT]*)\$/", $targetstring, $matches)) {
         $inbw = unformat_number($matches[1], $map->kilo);
         $outbw = $inbw;
         $data_time = time();
     }
     wm_debug("Static ReadData: Returning ({$inbw},{$outbw},{$data_time})\n");
     return array($inbw, $outbw, $data_time);
 }
Example #13
0
 /**
  * SaveQuery
  *  
  * This function handles saving the query parameters to the user preferences
  * SavedSearch.php does something very similar when saving saved searches as well
  * 
  * @see SavedSearch
  * @param $name String name  to identify this query
  */
 function SaveQuery($name)
 {
     global $current_user, $timedate;
     if (isset($this->query['module'])) {
         $bean = loadBean($this->query['module']);
         if (!empty($bean)) {
             foreach ($this->query as $key => $value) {
                 //Filter date fields to ensure it is saved to DB format, but also avoid empty values
                 if (!empty($value) && preg_match('/^(start_range_|end_range_|range_)?(.*?)(_advanced|_basic)$/', $key, $match)) {
                     $field = $match[2];
                     if (isset($bean->field_defs[$field]['type']) && empty($bean->field_defs[$field]['disable_num_format'])) {
                         $type = $bean->field_defs[$field]['type'];
                         if (($type == 'date' || $type == 'datetime' || $type == 'datetimecombo') && !preg_match('/^\\[.*?\\]$/', $value)) {
                             $db_format = $timedate->to_db_date($value, false);
                             $this->query[$key] = $db_format;
                         } else {
                             if ($type == 'int' || $type == 'currency' || $type == 'decimal' || $type == 'float') {
                                 if (preg_match('/[^\\d]/', $value)) {
                                     require_once 'modules/Currencies/Currency.php';
                                     $this->query[$key] = unformat_number($value);
                                     //Flag this value as having been unformatted
                                     $this->query[$key . '_unformatted_number'] = true;
                                     //If the type is of currency and there was a currency symbol (non-digit), save the symbol
                                     if ($type == 'currency' && preg_match('/^([^\\d])/', $value, $match)) {
                                         $this->query[$key . '_currency_symbol'] = $match[1];
                                     }
                                 } else {
                                     //unset any flags
                                     if (isset($this->query[$key . '_unformatted_number'])) {
                                         unset($this->query[$key . '_unformatted_number']);
                                     }
                                     if (isset($this->query[$key . '_currency_symbol'])) {
                                         unset($this->query[$key . '_currency_symbol']);
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     $current_user->setPreference($name . 'Q', $this->query);
 }
Example #14
0
 function handleAdd()
 {
     global $current_user;
     if ($current_user->is_admin) {
         if (isset($_POST['edit']) && $_POST['edit'] == 'true' && isset($_POST['name']) && !empty($_POST['name']) && isset($_POST['conversion_rate']) && !empty($_POST['conversion_rate']) && isset($_POST['symbol']) && !empty($_POST['symbol'])) {
             $currency = new Currency();
             if (isset($_POST['record']) && !empty($_POST['record'])) {
                 $currency->retrieve($_POST['record']);
             }
             $currency->name = $_POST['name'];
             $currency->status = $_POST['status'];
             $currency->symbol = $_POST['symbol'];
             $currency->iso4217 = $_POST['iso4217'];
             $currency->conversion_rate = unformat_number($_POST['conversion_rate']);
             $currency->save();
             $this->focus = $currency;
         }
     }
 }
Example #15
0
 /**
  * handle creating or updating a currency record
  *
  */
 function handleAdd()
 {
     global $current_user;
     if ($current_user->is_admin) {
         if (isset($_POST['edit']) && $_POST['edit'] == 'true' && isset($_POST['name']) && !empty($_POST['name']) && isset($_POST['conversion_rate']) && !empty($_POST['conversion_rate']) && isset($_POST['symbol']) && !empty($_POST['symbol'])) {
             $currency = BeanFactory::getBean('Currencies');
             $isUpdate = false;
             if (isset($_POST['record']) && !empty($_POST['record'])) {
                 $isUpdate = true;
                 $currency->retrieve($_POST['record']);
             }
             $currency->name = $_POST['name'];
             $currency->status = $_POST['status'];
             $currency->symbol = $_POST['symbol'];
             $currency->iso4217 = $_POST['iso4217'];
             $previousConversionRate = $currency->conversion_rate;
             $currency->conversion_rate = (string) unformat_number($_POST['conversion_rate']);
             $currency->save();
             $this->focus = $currency;
             // Used to tell calling code that a change was made
             $this->recordSaved = true;
             //Check if the conversion rates changed and, if so, update the rates with a scheduler job
             if ($isUpdate && $previousConversionRate != $currency->conversion_rate) {
                 global $timedate;
                 // use bean factory here
                 $job = BeanFactory::getBean('SchedulersJobs');
                 $job->name = "SugarJobUpdateCurrencyRates: " . $timedate->getNow()->asDb();
                 $job->target = "class::SugarJobUpdateCurrencyRates";
                 $job->data = $currency->id;
                 $job->retry_count = 0;
                 $job->assigned_user_id = $current_user->id;
                 $jobQueue = new SugarJobQueue();
                 $jobQueue->submitJob($job);
             }
         }
     }
 }
Example #16
0
 /**
  * Function corrects any bad formatting done by 3rd party/custom code
  *
  * This function will be removed in a future release, it is only here to assist upgrading existing code that expects formatted data in the bean
  */
 function fixUpFormatting()
 {
     global $timedate;
     static $boolean_false_values = array('off', 'false', '0', 'no');
     foreach ($this->field_defs as $field => $def) {
         if (!isset($this->{$field})) {
             continue;
         }
         if (isset($def['source']) && $def['source'] == 'non-db' || $field == 'deleted') {
             continue;
         }
         if (isset($this->fetched_row[$field]) && $this->{$field} == $this->fetched_row[$field]) {
             // Don't hand out warnings because the field was untouched between retrieval and saving, most database drivers hand pretty much everything back as strings.
             continue;
         }
         $reformatted = false;
         switch ($def['type']) {
             case 'datetime':
             case 'datetimecombo':
                 if (empty($this->{$field})) {
                     break;
                 }
                 if ($this->{$field} == 'NULL') {
                     $this->{$field} = '';
                     break;
                 }
                 if (!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/', $this->{$field})) {
                     // This appears to be formatted in user date/time
                     $this->{$field} = $timedate->to_db($this->{$field});
                     $reformatted = true;
                 }
                 break;
             case 'date':
                 if (empty($this->{$field})) {
                     break;
                 }
                 if ($this->{$field} == 'NULL') {
                     $this->{$field} = '';
                     break;
                 }
                 if (!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $this->{$field})) {
                     // This date appears to be formatted in the user's format
                     $this->{$field} = $timedate->to_db_date($this->{$field}, false);
                     $reformatted = true;
                 }
                 break;
             case 'time':
                 if (empty($this->{$field})) {
                     break;
                 }
                 if ($this->{$field} == 'NULL') {
                     $this->{$field} = '';
                     break;
                 }
                 if (preg_match('/(am|pm)/i', $this->{$field})) {
                     // This time appears to be formatted in the user's format
                     $this->{$field} = $timedate->fromUserTime($this->{$field})->format(TimeDate::DB_TIME_FORMAT);
                     $reformatted = true;
                 }
                 break;
             case 'double':
             case 'decimal':
             case 'currency':
             case 'float':
                 if ($this->{$field} === '' || $this->{$field} == NULL || $this->{$field} == 'NULL') {
                     continue;
                 }
                 if (is_string($this->{$field})) {
                     $this->{$field} = (double) unformat_number($this->{$field});
                     $reformatted = true;
                 }
                 break;
             case 'uint':
             case 'ulong':
             case 'long':
             case 'short':
             case 'tinyint':
             case 'int':
                 if ($this->{$field} === '' || $this->{$field} == NULL || $this->{$field} == 'NULL') {
                     continue;
                 }
                 if (is_string($this->{$field})) {
                     $this->{$field} = (int) unformat_number($this->{$field});
                     $reformatted = true;
                 }
                 break;
             case 'bool':
                 if (empty($this->{$field})) {
                     $this->{$field} = false;
                 } else {
                     if (true === $this->{$field} || 1 == $this->{$field}) {
                         $this->{$field} = true;
                     } else {
                         if (in_array(strval($this->{$field}), $boolean_false_values)) {
                             $this->{$field} = false;
                             $reformatted = true;
                         } else {
                             $this->{$field} = true;
                             $reformatted = true;
                         }
                     }
                 }
                 break;
             case 'encrypt':
                 $this->{$field} = $this->encrpyt_before_save($this->{$field});
                 break;
         }
         if ($reformatted) {
             $GLOBALS['log']->deprecated('Formatting correction: ' . $this->module_dir . '->' . $field . ' had formatting automatically corrected. This will be removed in the future, please upgrade your external code');
         }
     }
 }
Example #17
0
 /**
  * @see SugarView::display()
  */
 public function display()
 {
     if (!empty($_REQUEST['handle']) && $_REQUEST['handle'] == 'save') {
         return $this->handleSave();
     }
     global $beanList;
     // get the EditView defs to check if opportunity_name exists, for a check below for populating data
     $opportunityNameInLayout = false;
     $editviewFile = 'modules/Leads/metadata/editviewdefs.php';
     $this->medataDataFile = $editviewFile;
     if (file_exists("custom/{$editviewFile}")) {
         $this->medataDataFile = "custom/{$editviewFile}";
     }
     include $this->medataDataFile;
     foreach ($viewdefs['Leads']['EditView']['panels'] as $panel_index => $section) {
         foreach ($section as $row_array) {
             foreach ($row_array as $cell) {
                 if (isset($cell['name']) && $cell['name'] == 'opportunity_name') {
                     $opportunityNameInLayout = true;
                 }
             }
         }
     }
     $this->medataDataFile = $this->fileName;
     if (file_exists("custom/{$this->fileName}")) {
         $this->medataDataFile = "custom/{$this->fileName}";
     }
     $this->loadDefs();
     $this->getRecord();
     $this->checkForDuplicates($this->focus);
     $smarty = new Sugar_Smarty();
     $ev = new EditView();
     $ev->ss = $smarty;
     $ev->view = "ConvertLead";
     echo $this->getModuleTitle();
     require_once "include/QuickSearchDefaults.php";
     $qsd = new QuickSearchDefaults();
     $qsd->setFormName("ConvertLead");
     $this->contact = new Contact();
     $smarty->assign("contact_def", $this->contact->field_defs);
     $smarty->assign("form_name", "ConvertLead");
     $smarty->assign("form_id", "ConvertLead");
     $smarty->assign("module", "Leads");
     $smarty->assign("view", "convertlead");
     $smarty->assign("bean", $this->focus);
     $smarty->assign("record_id", $this->focus->id);
     $smarty->display("modules/Leads/tpls/ConvertLeadHeader.tpl");
     echo "<div class='edit view' style='width:auto;'>";
     foreach ($this->defs as $module => $vdef) {
         if (!isset($beanList[$module])) {
             continue;
         }
         $bean = $beanList[$module];
         $focus = new $bean();
         $focus->fill_in_additional_detail_fields();
         foreach ($focus->field_defs as $field => $def) {
             if (isset($vdef[$ev->view]['copyData']) && $vdef[$ev->view]['copyData']) {
                 if ($module == "Accounts" && $field == 'name') {
                     $focus->name = $this->focus->account_name;
                 } else {
                     if ($module == "Opportunities" && $field == 'amount') {
                         $focus->amount = unformat_number($this->focus->opportunity_amount);
                     } else {
                         if ($module == "Opportunities" && $field == 'name') {
                             if ($opportunityNameInLayout && !empty($this->focus->opportunity_name)) {
                                 $focus->name = $this->focus->opportunity_name;
                             }
                         } else {
                             if ($field == "id") {
                                 //If it is not a contact, don't copy the ID from the lead
                                 if ($module == "Contacts") {
                                     $focus->{$field} = $this->focus->{$field};
                                 }
                             } else {
                                 if (is_a($focus, "Company") && $field == 'phone_office') {
                                     //Special case where company and person have the same field with a different name
                                     $focus->phone_office = $this->focus->phone_work;
                                 } else {
                                     if (isset($this->focus->{$field})) {
                                         $focus->{$field} = $this->focus->{$field};
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         //Copy over email data
         $ev->setup($module, $focus, $this->medataDataFile, "modules/Leads/tpls/ConvertLead.tpl", false);
         $ev->process();
         echo $ev->display(false);
         echo $this->getValidationJS($module, $focus, $vdef[$ev->view]);
     }
     echo "</div>";
     echo $qsd->getQSScriptsJSONAlreadyDefined();
     $smarty->display("modules/Leads/tpls/ConvertLeadFooter.tpl");
 }
Example #18
0
 * If you do not agree to all of the applicable terms or do not have the
 * authority to bind the entity as an authorized representative, then do not
 * install or use this SugarCRM file.
 *
 * Copyright (C) SugarCRM Inc. All rights reserved.
 */
$module = $_REQUEST['save_module'];
$record = $_REQUEST['save_record'];
$field_value = $_REQUEST['save_value'];
$field = $_REQUEST['save_field_name'];
$type = $_REQUEST['type'];
$bean = BeanFactory::getBean($module, $record);
if ($type != 'currency') {
    $bean->{$field} = $field_value;
} else {
    $bean->{$field} = unformat_number($field_value);
}
$bean->save(false);
$ret_array = array();
$ret_array['id'] = $record;
$ret_array['field'] = $field;
if ($type != 'currency') {
    $ret_array['value'] = $bean->{$field};
} else {
    global $locale;
    $params = array();
    $params['currency_id'] = $_REQUEST['currency_id'];
    $params['convert'] = false;
    $params['currency_symbol'] = $_REQUEST['currency_symbol'];
    $ret_array['currency_formatted_value'] = currency_format_number($bean->{$field}, $params);
    $ret_array['formatted_value'] = format_number($bean->{$field});
Example #19
0
 /**
  * Removes formatting from values posted from the user interface.
  * It only unformats numbers.  Function relies on user/system prefernce for format strings.
  *
  * Internal Function, do not override.
  */
 function unformat_all_fields()
 {
     global $disable_num_format, $current_user;
     if (!empty($this->unformated_numbers) || !empty($disable_num_format) || empty($current_user)) {
         return;
     }
     // turned off at bean level?
     if (!empty($this->disable_num_format) && $this->disable_num_format || empty($this->field_defs)) {
         return;
     }
     foreach ($this->field_defs as $fieldDef) {
         $type = empty($fieldDef['type']) ? $fieldDef['dbType'] : $fieldDef['type'];
         $field = $fieldDef['name'];
         if (in_array($type, array('int', 'float', 'double', 'uint', 'ulong', 'long', 'short', 'tinyint', 'currency', 'decimal'))) {
             if (empty($fieldDef['disable_num_format']) && !empty($this->{$field})) {
                 $this->{$field} = unformat_number($this->{$field});
             }
         } else {
             if ($type == 'encrypt' && !empty($this->{$field})) {
                 $this->{$field} = $this->encrpyt_before_save($this->{$field});
             }
         }
     }
     $this->unformated_numbers = true;
 }
Example #20
0
			$map->links['DEFAULT']->max_bandwidth_in_cfg = $bwin;
			$map->links['DEFAULT']->max_bandwidth_out_cfg = $bwout;
			$map->links['DEFAULT']->max_bandwidth_in = unformat_number($bwin, $map->kilo);
                        $map->links['DEFAULT']->max_bandwidth_out = unformat_number($bwout, $map->kilo);
			
			// $map->defaultlink->SetBandwidth($bwin,$bwout);
			foreach ($map->links as $link)
			{
			    if( ($link->max_bandwidth_in_cfg == $bwin_old) || ($link->max_bandwidth_out_cfg == $bwout_old) )
			    {
	    //			$link->SetBandwidth($bwin,$bwout);
				    $link_name = $link->name;
				    $map->links[$link_name]->max_bandwidth_in_cfg = $bwin;
				    $map->links[$link_name]->max_bandwidth_out_cfg = $bwout;
				    $map->links[$link_name]->max_bandwidth_in = unformat_number($bwin, $map->kilo);
				    $map->links[$link_name]->max_bandwidth_out = unformat_number($bwout, $map->kilo);
			    }
			}
		}

		$map->WriteConfig($mapfile);
		break; 

	case 'set_map_style':
		$map->ReadConfig($mapfile);

		if(wm_editor_validate_one_of($_REQUEST['mapstyle_htmlstyle'],array('static','overlib'),false)) {
		    $map->htmlstyle = strtolower($_REQUEST['mapstyle_htmlstyle']); 		    
		}

		$map->keyfont = intval($_REQUEST['mapstyle_legendfont']);
Example #21
0
function fixUpFormatting($module, $field, $value)
{
    global $timedate, $beanFiles, $beanList;
    require_once $beanFiles[$beanList[$module]];
    $bean = new $beanList[$module]();
    static $boolean_false_values = array('off', 'false', '0', 'no');
    switch ($bean->field_defs[$field]['type']) {
        case 'datetime':
        case 'datetimecombo':
            if (empty($value)) {
                break;
            }
            if ($value == 'NULL') {
                $value = '';
                break;
            }
            if (!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/', $value)) {
                // This appears to be formatted in user date/time
                $value = $timedate->to_db($value);
            }
            break;
        case 'date':
            if (empty($value)) {
                break;
            }
            if ($value == 'NULL') {
                $value = '';
                break;
            }
            if (!preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $value)) {
                // This date appears to be formatted in the user's format
                $value = $timedate->to_db_date($value, false);
            }
            break;
        case 'time':
            if (empty($value)) {
                break;
            }
            if ($value == 'NULL') {
                $value = '';
                break;
            }
            if (preg_match('/(am|pm)/i', $value)) {
                // This time appears to be formatted in the user's format
                $value = $timedate->fromUserTime($value)->format(TimeDate::DB_TIME_FORMAT);
            }
            break;
        case 'double':
        case 'decimal':
        case 'currency':
        case 'float':
            if ($value === '' || $value == NULL || $value == 'NULL') {
                continue;
            }
            if (is_string($value)) {
                $value = (double) unformat_number($value);
            }
            break;
        case 'uint':
        case 'ulong':
        case 'long':
        case 'short':
        case 'tinyint':
        case 'int':
            if ($value === '' || $value == NULL || $value == 'NULL') {
                continue;
            }
            if (is_string($value)) {
                $value = (int) unformat_number($value);
            }
            break;
        case 'bool':
            if (empty($value)) {
                $value = false;
            } else {
                if (true === $value || 1 == $value) {
                    $value = true;
                } else {
                    if (in_array(strval($value), $boolean_false_values)) {
                        $value = false;
                    } else {
                        $value = true;
                    }
                }
            }
            break;
        case 'encrypt':
            $value = $this->encrpyt_before_save($value);
            break;
    }
    return $value;
}
Example #22
0
 function handleSave($prefix, $redirect = true, $useRequired = false, $id = null, $searchModuleBean)
 {
     global $current_user, $timedate;
     $focus = new SavedSearch();
     if ($id) {
         $focus->retrieve($id);
     }
     if ($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))) {
         return null;
     }
     $ignored_inputs = array('PHPSESSID', 'module', 'action', 'saved_search_name', 'saved_search_select', 'advanced', 'Calls_divs', 'ACLRoles_divs');
     $contents = $_REQUEST;
     if ($id == null) {
         $focus->name = $contents['saved_search_name'];
     }
     $focus->search_module = $contents['search_module'];
     foreach ($contents as $input => $value) {
         if (in_array($input, $ignored_inputs)) {
             unset($contents[$input]);
             continue;
         }
         //Filter date fields to ensure it is saved to DB format, but also avoid empty values
         if (!empty($value) && preg_match('/^(start_range_|end_range_|range_)?(.*?)(_advanced|_basic)$/', $input, $match)) {
             $field = $match[2];
             if (isset($searchModuleBean->field_defs[$field]['type'])) {
                 $type = $searchModuleBean->field_defs[$field]['type'];
                 //Avoid macro values for the date types
                 if (($type == 'date' || $type == 'datetime' || $type == 'datetimecombo') && !preg_match('/^\\[.*?\\]$/', $value)) {
                     $db_format = $timedate->to_db_date($value, false);
                     $contents[$input] = $db_format;
                 } else {
                     if ($type == 'int' || $type == 'currency' || $type == 'decimal' || $type == 'float') {
                         if (preg_match('/[^\\d]/', $value)) {
                             require_once 'modules/Currencies/Currency.php';
                             $contents[$input] = unformat_number($value);
                             //Flag this value as having been unformatted
                             $contents[$input . '_unformatted_number'] = true;
                             //If the type is of currency and there was a currency symbol (non-digit), save the symbol
                             if ($type == 'currency' && preg_match('/^([^\\d])/', $value, $match)) {
                                 $contents[$input . '_currency_symbol'] = $match[1];
                             }
                         } else {
                             //unset any flags
                             if (isset($contents[$input . '_unformatted_number'])) {
                                 unset($contents[$input . '_unformatted_number']);
                             }
                             if (isset($contents[$input . '_currency_symbol'])) {
                                 unset($contents[$input . '_currency_symbol']);
                             }
                         }
                     }
                 }
             }
         }
     }
     $contents['advanced'] = true;
     $focus->contents = base64_encode(serialize($contents));
     $focus->assigned_user_id = $current_user->id;
     $focus->new_schema = true;
     $saved_search_id = $focus->save();
     $GLOBALS['log']->debug("Saved record with id of " . $focus->id);
     $orderBy = empty($contents['orderBy']) ? 'name' : $contents['orderBy'];
     $search_query = "&orderBy=" . $orderBy . "&sortOrder=" . $contents['sortOrder'] . "&query=" . $_REQUEST['query'] . "&searchFormTab=" . $_REQUEST['searchFormTab'] . '&showSSDIV=' . $contents['showSSDIV'];
     if ($redirect) {
         $this->handleRedirect($focus->search_module, $search_query, $saved_search_id, 'true');
     }
 }
Example #23
0
 /**
  * @see SugarView::display()
  */
 public function display()
 {
     if (!empty($_REQUEST['handle']) && $_REQUEST['handle'] == 'save') {
         return $this->handleSave();
     }
     global $beanList;
     // get the EditView defs to check if opportunity_name exists, for a check below for populating data
     $opportunityNameInLayout = false;
     $editviewFile = 'modules/Leads/metadata/editviewdefs.php';
     $this->medataDataFile = $editviewFile;
     if (file_exists("custom/{$editviewFile}")) {
         $this->medataDataFile = "custom/{$editviewFile}";
     }
     include $this->medataDataFile;
     foreach ($viewdefs['Leads']['EditView']['panels'] as $panel_index => $section) {
         foreach ($section as $row_array) {
             foreach ($row_array as $cell) {
                 if (isset($cell['name']) && $cell['name'] == 'opportunity_name') {
                     $opportunityNameInLayout = true;
                 }
             }
         }
     }
     $this->medataDataFile = $this->fileName;
     if (file_exists("custom/{$this->fileName}")) {
         $this->medataDataFile = "custom/{$this->fileName}";
     }
     $this->loadDefs();
     $this->getRecord();
     $this->checkForDuplicates($this->focus);
     $smarty = new Sugar_Smarty();
     $ev = new EditView();
     $ev->ss = $smarty;
     $ev->view = "ConvertLead";
     echo $this->getModuleTitle();
     require_once "include/QuickSearchDefaults.php";
     $qsd = QuickSearchDefaults::getQuickSearchDefaults();
     $qsd->setFormName("ConvertLead");
     $this->contact = new Contact();
     /*
      * Setup filter for Account/Contact popup picker
      */
     $filter = '';
     // Check if Lead has an account set
     if (!empty($this->focus->account_name)) {
         $filter .= '&name_advanced=' . urlencode($this->focus->account_name);
     }
     // Check if Lead First name is available
     if (!empty($this->focus->first_name)) {
         $filter .= '&first_name_advanced=' . urlencode($this->focus->first_name);
     }
     // Lead Last Name is always available
     $filter .= '&last_name_advanced=' . urlencode($this->focus->last_name);
     $smarty->assign('initialFilter', $filter);
     $smarty->assign('displayParams', array('initial_filter' => '{$initialFilter}'));
     $relatedFields = $this->contact->get_related_fields();
     $selectFields = array();
     foreach ($this->defs as $moduleName => $mDefs) {
         if (!empty($mDefs[$ev->view]['select']) && !empty($relatedFields[$mDefs[$ev->view]['select']])) {
             $selectFields[$moduleName] = $mDefs[$ev->view]['select'];
             continue;
         }
         foreach ($relatedFields as $fDef) {
             if (!empty($fDef['link']) && !empty($fDef['module']) && $fDef['module'] == $moduleName) {
                 $selectFields[$moduleName] = $fDef['name'];
                 break;
             }
         }
     }
     $smarty->assign('selectFields', $selectFields);
     $smarty->assign("contact_def", $this->contact->field_defs);
     $smarty->assign("form_name", "ConvertLead");
     $smarty->assign("form_id", "ConvertLead");
     $smarty->assign("module", "Leads");
     $smarty->assign("view", "convertlead");
     $smarty->assign("bean", $this->focus);
     $smarty->assign("record_id", $this->focus->id);
     global $mod_strings;
     $smarty->assign('MOD', $mod_strings);
     $smarty->display("modules/Leads/tpls/ConvertLeadHeader.tpl");
     echo "<div class='edit view' style='width:auto;'>";
     global $sugar_config, $app_list_strings, $app_strings;
     $smarty->assign('lead_conv_activity_opt', $sugar_config['lead_conv_activity_opt']);
     //Switch up list depending on copy or move
     if ($sugar_config['lead_conv_activity_opt'] == 'move') {
         $smarty->assign('convertModuleListOptions', get_select_options_with_id(array('None' => $app_strings['LBL_NONE'], 'Contacts' => $app_list_strings["moduleListSingular"]['Contacts']), ''));
     } else {
         if ($sugar_config['lead_conv_activity_opt'] == 'copy') {
             $smarty->assign('convertModuleListOptions', get_select_options_with_id(array('Contacts' => $app_list_strings["moduleListSingular"]['Contacts']), ''));
         }
     }
     foreach ($this->defs as $module => $vdef) {
         if (!isset($beanList[$module])) {
             continue;
         }
         $bean = $beanList[$module];
         $focus = new $bean();
         // skip if we aren't allowed to save this bean
         if (!$focus->ACLAccess('save')) {
             continue;
         }
         $focus->fill_in_additional_detail_fields();
         foreach ($focus->field_defs as $field => $def) {
             if (isset($vdef[$ev->view]['copyData']) && $vdef[$ev->view]['copyData']) {
                 if ($module == "Accounts" && $field == 'name') {
                     $focus->name = $this->focus->account_name;
                 } else {
                     if ($module == "Opportunities" && $field == 'amount') {
                         $focus->amount = unformat_number($this->focus->opportunity_amount);
                     } else {
                         if ($module == "Opportunities" && $field == 'name') {
                             if ($opportunityNameInLayout && !empty($this->focus->opportunity_name)) {
                                 $focus->name = $this->focus->opportunity_name;
                             }
                         } else {
                             if ($field == "id") {
                                 //If it is not a contact, don't copy the ID from the lead
                                 if ($module == "Contacts") {
                                     $focus->{$field} = $this->focus->{$field};
                                 }
                             } else {
                                 if (is_a($focus, "Company") && $field == 'phone_office') {
                                     //Special case where company and person have the same field with a different name
                                     $focus->phone_office = $this->focus->phone_work;
                                 } else {
                                     if (strpos($field, "billing_address") !== false && $focus->field_defs[$field]["type"] == "varchar") {
                                         $tmp_field = str_replace("billing_", "primary_", $field);
                                         $focus->field_defs[$field]["type"] = "text";
                                         if (isset($this->focus->{$tmp_field})) {
                                             $focus->{$field} = $this->focus->{$tmp_field};
                                         }
                                     } else {
                                         if (strpos($field, "shipping_address") !== false && $focus->field_defs[$field]["type"] == "varchar") {
                                             $tmp_field = str_replace("shipping_", "primary_", $field);
                                             if (isset($this->focus->{$tmp_field})) {
                                                 $focus->{$field} = $this->focus->{$tmp_field};
                                             }
                                             $focus->field_defs[$field]["type"] = "text";
                                         } else {
                                             if (isset($this->focus->{$field})) {
                                                 $focus->{$field} = $this->focus->{$field};
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         //Copy over email data
         $ev->setup($module, $focus, $this->medataDataFile, "modules/Leads/tpls/ConvertLead.tpl", false);
         $ev->process();
         echo $ev->display(false);
         echo $this->getValidationJS($module, $focus, $vdef[$ev->view]);
     }
     echo "</div>";
     echo $qsd->getQSScriptsJSONAlreadyDefined();
     // need to re-assign bean as it gets overridden by $ev->display
     $smarty->assign("bean", $this->focus);
     $smarty->display("modules/Leads/tpls/ConvertLeadFooter.tpl");
 }
Example #24
0
$camp_query1 .= " group by camp.name";
$opp_query1 .= " and deleted=0";
$camp_result1 = $focus->db->query($camp_query1);
$camp_data1 = $focus->db->fetchByAssoc($camp_result1);
if (unformat_number($focus->impressions) > 0) {
    $cost_per_impression = unformat_number($focus->actual_cost) / unformat_number($focus->impressions);
} else {
    $cost_per_impression = format_number(0);
}
$smarty->assign("COST_PER_IMPRESSION", currency_format_number($cost_per_impression));
if (empty($camp_data1['click_thru_link'])) {
    $camp_data1['click_thru_link'] = 0;
}
$click_thru_links = $camp_data1['click_thru_link'];
if ($click_thru_links > 0) {
    $cost_per_click_thru = unformat_number($focus->actual_cost) / unformat_number($click_thru_links);
} else {
    $cost_per_click_thru = format_number(0);
}
$smarty->assign("COST_PER_CLICK_THROUGH", currency_format_number($cost_per_click_thru));
$currency = new Currency();
if (isset($focus->currency_id) && !empty($focus->currency_id)) {
    $currency->retrieve($focus->currency_id);
    if ($currency->deleted != 1) {
        $smarty->assign("CURRENCY", $currency->iso4217 . ' ' . $currency->symbol);
    } else {
        $smarty->assign("CURRENCY", $currency->getDefaultISO4217() . ' ' . $currency->getDefaultCurrencySymbol());
    }
} else {
    $smarty->assign("CURRENCY", $currency->getDefaultISO4217() . ' ' . $currency->getDefaultCurrencySymbol());
}
 /**
  * BWC modules always unformat server-side
  *
  * @param string $formattedField
  * @param array $vardef
  * @return null|string
  */
 public function unformatField($formattedField, $vardef)
 {
     if ($formattedField === '' || $formattedField === null) {
         return null;
     }
     if (is_array($formattedField)) {
         $formattedField = array_shift($formattedField);
     }
     return (string) unformat_number($formattedField);
 }
Example #26
0
 /**
  * generateSearchWhere
  *
  * This function serves as the central piece of SearchForm2.php
  * It is responsible for creating the WHERE clause for a given search operation
  *
  * @param bool $add_custom_fields boolean indicating whether or not custom fields should be added
  * @param string $module Module to search against
  *
  * @return string the SQL WHERE clause based on the arguments supplied in SearchForm2 instance
  */
 public function generateSearchWhere($add_custom_fields = false, $module = '')
 {
     global $timedate;
     $db = $this->seed->db;
     $this->searchColumns = array();
     $values = $this->searchFields;
     $where_clauses = array();
     $like_char = '%';
     $table_name = $this->seed->object_name;
     $this->seed->fill_in_additional_detail_fields();
     //rrs check for team_id
     foreach ($this->searchFields as $field => $parms) {
         $GLOBALS['log']->debug('SearchForm2.generateSearchWhere, field: ' . $field);
         $GLOBALS['log']->debug('SearchForm2.generateSearchWhere, parms: ' . print_r($parms, TRUE));
         $customField = false;
         // Jenny - Bug 7462: We need a type check here to avoid database errors
         // when searching for numeric fields. This is a temporary fix until we have
         // a generic search form validation mechanism.
         $type = !empty($this->seed->field_name_map[$field]['type']) ? $this->seed->field_name_map[$field]['type'] : '';
         $GLOBALS['log']->debug('SearchForm2.generateSearchWhere, type: ' . $type);
         //If range search is enabled for the field, we first check if this is the starting range
         if (!empty($parms['enable_range_search']) && empty($type)) {
             if (preg_match('/^start_range_(.*?)$/', $field, $match)) {
                 $real_field = $match[1];
                 $start_field = 'start_range_' . $real_field;
                 $end_field = 'end_range_' . $real_field;
                 if (isset($this->searchFields[$start_field]['value']) && isset($this->searchFields[$end_field]['value'])) {
                     $this->searchFields[$real_field]['value'] = $this->searchFields[$start_field]['value'] . '<>' . $this->searchFields[$end_field]['value'];
                     $this->searchFields[$real_field]['operator'] = 'between';
                     $parms['value'] = $this->searchFields[$real_field]['value'];
                     $parms['operator'] = 'between';
                     $field_type = isset($this->seed->field_name_map[$real_field]['type']) ? $this->seed->field_name_map[$real_field]['type'] : '';
                     if ($field_type == 'datetimecombo' || $field_type == 'datetime') {
                         $type = $field_type;
                     }
                     $field = $real_field;
                     unset($this->searchFields[$end_field]['value']);
                 } else {
                     //if both start and end ranges have not been defined, skip this filter.
                     continue;
                 }
             } else {
                 if (preg_match('/^range_(.*?)$/', $field, $match) && isset($this->searchFields[$field]['value'])) {
                     $real_field = $match[1];
                     //Special case for datetime and datetimecombo fields.  By setting the type here we allow an actual between search
                     if (in_array($parms['operator'], array('=', 'between', "not_equal", 'less_than', 'greater_than', 'less_than_equals', 'greater_than_equals'))) {
                         $field_type = isset($this->seed->field_name_map[$real_field]['type']) ? $this->seed->field_name_map[$real_field]['type'] : '';
                         if (strtolower($field_type) == 'readonly' && isset($this->seed->field_name_map[$real_field]['dbType'])) {
                             $field_type = $this->seed->field_name_map[$real_field]['dbType'];
                         }
                         if ($field_type == 'datetimecombo' || $field_type == 'datetime' || $field_type == 'int') {
                             $type = $field_type;
                         }
                     }
                     $this->searchFields[$real_field]['value'] = $this->searchFields[$field]['value'];
                     $this->searchFields[$real_field]['operator'] = $this->searchFields[$field]['operator'];
                     $params['value'] = $this->searchFields[$field]['value'];
                     $params['operator'] = $this->searchFields[$field]['operator'];
                     unset($this->searchFields[$field]['value']);
                     $field = $real_field;
                 } else {
                     //Skip this range search field, it is the end field THIS IS NEEDED or the end range date will break the query
                     continue;
                 }
             }
         }
         //Test to mark whether or not the field is a custom field
         if (!empty($this->seed->field_name_map[$field]['source']) && ($this->seed->field_name_map[$field]['source'] == 'custom_fields' || $this->seed->field_name_map[$field]['source'] == 'non-db' && (!empty($this->seed->field_name_map[$field]['custom_module']) || isset($this->seed->field_name_map[$field]['ext2'])))) {
             $customField = true;
         }
         if ($type == 'int' && isset($parms['value']) && !empty($parms['value'])) {
             require_once 'include/SugarFields/SugarFieldHandler.php';
             $intField = SugarFieldHandler::getSugarField('int');
             $newVal = $intField->getSearchWhereValue($parms['value']);
             $parms['value'] = $newVal;
         } elseif ($type == 'html' && $customField) {
             continue;
         }
         if (isset($parms['value']) && $parms['value'] != "") {
             $operator = $db->isNumericType($type) ? '=' : 'like';
             if (!empty($parms['operator'])) {
                 $operator = strtolower($parms['operator']);
             }
             if (is_array($parms['value'])) {
                 $field_value = '';
                 // always construct the where clause for multiselects using the 'like' form to handle combinations of multiple $vals and multiple $parms
                 if (!empty($this->seed->field_name_map[$field]['isMultiSelect']) && $this->seed->field_name_map[$field]['isMultiSelect']) {
                     // construct the query for multenums
                     // use the 'like' query as both custom and OOB multienums are implemented with types that cannot be used with an 'in'
                     $operator = 'custom_enum';
                     $table_name = $this->seed->table_name;
                     if ($customField) {
                         $table_name .= "_cstm";
                     }
                     $db_field = $table_name . "." . $field;
                     foreach ($parms['value'] as $val) {
                         if ($val != ' ' and $val != '') {
                             $qVal = $db->quote($val);
                             if (!empty($field_value)) {
                                 $field_value .= ' or ';
                             }
                             $field_value .= "{$db_field} like '%^{$qVal}^%'";
                         } else {
                             $field_value .= '(' . $db_field . ' IS NULL or ' . $db_field . "='^^' or " . $db_field . "='')";
                         }
                     }
                 } else {
                     $operator = $operator != 'subquery' ? 'in' : $operator;
                     $GLOBALS['log']->debug('SearchForm2.generateSearchWhere, value_count: ' . count($parms['value']));
                     $GLOBALS['log']->debug('SearchForm2.generateSearchWhere, value-0: ' . $parms['value'][0]);
                     if (count($parms['value']) == 1 && empty($parms['value'][0])) {
                         continue;
                     }
                     foreach ($parms['value'] as $val) {
                         if ($val != ' ' and $val != '') {
                             if (!empty($field_value)) {
                                 $field_value .= ',';
                             }
                             $field_value .= $db->quoteType($type, $val);
                         } else {
                             if ($operator == 'in') {
                                 $operator = 'isnull';
                             }
                         }
                     }
                 }
             } else {
                 $field_value = $parms['value'];
             }
             //set db_fields array.
             if (!isset($parms['db_field'])) {
                 $parms['db_field'] = array($field);
             }
             //This if-else block handles the shortcut checkbox selections for "My Items" and "Closed Only"
             if (!empty($parms['my_items'])) {
                 if ($parms['value'] == false) {
                     continue;
                 } else {
                     //my items is checked.
                     global $current_user;
                     $field_value = $db->quote($current_user->id);
                     $operator = '=';
                 }
             } else {
                 if (!empty($parms['closed_values']) && is_array($parms['closed_values'])) {
                     if ($parms['value'] == false) {
                         continue;
                     } else {
                         $field_value = '';
                         foreach ($parms['closed_values'] as $closed_value) {
                             $field_value .= "," . $db->quoted($closed_value);
                         }
                         $field_value = substr($field_value, 1);
                     }
                 }
             }
             $where = '';
             $itr = 0;
             if ($field_value != '' || $operator == 'isnull') {
                 $this->searchColumns[strtoupper($field)] = $field;
                 foreach ($parms['db_field'] as $db_field) {
                     if (strstr($db_field, '.') === false) {
                         //Try to get the table for relate fields from link defs
                         if ($type == 'relate' && !empty($this->seed->field_name_map[$field]['link']) && !empty($this->seed->field_name_map[$field]['rname'])) {
                             $link = $this->seed->field_name_map[$field]['link'];
                             $relname = $link['relationship'];
                             if ($this->seed->load_relationship($link)) {
                                 //Martin fix #27494
                                 $db_field = $this->seed->field_name_map[$field]['name'];
                             } else {
                                 //Best Guess for table name
                                 $db_field = strtolower($link['module']) . '.' . $db_field;
                             }
                         } else {
                             if ($type == 'parent') {
                                 if (!empty($this->searchFields['parent_type'])) {
                                     $parentType = $this->searchFields['parent_type'];
                                     $rel_module = $parentType['value'];
                                     global $beanFiles, $beanList;
                                     if (!empty($beanFiles[$beanList[$rel_module]])) {
                                         require_once $beanFiles[$beanList[$rel_module]];
                                         $rel_seed = new $beanList[$rel_module]();
                                         $db_field = 'parent_' . $rel_module . '_' . $rel_seed->table_name . '.name';
                                     }
                                 }
                             } else {
                                 if ($type == 'relate' && $customField && !empty($this->seed->field_name_map[$field]['module'])) {
                                     $db_field = !empty($this->seed->field_name_map[$field]['name']) ? $this->seed->field_name_map[$field]['name'] : 'name';
                                 } else {
                                     if (!$customField) {
                                         if (!empty($this->seed->field_name_map[$field]['db_concat_fields'])) {
                                             $db_field = $db->concat($this->seed->table_name, $this->seed->field_name_map[$db_field]['db_concat_fields']);
                                         } else {
                                             $db_field = $this->seed->table_name . "." . $db_field;
                                         }
                                     } else {
                                         if (!empty($this->seed->field_name_map[$field]['db_concat_fields'])) {
                                             $db_field = $db->concat($this->seed->table_name . "_cstm.", $this->seed->field_name_map[$db_field]['db_concat_fields']);
                                         } else {
                                             $db_field = $this->seed->table_name . "_cstm." . $db_field;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                     if ($type == 'date') {
                         // The regular expression check is to circumvent special case YYYY-MM
                         $operator = '=';
                         if (preg_match('/^\\d{4}.\\d{1,2}$/', $field_value) != 0) {
                             // preg_match returns number of matches
                             $db_field = $this->seed->db->convert($db_field, "date_format", array("%Y-%m"));
                         } else {
                             $field_value = $timedate->to_db_date($field_value, false);
                             $db_field = $this->seed->db->convert($db_field, "date_format", array("%Y-%m-%d"));
                         }
                     }
                     if ($type == 'datetime' || $type == 'datetimecombo') {
                         try {
                             if ($operator == '=' || $operator == 'between') {
                                 // FG - bug45287 - If User asked for a range, takes edges from it.
                                 $placeholderPos = strpos($field_value, "<>");
                                 if ($placeholderPos !== FALSE && $placeholderPos > 0) {
                                     $datesLimit = explode("<>", $field_value);
                                     $dateStart = $timedate->getDayStartEndGMT($datesLimit[0]);
                                     $dateEnd = $timedate->getDayStartEndGMT($datesLimit[1]);
                                     $dates = $dateStart;
                                     $dates['end'] = $dateEnd['end'];
                                     $dates['enddate'] = $dateEnd['enddate'];
                                     $dates['endtime'] = $dateEnd['endtime'];
                                 } else {
                                     $dates = $timedate->getDayStartEndGMT($field_value);
                                 }
                                 // FG - bug45287 - Note "start" and "end" are the correct interval at GMT timezone
                                 $field_value = array($dates["start"], $dates["end"]);
                                 $operator = 'between';
                             } else {
                                 if ($operator == 'not_equal') {
                                     $dates = $timedate->getDayStartEndGMT($field_value);
                                     $field_value = array($dates["start"], $dates["end"]);
                                     $operator = 'date_not_equal';
                                 } else {
                                     if ($operator == 'greater_than') {
                                         $dates = $timedate->getDayStartEndGMT($field_value);
                                         $field_value = $dates["end"];
                                     } else {
                                         if ($operator == 'less_than') {
                                             $dates = $timedate->getDayStartEndGMT($field_value);
                                             $field_value = $dates["start"];
                                         } else {
                                             if ($operator == 'greater_than_equals') {
                                                 $dates = $timedate->getDayStartEndGMT($field_value);
                                                 $field_value = $dates["start"];
                                             } else {
                                                 if ($operator == 'less_than_equals') {
                                                     $dates = $timedate->getDayStartEndGMT($field_value);
                                                     $field_value = $dates["end"];
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         } catch (Exception $timeException) {
                             //In the event that a date value is given that cannot be correctly processed by getDayStartEndGMT method,
                             //just skip searching on this field and continue.  This may occur if user switches locale date formats
                             //in another browser screen, but re-runs a search with the previous format on another screen
                             $GLOBALS['log']->error($timeException->getMessage());
                             continue;
                         }
                     }
                     if ($type == 'decimal' || $type == 'float' || $type == 'currency' || !empty($parms['enable_range_search']) && empty($parms['is_date_field'])) {
                         require_once 'modules/Currencies/Currency.php';
                         //we need to handle formatting either a single value or 2 values in case the 'between' search option is set
                         //start by splitting the string if the between operator exists
                         $fieldARR = explode('<>', $field_value);
                         //set the first pass through boolean
                         $values = array();
                         foreach ($fieldARR as $fv) {
                             //reset the field value, it will be rebuild in the foreach loop below
                             $tmpfield_value = unformat_number($fv);
                             if ($type == 'currency' && stripos($field, '_usdollar') !== FALSE) {
                                 // It's a US Dollar field, we need to do some conversions from the user's local currency
                                 $currency_id = $GLOBALS['current_user']->getPreference('currency');
                                 if (empty($currency_id)) {
                                     $currency_id = -99;
                                 }
                                 if ($currency_id != -99) {
                                     $currency = new Currency();
                                     $currency->retrieve($currency_id);
                                     $tmpfield_value = $currency->convertToDollar($tmpfield_value);
                                 }
                             }
                             $values[] = $tmpfield_value;
                         }
                         $field_value = join('<>', $values);
                         if (!empty($parms['enable_range_search']) && $parms['operator'] == '=' && $type != 'int') {
                             // Databases can't really search for floating point numbers, because they can't be accurately described in binary,
                             // So we have to fuzz out the math a little bit
                             $field_value = array($field_value - 0.01, $field_value + 0.01);
                             $operator = 'between';
                         }
                     }
                     if ($db->supports("case_sensitive") && isset($parms['query_type']) && $parms['query_type'] == 'case_insensitive') {
                         $db_field = 'upper(' . $db_field . ")";
                         $field_value = strtoupper($field_value);
                     }
                     $itr++;
                     if (!empty($where)) {
                         $where .= " OR ";
                     }
                     //Here we make a last attempt to determine the field type if possible
                     if (empty($type) && isset($parms['db_field']) && isset($parms['db_field'][0]) && isset($this->seed->field_defs[$parms['db_field'][0]]['type'])) {
                         $type = $this->seed->field_defs[$parms['db_field'][0]]['type'];
                     }
                     switch (strtolower($operator)) {
                         case 'subquery':
                             $in = 'IN';
                             if (isset($parms['subquery_in_clause'])) {
                                 if (!is_array($parms['subquery_in_clause'])) {
                                     $in = $parms['subquery_in_clause'];
                                 } elseif (isset($parms['subquery_in_clause'][$field_value])) {
                                     $in = $parms['subquery_in_clause'][$field_value];
                                 }
                             }
                             $sq = $parms['subquery'];
                             if (is_array($sq)) {
                                 $and_or = ' AND ';
                                 if (isset($sq['OR'])) {
                                     $and_or = ' OR ';
                                 }
                                 $first = true;
                                 foreach ($sq as $q) {
                                     if (empty($q) || strlen($q) < 2) {
                                         continue;
                                     }
                                     if (!$first) {
                                         $where .= $and_or;
                                     }
                                     $where .= " {$db_field} {$in} ({$q} " . $this->seed->db->quoted($field_value . '%') . ") ";
                                     $first = false;
                                 }
                             } elseif (!empty($parms['query_type']) && $parms['query_type'] == 'format') {
                                 $stringFormatParams = array(0 => $field_value, 1 => $GLOBALS['current_user']->id);
                                 $where .= "{$db_field} {$in} (" . string_format($parms['subquery'], $stringFormatParams) . ")";
                             } else {
                                 //Bug#37087: Re-write our sub-query to it is executed first and contents stored in a derived table to avoid mysql executing the query
                                 //outside in. Additional details: http://bugs.mysql.com/bug.php?id=9021
                                 $selectCol = ' * ';
                                 //use the select column in the subquery if it exists
                                 if (!empty($parms['subquery'])) {
                                     $selectCol = $this->getSelectCol($parms['subquery']);
                                 }
                                 $where .= "{$db_field} {$in} (select {$selectCol} from ({$parms['subquery']} " . $this->seed->db->quoted($field_value . '%') . ") {$field}_derived)";
                             }
                             break;
                         case 'like':
                             if ($type == 'bool' && $field_value == 0) {
                                 // Bug 43452 - FG - Added parenthesis surrounding the OR (without them the WHERE clause would be broken)
                                 $where .= "( " . $db_field . " = '0' OR " . $db_field . " IS NULL )";
                             } else {
                                 // check to see if this is coming from unified search or not
                                 $UnifiedSearch = !empty($parms['force_unifiedsearch']);
                                 if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'UnifiedSearch') {
                                     $UnifiedSearch = true;
                                 }
                                 // If it is a unified search and if the search contains more then 1 word (contains space)
                                 // and if it's the last element from db_field (so we do the concat only once, not for every db_field element)
                                 // we concat the db_field array() (both original, and in reverse order) and search for the whole string in it
                                 if ($UnifiedSearch && strpos($field_value, ' ') !== false && strpos($db_field, $parms['db_field'][count($parms['db_field']) - 1]) !== false) {
                                     // Get the table name used for concat
                                     $concat_table = explode('.', $db_field);
                                     $concat_table = $concat_table[0];
                                     // Get the fields for concatenating
                                     $concat_fields = $parms['db_field'];
                                     // If db_fields (e.g. contacts.first_name) contain table name, need to remove it
                                     for ($i = 0; $i < count($concat_fields); $i++) {
                                         if (strpos($concat_fields[$i], $concat_table) !== false) {
                                             $concat_fields[$i] = substr($concat_fields[$i], strlen($concat_table) + 1);
                                         }
                                     }
                                     // Concat the fields and search for the value
                                     $where .= $this->seed->db->concat($concat_table, $concat_fields) . " LIKE " . $this->seed->db->quoted($field_value . $like_char);
                                     $where .= ' OR ' . $this->seed->db->concat($concat_table, array_reverse($concat_fields)) . " LIKE " . $this->seed->db->quoted($field_value . $like_char);
                                 } else {
                                     //Check if this is a first_name, last_name search
                                     if (isset($this->seed->field_name_map) && isset($this->seed->field_name_map[$db_field])) {
                                         $vardefEntry = $this->seed->field_name_map[$db_field];
                                         if (!empty($vardefEntry['db_concat_fields']) && in_array('first_name', $vardefEntry['db_concat_fields']) && in_array('last_name', $vardefEntry['db_concat_fields'])) {
                                             if (!empty($GLOBALS['app_list_strings']['salutation_dom']) && is_array($GLOBALS['app_list_strings']['salutation_dom'])) {
                                                 foreach ($GLOBALS['app_list_strings']['salutation_dom'] as $salutation) {
                                                     if (!empty($salutation) && strpos($field_value, $salutation) === 0) {
                                                         $field_value = trim(substr($field_value, strlen($salutation)));
                                                         break;
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                     //field is not last name or this is not from global unified search, so do normal where clause
                                     $where .= $db_field . " like " . $this->seed->db->quoted(sql_like_string($field_value, $like_char));
                                 }
                             }
                             break;
                         case 'not in':
                             $where .= $db_field . ' not in (' . $field_value . ')';
                             break;
                         case 'in':
                             $where .= $db_field . ' in (' . $field_value . ')';
                             break;
                         case '=':
                             if ($type == 'bool' && $field_value == 0) {
                                 $where .= "({$db_field} = 0 OR {$db_field} IS NULL)";
                             } else {
                                 $where .= $db_field . " = " . $db->quoteType($type, $field_value);
                             }
                             break;
                             // tyoung bug 15971 - need to add these special cases into the $where query
                         // tyoung bug 15971 - need to add these special cases into the $where query
                         case 'custom_enum':
                             $where .= $field_value;
                             break;
                         case 'between':
                             if (!is_array($field_value)) {
                                 $field_value = explode('<>', $field_value);
                             }
                             $field_value[0] = $db->quoteType($type, $field_value[0]);
                             $field_value[1] = $db->quoteType($type, $field_value[1]);
                             $where .= "({$db_field} >= {$field_value[0]} AND {$db_field} <= {$field_value[1]})";
                             break;
                         case 'date_not_equal':
                             if (!is_array($field_value)) {
                                 $field_value = explode('<>', $field_value);
                             }
                             $field_value[0] = $db->quoteType($type, $field_value[0]);
                             $field_value[1] = $db->quoteType($type, $field_value[1]);
                             $where .= "({$db_field} IS NULL OR {$db_field} < {$field_value[0]} OR {$db_field} > {$field_value[1]})";
                             break;
                         case 'innerjoin':
                             $this->seed->listview_inner_join[] = $parms['innerjoin'] . " '" . $parms['value'] . "%')";
                             break;
                         case 'not_equal':
                             $field_value = $db->quoteType($type, $field_value);
                             $where .= "({$db_field} IS NULL OR {$db_field} != {$field_value})";
                             break;
                         case 'greater_than':
                             $field_value = $db->quoteType($type, $field_value);
                             $where .= "{$db_field} > {$field_value}";
                             break;
                         case 'greater_than_equals':
                             $field_value = $db->quoteType($type, $field_value);
                             $where .= "{$db_field} >= {$field_value}";
                             break;
                         case 'less_than':
                             $field_value = $db->quoteType($type, $field_value);
                             $where .= "{$db_field} < {$field_value}";
                             break;
                         case 'less_than_equals':
                             $field_value = $db->quoteType($type, $field_value);
                             $where .= "{$db_field} <= {$field_value}";
                             break;
                         case 'next_7_days':
                         case 'last_7_days':
                         case 'last_month':
                         case 'this_month':
                         case 'next_month':
                         case 'last_30_days':
                         case 'next_30_days':
                         case 'this_year':
                         case 'last_year':
                         case 'next_year':
                             if (!empty($field) && !empty($this->seed->field_name_map[$field]['type'])) {
                                 $where .= $this->parseDateExpression(strtolower($operator), $db_field, $this->seed->field_name_map[$field]['type']);
                             } else {
                                 $where .= $this->parseDateExpression(strtolower($operator), $db_field);
                             }
                             break;
                         case 'isnull':
                             $where .= "({$db_field} IS NULL OR {$db_field} = '')";
                             if ($field_value != '') {
                                 $where .= ' OR ' . $db_field . " in (" . $field_value . ')';
                             }
                             break;
                     }
                 }
             }
             if (!empty($where)) {
                 if ($itr > 1) {
                     array_push($where_clauses, '( ' . $where . ' )');
                 } else {
                     array_push($where_clauses, $where);
                 }
             }
         }
     }
     $GLOBALS['log']->debug('SearchForm2.generateSearchWhere, where_clauses: ' . print_r($where_clauses, TRUE));
     return $where_clauses;
 }
Example #27
0
function ReadConfig($input, $is_include=FALSE)
{
	global $weathermap_error_suppress;

	$curnode=null;
	$curlink=null;
	$matches=0;
	$nodesseen=0;
	$linksseen=0;
	$scalesseen=0;
	$last_seen="GLOBAL";
	$filename = "";
	$objectlinecount=0;

	 // check if $input is more than one line. if it is, it's a text of a config file
	// if it isn't, it's the filename

	$lines = array();
	
	if( (strchr($input,"\n")!=FALSE) || (strchr($input,"\r")!=FALSE ) )
	{
		 wm_debug("ReadConfig Detected that this is a config fragment.\n");
			 // strip out any Windows line-endings that have gotten in here
			 $input=str_replace("\r", "", $input);
			 $lines = split("/n",$input);
			 $filename = "{text insert}";
	}
	else
	{
		wm_debug("ReadConfig Detected that this is a config filename.\n");
		 $filename = $input;
		 
		if($is_include){ 
			wm_debug("ReadConfig Detected that this is an INCLUDED config filename.\n");
			if($is_include && in_array($filename, $this->included_files))
			{
				wm_warn("Attempt to include '$filename' twice! Skipping it.\n");
				return(FALSE);
			}
			else
			{
				$this->included_files[] = $filename;
				$this->has_includes = TRUE;
			}
		}
		
		$fd=fopen($filename, "r");
		 
		if ($fd)
		{
				while (!feof($fd))
				{
					$buffer=fgets($fd, 4096);
					// strip out any Windows line-endings that have gotten in here
					$buffer=str_replace("\r", "", $buffer);
					$lines[] = $buffer;
				}
				fclose($fd);
		}
	}
		
	$linecount = 0;
	$objectlinecount = 0;

	foreach($lines as $buffer)
	{
		$linematched=0;
		$linecount++;
		
		if (preg_match("/^\s*#/", $buffer)) {
			// this is a comment line
		}
		else
		{
			$buffer = trim($buffer);	
			
			// for any other config elements that are shared between nodes and links, they can use this
			unset($curobj);
			$curobj = NULL;
			if($last_seen == "LINK") $curobj = &$curlink;
			if($last_seen == "NODE") $curobj = &$curnode;
			if($last_seen == "GLOBAL") $curobj = &$this;
			
			$objectlinecount++;

			#if (preg_match("/^\s*(LINK|NODE)\s+([A-Za-z][A-Za-z0-9_\.\-\:]*)\s*$/i", $buffer, $matches))
			if (preg_match("/^\s*(LINK|NODE)\s+(\S+)\s*$/i", $buffer, $matches))
			{
				$objectlinecount = 0;
				if(1==1)
				{
					$this->ReadConfig_Commit($curobj);
				}
				else
				{
					// first, save the previous item, before starting work on the new one
					if ($last_seen == "NODE")
					{
						$this->nodes[$curnode->name]=$curnode;
						if($curnode->template == 'DEFAULT') $this->node_template_tree[ "DEFAULT" ][]= $curnode->name;
					
						wm_debug ("Saving Node: " . $curnode->name . "\n");
					}

					if ($last_seen == "LINK")
					{
						if (isset($curlink->a) && isset($curlink->b))
						{
							$this->links[$curlink->name]=$curlink;
							wm_debug ("Saving Link: " . $curlink->name . "\n");
						}
						else
						{
							$this->links[$curlink->name]=$curlink;
							wm_debug ("Saving Template-Only Link: " . $curlink->name . "\n");
						}
						if($curlink->template == 'DEFAULT') $this->link_template_tree[ "DEFAULT" ][]= $curlink->name;				
					}
				}

				if ($matches[1] == 'LINK')
				{
					if ($matches[2] == 'DEFAULT')
					{
						if ($linksseen > 0) { wm_warn
							("LINK DEFAULT is not the first LINK. Defaults will not apply to earlier LINKs. [WMWARN26]\n");
						}
						unset($curlink);
						wm_debug("Loaded LINK DEFAULT\n");
						$curlink = $this->links['DEFAULT'];
					}
					else
					{
						unset($curlink);

						if(isset($this->links[$matches[2]]))
						{
							wm_warn("Duplicate link name ".$matches[2]." at line $linecount - only the last one defined is used. [WMWARN25]\n");
						}
						
						wm_debug("New LINK ".$matches[2]."\n");
						$curlink=new WeatherMapLink;
						$curlink->name=$matches[2];
						$curlink->Reset($this);
										
						$linksseen++;
					}

					$last_seen="LINK";
					$curlink->configline = $linecount;
					$linematched++;
					$curobj = &$curlink;
				}

				if ($matches[1] == 'NODE')
				{
					if ($matches[2] == 'DEFAULT')
					{
						if ($nodesseen > 0) { wm_warn
							("NODE DEFAULT is not the first NODE. Defaults will not apply to earlier NODEs. [WMWARN27]\n");
						}

						unset($curnode);
						wm_debug("Loaded NODE DEFAULT\n");
						$curnode = $this->nodes['DEFAULT'];
					}
					else
					{
						unset($curnode);

						if(isset($this->nodes[$matches[2]]))
						{
							wm_warn("Duplicate node name ".$matches[2]." at line $linecount - only the last one defined is used. [WMWARN24]\n");
						}

						$curnode=new WeatherMapNode;
						$curnode->name=$matches[2];
						$curnode->Reset($this);
						
						$nodesseen++;
					}

					$curnode->configline = $linecount;
					$last_seen="NODE";
					$linematched++;
					$curobj = &$curnode;
				}
				
				# record where we first heard about this object
				$curobj->defined_in = $filename;
			}

			// most of the config keywords just copy stuff into object properties.
			// these are all dealt with from this one array. The special-cases
			// follow on from that
			$config_keywords = array(
					array('LINK','/^\s*(MAXVALUE|BANDWIDTH)\s+(\d+\.?\d*[KMGT]?)\s+(\d+\.?\d*[KMGT]?)\s*$/i',array('max_bandwidth_in_cfg'=>2,'max_bandwidth_out_cfg'=>3)),
					array('LINK','/^\s*(MAXVALUE|BANDWIDTH)\s+(\d+\.?\d*[KMGT]?)\s*$/i',array('max_bandwidth_in_cfg'=>2,'max_bandwidth_out_cfg'=>2)),
					array('NODE','/^\s*(MAXVALUE)\s+(\d+\.?\d*[KMGT]?)\s+(\d+\.?\d*[KMGT]?)\s*$/i',array('max_bandwidth_in_cfg'=>2,'max_bandwidth_out_cfg'=>3)),
					array('NODE','/^\s*(MAXVALUE)\s+(\d+\.?\d*[KMGT]?)\s*$/i',array('max_bandwidth_in_cfg'=>2,'max_bandwidth_out_cfg'=>2)),
					array('GLOBAL','/^\s*BACKGROUND\s+(.*)\s*$/i',array('background'=>1)),
					array('GLOBAL','/^\s*HTMLOUTPUTFILE\s+(.*)\s*$/i',array('htmloutputfile'=>1)),
					array('GLOBAL','/^\s*HTMLSTYLESHEET\s+(.*)\s*$/i',array('htmlstylesheet'=>1)),
					array('GLOBAL','/^\s*IMAGEOUTPUTFILE\s+(.*)\s*$/i',array('imageoutputfile'=>1)),
					array('GLOBAL','/^\s*IMAGEURI\s+(.*)\s*$/i',array('imageuri'=>1)),
					array('GLOBAL','/^\s*TITLE\s+(.*)\s*$/i',array('title'=>1)),
					array('GLOBAL','/^\s*HTMLSTYLE\s+(static|overlib)\s*$/i',array('htmlstyle'=>1)),
					array('GLOBAL','/^\s*KEYFONT\s+(\d+)\s*$/i',array('keyfont'=>1)),
					array('GLOBAL','/^\s*TITLEFONT\s+(\d+)\s*$/i',array('titlefont'=>1)),
					array('GLOBAL','/^\s*TIMEFONT\s+(\d+)\s*$/i',array('timefont'=>1)),
					array('GLOBAL','/^\s*TITLEPOS\s+(-?\d+)\s+(-?\d+)\s*$/i',array('titlex'=>1, 'titley'=>2)),
					array('GLOBAL','/^\s*TITLEPOS\s+(-?\d+)\s+(-?\d+)\s+(.*)\s*$/i',array('titlex'=>1, 'titley'=>2, 'title'=>3)),
					array('GLOBAL','/^\s*TIMEPOS\s+(-?\d+)\s+(-?\d+)\s*$/i',array('timex'=>1, 'timey'=>2)),
					array('GLOBAL','/^\s*TIMEPOS\s+(-?\d+)\s+(-?\d+)\s+(.*)\s*$/i',array('timex'=>1, 'timey'=>2, 'stamptext'=>3)),
					array('GLOBAL','/^\s*MINTIMEPOS\s+(-?\d+)\s+(-?\d+)\s*$/i',array('mintimex'=>1, 'mintimey'=>2)),
					array('GLOBAL','/^\s*MINTIMEPOS\s+(-?\d+)\s+(-?\d+)\s+(.*)\s*$/i',array('mintimex'=>1, 'mintimey'=>2, 'minstamptext'=>3)),
					array('GLOBAL','/^\s*MAXTIMEPOS\s+(-?\d+)\s+(-?\d+)\s*$/i',array('maxtimex'=>1, 'maxtimey'=>2)),
					array('GLOBAL','/^\s*MAXTIMEPOS\s+(-?\d+)\s+(-?\d+)\s+(.*)\s*$/i',array('maxtimex'=>1, 'maxtimey'=>2, 'maxstamptext'=>3)),
					array('NODE', "/^\s*LABEL\s*$/i", array('label'=>'')),	# special case for blank labels
					array('NODE', "/^\s*LABEL\s+(.*)\s*$/i", array('label'=>1)),
					array('(LINK|GLOBAL)', "/^\s*WIDTH\s+(\d+)\s*$/i", array('width'=>1)),
					array('(LINK|GLOBAL)', "/^\s*HEIGHT\s+(\d+)\s*$/i", array('height'=>1)),
					array('LINK', "/^\s*WIDTH\s+(\d+\.\d+)\s*$/i", array('width'=>1)),
					array('LINK', '/^\s*ARROWSTYLE\s+(classic|compact)\s*$/i', array('arrowstyle'=>1)),
					array('LINK', '/^\s*VIASTYLE\s+(curved|angled)\s*$/i', array('viastyle'=>1)),
					array('LINK', '/^\s*INCOMMENT\s+(.*)\s*$/i', array('comments[IN]'=>1)),
					array('LINK', '/^\s*OUTCOMMENT\s+(.*)\s*$/i', array('comments[OUT]'=>1)),
					array('LINK', '/^\s*BWFONT\s+(\d+)\s*$/i', array('bwfont'=>1)),
					array('LINK', '/^\s*COMMENTFONT\s+(\d+)\s*$/i', array('commentfont'=>1)),
					array('LINK', '/^\s*COMMENTSTYLE\s+(edge|center)\s*$/i', array('commentstyle'=>1)),
					array('LINK', '/^\s*DUPLEX\s+(full|half)\s*$/i', array('duplex'=>1)),
					array('LINK', '/^\s*BWSTYLE\s+(classic|angled)\s*$/i', array('labelboxstyle'=>1)),
					array('LINK', '/^\s*LINKSTYLE\s+(twoway|oneway)\s*$/i', array('linkstyle'=>1)),
					array('LINK', '/^\s*BWLABELPOS\s+(\d+)\s(\d+)\s*$/i', array('labeloffset_in'=>1,'labeloffset_out'=>2)),
					array('LINK', '/^\s*COMMENTPOS\s+(\d+)\s(\d+)\s*$/i', array('commentoffset_in'=>1, 'commentoffset_out'=>2)),
					array('LINK', '/^\s*USESCALE\s+([A-Za-z][A-Za-z0-9_]*)\s*$/i', array('usescale'=>1)),
					array('LINK', '/^\s*USESCALE\s+([A-Za-z][A-Za-z0-9_]*)\s+(absolute|percent)\s*$/i', array('usescale'=>1,'scaletype'=>2)),

					array('LINK', '/^\s*SPLITPOS\s+(\d+)\s*$/i', array('splitpos'=>1)),
					
					array('NODE', '/^\s*LABELOFFSET\s+([-+]?\d+)\s+([-+]?\d+)\s*$/i', array('labeloffsetx'=>1,'labeloffsety'=>2)),
					array('NODE', '/^\s*LABELOFFSET\s+(C|NE|SE|NW|SW|N|S|E|W)\s*$/i', array('labeloffset'=>1)),
                                        array('NODE', '/^\s*LABELOFFSET\s+((C|NE|SE|NW|SW|N|S|E|W)\d+)\s*$/i', array('labeloffset'=>1)),
                                        array('NODE', '/^\s*LABELOFFSET\s+(-?\d+r\d+)\s*$/i', array('labeloffset'=>1)),
                            
					array('NODE', '/^\s*LABELFONT\s+(\d+)\s*$/i', array('labelfont'=>1)),
					array('NODE', '/^\s*LABELANGLE\s+(0|90|180|270)\s*$/i', array('labelangle'=>1)),
					# array('(NODE|LINK)', '/^\s*TEMPLATE\s+(\S+)\s*$/i', array('template'=>1)),						
					
					array('LINK', '/^\s*OUTBWFORMAT\s+(.*)\s*$/i', array('bwlabelformats[OUT]'=>1,'labelstyle'=>'--')),
					array('LINK', '/^\s*INBWFORMAT\s+(.*)\s*$/i', array('bwlabelformats[IN]'=>1,'labelstyle'=>'--')),
					# array('NODE','/^\s*ICON\s+none\s*$/i',array('iconfile'=>'')),
					array('NODE','/^\s*ICON\s+(\S+)\s*$/i',array('iconfile'=>1, 'iconscalew'=>'#0', 'iconscaleh'=>'#0')),
					array('NODE','/^\s*ICON\s+(\S+)\s*$/i',array('iconfile'=>1)),
					array('NODE','/^\s*ICON\s+(\d+)\s+(\d+)\s+(inpie|outpie|box|rbox|round|gauge|nink)\s*$/i',array('iconfile'=>3, 'iconscalew'=>1, 'iconscaleh'=>2)),
					array('NODE','/^\s*ICON\s+(\d+)\s+(\d+)\s+(\S+)\s*$/i',array('iconfile'=>3, 'iconscalew'=>1, 'iconscaleh'=>2)),
					
					array('NODE','/^\s*NOTES\s+(.*)\s*$/i',array('notestext[IN]'=>1,'notestext[OUT]'=>1)),
					array('LINK','/^\s*NOTES\s+(.*)\s*$/i',array('notestext[IN]'=>1,'notestext[OUT]'=>1)),
					array('LINK','/^\s*INNOTES\s+(.*)\s*$/i',array('notestext[IN]'=>1)),
					array('LINK','/^\s*OUTNOTES\s+(.*)\s*$/i',array('notestext[OUT]'=>1)),
					
					array('NODE','/^\s*INFOURL\s+(.*)\s*$/i',array('infourl[IN]'=>1,'infourl[OUT]'=>1)),
					array('LINK','/^\s*INFOURL\s+(.*)\s*$/i',array('infourl[IN]'=>1,'infourl[OUT]'=>1)),
					array('LINK','/^\s*ININFOURL\s+(.*)\s*$/i',array('infourl[IN]'=>1)),
					array('LINK','/^\s*OUTINFOURL\s+(.*)\s*$/i',array('infourl[OUT]'=>1)),
					
					array('NODE','/^\s*OVERLIBCAPTION\s+(.*)\s*$/i',array('overlibcaption[IN]'=>1,'overlibcaption[OUT]'=>1)),
					array('LINK','/^\s*OVERLIBCAPTION\s+(.*)\s*$/i',array('overlibcaption[IN]'=>1,'overlibcaption[OUT]'=>1)),
					array('LINK','/^\s*INOVERLIBCAPTION\s+(.*)\s*$/i',array('overlibcaption[IN]'=>1)),
					array('LINK','/^\s*OUTOVERLIBCAPTION\s+(.*)\s*$/i',array('overlibcaption[OUT]'=>1)),
											
					array('(NODE|LINK)', "/^\s*ZORDER\s+([-+]?\d+)\s*$/i", array('zorder'=>1)),
					array('(NODE|LINK)', "/^\s*OVERLIBWIDTH\s+(\d+)\s*$/i", array('overlibwidth'=>1)),
					array('(NODE|LINK)', "/^\s*OVERLIBHEIGHT\s+(\d+)\s*$/i", array('overlibheight'=>1)),
					array('NODE', "/^\s*POSITION\s+([-+]?\d+)\s+([-+]?\d+)\s*$/i", array('x'=>1,'y'=>2)),
					array('NODE', "/^\s*POSITION\s+(\S+)\s+([-+]?\d+)\s+([-+]?\d+)\s*$/i", array('x'=>2,'y'=>3,'original_x'=>2,'original_y'=>3,'relative_to'=>1,'relative_resolved'=>FALSE)),
					array('NODE', "/^\s*POSITION\s+(\S+)\s+([-+]?\d+)r(\d+)\s*$/i", array('x'=>2,'y'=>3,'original_x'=>2,'original_y'=>3,'relative_to'=>1,'polar'=>TRUE,'relative_resolved'=>FALSE))
					);

			// alternative for use later where quoted strings are more useful
			$args = wm_parse_string($buffer);

			// this loop replaces a whole pile of duplicated ifs with something with consistent handling 
			foreach ($config_keywords as $keyword)
			{
				if(preg_match("/".$keyword[0]."/",$last_seen))
				{
					$statskey = $last_seen."-".$keyword[1];
					$statskey = str_replace( array('/^\s*','\s*$/i'),array('',''), $statskey);
					if(!isset($this->usage_stats[$statskey])) $this->usage_stats[$statskey] = 0;
					
					if(preg_match($keyword[1],$buffer,$matches))
					{
						# print "CONFIG MATCHED: ".$keyword[1]."\n";
						
						$this->usage_stats[$statskey]++;
						
						foreach ($keyword[2] as $key=>$val)
						{
							// so we can poke in numbers too, if the value starts with #
							// then take the # off, and treat the rest as a number literal
							if(preg_match("/^#(.*)/",$val,$m))
							{
								$val = $m[1];
							}	
							elseif(is_numeric($val)) 
							{
								// if it's a number, then it;s a match number,
								// otherwise it's a literal to be put into a variable
								$val = $matches[$val];
							}
							
							assert('is_object($curobj)');
							
							if(preg_match('/^(.*)\[([^\]]+)\]$/',$key,$m))
							{
								$index = constant($m[2]);
								$key = $m[1];
								$curobj->{$key}[$index] = $val;
							}
							else
							{
								$curobj->$key = $val;
							}
						}
						$linematched++;
						# print "\n\n";
						break;
					}
				}
			}

			if (preg_match("/^\s*NODES\s+(\S+)\s+(\S+)\s*$/i", $buffer, $matches))
			{
				if ($last_seen == 'LINK')
				{
					$valid_nodes=2;

					foreach (array(1, 2)as $i)
					{
						$endoffset[$i]='C';
						$nodenames[$i]=$matches[$i];

						// percentage of compass - must be first
						if (preg_match("/:(NE|SE|NW|SW|N|S|E|W|C)(\d+)$/i", $matches[$i], $submatches))
						{
							$endoffset[$i]=$submatches[1].$submatches[2];
							$nodenames[$i]=preg_replace("/:(NE|SE|NW|SW|N|S|E|W|C)\d+$/i", '', $matches[$i]);
							$this->need_size_precalc=TRUE;
						}
						
						if (preg_match("/:(NE|SE|NW|SW|N|S|E|W|C)$/i", $matches[$i], $submatches))
						{
							$endoffset[$i]=$submatches[1];
							$nodenames[$i]=preg_replace("/:(NE|SE|NW|SW|N|S|E|W|C)$/i", '', $matches[$i]);
							$this->need_size_precalc=TRUE;
						}

						if( preg_match("/:(-?\d+r\d+)$/i", $matches[$i], $submatches) )
						{
							$endoffset[$i]=$submatches[1];
							$nodenames[$i]=preg_replace("/:(-?\d+r\d+)$/i", '', $matches[$i]);
							$this->need_size_precalc=TRUE;
						}

						if (preg_match("/:([-+]?\d+):([-+]?\d+)$/i", $matches[$i], $submatches))
						{
							$xoff = $submatches[1];
							$yoff = $submatches[2];
							$endoffset[$i]=$xoff.":".$yoff;
							$nodenames[$i]=preg_replace("/:$xoff:$yoff$/i", '', $matches[$i]);
							$this->need_size_precalc=TRUE;
						}

						if (!array_key_exists($nodenames[$i], $this->nodes))
						{
							wm_warn ("Unknown node '" . $nodenames[$i] . "' on line $linecount of config\n");
							$valid_nodes--;
						}
					}
					
					// TODO - really, this should kill the whole link, and reset for the next one
					if ($valid_nodes == 2)
					{
						$curlink->a=$this->nodes[$nodenames[1]];
						$curlink->b=$this->nodes[$nodenames[2]];
						$curlink->a_offset=$endoffset[1];
						$curlink->b_offset=$endoffset[2];
					}
					else {
						// this'll stop the current link being added
						$last_seen="broken"; }

						$linematched++;
				}
			}

			if ( $last_seen=='GLOBAL' && preg_match("/^\s*INCLUDE\s+(.*)\s*$/i", $buffer, $matches))
			{
				if(file_exists($matches[1])){
					wm_debug("Including '{$matches[1]}'\n");
					$this->ReadConfig($matches[1], TRUE);
					$last_seen = "GLOBAL";				
				}else{
					wm_warn("INCLUDE File '{$matches[1]}' not found!\n");
				}
				$linematched++;
			}
			
			if ( ( $last_seen=='NODE' || $last_seen=='LINK' ) && preg_match("/^\s*TARGET\s+(.*)\s*$/i", $buffer, $matches))
			{
				$linematched++;
				# $targets=preg_split('/\s+/', $matches[1], -1, PREG_SPLIT_NO_EMPTY);
				$rawtargetlist = $matches[1]." ";
							
				if($args[0]=='TARGET')
				{
					// wipe any existing targets, otherwise things in the DEFAULT accumulate with the new ones
					$curobj->targets = array();
					array_shift($args); // take off the actual TARGET keyword
					
					foreach($args as $arg)
					{
						// we store the original TARGET string, and line number, along with the breakdown, to make nicer error messages later
						// array of 7 things:
						// - only 0,1,2,3,4 are used at the moment (more used to be before DS plugins)
						// 0 => final target string (filled in by ReadData)
						// 1 => multiplier (filled in by ReadData)
						// 2 => config filename where this line appears
						// 3 => linenumber in that file
						// 4 => the original target string
						// 5 => the plugin to use to pull data 
						$newtarget=array('','',$filename,$linecount,$arg,"","");
						if ($curobj)
						{
							wm_debug("  TARGET: $arg\n");
							$curobj->targets[]=$newtarget;
						}
					}
				}
			}
			
			if ($last_seen == 'LINK' && preg_match(
				"/^\s*BWLABEL\s+(bits|percent|unformatted|none)\s*$/i", $buffer,
				$matches))
			{
				$format_in = '';
				$format_out = '';
				$style = strtolower($matches[1]);
				if($style=='percent')
				{
					$format_in = FMT_PERC_IN;
					$format_out = FMT_PERC_OUT;
				}
				if($style=='bits')
				{
					$format_in = FMT_BITS_IN;
					$format_out = FMT_BITS_OUT;
				}
				if($style=='unformatted')
				{
					$format_in = FMT_UNFORM_IN;
					$format_out = FMT_UNFORM_OUT;
				}

				$curobj->labelstyle=$style;
				$curobj->bwlabelformats[IN] = $format_in;
				$curobj->bwlabelformats[OUT] = $format_out;
				$linematched++;
			}			
			
			if (preg_match("/^\s*SET\s+(\S+)\s+(.*)\s*$/i", $buffer, $matches))
			{
					$curobj->add_hint($matches[1],trim($matches[2]));
					
					if($curobj->my_type() == "map" && substr($matches[1],0,7)=='nowarn_') {
						$weathermap_error_suppress[$matches[1]] = 1;
					}
					
					$linematched++;
			}				

			// allow setting a variable to ""
			if (preg_match("/^\s*SET\s+(\S+)\s*$/i", $buffer, $matches))
			{
					$curobj->add_hint($matches[1],'');
					
					if($curobj->my_type() == "map" && substr($matches[1],0,7)=='nowarn_') {
						$weathermap_error_suppress[$matches[1]] = 1;
					}
					
					$linematched++;
			}				
			
			if (preg_match("/^\s*(IN|OUT)?OVERLIBGRAPH\s+(.+)$/i", $buffer, $matches))
			{
				$this->has_overlibs = TRUE;
				if($last_seen == 'NODE' && $matches[1] != '') {
						wm_warn("IN/OUTOVERLIBGRAPH make no sense for a NODE! [WMWARN42]\n");
					} else if($last_seen == 'LINK' || $last_seen=='NODE' ) {
				
						$urls = preg_split('/\s+/', $matches[2], -1, PREG_SPLIT_NO_EMPTY);

						if($matches[1] == 'IN') $index = IN;
						if($matches[1] == 'OUT') $index = OUT;
						if($matches[1] == '') {
							$curobj->overliburl[IN]=$urls;
							$curobj->overliburl[OUT]=$urls;
						} else {
							$curobj->overliburl[$index]=$urls;
						}
						$linematched++;
					}
			}			
		
			// array('(NODE|LINK)', '/^\s*TEMPLATE\s+(\S+)\s*$/i', array('template'=>1)),
				
			if ( ( $last_seen=='NODE' || $last_seen=='LINK' ) && preg_match("/^\s*TEMPLATE\s+(\S+)\s*$/i", $buffer, $matches))
			{
				$tname = $matches[1];
				if( ($last_seen=='NODE' && isset($this->nodes[$tname])) || ($last_seen=='LINK' && isset($this->links[$tname])) )
				{
					$curobj->template = $matches[1];
					wm_debug("Resetting to template $last_seen ".$curobj->template."\n");
					$curobj->Reset($this);
					if( $objectlinecount > 1 ) wm_warn("line $linecount: TEMPLATE is not first line of object. Some data may be lost. [WMWARN39]\n");
					// build up a list of templates - this will be useful later for the tree view
					
					if($last_seen == 'NODE') $this->node_template_tree[ $tname ][]= $curobj->name;
					if($last_seen == 'LINK') $this->link_template_tree[ $tname ][]= $curobj->name;
				}
				else
				{
					wm_warn("line $linecount: $last_seen TEMPLATE '$tname' doesn't exist! (if it does exist, check it's defined first) [WMWARN40]\n");
				}
				$linematched++;	
				
			}

			if ($last_seen == 'LINK' && preg_match("/^\s*VIA\s+([-+]?\d+)\s+([-+]?\d+)\s*$/i", $buffer, $matches))
			{
				$curlink->vialist[]=array
					(
						$matches[1],
						$matches[2]
					);

				$linematched++;
			}

			if ($last_seen == 'LINK' && preg_match("/^\s*VIA\s+(\S+)\s+([-+]?\d+)\s+([-+]?\d+)\s*$/i", $buffer, $matches))
			{
				$curlink->vialist[]=array
					(
						$matches[2],
						$matches[3],
						$matches[1]
					);

				$linematched++;
			}

			if( ($last_seen == 'NODE') && preg_match("/^\s*USE(ICON)?SCALE\s+([A-Za-z][A-Za-z0-9_]*)(\s+(in|out))?(\s+(absolute|percent))?\s*$/i",$buffer,$matches))
			{
				$svar = '';
				$stype = 'percent';
				if(isset($matches[3]))
				{
					$svar = trim($matches[3]);
				}
				if(isset($matches[6]))
				{
					$stype = strtolower(trim($matches[6]));
				}
				// opens the door for other scaley things...
				switch($matches[1])
				{
					case 'ICON':
						$varname = 'iconscalevar';
						$uvarname = 'useiconscale';
						$tvarname = 'iconscaletype';
						
						// if(!function_exists("imagefilter"))
						// {
						// 	warn("ICON SCALEs require imagefilter, which is not present in your PHP [WMWARN040]\n");
						// }
						break;
					default:
						$varname = 'scalevar';
						$uvarname = 'usescale';
						$tvarname = 'scaletype';
						break;
				}

				if($svar != '')
				{
					$curnode->$varname = $svar;
				}
				$curnode->$tvarname = $stype;
				$curnode->$uvarname = $matches[2];

				// warn("Set $varname and $uvarname\n");

				// print ">> $stype $svar ".$matches[2]." ".$curnode->name." \n";

				$linematched++;
			}

			// one REGEXP to rule them all:
//				if(preg_match("/^\s*SCALE\s+([A-Za-z][A-Za-z0-9_]*\s+)?(\d+\.?\d*)\s+(\d+\.?\d*)\s+(\d+)\s+(\d+)\s+(\d+)(?:\s+(\d+)\s+(\d+)\s+(\d+))?\s*$/i",
//	0.95b		if(preg_match("/^\s*SCALE\s+([A-Za-z][A-Za-z0-9_]*\s+)?(\d+\.?\d*)\s+(\d+\.?\d*)\s+(\d+)\s+(\d+)\s+(\d+)(?:\s+(\d+)\s+(\d+)\s+(\d+))?\s*(.*)$/i",
			if(preg_match("/^\s*SCALE\s+([A-Za-z][A-Za-z0-9_]*\s+)?(\-?\d+\.?\d*[munKMGT]?)\s+(\-?\d+\.?\d*[munKMGT]?)\s+(?:(\d+)\s+(\d+)\s+(\d+)(?:\s+(\d+)\s+(\d+)\s+(\d+))?|(none))\s*(.*)$/i",
				$buffer, $matches))
			{
				// The default scale name is DEFAULT
				if($matches[1]=='') $matches[1] = 'DEFAULT';
				else $matches[1] = trim($matches[1]);

				$key=$matches[2] . '_' . $matches[3];

				$this->colours[$matches[1]][$key]['key']=$key;

				$tag = $matches[11];				

				$this->colours[$matches[1]][$key]['tag']=$tag;

				$this->colours[$matches[1]][$key]['bottom'] = unformat_number($matches[2], $this->kilo);
				$this->colours[$matches[1]][$key]['top'] = unformat_number($matches[3], $this->kilo);
				$this->colours[$matches[1]][$key]['special'] = 0;

				if(isset($matches[10]) && $matches[10] == 'none')
				{
					$this->colours[$matches[1]][$key]['red1'] = -1;
					$this->colours[$matches[1]][$key]['green1'] = -1;
					$this->colours[$matches[1]][$key]['blue1'] = -1;
				}
				else
				{
					$this->colours[$matches[1]][$key]['red1'] = (int)($matches[4]);
					$this->colours[$matches[1]][$key]['green1'] = (int)($matches[5]);
					$this->colours[$matches[1]][$key]['blue1'] = (int)($matches[6]);
				}

				// this is the second colour, if there is one
				if(isset($matches[7]) && $matches[7] != '')
				{
					$this->colours[$matches[1]][$key]['red2'] = (int) ($matches[7]);
					$this->colours[$matches[1]][$key]['green2'] = (int) ($matches[8]);
					$this->colours[$matches[1]][$key]['blue2'] = (int) ($matches[9]);
				}


				if(! isset($this->numscales[$matches[1]]))
				{
					$this->numscales[$matches[1]]=1;
				}
				else
				{
					$this->numscales[$matches[1]]++;
				}
				// we count if we've seen any default scale, otherwise, we have to add
				// one at the end.
				if($matches[1]=='DEFAULT')
				{
					$scalesseen++;
				}

				$linematched++;
			}

			if (preg_match("/^\s*KEYPOS\s+([A-Za-z][A-Za-z0-9_]*\s+)?(-?\d+)\s+(-?\d+)(.*)/i", $buffer, $matches))
			{
				$whichkey = trim($matches[1]);
				if($whichkey == '') $whichkey = 'DEFAULT';

				$this->keyx[$whichkey]=$matches[2];
				$this->keyy[$whichkey]=$matches[3];
				$extra=trim($matches[4]);

				if ($extra != '')
					$this->keytext[$whichkey] = $extra;
				if(!isset($this->keytext[$whichkey]))
					$this->keytext[$whichkey] = "DEFAULT TITLE";
				if(!isset($this->keystyle[$whichkey]))
					$this->keystyle[$whichkey] = "classic";

				$linematched++;
			}

			
			// truetype font definition (actually, we don't really check if it's truetype) - filename + size
			if (preg_match("/^\s*FONTDEFINE\s+(\d+)\s+(\S+)\s+(\d+)\s*$/i", $buffer, $matches))
			{
				if (function_exists("imagettfbbox"))
				{
					// test if this font is valid, before adding it to the font table...
					$bounds=@imagettfbbox($matches[3], 0, $matches[2], "Ignore me");

					if (isset($bounds[0]))
					{
						$this->fonts[$matches[1]] = new WMFont();
						$this->fonts[$matches[1]]->type="truetype";
						$this->fonts[$matches[1]]->file=$matches[2];
						$this->fonts[$matches[1]]->size=$matches[3];
					}
					else { wm_warn
						("Failed to load ttf font " . $matches[2] . " - at config line $linecount [WMWARN30]");
					}
				}
				else { wm_warn
					("imagettfbbox() is not a defined function. You don't seem to have FreeType compiled into your gd module. [WMWARN31]\n");
				}

				$linematched++;
			}

			// GD font definition (no size here)
			if (preg_match("/^\s*FONTDEFINE\s+(\d+)\s+(\S+)\s*$/i", $buffer, $matches))
			{
				$newfont=imageloadfont($matches[2]);

				if ($newfont)
				{
					$this->fonts[$matches[1]] = new WMFont();
					$this->fonts[$matches[1]]->type="gd";
					$this->fonts[$matches[1]]->file=$matches[2];
					$this->fonts[$matches[1]]->gdnumber=$newfont;
				}
				else { wm_warn ("Failed to load GD font: " . $matches[2]
					. " ($newfont) at config line $linecount [WMWARN32]\n"); }

				$linematched++;
			}

			if(preg_match("/^\s*KEYSTYLE\s+([A-Za-z][A-Za-z0-9_]+\s+)?(classic|horizontal|vertical|inverted|tags)\s?(\d+)?\s*$/i",$buffer, $matches)) {
				$whichkey = trim($matches[1]);
				if($whichkey == '') $whichkey = 'DEFAULT';
				$this->keystyle[$whichkey] = strtolower($matches[2]);

				if(isset($matches[3]) && $matches[3] != '')
				{
					$this->keysize[$whichkey] = $matches[3];
				}
				else
				{
					$this->keysize[$whichkey] = $this->keysize['DEFAULT'];
				}

				$linematched++;
			}

			
			if (preg_match("/^\s*KILO\s+(\d+)\s*$/i", $buffer, $matches))
			{
				$this->kilo=$matches[1];
				# $this->defaultlink->owner->kilo=$matches[1];
				# $this->links['DEFAULT']=$matches[1];
				$linematched++;
			}
			
			if (preg_match(
				"/^\s*(TIME|TITLE|KEYBG|KEYTEXT|KEYOUTLINE|BG)COLOR\s+(\d+)\s+(\d+)\s+(\d+)\s*$/i",
				$buffer,
				$matches))
			{
				$key=$matches[1];
								
				# "Found colour line for $key\n";
				$this->colours['DEFAULT'][$key]['red1']=$matches[2];
				$this->colours['DEFAULT'][$key]['green1']=$matches[3];
				$this->colours['DEFAULT'][$key]['blue1']=$matches[4];
				$this->colours['DEFAULT'][$key]['bottom']=-2;
				$this->colours['DEFAULT'][$key]['top']=-1;
				$this->colours['DEFAULT'][$key]['special']=1;

				$linematched++;
			}

			if (($last_seen == 'NODE') && (preg_match(
				"/^\s*(AICONOUTLINE|AICONFILL|LABELFONT|LABELFONTSHADOW|LABELBG|LABELOUTLINE)COLOR\s+((\d+)\s+(\d+)\s+(\d+)|none|contrast|copy)\s*$/i",
				$buffer,
				$matches)))
			{
				$key=$matches[1];
				$field=strtolower($matches[1]) . 'colour';
				$val = strtolower($matches[2]);

				if(isset($matches[3]))	// this is a regular colour setting thing
				{
					$curnode->$field=array(	$matches[3],$matches[4],$matches[5]);
					$linematched++;
				}

				if($val == 'none' && ($matches[1]=='LABELFONTSHADOW' || $matches[1]=='LABELBG' || $matches[1]=='LABELOUTLINE' || $matches[1]=='AICONOUTLINE'))
				{
					$curnode->$field=array(-1,-1,-1);
					$linematched++;
				}
				
				if($val == 'contrast' && $matches[1]=='LABELFONT')
				{
					$curnode->$field=array(-3,-3,-3);
					$linematched++;
				}

				if($matches[2] == 'copy' && $matches[1]=='AICONFILL')
				{
					$curnode->$field=array(-2,-2,-2);
					$linematched++;
				}
			}

			if (($last_seen == 'LINK') && (preg_match(
				"/^\s*(COMMENTFONT|BWBOX|BWFONT|BWOUTLINE|OUTLINE)COLOR\s+((\d+)\s+(\d+)\s+(\d+)|none|contrast|copy)\s*$/i",
				$buffer,
				$matches)))
			{
				$key=$matches[1];
				$field=strtolower($matches[1]) . 'colour';
				$val = strtolower($matches[2]);

				if(isset($matches[3]))	// this is a regular colour setting thing
				{
					$curlink->$field=array(	$matches[3],$matches[4],$matches[5]);
					$linematched++;
				}
				
				if($val == 'none' && ($key=='BWBOX' || $key=='BWOUTLINE' || $key=='OUTLINE'))
				{
					// print "***********************************\n";
					$curlink->$field=array(-1,-1,-1);
					$linematched++;
				}
				
				if($val == 'contrast' && $key=='COMMENTFONT')
				{
					// print "***********************************\n";
					$curlink->$field=array(-3,-3,-3);
					$linematched++;
				}
			}

			if ($last_seen == 'LINK' && preg_match(
				"/^\s*ARROWSTYLE\s+(\d+)\s+(\d+)\s*$/i", $buffer, $matches))
			{
				$curlink->arrowstyle=$matches[1] . ' ' . $matches[2];
				$linematched++;
			}
			

			if ($linematched == 0 && trim($buffer) != '') { wm_warn
				("Unrecognised config on line $linecount: $buffer\n"); }

			if ($linematched > 1) { wm_warn
			("Same line ($linecount) interpreted twice. This is a program error. Please report to Howie with your config!\nThe line was: $buffer");
			}
		} // if blankline
	}     // while

	if(1==1)
	{
		$this->ReadConfig_Commit($curobj);
	}
	else
	{
	if ($last_seen == "NODE")
	{
		$this->nodes[$curnode->name]=$curnode;
		wm_debug ("Saving Node: " . $curnode->name . "\n");
		if($curnode->template == 'DEFAULT') $this->node_template_tree[ "DEFAULT" ][]= $curnode->name;	
	}

	if ($last_seen == "LINK")
	{
		if (isset($curlink->a) && isset($curlink->b))
		{
			$this->links[$curlink->name]=$curlink;
			wm_debug ("Saving Link: " . $curlink->name . "\n");
			if($curlink->template == 'DEFAULT') $this->link_template_tree[ "DEFAULT" ][]= $curlink->name;				
		}
		else { wm_warn ("Dropping LINK " . $curlink->name . " - it hasn't got 2 NODES!"); }
	}
	}
	
		
	wm_debug("ReadConfig has finished reading the config ($linecount lines)\n");
	wm_debug("------------------------------------------\n");

	// load some default colouring, otherwise it all goes wrong
	if ($scalesseen == 0)
	{
		wm_debug ("Adding default SCALE colour set (no SCALE lines seen).\n");
		$defaults=array
			(
				'0_0' => array('bottom' => 0, 'top' => 0, 'red1' => 192, 'green1' => 192, 'blue1' => 192, 'special'=>0),
				'0_1' => array('bottom' => 0, 'top' => 1, 'red1' => 255, 'green1' => 255, 'blue1' => 255, 'special'=>0),
				'1_10' => array('bottom' => 1, 'top' => 10, 'red1' => 140, 'green1' => 0, 'blue1' => 255, 'special'=>0),
				'10_25' => array('bottom' => 10, 'top' => 25, 'red1' => 32, 'green1' => 32, 'blue1' => 255, 'special'=>0),
				'25_40' => array('bottom' => 25, 'top' => 40, 'red1' => 0, 'green1' => 192, 'blue1' => 255, 'special'=>0),
				'40_55' => array('bottom' => 40, 'top' => 55, 'red1' => 0, 'green1' => 240, 'blue1' => 0, 'special'=>0),
				'55_70' => array('bottom' => 55, 'top' => 70, 'red1' => 240, 'green1' => 240, 'blue1' => 0, 'special'=>0),
				'70_85' => array('bottom' => 70, 'top' => 85, 'red1' => 255, 'green1' => 192, 'blue1' => 0, 'special'=>0),
				'85_100' => array('bottom' => 85, 'top' => 100, 'red1' => 255, 'green1' => 0, 'blue1' => 0, 'special'=>0)
			);

		foreach ($defaults as $key => $def)
		{
			$this->colours['DEFAULT'][$key]=$def;
			$this->colours['DEFAULT'][$key]['key']=$key;
			$scalesseen++;
		}
		// we have a 0-0 line now, so we need to hide that.
		$this->add_hint("key_hidezero_DEFAULT",1);
	}
	else { wm_debug ("Already have $scalesseen scales, no defaults added.\n"); }
	
	$this->numscales['DEFAULT']=$scalesseen;
	$this->configfile="$filename";

	if($this->has_overlibs && $this->htmlstyle == 'static')
	{
		wm_warn("OVERLIBGRAPH is used, but HTMLSTYLE is static. This is probably wrong. [WMWARN41]\n");
	}
	
	wm_debug("Building cache of z-layers and finalising bandwidth.\n");

// 	$allitems = array_merge($this->links, $this->nodes);

	$allitems = array();
	foreach ($this->nodes as $node)
	{
		$allitems[] = $node;
	}
	foreach ($this->links as $link)
	{
		$allitems[] = $link;
	}
	
	# foreach ($allitems as &$item)
	foreach ($allitems as $ky=>$vl)
	{
		$item =& $allitems[$ky];
		$z = $item->zorder;
		if(!isset($this->seen_zlayers[$z]) || !is_array($this->seen_zlayers[$z]))
		{
			$this->seen_zlayers[$z]=array();
		}
		array_push($this->seen_zlayers[$z], $item);
		
		// while we're looping through, let's set the real bandwidths
		if($item->my_type() == "LINK")
		{
			$this->links[$item->name]->max_bandwidth_in = unformat_number($item->max_bandwidth_in_cfg, $this->kilo);
			$this->links[$item->name]->max_bandwidth_out = unformat_number($item->max_bandwidth_out_cfg, $this->kilo);
		}
		elseif($item->my_type() == "NODE")
		{
			$this->nodes[$item->name]->max_bandwidth_in = unformat_number($item->max_bandwidth_in_cfg, $this->kilo);
			$this->nodes[$item->name]->max_bandwidth_out = unformat_number($item->max_bandwidth_out_cfg, $this->kilo);
		}
		else
		{
			wm_warn("Internal bug - found an item of type: ".$item->my_type()."\n");
		}
		// $item->max_bandwidth_in=unformat_number($item->max_bandwidth_in_cfg, $this->kilo);
		// $item->max_bandwidth_out=unformat_number($item->max_bandwidth_out_cfg, $this->kilo);
		
		wm_debug (sprintf("   Setting bandwidth on ".$item->my_type()." $item->name (%s -> %d bps, %s -> %d bps, KILO = %d)\n", $item->max_bandwidth_in_cfg, $item->max_bandwidth_in, $item->max_bandwidth_out_cfg, $item->max_bandwidth_out, $this->kilo));		
	}

	wm_debug("Found ".sizeof($this->seen_zlayers)." z-layers including builtins (0,100).\n");

	// calculate any relative positions here - that way, nothing else
	// really needs to know about them

	wm_debug("Resolving relative positions for NODEs...\n");
	// safety net for cyclic dependencies
	$i=100;
	do
	{
		$skipped = 0; $set=0;
		foreach ($this->nodes as $node)
		{
			if( ($node->relative_to != '') && (!$node->relative_resolved))
			{
				wm_debug("Resolving relative position for NODE ".$node->name." to ".$node->relative_to."\n");
				if(array_key_exists($node->relative_to,$this->nodes))
				{
					
					// check if we are relative to another node which is in turn relative to something
					// we need to resolve that one before we can resolve this one!
					if(  ($this->nodes[$node->relative_to]->relative_to != '') && (!$this->nodes[$node->relative_to]->relative_resolved) )
					{
						wm_debug("Skipping unresolved relative_to. Let's hope it's not a circular one\n");
						$skipped++;
					}
					else
					{
						$rx = $this->nodes[$node->relative_to]->x;
						$ry = $this->nodes[$node->relative_to]->y;
						
						if($node->polar)
						{
							// treat this one as a POLAR relative coordinate.
							// - draw rings around a node!
							$angle = $node->x;
							$distance = $node->y;
							$newpos_x = $rx + $distance * sin(deg2rad($angle));
							$newpos_y = $ry - $distance * cos(deg2rad($angle));
							wm_debug("->$newpos_x,$newpos_y\n");
							$this->nodes[$node->name]->x = $newpos_x;
							$this->nodes[$node->name]->y = $newpos_y;
							$this->nodes[$node->name]->relative_resolved=TRUE;
							$set++;
						}
						else
						{
							
							// save the relative coords, so that WriteConfig can work
							// resolve the relative stuff
	
							$newpos_x = $rx + $this->nodes[$node->name]->x;
							$newpos_y = $ry + $this->nodes[$node->name]->y;
							wm_debug("->$newpos_x,$newpos_y\n");
							$this->nodes[$node->name]->x = $newpos_x;
							$this->nodes[$node->name]->y = $newpos_y;
							$this->nodes[$node->name]->relative_resolved=TRUE;
							$set++;
						}
					}
				}
				else
				{
					wm_warn("NODE ".$node->name." has a relative position to an unknown node! [WMWARN10]\n");
				}
			}
		}
		wm_debug("Relative Positions Cycle $i - set $set and Skipped $skipped for unresolved dependencies\n");
		$i--;
	} while( ($set>0) && ($i!=0)  );

	if($skipped>0)
	{
		wm_warn("There are Circular dependencies in relative POSITION lines for $skipped nodes. [WMWARN11]\n");
	}

	wm_debug("-----------------------------------\n");


	wm_debug("Running Pre-Processing Plugins...\n");
	foreach ($this->preprocessclasses as $pre_class)
	{
		wm_debug("Running $pre_class"."->run()\n");
		$this->plugins['pre'][$pre_class]->run($this);
	}
	wm_debug("Finished Pre-Processing Plugins...\n");

	return (TRUE);
}
 function queryFilterBetween(&$layout_def)
 {
     return $this->_get_column_select($layout_def) . " BETWEEN " . $GLOBALS['db']->quote(unformat_number($layout_def['input_name0'])) . " AND " . $GLOBALS['db']->quote(unformat_number($layout_def['input_name1'])) . "\n";
 }
Example #29
0
/**
 * Generate a string for displaying a unique identifier that is composed
 * of a system_id and number.  This is use to allow us to generate quote
 * numbers using a DB auto-increment key from offline clients and still
 * have the number be unique (since it is modified by the system_id.
 *
 * @param	$num of bean
 * @param	$system_id from system
 * @return	$result a formatted string
 */
function format_number_display($num, $system_id)
{
    global $sugar_config;
    if (isset($num) && !empty($num)) {
        $num = unformat_number($num);
        if (isset($system_id) && $system_id == 1) {
            return sprintf("%d", $num);
        } else {
            return sprintf("%d-%d", $num, $system_id);
        }
    }
}
Example #30
0
function process_action_update($focus, $action_array)
{
    foreach ($action_array['basic'] as $field => $new_value) {
        if (empty($action_array['basic_ext'][$field])) {
            //if we have a relate field, make sure the related record still exists.
            if ($focus->field_defs[$field]['type'] == "relate") {
                $relBean = BeanFactory::getBean($focus->field_defs[$field]['module']);
                $relBean->retrieve($new_value);
                if (empty($relBean->id) && (!empty($focus->required_fields[$field]) && $focus->required_fields[$field] == true)) {
                    $GLOBALS['log']->info("workflow attempting to set relate field {$field} to invalid id: {$new_value}");
                    continue;
                }
            }
            if (!empty($focus->field_defs[$field]['calculated'])) {
                $GLOBALS['log']->info("workflow attempting to update calculated field {$field}.");
                continue;
            }
            if (in_array($focus->field_defs[$field]['type'], array('double', 'decimal', 'currency', 'float'))) {
                $new_value = (double) unformat_number($new_value);
            } elseif ($focus->field_defs[$field]['type'] === 'multienum') {
                $new_value = workflow_convert_multienum_value($new_value);
            }
            $focus->{$field} = convert_bool($new_value, $focus->field_defs[$field]['type']);
            execute_special_logic($field, $focus);
        }
        //otherwise rely on the basic_ext to handle the action for this field
        if ($field == "assigned_user_id" && (empty($_REQUEST['massupdate']) || $_REQUEST['massupdate'] === 'false')) {
            $focus->notify_inworkflow = true;
        }
        if ($field == "email1") {
            $focus->email1_set_in_workflow = $focus->email1;
        }
        if ($field == "email2") {
            $focus->email2_set_in_workflow = $focus->email2;
        }
    }
    foreach ($action_array['basic_ext'] as $field => $new_value) {
        if (!empty($focus->field_defs[$field]['calculated'])) {
            $GLOBALS['log']->info("workflow attempting to update calculated field {$field}.");
            continue;
        }
        $fieldType = get_field_type($focus->field_defs[$field]);
        //Only here if there is a datetime.
        if ($new_value == 'Triggered Date') {
            $focus->{$field} = get_expiry_date($fieldType, $action_array['basic'][$field], $fieldType === 'date');
            if ($focus->field_defs[$field]['type'] == 'date' && !empty($focus->field_defs[$field]['rel_field'])) {
                $rel_field = $focus->field_defs[$field]['rel_field'];
                $focus->{$rel_field} = get_expiry_date('time', $action_array['basic'][$field]);
            }
            execute_special_logic($field, $focus);
        }
        if ($new_value == 'Existing Value') {
            $focus->{$field} = get_expiry_date($fieldType, $action_array['basic'][$field], false, true, $focus->{$field});
            execute_special_logic($field, $focus);
        }
    }
    foreach ($action_array['advanced'] as $field => $meta_array) {
        if (!empty($focus->field_defs[$field]['calculated'])) {
            $GLOBALS['log']->info("workflow attempting to update calculated field {$field}.");
            continue;
        }
        $new_value = process_advanced_actions($focus, $field, $meta_array, $focus);
        $focus->{$field} = $new_value;
        execute_special_logic($field, $focus);
    }
    $focus->in_workflow = true;
    if (!empty($focus->email1_set_in_workflow)) {
        $focus->emailAddress->dontLegacySave = false;
        $focus->emailAddress->handleLegacySave($focus);
    }
    //end function process_action_update
}