function math_pyramid_check(WC_Challenge $chall, $formula, $maxlen, $precision = 4) { error_reporting(E_ERROR); GWF_Debug::setDieOnError(false); GWF_Debug::setMailOnError(false); $len = strlen($formula); $tests = array('0' => 0, '1' => 0.2357, '3.14' => 7.2971, '10' => 235.7023, '100' => 235702.2604); $eval = new EvalMath(); $fa = "f(a) = {$formula}"; if (false === $eval->evaluate($fa)) { echo GWF_HTML::error('Math Pyramid', $chall->lang('err_formula', array(htmlspecialchars($fa)))); return false; } GWF_Debug::setDieOnError(true); GWF_Debug::setMailOnError(true); $back = GWF_HTML::message('Math Pyramid', $chall->lang('msg_formula', array(htmlspecialchars($fa))), false); $correct = 0; foreach ($tests as $a => $result) { $result2 = $eval->evaluate("f({$a})"); $result = sprintf('%.0' . $precision . 'f', $result); $result2 = sprintf('%.0' . $precision . 'f', $result2); if ($result === $result2) { $back .= GWF_HTML::message('Math Pyramid', $chall->lang('msg_correct', array($a, $result2, $result)), false); $correct++; } else { $back .= GWF_HTML::error('Math Pyramid', $chall->lang('err_wrong', array($a, $result2, $result)), false); } } require_once GWF_CORE_PATH . 'module/WeChall/WC_MathChall.php'; if ($chall->getID() > 0 && $correct === count($tests)) { if (false === WC_MathChall::insertSolution($chall->getID(), GWF_Session::getUserID(), $formula)) { $back .= GWF_HTML::err('ERR_DATABASE', array(__FILE__, __LINE__)); } else { $back .= GWF_HTML::message('Math Pyramid', WC_HTML::lang('msg_wmc_sol_inserted', array($len, WC_MathChall::getLimitedHREF($chall, $len))), false); } } # Check Len if ($len > $maxlen) { $back .= GWF_HTML::error('Math Pyramid', $chall->lang('err_too_long', array($len, $maxlen)), false); } echo $back; if ($correct === count($tests) && $len <= $maxlen) { if ($len < $maxlen) { echo GWF_HTML::message('Math Pyramid', $chall->lang('msg_new_record', array($len, $maxlen)), false); GWF_Settings::setSetting('WC_MATH_PYRAMID', $len); } $chall->onChallengeSolved(GWF_Session::getUserID()); } }
/** * Test the return types for the random number generators. * * @since 1.5.0 */ public function test_rand_functions_type() { $result = $this->evalmath->evaluate('rand_float()'); $this->assertInternalType('float', $result); $result = $this->evalmath->evaluate('rand_int(0,1000)'); $this->assertInternalType('int', $result); }
/** * Evaluate a math expression. * * @since 1.0.0 * * @param string $expression without leading = sign. * @return string Result of the evaluation. */ protected function _evaluate_math_expression($expression) { // Straight up evaluation, without parsing of variable or function assignments (which is why we only need one instance of the object). $result = $this->evalmath->evaluate($expression); if (false === $result) { return '!ERROR! ' . $this->evalmath->last_error; } else { return (string) $result; } }
function output_mapping($input, $type) { switch ($type) { case 'Mathematical expression': $result_type = $type; include 'tools/math/evalmath.php'; $m = new EvalMath(); $output = $m->evaluate($input); break; default: $result_type = $type; $output = FALSE; } return array('output' => $output, 'type' => $result_type); }
function draw(&$row, $fields) { global $_CAMILA; $formula = $this->report->formulas[$this->field]; $ttemp = new MiniTemplator(); $ttemp->setTemplateString($formula); foreach ($fields as $key) { if ($key->value != '') { $ttemp->setVariable($key->title, $key->value, true); } else { $ttemp->setVariable($key->title, '0', true); } } $ttemp->generateOutputToString($formula); $m = new EvalMath(); $this->value = $m->evaluate($formula); parent::draw($row, $fields); }
function dotags($tags, $topic) { global $auth, $db, $user, $config, $template; global $phpEx, $phpbb_root_path; include_once $phpbb_root_path . 'roller/evalmath.class.' . $phpEx; // Need the maths $results; foreach ($tags as $tag) { $tag = str_replace(array('{', '}'), '', $tag); $tag = explode(" ", $tag); $secondparam = ""; for ($i = 1; $i < count($tag); $i++) { $secondparam = $secondparam . " " . $tag[$i]; } $m = new EvalMath(); $math = $m->evaluate($secondparam); switch (strtoupper($tag[0])) { case "ROLL": $results .= roll($math, 10); break; case "9AGAIN": $results .= roll($math, 9); break; case "8AGAIN": $results .= roll($math, 8); break; case "9-AGAIN": $results .= roll($math, 9); break; case "8-AGAIN": $results .= roll($math, 8); break; default: $results .= "<br />The {$tag['0']} command is not recognized. <br />"; // return false; } } return $results; }
function uni_cpo_calculate_price_ajax() { $aResult['status'] = 'error'; $sProductId = $_POST['uni_cpo_product_id']; $aProductCustom = get_post_custom($sProductId); if ($aProductCustom['_uni_cpo_enable_custom_options_calc'][0] == 'yes') { $aCustomOptions = uni_cpo_get_product_attributes($sProductId); $aArr = array(); if ($aCustomOptions) { foreach ($aCustomOptions as $aOption) { if (empty($aOption['is_visible']) || $aOption['is_taxonomy'] && !taxonomy_exists($aOption['name'])) { continue; } switch ($aOption['cpo_type']) { case 'input': if ($aOption['value']) { foreach ($aOption['value'] as $sValue) { $oTerm = get_term_by('slug', $sValue, $aOption['name']); $aTermData = get_option('uni_cpo_attr_' . $oTerm->term_id . '_data'); if (isset($_POST['uni_cpo_' . $sValue]) && !empty($_POST['uni_cpo_' . $sValue])) { $aArr['{uni_cpo_' . $sValue . '}'] = $_POST['uni_cpo_' . $sValue]; } else { $aArr['{uni_cpo_' . $sValue . '}'] = '0'; } } } break; case 'input_number': if ($aOption['value']) { foreach ($aOption['value'] as $sValue) { $oTerm = get_term_by('slug', $sValue, $aOption['name']); $aTermData = get_option('uni_cpo_attr_' . $oTerm->term_id . '_data'); if (isset($_POST['uni_cpo_' . $sValue]) && !empty($_POST['uni_cpo_' . $sValue])) { $aArr['{uni_cpo_' . $sValue . '}'] = $_POST['uni_cpo_' . $sValue]; } else { $aArr['{uni_cpo_' . $sValue . '}'] = '0'; } } } break; case 'select': $sParentTermSlug = $aOption['name']; //$sFieldValue = $_POST['uni_cpo_'.$sParentTermSlug]; if (isset($_POST['uni_cpo_' . $sParentTermSlug]) && !empty($_POST['uni_cpo_' . $sParentTermSlug])) { $oTerm = get_term_by('slug', $_POST['uni_cpo_' . $sParentTermSlug], $aOption['name']); $aTermData = get_option('uni_cpo_attr_' . $oTerm->term_id . '_data'); $aArr['{uni_cpo_' . $sParentTermSlug . '}'] = floatval($aTermData['attr_price']); } else { $aArr['{uni_cpo_' . $sParentTermSlug . '}'] = '0'; } break; case 'checkbox': if ($aOption['value']) { foreach ($aOption['value'] as $sValue) { $oTerm = get_term_by('slug', $sValue, $aOption['name']); $aTermData = get_option('uni_cpo_attr_' . $oTerm->term_id . '_data'); if (isset($_POST['uni_cpo_' . $sValue])) { $aArr['{uni_cpo_' . $sValue . '}'] = $_POST['uni_cpo_' . $sValue]; } else { $aArr['{uni_cpo_' . $sValue . '}'] = '0'; } } } break; case 'checkbox_multiple': $aCheckboxed = isset($_POST['uni_cpo_' . $aOption['name']]) ? $_POST['uni_cpo_' . $aOption['name']] : ''; if (isset($aCheckboxed) && !empty($aCheckboxed)) { foreach ($aCheckboxed as $sValue) { $oTerm = get_term_by('slug', $sValue, $aOption['name']); $aTermData = get_option('uni_cpo_attr_' . $oTerm->term_id . '_data'); if (isset($aTermData['attr_price'])) { $aArr['{uni_cpo_' . $sValue . '}'] = floatval($aTermData['attr_price']); } else { $aArr['{uni_cpo_' . $sValue . '}'] = '0'; } } } break; case 'radio': $sParentTermSlug = $aOption['name']; //$sFieldValue = $_POST['uni_cpo_'.$sParentTermSlug]; if (isset($_POST['uni_cpo_' . $sParentTermSlug]) && !empty($_POST['uni_cpo_' . $sParentTermSlug])) { $oTerm = get_term_by('slug', $_POST['uni_cpo_' . $sParentTermSlug], $aOption['name']); $aTermData = get_option('uni_cpo_attr_' . $oTerm->term_id . '_data'); $aArr['{uni_cpo_' . $sParentTermSlug . '}'] = floatval($aTermData['attr_price']); } else { $aArr['{uni_cpo_' . $sParentTermSlug . '}'] = '0'; } break; case 'color': $sParentTermSlug = $aOption['name']; //$sFieldValue = $_POST['uni_cpo_'.$sParentTermSlug]; if (isset($_POST['uni_cpo_' . $sParentTermSlug]) && !empty($_POST['uni_cpo_' . $sParentTermSlug])) { $aArr['{uni_cpo_' . $sParentTermSlug . '}'] = '0'; foreach ($aOption['value'] as $sValue) { $oTerm = get_term_by('slug', $sValue, $aOption['name']); $aTermData = get_option('uni_cpo_attr_' . $oTerm->term_id . '_data'); if ($aTermData['attr_color_code'] == $_POST['uni_cpo_' . $sParentTermSlug]) { $aArr['{uni_cpo_' . $sParentTermSlug . '}'] = floatval($aTermData['attr_price']); } } } else { $aArr['{uni_cpo_' . $sParentTermSlug . '}'] = '0'; } break; case 'color_ext': $sParentTermSlug = $aOption['name']; $sFieldValue = $_POST['uni_cpo_' . $sParentTermSlug]; if (isset($_POST['uni_cpo_' . $sParentTermSlug]) && !empty($_POST['uni_cpo_' . $sParentTermSlug])) { foreach ($aOption['value'] as $sValue) { $oTerm = get_term_by('slug', $sValue, $aOption['name']); $aTermData = get_option('uni_cpo_attr_' . $oTerm->term_id . '_data'); $aArr['{uni_cpo_' . $sParentTermSlug . '}'] = floatval($aTermData['attr_price']); } } else { $aArr['{uni_cpo_' . $sParentTermSlug . '}'] = '0'; } break; case 'textarea': /* if ( $aOption['value'] ) { foreach ( $aOption['value'] as $sValue ) { $oTerm = get_term_by('slug', $sValue, $aOption['name']); $aTermData = get_option('uni_cpo_attr_'.$oTerm->term_id.'_data'); if ( $_POST['uni_cpo_'.$sValue] ) { $aArr['{uni_cpo_'.$sValue.'}'] = $_POST['uni_cpo_'.$sValue]; } else { $aArr['{uni_cpo_'.$sValue.'}'] = '0'; } } } */ break; } } } $sGlobalFormula = $aProductCustom['_uni_cpo_formula'][0]; // conditions if (isset($aProductCustom['_uni_cpo_conditions_enable'][0]) && !empty($aProductCustom['_uni_cpo_conditions_enable'][0])) { $aConditions = maybe_unserialize($aProductCustom['_uni_cpo_conditions_data'][0]); if (isset($aConditions) && !empty($aConditions)) { $aPostData = $_POST; $sConditionFormula = uni_cpo_conditions_logic($aConditions, $aPostData, true); if (isset($sConditionFormula) && !empty($sConditionFormula)) { $sGlobalFormula = $sConditionFormula; } } } //print_r(' || '.$sGlobalFormula); if (!$aProductCustom['_sale_price'][0]) { $sProductPrice = $aProductCustom['_regular_price'][0]; } else { //sale price $sProductPrice = $aProductCustom['_sale_price'][0]; } $sGlobalFormula = str_replace("{uni_cpo_price}", $sProductPrice, $sGlobalFormula); //print_r($sGlobalFormula); if ($aArr) { foreach ($aArr as $Key => $Value) { if (is_array($Value)) { if (!empty($Value)) { foreach ($Value as $ChildKey => $ChildValue) { $ChildKey = '{' . $ChildKey . '}'; $sSearch = "/({$ChildKey})/"; $sGlobalFormula = preg_replace($sSearch, $ChildValue, $sGlobalFormula); } } } else { $sSearch = "/({$Key})/"; $sGlobalFormula = preg_replace($sSearch, $Value, $sGlobalFormula); } } } // change all forgotten cpo vars to zero $search = "/{([^}]*)}/"; $sGlobalFormula = preg_replace($search, '0', $sGlobalFormula); //print_r($sGlobalFormula); $m = new EvalMath(); $m->suppress_errors = true; $sOrderPrice = $m->evaluate($sGlobalFormula); $fOrderPrice = floatval($sOrderPrice); $fMinPrice = floatval($aProductCustom['_uni_cpo_min_price'][0]); $aResult['status'] = 'success'; if (!empty($fMinPrice) && $fOrderPrice < $fMinPrice) { $aResult['message'] = uni_cpo_get_formatted_price($fMinPrice); $aResult['total'] = uni_cpo_get_formatted_price($fMinPrice * $_POST['uni_quantity']); } else { $aResult['message'] = uni_cpo_get_formatted_price($fOrderPrice); $aResult['total'] = uni_cpo_get_formatted_price($fOrderPrice * $_POST['uni_quantity']); } echo json_encode($aResult); die; } else { echo json_encode($aResult); die; } }
function setRangeMax($range_max) { include_once "./Services/Math/classes/class.EvalMath.php"; $math = new EvalMath(); $math->suppress_errors = TRUE; $result = $math->evaluate($range_max); $this->range_max = $result; }
private function check_condition($condition, &$values, $response) { global $CFG; $decsep = get_string('decsep', 'langconfig'); $thousandssep = get_string('thousandssep', 'langconfig'); $values = ''; $interval = false; $operators = array('<=', '>=', '<', '>', '='); // careful with operators relative positions here, see following foreach() foreach ($operators as $operator) { $operatorposition = strpos($condition, $operator); if ($operatorposition !== false) { $conditionsides = explode($operator, $condition); $left = trim($conditionsides[0]); $right = trim($conditionsides[1]); break; } } include_once $CFG->libdir . '/evalmath/evalmath.class.php'; $math = new EvalMath(); $math->suppress_errors = true; // assigning variables values : foreach ($response as $param => &$value) { // in case someone used locale-dependant $decsep and/or $thousandssep, // make it machine-readable: $value = str_replace(' ', '', $value); $value = str_replace($thousandssep, '', $value); $value = str_replace($decsep, '.', $value); $value = floatval($value); // EvalMath doesn't like uppercase variable names $math->evaluate(strtolower(substr($param, 7)) . '=' . $value); } $leftvalue = $math->evaluate($left); if ($operator == '=') { $operator = '=='; $matches = array(); if (preg_match('/^\\s*([A-Z]*[a-z]*\\w*)\\s*=\\s*([\\[|\\]])(.+);(.+)([\\[|\\]])$/', $condition, $matches)) { // we're dealing with an interval $interval = true; $operator = ''; $rightvalue = $matches[2] == "[" ? ">=" : ">"; $val1 = (double) $math->evaluate(strtolower($matches[3])); $val2 = (double) $math->evaluate(strtolower($matches[4])); // failsafe : EvalMath returns false instead of zero, so cast result as float $rightvalue .= $val1 . " && " . $leftvalue; $rightvalue .= $matches[5] == "]" ? "<=" : "<"; $rightvalue .= $val2; } } if (!$interval) { $rightvalue = $math->evaluate($right); $values .= number_format($leftvalue, 2, $decsep, $thousandssep) . ' ' . $operator . ' ' . number_format($rightvalue, 2, $decsep, $thousandssep); } else { $values .= $leftvalue . ' = ' . $matches[2] . number_format($val1, 3, $decsep, $thousandssep) . ';' . number_format($val2, 3, $decsep, $thousandssep) . $matches[5]; } if (strlen($leftvalue) > 0 && isset($operator) && strlen($rightvalue) > 0 && eval('return(' . $leftvalue . $operator . $rightvalue . ');')) { $valuesspan = '<span'; $valuesspan .= $this->usecolorforfeedback ? ' style="color:#090"' : ''; $valuesspan .= '>' . get_string('conditionverified', 'qtype_multinumerical') . ' : ' . $values . '</span>'; $values = $valuesspan; return true; } $valuesspan = '<span'; $valuesspan .= $this->usecolorforfeedback ? ' style="color:#f00"' : ''; $valuesspan .= '>' . get_string('conditionnotverified', 'qtype_multinumerical') . ' : ' . $values . '</span>'; $values = $valuesspan; return false; }
/** * Return the value of a custom field * * @param string $key * * @return mixed */ public function getCustomField($key) { $var_name = "_customfield{$key}"; if (property_exists($this, $var_name)) { $customtype = TBGCustomDatatype::getByKey($key); if ($customtype->getType() == TBGCustomDatatype::CALCULATED_FIELD) { $result = null; $options = $customtype->getOptions(); if (!empty($options)) { $formula = array_pop($options)->getValue(); preg_match_all('/{([[:alnum:]]+)}/', $formula, $matches); $hasValues = false; for ($i = 0; $i < count($matches[0]); $i++) { $value = $this->getCustomField($matches[1][$i]); if ($value instanceof TBGCustomDatatypeOption) { $value = $value->getValue(); } if (is_numeric($value)) { $hasValues = true; } $value = floatval($value); $formula = str_replace($matches[0][$i], $value, $formula); } // Check to verify formula only includes numbers and allowed operators if ($hasValues && !preg_match('/[^0-9\\+-\\/*\\(\\)%]/', $formula)) { try { $m = new EvalMath(); $m->suppress_errors = true; $result = $m->evaluate($formula); if (!empty($m->last_error)) { $result = $m->last_error; } else { $result = round($result, 2); } } catch (Exception $e) { $result = 'N/A'; } } } return $result; } elseif ($this->{$var_name} && $customtype->hasCustomOptions() && !$this->{$var_name} instanceof TBGCustomDatatypeOption) { $this->{$var_name} = new TBGCustomDatatypeOption($this->{$var_name}); } return $this->{$var_name}; } else { return null; } }
/** * Saves the learners input of the question to the database. * * @access public * @param integer $active_id Active id of the user * @param integer $pass Test pass * @return boolean $status */ public function saveWorkingData($active_id, $pass = NULL) { global $ilDB; global $ilUser; if (is_null($pass)) { include_once "./Modules/Test/classes/class.ilObjTest.php"; $pass = ilObjTest::_getPass($active_id); } $entered_values = 0; $numeric_result = str_replace(",", ".", $_POST["numeric_result"]); include_once "./Services/Math/classes/class.EvalMath.php"; $math = new EvalMath(); $math->suppress_errors = TRUE; $result = $math->evaluate($numeric_result); $returnvalue = true; if (($result === FALSE || $result === TRUE) && strlen($result) > 0) { ilUtil::sendInfo($this->lng->txt("err_no_numeric_value"), true); $returnvalue = false; } $result = $ilDB->queryF("SELECT solution_id FROM tst_solutions WHERE active_fi = %s AND question_fi = %s AND pass = %s", array('integer', 'integer', 'integer'), array($active_id, $this->getId(), $pass)); $row = $ilDB->fetchAssoc($result); $update = $row["solution_id"]; if ($update) { if (strlen($numeric_result)) { $affectedRows = $ilDB->update("tst_solutions", array("value1" => array("clob", trim($numeric_result)), "tstamp" => array("integer", time())), array("solution_id" => array("integer", $update))); $entered_values++; } else { $affectedRows = $ilDB->manipulateF("DELETE FROM tst_solutions WHERE solution_id = %s", array('integer'), array($update)); } } else { if (strlen($numeric_result)) { $next_id = $ilDB->nextId('tst_solutions'); $affectedRows = $ilDB->insert("tst_solutions", array("solution_id" => array("integer", $next_id), "active_fi" => array("integer", $active_id), "question_fi" => array("integer", $this->getId()), "value1" => array("clob", trim($numeric_result)), "value2" => array("clob", null), "pass" => array("integer", $pass), "tstamp" => array("integer", time()))); $entered_values++; } } if ($entered_values) { include_once "./Modules/Test/classes/class.ilObjAssessmentFolder.php"; if (ilObjAssessmentFolder::_enabledAssessmentLogging()) { $this->logAction($this->lng->txtlng("assessment", "log_user_entered_values", ilObjAssessmentFolder::_getLogLanguage()), $active_id, $this->getId()); } } else { include_once "./Modules/Test/classes/class.ilObjAssessmentFolder.php"; if (ilObjAssessmentFolder::_enabledAssessmentLogging()) { $this->logAction($this->lng->txtlng("assessment", "log_user_not_entered_values", ilObjAssessmentFolder::_getLogLanguage()), $active_id, $this->getId()); } } return $returnvalue; }
/** * Generate a set of suggestions for the given bank transaction * * @return array(match structures) */ public function match(CRM_Banking_BAO_BankTransaction $btx, CRM_Banking_Matcher_Context $context) { $config = $this->_plugin_config; $threshold = $this->getThreshold(); $data_parsed = $btx->getDataParsed(); $probability = 1.0 - $this->getPenalty($btx); $cancellation_mode = (bool) $config->cancellation_enabled && $btx->amount < 0; // look for the 'sepa_mandate' key if (empty($data_parsed['sepa_mandate'])) { return null; } // now load the mandate $mandate_reference = $data_parsed['sepa_mandate']; $mandate = civicrm_api('SepaMandate', 'getsingle', array('version' => 3, 'reference' => $mandate_reference)); if (!empty($mandate['is_error'])) { CRM_Core_Session::setStatus(sprintf(ts("Couldn't load SEPA mandate for reference %s"), $mandate_reference), ts('Error'), 'error'); return null; } // find the contribution if ($mandate['type'] == 'OOFF' && $mandate['entity_table'] == 'civicrm_contribution') { $contribution_id = $mandate['entity_id']; } elseif ($mandate['entity_table'] == 'civicrm_contribution_recur') { $contribution_recur_id = $mandate['entity_id']; $value_date = strtotime($btx->value_date); if ($cancellation_mode) { $earliest_date = date('Ymdhis', strtotime($config->cancellation_date_minimum, $value_date)); $latest_date = date('Ymdhis', strtotime($config->cancellation_date_maximum, $value_date)); } else { $earliest_date = date('Ymdhis', strtotime($config->received_date_minimum, $value_date)); $latest_date = date('Ymdhis', strtotime($config->received_date_maximum, $value_date)); } $contribution_id = 0; $find_contribution_query = "\n SELECT id\n FROM civicrm_contribution\n WHERE contribution_recur_id={$contribution_recur_id}\n AND receive_date <= DATE('{$latest_date}')\n AND receive_date >= DATE('{$earliest_date}');"; $found_contribution = CRM_Core_DAO::executeQuery($find_contribution_query); while ($found_contribution->fetch()) { if (!$contribution_id) { $contribution_id = $found_contribution->id; } else { // this is the second contribution found! CRM_Core_Session::setStatus(ts("There was more than one matching contribution found! Try to configure the plugin with a smaller search time span."), ts('Error'), 'error'); return null; } } if (!$contribution_id) { // no contribution found CRM_Core_Session::setStatus(ts("There was no matching contribution! Try to configure the plugin with a larger search time span."), ts('Error'), 'error'); return null; } } else { error_log("org.project60.sepa: matcher_sepa: Bad mandate type."); return null; } // now, let's have a look at this contribution and its contact... $contribution = civicrm_api('Contribution', 'getsingle', array('id' => $contribution_id, 'version' => 3)); if (!empty($contribution['is_error'])) { CRM_Core_Session::setStatus(ts("The contribution connected to this mandate could not be read."), ts('Error'), 'error'); return null; } $contact = civicrm_api('Contact', 'getsingle', array('id' => $contribution['contact_id'], 'version' => 3)); if (!empty($contact['is_error'])) { CRM_Core_Session::setStatus(ts("The contact connected to this mandate could not be read."), ts('Error'), 'error'); return null; } // now: create a suggestion $suggestion = new CRM_Banking_Matcher_Suggestion($this, $btx); $suggestion->setParameter('contribution_id', $contribution_id); $suggestion->setParameter('contact_id', $contribution['contact_id']); $suggestion->setParameter('mandate_id', $mandate['id']); $suggestion->setParameter('mandate_reference', $mandate_reference); if (!$cancellation_mode) { // STANDARD SUGGESTION: $suggestion->setTitle(ts("SEPA SDD Transaction")); // add penalties for deviations in amount,status,deleted contact if ($btx->amount != $contribution['total_amount']) { $suggestion->addEvidence($config->deviation_penalty, ts("The contribution does not feature the expected amount.")); $probability -= $config->deviation_penalty; } $status_inprogress = banking_helper_optionvalue_by_groupname_and_name('contribution_status', 'In Progress'); if ($contribution['contribution_status_id'] != $status_inprogress) { $suggestion->addEvidence($config->deviation_penalty, ts("The contribution does not have the expected status 'in Progress'.")); $probability -= $config->deviation_penalty; } if (!empty($contact['contact_is_deleted'])) { $suggestion->addEvidence($config->deviation_penalty, ts("The contact this mandate belongs to has been deleted.")); $probability -= $config->deviation_penalty; } } else { // CANCELLATION SUGGESTION: $suggestion->setTitle(ts("Cancel SEPA SDD Transaction")); $suggestion->setParameter('cancellation_mode', $cancellation_mode); // calculate penalties (based on CRM_Banking_PluginImpl_Matcher_ExistingContribution::rateContribution) $contribution_amount = $contribution['total_amount']; $target_amount = -$context->btx->amount; $amount_range_rel = $contribution_amount * ($config->cancellation_amount_relative_maximum - $config->cancellation_amount_relative_minimum); $amount_range_abs = $config->cancellation_amount_absolute_maximum - $config->cancellation_amount_absolute_minimum; $amount_range = max($amount_range_rel, $amount_range_abs); $amount_delta = $contribution_amount - $target_amount; // check for amount limits if ($amount_range) { $penalty = $config->cancellation_amount_penalty * (abs($amount_delta) / $amount_range); if ($penalty > $config->cancellation_penalty_threshold) { $suggestion->addEvidence($config->cancellation_amount_penalty, ts("The cancellation fee, i.e. the deviation from the original amount, is not in the specified range.")); $probability -= $penalty; } } // add general cancellation penalty, if set $probability -= (double) $config->cancellation_general_penalty; // generate cancellation extra parameters if ($config->cancellation_cancel_reason) { // determine the cancel reason if (empty($data_parsed[$config->cancellation_cancel_reason_source])) { $suggestion->setParameter('cancel_reason', $config->cancellation_cancel_reason_default); } else { $suggestion->setParameter('cancel_reason', $data_parsed[$config->cancellation_cancel_reason_source]); } } if ($config->cancellation_cancel_fee) { // calculate / determine the cancellation fee try { $meval = new EvalMath(); // first initialise variables 'difference' and 'source' $meval->evaluate("difference = -{$btx->amount} - {$contribution_amount}"); if (empty($config->cancellation_cancel_fee_source) || empty($data_parsed[$config->cancellation_cancel_fee_source])) { $meval->evaluate("source = 0.0"); } else { $meval->evaluate("source = {$data_parsed[$config->cancellation_cancel_fee_source]}"); } $suggestion->setParameter('cancel_fee', number_format($meval->evaluate($config->cancellation_cancel_fee_default), 2)); } catch (Exception $e) { error_log("org.project60.banking.matcher.existing: Couldn't calculate cancellation_fee. Error was: {$e}"); } } } // store it $suggestion->setProbability($probability); $btx->addSuggestion($suggestion); return $this->_suggestions; }
public function setRangeMax($range_max) { // include_once "./Services/Math/classes/class.EvalMath.php"; // $math = new EvalMath(); // $math->suppress_errors = TRUE; // $result = $math->evaluate($range_max); // $val = (strlen($result) > 8) ? strtoupper(sprintf("%e", $result)) : $result; // $this->range_max = $val; include_once "./Services/Math/classes/class.EvalMath.php"; $math = new EvalMath(); $math->suppress_errors = TRUE; $result = $math->evaluate($range_max); $this->range_max = $result; }
$equationval = $_REQUEST['equationval']; $_SESSION['equation'] = $equation; $_SESSION['equationval'] = $equationval; $_SESSION['iname'] = $iname; if (isset($_REQUEST['ComputeValues'])) { $X = ''; $Val = ''; include 'evalmath.class.php'; $equation = preg_replace("/(^[\r\n]*|[\r\n]+)[\\s\t]*[\r\n]+/", "\n", $equation); $equation = str_replace(' ', '', $equation); $m = new EvalMath(); $m->suppress_errors = true; $Tch = explode("\n", $equation); foreach ($Tch as $value) { $X = explode("=", $value); $res = $m->evaluate($value); // echo $res."<br>"; if ($X[0] != '') { $Val = $Val . $X[0] . "=" . $res . "\n"; } } $Val = preg_replace("/(^[\r\n]*|[\r\n]+)[\\s\t]*[\r\n]+/", "\n", $Val); $Val = str_replace(' ', '', $Val); mysql_select_db("{$DBM}"); $req = "UPDATE `indicator` SET `iequation` ='{$equation}',`ivalues` ='{$Val}' WHERE iname='{$iname}'"; mysql_query($req); mysql_close(); header('Location: LoadIndicator.php?cn=' . $iname); } else { echo "<html>"; echo "<body>";
public function testInvalidExpressions() { $Eval = new EvalMath(); $Eval->suppress_errors = true; $result = $Eval->evaluate('()'); $this->assertEqual($Eval->getLastError(), 'Unexpected \')\''); $result = $Eval->evaluate('1)'); $this->assertEqual($Eval->getLastError(), 'Unexpected \')\''); $result = $Eval->evaluate('(('); $this->assertEqual($Eval->getLastError(), 'Expecting \')\''); $result = $Eval->evaluate('2+3+'); $this->assertEqual($Eval->getLastError(), 'Operator \'+\' lacks operand'); $Eval->suppress_errors = false; $this->expectError('Unexpected \',\''); $result = $Eval->evaluate('a(1,2'); $this->assertEqual($Eval->getLastError(), 'Unexpected \',\''); $this->assertIdentical(false, $result); $this->expectError('Illegal character \'#\''); $result = $Eval->evaluate('#'); $this->assertEqual($Eval->getLastError(), 'Illegal character \'#\''); $this->assertIdentical(false, $result); $this->expectError('Wrong number of arguments (3 given, 2 expected)'); $Eval->evaluate('f(x,y) = x+y'); $result = $Eval->evaluate('f(2,3,4)'); $this->assertEqual($Eval->getLastError(), 'Wrong number of arguments (3 given, 2 expected)'); $this->assertIdentical(false, $result); $this->expectError('Too many arguments (2 given, 1 expected)'); $result = $Eval->evaluate('log(2,1)'); $this->assertEqual($Eval->getLastError(), 'Too many arguments (2 given, 1 expected)'); $this->assertIdentical(false, $result); $this->expectError('Undefined variable \'z\' in function definition'); $result = $Eval->evaluate('f(x,y) = x+y+z'); $this->assertEqual($Eval->getLastError(), 'Undefined variable \'z\' in function definition'); $this->assertIdentical(false, $result); unset($Eval); }
function decomposer($equation) { $fb = array('sin', 'cos', 'tan', 'sqrt', 'abs', 'ln', 'log', 'exp'); $bg = array('sinh', 'arcsin', 'asin', 'arcsinh', 'asinh', 'cosh', 'arccos', 'acos', 'arccosh', 'acosh', 'tanh', 'arctan', 'atan', 'arctanh', 'atanh'); $c = array('+', '-', '(', ')', '/', '*', '^'); $numeric = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0'); $X = explode('=', $equation); $output = $X[0]; $Y = $X[1]; foreach ($numeric as $key => $v) { $Y = str_replace($v, '#', $Y); } foreach ($c as $key => $v) { $Y = str_replace($v, '#', $Y); } foreach ($bg as $key => $v) { $Y = str_replace($v, '#', $Y); } foreach ($fb as $key => $v) { $Y = str_replace($v, '#', $Y); } $Y = str_replace(' ', '', $Y); for ($i = 0; $i < strlen($Y); $i++) { if ($Y[$i] == '#') { for ($j = $i + 1; $j < strlen($Y); $j++) { if ($Y[$j] == '#') { $Y[$j] = ' '; } else { break; } } } } $Y = str_replace(' ', '', $Y); $input = ''; if ($Y[0] == '#') { for ($i = 1; $i < strlen($Y); $i++) { $input = $input . $Y[$i]; } } else { $input = $Y; } $input = explode('#', $input); $input = array_unique($input); $j = 0; for ($i = 0; $i < sizeof($input); $i++) { if (strlen($input[$i]) != 0) { $INPUT[$j] = $input[$i]; $j++; } } $f = $X[1]; foreach ($INPUT as $key => $value) { $kamich = rand(1, 5); $f = str_replace($value, "{$kamich}", $f); } $m = new EvalMath(); $m->suppress_errors = true; $res = $m->evaluate($f); if ($res == false) { $result = array("Er" => "Somthing Wrong with your Equation"); } else { $result = array("output" => $output, "input" => json_encode($INPUT)); } echo json_encode($result); }
public function isValidSolutionSubmit($numeric_solution) { require_once './Services/Math/classes/class.EvalMath.php'; $math = new EvalMath(); $math->suppress_errors = TRUE; $result = $math->evaluate($numeric_solution); return !(($result === FALSE || $result === TRUE) && strlen($numeric_solution) > 0); }
function Evaluation($id, $value, $input, $exercise_id, $operatorData, $answer) { $m = new EvalMath(); $xml = simplexml_load_file($exercise_id) or die("Error: Cannot create object"); $count_options = $xml->input[$id]->count(); for ($i = 0; $i < $count_options; $i++) { $operator = $xml->input[$id]->option[$i]->operator; $equation = trim($xml->input[$id]->option[$i]->equation); $data = explode(" ", $equation); $equation = ""; $operatorDT = ""; if ($operator == 'IF') { // retrieve elements from de conditional $cont = 0; foreach ($data as $element) { if ($element[0] == 'v') { $trimmed = intval(ltrim($element, "v")); $value[$cont] = strval($input[$trimmed]); } elseif ($element[0] == 'a') { $trimmed = intval(ltrim($element, "a")); $value[$cont] = strval($answer[$trimmed - 1]); } else { $value[$cont] = strval($element); } //if($value[$cont] == "==") // return "ccc"; $cont++; } // evaluate one or two conditional statements if ($cont <= 3) { if (condicional($value[0], $data[1], $value[2])) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } } else { if ($data[3] == "and") { if (condicional($value[0], $data[1], $value[2]) and condicional($value[4], $data[5], $value[6])) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } } else { if ($data[3] == "or") { if (condicional($value[0], $data[1], $value[2]) or condicional($value[4], $data[5], $value[6])) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } } } } /* switch($data[1]) { case "==": if($equation == $data[2]) {return $xml->input[$id]->option[$i]->result; $i=$count_options; } break; case "!=": if($equation != $data[2]) {return $xml->input[$id]->option[$i]->result; $i=$count_options; } break; case "GT": if($equation > $data[2]) {return $xml->input[$id]->option[$i]->result; $i=$count_options; } break; case "GE": if($equation >= $data[2]) {return $xml->input[$id]->option[$i]->result; $i=$count_options; } break; case "LT": if($equation < $data[2]) {return $xml->input[$id]->option[$i]->result; $i=$count_options; } break; case "LE": if($equation <= $data[2]) {return $xml->input[$id]->option[$i]->result; $i=$count_options; } break; } // SWITCH */ } else { foreach ($data as $element) { if (is_numeric($element)) { $equation .= $element; } else { if ($element[0] == 'o') { $operatorDT = ltrim($element, "o"); } elseif ($element[0] == 'v') { $trimmed = intval(ltrim($element, "v")); $equation .= $input[$trimmed]; } elseif ($element[0] == 'a') { $trimmed = intval(ltrim($element, "a")); $equation .= $answer[$trimmed - 1]; } else { $equation .= $element; } /* elseif (strpos($element,'v') === False) { $equation .= $element; } else { $trimmed = intval(ltrim($element, "v")); $equation .= $input[$trimmed]; } */ } } // return $equation[3]; // $equation = "mcm(2,4)"; if (strstr($equation, "mcm")) { $valor = explode(",", substr($equation, 3)); $equation_result = mcm(intval($valor[0]), intval($valor[1])); } elseif (strstr($equation, "smn")) { $valor = explode(",", substr($equation, 3)); $equation_result = smn(intval($valor[0]), intval($valor[1])); } elseif (strstr($equation, "smd")) { $valor = explode(",", substr($equation, 3)); $equation_result = smd(intval($valor[0]), intval($valor[1])); } elseif (strstr($equation, "cod")) { $valor = explode(",", substr($equation, 3)); $equation_result = cod(intval($valor[0]), intval($valor[1])); } elseif (strstr($equation, "red")) { $valor = explode(",", substr($equation, 3)); $equation_result = red(intval($valor[0]), intval($valor[1])); } elseif (strstr($equation, "txt")) { $valor = explode(",", substr($equation, 3)); $equation_result = txt($valor[0], $valor[1]); } else { $equation_result = $m->evaluate($equation); } if ($operatorDT == "") { $operatorData = ""; } // return strval($equation_result); switch ($operator) { case "==": if ($equation_result == $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "!=": if ($equation_result != $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "GT": if ($equation_result > $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "GE": if ($equation_result >= $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "LT": if ($equation_result < $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "LE": if ($equation_result <= $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; } // SWITCH } // else IF } // option's LOOP }
function refresh($json, $after = null, $before = null) { $trace = $this->TraceOrigin[0]; $this->name = $json["Name"]; $formule = $json["formule"]; $this->formule = $json["formule"]; $input = $json["input"]; $variable = array(); $transformation = $json["Transformation"]; // verification si la dernière transformation est faite ou non !! // si oui pas la peine de refaire toutes les transformation. avec KTBS les obsels se propagent !!!cool non ? // si non on fait les transformations. $s = sizeof($transformation) - 1; $tname = str_replace(' ', '_', $this->name . " {$s}"); $b = $trace->getBaseUri(); $trverif = new Trace($b . $tname); $c = $json["createdOn"]; $encode = true; if (!$trverif->exist()) { $encode = false; $k = 0; $models = array(); if ($transformation == null && $c == null) { $encode = false; goto notransformation; } if ($transformation == null && $c != null) { $encode = true; goto notransformation; } } else { $trace = $trverif; } notransformation: $this->ComputedTrace = $trace; $reponse = RestfulHelper::getInfo($trace->getUri()); while ($reponse == null) { sleep(2); $reponse = RestfulHelper::getInfo($trace->getUri()); } $values = array(); // $cond = array(); // if($after != null){ // $time = strtotime($after)*1000; // $cond[] = 'minb='.$time; // } // if($before != null){ // $time = strtotime($before)*1000; // $cond[] = 'maxb='.$time; // } // $times = implode('&', $cond); $Tcomp = new ComputedTrace($trace->getBaseUri(), 'time' . str_replace(' ', '_', $this->name)); if ($Tcomp->exist()) { $Tcomp->Delete(); } $Tcomp->config('filter', array($trace)); $Tcomp->setFilterParameter($after, $before); $Tcomp->filter(); $trace = new Trace($Tcomp->getUri()); foreach ($input as $key => $value) { $sparql = $value["operation"]; if ($encode == false) { $sparql = urlencode($sparql); } $URL = null; // if(strlen($times) == 0 ){ $URL = $trace->getUri() . "@obsels?query=" . $sparql; // } // else{ // $URL = $trace->getUri()."@obsels?".$times."&query=".$sparql; // } $r = RestfulHelper::httpInfo($URL); while ($r == "409") { sleep(1); $r = RestfulHelper::httpInfo($URL); } $reponse = RestfulHelper::getInfo($URL); $rep = json_decode($reponse, true); $res = $rep['results']; $resultat = $res['bindings']; $val = $resultat[0]; $keys = array_keys($val); $a = $val[$keys[0]]; $va = $a["value"]; if (gettype(intval($va)) != "integer") { $va = 0; } $values[$value['name']] = $va; } $f = $formule; foreach ($values as $key => $value) { $f = str_replace($key, $value, $f); } $m = new EvalMath(); $m->suppress_errors = true; $equation = explode("=", $f); $res = $m->evaluate($equation[1]); $Tcomp->Delete(); if ($res == false) { return array("var" => $equation[0], "val" => "ERROR : Time intervale caused an error"); } else { return array("var" => $equation[0], "val" => $res); } }
function check_permissions($userid, $context) { global $DB, $CFG, $USER; if (has_capability('block/configurable_reports:manageownreports', $context, $userid) && $this->config->ownerid == $userid) { return true; } if (has_capability('block/configurable_reports:managereports', $context, $userid)) { return true; } if (empty($this->config->visible)) { return false; } $components = cr_unserialize($this->config->components); $permissions = isset($components['permissions']) ? $components['permissions'] : array(); if (empty($permissions['elements'])) { return has_capability('block/configurable_reports:viewreports', $context); } else { $i = 1; $cond = array(); foreach ($permissions['elements'] as $p) { require_once $CFG->dirroot . '/blocks/configurable_reports/plugin.class.php'; require_once $CFG->dirroot . '/blocks/configurable_reports/components/permissions/' . $p['pluginname'] . '/plugin.class.php'; $classname = 'plugin_' . $p['pluginname']; $class = new $classname($this->config); $cond[$i] = $class->execute($userid, $context, $p['formdata']); $i++; } if (count($cond) == 1) { return $cond[1]; } else { $m = new EvalMath(); $orig = $dest = array(); if (isset($permissions['config']) && isset($permissions['config']->conditionexpr)) { $logic = trim($permissions['config']->conditionexpr); // Security // No more than: conditions * 10 chars $logic = substr($logic, 0, count($permissions['elements']) * 10); $logic = str_replace(array('and', 'or'), array('&&', '||'), strtolower($logic)); // More Security Only allowed chars $logic = preg_replace('/[^&c\\d\\s|()]/i', '', $logic); //$logic = str_replace('c','$c',$logic); $logic = str_replace(array('&&', '||'), array('*', '+'), $logic); for ($j = $i - 1; $j > 0; $j--) { $orig[] = 'c' . $j; $dest[] = $cond[$j] ? 1 : 0; } return $m->evaluate(str_replace($orig, $dest, $logic)); } else { return false; } } } }
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?> "> y(x) = <input type="text" name="function" value="<?php echo isset($_POST['function']) ? htmlspecialchars($_POST['function']) : ''; ?> "> <input type="submit"> </form> <?php if (isset($_POST['function']) and $_POST['function']) { include 'evalmath.class.php'; $m = new EvalMath(); $m->suppress_errors = true; if ($m->evaluate('y(x) = ' . $_POST['function'])) { print "\t<table border=\"1\">\n"; print "\t\t<tr><th>x</th><th>y(x)</th>\n"; for ($x = -2; $x <= 2; $x += 0.2) { $x = round($x, 2); print "\t\t<tr><td>{$x}</td><td>" . $m->e("y({$x})") . "</td></tr>\n"; } print "\t</table>\n"; } else { print "\t<p>Could not evaluate function: " . $m->last_error . "</p>\n"; } } ?> </body> </html>
/** * abstract function which creates the form to create / edit the answers of the question * @param FormValidator $form */ function processAnswersCreation($form) { if (!self::isAnswered()) { $table = Database::get_course_table(TABLE_QUIZ_ANSWER); Database::delete($table, array('c_id = ? AND question_id = ?' => array($this->course['real_id'], $this->id))); $answer = $form->getSubmitValue('answer'); $formula = $form->getSubmitValue('formula'); $lowestValues = $form->getSubmitValue('lowestValue'); $highestValues = $form->getSubmitValue('highestValue'); $answerVariations = $form->getSubmitValue('answerVariations'); $this->weighting = $form->getSubmitValue('weighting'); // Create as many answers as $answerVariations for ($j = 0; $j < $answerVariations; $j++) { $auxAnswer = $answer; $auxFormula = $formula; $nb = preg_match_all('/\\[[^\\]]*\\]/', $auxAnswer, $blanks); if ($nb > 0) { for ($i = 0; $i < $nb; ++$i) { $blankItem = $blanks[0][$i]; $replace = array("[", "]"); $newBlankItem = str_replace($replace, "", $blankItem); $newBlankItem = "[" . trim($newBlankItem) . "]"; // take random float values when one or both edge values have a decimal point $randomValue = strpos($lowestValues[$i], '.') !== false || strpos($highestValues[$i], '.') !== false ? mt_rand($lowestValues[$i] * 100, $highestValues[$i] * 100) / 100 : mt_rand($lowestValues[$i], $highestValues[$i]); $auxAnswer = str_replace($blankItem, $randomValue, $auxAnswer); $auxFormula = str_replace($blankItem, $randomValue, $auxFormula); } require_once api_get_path(LIBRARY_PATH) . 'evalmath.class.php'; $math = new EvalMath(); $result = $math->evaluate($auxFormula); $result = number_format($result, 2, ".", ""); // Remove decimal trailing zeros $result = rtrim($result, "0"); // If it is an integer (ends in .00) remove the decimal point if (mb_substr($result, -1) === ".") { $result = str_replace(".", "", $result); } // Attach formula $auxAnswer .= " [" . $result . "]@@" . $formula; } $this->save(); $objAnswer = new answer($this->id); $objAnswer->createAnswer($auxAnswer, 1, '', $this->weighting, null); $objAnswer->position = array(); $objAnswer->save(); } } }
/** * Generate a set of suggestions for the given bank transaction * * @return array(match structures) */ public function match(CRM_Banking_BAO_BankTransaction $btx, CRM_Banking_Matcher_Context $context) { $config = $this->_plugin_config; $threshold = $this->getThreshold(); $penalty = $this->getPenalty($btx); $data_parsed = $btx->getDataParsed(); // first see if all the required values are there if (!$this->requiredValuesPresent($btx)) { return null; } // resolve accepted states $accepted_status_ids = $this->getAcceptedContributionStatusIDs(); $contributions = array(); $contribution2contact = array(); $contribution2totalamount = array(); $contributions_identified = array(); // check if this is actually enabled if ($config->contribution_search) { // find contacts $contacts_found = $context->findContacts($threshold, $data_parsed['name'], $config->lookup_contact_by_name); // with the identified contacts, look up contributions foreach ($contacts_found as $contact_id => $contact_probabiliy) { if ($contact_probabiliy < $threshold) { continue; } $potential_contributions = $this->getPotentialContributionsForContact($contact_id, $context); foreach ($potential_contributions as $contribution) { // check for expected status if (!in_array($contribution['contribution_status_id'], $accepted_status_ids)) { continue; } $contribution_probability = $this->rateContribution($contribution, $context); // apply penalty $contribution_probability -= $penalty; if ($contribution_probability > $threshold) { $contributions[$contribution['id']] = $contribution_probability; $contribution2contact[$contribution['id']] = $contact_id; $contribution2totalamount[$contribution['id']] = $contribution['total_amount']; } } } } // add the contributions coming in from a list (if any) if (!empty($config->contribution_list)) { if (!empty($data_parsed[$config->contribution_list])) { $id_list = explode(',', $data_parsed[$config->contribution_list]); foreach ($id_list as $contribution_id_string) { $contribution_id = (int) $contribution_id_string; if ($contribution_id) { $contribution_bao = new CRM_Contribute_DAO_Contribution(); if ($contribution_bao->get('id', $contribution_id)) { $contribution = $contribution_bao->toArray(); // check for expected status if (!in_array($contribution['contribution_status_id'], $accepted_status_ids)) { continue; } $contribution_probability = $this->rateContribution($contribution, $context); // apply penalty $contribution_probability -= $penalty; if ($contribution_probability > $threshold) { $contributions[$contribution['id']] = $contribution_probability; $contribution2contact[$contribution['id']] = $contribution['contact_id']; $contribution2totalamount[$contribution['id']] = $contribution['total_amount']; $contacts_found[$contribution['contact_id']] = 1.0; $contributions_identified[] = $contribution['id']; } } } } } } // transform all of the contributions found into suggestions foreach ($contributions as $contribution_id => $contribution_probability) { $contact_id = $contribution2contact[$contribution_id]; $suggestion = new CRM_Banking_Matcher_Suggestion($this, $btx); if (!in_array($contribution_id, $contributions_identified)) { if ($contacts_found[$contact_id] >= 1.0) { $suggestion->addEvidence(1.0, ts("Contact was positively identified.")); } else { $suggestion->addEvidence($contacts_found[$contact_id], ts("Contact was likely identified.")); } } if ($contribution_probability >= 1.0) { $suggestion->setTitle(ts("Matching contribution found")); if ($config->mode != "cancellation") { $suggestion->addEvidence(1.0, ts("A pending contribution matching the transaction was found.")); } else { $suggestion->addEvidence(1.0, ts("This transaction is the <b>cancellation</b> of the below contribution.")); } } else { $suggestion->setTitle(ts("Possible matching contribution found")); if ($config->mode != "cancellation") { $suggestion->addEvidence($contacts_found[$contact_id], ts("A pending contribution partially matching the transaction was found.")); } else { $suggestion->addEvidence($contacts_found[$contact_id], ts("This transaction could be the <b>cancellation</b> of the below contribution.")); } } $suggestion->setId("existing-{$contribution_id}"); $suggestion->setParameter('contribution_id', $contribution_id); $suggestion->setParameter('contact_id', $contact_id); $suggestion->setParameter('mode', $config->mode); // generate cancellation extra parameters if ($config->mode == 'cancellation') { if ($config->cancellation_cancel_reason) { // determine the cancel reason if (empty($data_parsed[$config->cancellation_cancel_reason_source])) { $suggestion->setParameter('cancel_reason', $config->cancellation_cancel_reason_default); } else { $suggestion->setParameter('cancel_reason', $data_parsed[$config->cancellation_cancel_reason_source]); } } if ($config->cancellation_cancel_fee) { // calculate / determine the cancellation fee try { $meval = new EvalMath(); // first initialise variables 'difference' and 'source' $meval->evaluate("difference = -{$btx->amount} - {$contribution2totalamount[$contribution_id]}"); if (empty($config->cancellation_cancel_fee_source) || empty($data_parsed[$config->cancellation_cancel_fee_source])) { $meval->evaluate("source = 0.0"); } else { $meval->evaluate("source = {$data_parsed[$config->cancellation_cancel_fee_source]}"); } $suggestion->setParameter('cancel_fee', $meval->evaluate($config->cancellation_cancel_fee_default)); } catch (Exception $e) { error_log("org.project60.banking.matcher.existing: Couldn't calculate cancellation_fee. Error was: {$e}"); } } } // set probability manually, I think the automatic calculation provided by ->addEvidence might not be what we need here $suggestion->setProbability($contribution_probability * $contacts_found[$contact_id]); // update title if requested if (!empty($config->title)) { $suggestion->setTitle($config->title); } $btx->addSuggestion($suggestion); } // that's it... return empty($this->_suggestions) ? null : $this->_suggestions; }
function Evaluation($id, $value, $input, $exercise_id, $operatorData, $answer) { $m = new EvalMath(); $xml = simplexml_load_file($exercise_id) or die("Error: Cannot create object"); // $ops = array("==", "!=", "GE", "LE", "GT", "LT"); $count_options = $xml->input[$id]->count(); for ($i = 0; $i < $count_options; $i++) { $operator = $xml->input[$id]->option[$i]->operator; $equation = trim($xml->input[$id]->option[$i]->equation); $data = explode(" ", $equation); $operatorDT = ""; if ($operator == 'IF') { if (strstr($equation, "and")) { $content = explode("and", $equation); $data1 = explode(" ", $content[0]); $data2 = explode(" ", $content[1]); if (evalStatement($data1, $input, $answer) and evalStatement($data2, $input, $answer)) { return $xml->input[$id]->option[$i]->result; } } elseif (strstr($equation, "or")) { $content = explode("or", $equation); $data1 = explode(" ", $content[0]); $data2 = explode(" ", $content[1]); if (evalStatement($data1, $input, $answer) or evalStatement($data2, $input, $answer)) { return $xml->input[$id]->option[$i]->result; } } else { if (evalStatement($data, $input, $answer)) { return $xml->input[$id]->option[$i]->result; } } } else { $equation = ""; foreach ($data as $element) { if (is_numeric($element)) { $equation .= $element; } else { if ($element[0] == 'o') { $operatorDT = ltrim($element, "o"); } elseif ($element[0] == 'v') { $trimmed = intval(ltrim($element, "v")); $equation .= $input[$trimmed]; } elseif ($element[0] == 'a') { $trimmed = intval(ltrim($element, "a")); $equation .= $answer[$trimmed - 1]; } else { $equation .= $element; } } } if (strstr($equation, "mcm")) { $valor = explode(",", substr($equation, 3)); $equation_result = mcm(intval($valor[0]), intval($valor[1])); } elseif (strstr($equation, "smn")) { $valor = explode(",", substr($equation, 3)); $equation_result = smn(intval($valor[0]), intval($valor[1])); } elseif (strstr($equation, "smd")) { $valor = explode(",", substr($equation, 3)); $equation_result = smd(intval($valor[0]), intval($valor[1])); } elseif (strstr($equation, "cod")) { $valor = explode(",", substr($equation, 3)); $equation_result = cod(intval($valor[0]), intval($valor[1])); } elseif (strstr($equation, "red")) { $valor = explode(",", substr($equation, 3)); $equation_result = red(intval($valor[0]), intval($valor[1])); } elseif (strstr($equation, "txt")) { $valor = explode(",", substr($equation, 3)); $equation_result = txt($valor[0], $valor[1]); } else { $equation_result = $m->evaluate($equation); } if ($operatorDT == "") { $operatorData = ""; } // return strval($equation_result); switch ($operator) { case "==": if ($equation_result == $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "!=": if ($equation_result != $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "GT": if ($equation_result > $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "GE": if ($equation_result >= $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "LT": if ($equation_result < $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "LE": if ($equation_result <= $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; } // SWITCH } // else IF } // option's LOOP }
/** * Calculates price based on expression * * @param Product $product The Product object to get information * @param String $expression The expression to parse * @param array $values Strings to replaces * @return int > 0 if OK, < 1 if KO */ public function parseExpression($product, $expression, $values) { global $user; //Accessible product values by expressions $values = array_merge($values, array("tva_tx" => $product->tva_tx, "localtax1_tx" => $product->localtax1_tx, "localtax2_tx" => $product->localtax2_tx, "weight" => $product->weight, "length" => $product->length, "surface" => $product->surface, "price_min" => $product->price_min)); //Retrieve all extrafield for product and add it to values $extrafields = new ExtraFields($this->db); $extralabels = $extrafields->fetch_name_optionals_label('product', true); $product->fetch_optionals($product->id, $extralabels); foreach ($extrafields->attribute_label as $key => $label) { $values["extrafield_" . $key] = $product->array_options['options_' . $key]; } //Process any pending updaters $price_updaters = new PriceGlobalVariableUpdater($this->db); foreach ($price_updaters->listPendingUpdaters() as $entry) { //Schedule the next update by adding current timestamp (secs) + interval (mins) $entry->update_next_update(dol_now() + $entry->update_interval * 60, $user); //Do processing $res = $entry->process(); //Store any error or clear status if OK $entry->update_status($res < 1 ? $entry->error : '', $user); } //Get all global values $price_globals = new PriceGlobalVariable($this->db); foreach ($price_globals->listGlobalVariables() as $entry) { $values["global_" . $entry->code] = $entry->value; } //Check if empty $expression = trim($expression); if (empty($expression)) { $this->error = array(20, null); return -2; } //Prepare the lib, parameters and values $em = new EvalMath(); $em->suppress_errors = true; //Don't print errors on page $this->error_expr = null; $last_result = null; //Iterate over each expression splitted by $separator_chr $expression = str_replace("\n", $this->separator_chr, $expression); foreach ($values as $key => $value) { $expression = str_replace($this->special_chr . $key . $this->special_chr, "{$value}", $expression); } $expressions = explode($this->separator_chr, $expression); $expressions = array_slice($expressions, 0, $this->limit); foreach ($expressions as $expr) { $expr = trim($expr); if (!empty($expr)) { $last_result = $em->evaluate($expr); $this->error = $em->last_error_code; if ($this->error !== null) { //$em->last_error is null if no error happened, so just check if error is not null $this->error_expr = $expr; return -3; } } } $vars = $em->vars(); if (empty($vars["price"])) { $vars["price"] = $last_result; } if (!isset($vars["price"])) { $this->error = array(21, $expression); return -4; } if ($vars["price"] < 0) { $this->error = array(22, $expression); return -5; } return $vars["price"]; }
function Evaluation($id, $value, $input, $exercise_id, $operatorData) { $m = new EvalMath(); $xml = simplexml_load_file($exercise_id) or die("Error: Cannot create object"); $count_options = $xml->input[$id]->count(); for ($i = 0; $i < $count_options; $i++) { $operator = $xml->input[$id]->option[$i]->operator; $equation = trim($xml->input[$id]->option[$i]->equation); $data = explode(" ", $equation); $equation = ""; $operatorDT = ""; if ($operator == 'IF') { $trimmed = intval(ltrim($data[0], "v")); $equation .= $input[$trimmed]; switch ($data[1]) { case "==": if ($equation == $data[2]) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "!=": if ($equation != $data[2]) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "GT": if ($equation > $data[2]) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "GE": if ($equation >= $data[2]) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "LT": if ($equation < $data[2]) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "LE": if ($equation <= $data[2]) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; } // SWITCH } else { foreach ($data as $element) { if (is_numeric($element)) { $equation .= $element; } else { if ($element[0] == 'o') { $operatorDT = ltrim($element, "o"); } elseif (strpos($element, 'v') === False) { $equation .= $element; } else { $trimmed = intval(ltrim($element, "v")); $equation .= $input[$trimmed]; } } } // return $equation[3]; // $equation = "mcm(2,4)"; if (strstr($equation, "mcm")) { $valor = explode(",", substr($equation, 3)); $equation_result = mcm(intval($valor[0]), intval($valor[1])); } else { $equation_result = $m->evaluate($equation); } if ($operatorDT == "") { $operatorData = ""; } // return strval($equation_result); switch ($operator) { case "==": if ($equation_result == $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "!=": if ($equation_result != $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "GT": if ($equation_result > $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "GE": if ($equation_result >= $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "LT": if ($equation_result < $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; case "LE": if ($equation_result <= $value && $operatorDT == $operatorData) { return $xml->input[$id]->option[$i]->result; $i = $count_options; } break; } // SWITCH } // else IF } // option's LOOP }
function validate($errors, $field) { if ($field->type == 'user_id') { // make sure we have a user ID if (!is_numeric($_POST['item_meta'][$field->id])) { $_POST['item_meta'][$field->id] = FrmProAppHelper::get_user_id_param($_POST['item_meta'][$field->id]); } //add user id to post variables to be saved with entry $_POST['frm_user_id'] = $_POST['item_meta'][$field->id]; } else { if ($field->type == 'time' and is_array($_POST['item_meta'][$field->id])) { $_POST['item_meta'][$field->id] = $value = $_POST['item_meta'][$field->id]['H'] . ':' . $_POST['item_meta'][$field->id]['m'] . (isset($_POST['item_meta'][$field->id]['A']) ? ' ' . $_POST['item_meta'][$field->id]['A'] : ''); } } // don't validate if going backwards if (FrmProFormsHelper::going_to_prev($field->form_id)) { return array(); } // clear any existing errors if draft if (FrmProFormsHelper::saving_draft($field->form_id) && isset($errors['field' . $field->id])) { unset($errors['field' . $field->id]); } //if the field is a file upload, check for a file if ($field->type == 'file' && isset($_FILES['file' . $field->id]) && !empty($_FILES['file' . $field->id]['name'])) { $filled = true; if (is_array($_FILES['file' . $field->id]['name'])) { $filled = false; foreach ($_FILES['file' . $field->id]['name'] as $n) { if (!empty($n)) { $filled = true; } } } if ($filled) { if (isset($errors['field' . $field->id])) { unset($errors['field' . $field->id]); } if (isset($field->field_options['restrict']) && $field->field_options['restrict'] && isset($field->field_options['ftypes']) && !empty($field->field_options['ftypes'])) { $mimes = $field->field_options['ftypes']; } else { $mimes = null; } //check allowed mime types for this field if (is_array($_FILES['file' . $field->id]['name'])) { foreach ($_FILES['file' . $field->id]['name'] as $name) { if (empty($name)) { continue; } $file_type = wp_check_filetype($name, $mimes); unset($name); if (!$file_type['ext']) { break; } } } else { $file_type = wp_check_filetype($_FILES['file' . $field->id]['name'], $mimes); } if (isset($file_type) && !$file_type['ext']) { $errors['field' . $field->id] = $field->field_options['invalid'] == __('This field is invalid', 'formidable') || $field->field_options['invalid'] == '' || $field->field_options['invalid'] == $field->name . ' ' . __('is invalid', 'formidable') ? __('Sorry, this file type is not permitted for security reasons.', 'formidable') : $field->field_options['invalid']; } unset($file_type); } unset($filled); } // if saving draft, only check file type since it won't be checked later if (FrmProFormsHelper::saving_draft($field->form_id)) { return $errors; } if (in_array($field->type, array('break', 'html', 'divider'))) { $hidden = FrmProFieldsHelper::is_field_hidden($field, stripslashes_deep($_POST)); global $frm_hidden_break, $frm_hidden_divider; if ($field->type == 'break') { $frm_hidden_break = array('field_order' => $field->field_order, 'hidden' => $hidden); } else { if ($field->type == 'divider') { $frm_hidden_divider = array('field_order' => $field->field_order, 'hidden' => $hidden); } } if (isset($errors['field' . $field->id])) { unset($errors['field' . $field->id]); } } $value = $_POST['item_meta'][$field->id]; if (($field->type != 'tag' and $value == 0 or $field->type == 'tag' and $value == '') and isset($field->field_options['post_field']) and $field->field_options['post_field'] == 'post_category' and $field->required == '1') { global $frm_settings; $errors['field' . $field->id] = (!isset($field->field_options['blank']) or $field->field_options['blank'] == '' or $field->field_options['blank'] == 'Untitled cannot be blank') ? $frm_settings->blank_msg : $field->field_options['blank']; } //Don't require fields hidden with shortcode fields="25,26,27" global $frm_vars; if (isset($frm_vars['show_fields']) and !empty($frm_vars['show_fields']) and is_array($frm_vars['show_fields']) and $field->required == '1' and isset($errors['field' . $field->id]) and !in_array($field->id, $frm_vars['show_fields']) and !in_array($field->field_key, $frm_vars['show_fields'])) { unset($errors['field' . $field->id]); $_POST['item_meta'][$field->id] = $value = ''; } //Don't require a conditionally hidden field if (isset($field->field_options['hide_field']) and !empty($field->field_options['hide_field'])) { if (FrmProFieldsHelper::is_field_hidden($field, stripslashes_deep($_POST))) { if (isset($errors['field' . $field->id])) { unset($errors['field' . $field->id]); } $_POST['item_meta'][$field->id] = $value = ''; } } //Don't require a field hidden in a conditional page or section heading if (isset($errors['field' . $field->id]) or $_POST['item_meta'][$field->id] != '') { global $frm_hidden_break, $frm_hidden_divider; if ($frm_hidden_break and $frm_hidden_break['hidden'] or $frm_hidden_divider and $frm_hidden_divider['hidden'] and (!$frm_hidden_break or $frm_hidden_break['field_order'] < $frm_hidden_divider['field_order'])) { if (isset($errors['field' . $field->id])) { unset($errors['field' . $field->id]); } $_POST['item_meta'][$field->id] = $value = ''; } } //make sure the [auto_id] is still unique if (!empty($field->default_value) and !is_array($field->default_value) and !empty($value) and is_numeric($value) and strpos($field->default_value, '[auto_id') !== false) { //make sure we are not editing if (isset($_POST) and !isset($_POST['id']) or !is_numeric($_POST['id'])) { $_POST['item_meta'][$field->id] = $value = FrmProFieldsHelper::get_default_value($field->default_value, $field); } } //check uniqueness if ($value and !empty($value) and isset($field->field_options['unique']) and $field->field_options['unique']) { $entry_id = (isset($_POST) and isset($_POST['id'])) ? $_POST['id'] : false; if ($field->type == 'time') { //TODO: add server-side validation for unique date-time } else { if ($field->type == 'date') { global $frmpro_settings; $old_value = $value; if (!preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', trim($value))) { $value = FrmProAppHelper::convert_date($value, $frmpro_settings->date_format, 'Y-m-d'); } if (FrmProEntryMetaHelper::value_exists($field->id, $value, $entry_id)) { $errors['field' . $field->id] = FrmProFieldsHelper::get_error_msg($field, 'unique_msg'); } $value = $old_value; } else { if (FrmProEntryMetaHelper::value_exists($field->id, $value, $entry_id)) { $errors['field' . $field->id] = FrmProFieldsHelper::get_error_msg($field, 'unique_msg'); } } } unset($entry_id); } // validate number settings if ('number' == $field->type && $value != '') { global $frm_settings; // only check if options are available in settings if ($frm_settings->use_html && isset($field->field_options['minnum']) && isset($field->field_options['maxnum'])) { //minnum maxnum if ((double) $value < $field->field_options['minnum']) { $errors['field' . $field->id] = __('Please select a higher number', 'formidable'); } else { if ((double) $value > $field->field_options['maxnum']) { $errors['field' . $field->id] = __('Please select a lower number', 'formidable'); } } } } if (!empty($value) and ($field->type == 'website' or $field->type == 'url' or $field->type == 'image')) { if (trim($value) == 'http://') { $_POST['item_meta'][$field->id] = $value = ''; } else { $value = esc_url_raw($value); $_POST['item_meta'][$field->id] = $value = preg_match('/^(https?|ftps?|mailto|news|feed|telnet):/is', $value) ? $value : 'http://' . $value; } } $errors = FrmProEntryMetaHelper::set_post_fields($field, $value, $errors); if (!FrmProFieldsHelper::is_field_visible_to_user($field)) { //don't validate admin only fields that can't be seen unset($errors['field' . $field->id]); return $errors; } if (false and isset($field->field_options['use_calc']) and !empty($field->field_options['use_calc']) and !empty($field->field_options['calc'])) { $field->field_options['calc'] = trim($field->field_options['calc']); preg_match_all("/\\[(.*?)\\]/s", $field->field_options['calc'], $calc_matches, PREG_PATTERN_ORDER); if (isset($calc_matches[1])) { foreach ($calc_matches[1] as $c) { if (is_numeric($c)) { $c_id = $c; } else { global $frm_field; $c_field = $frm_field->getOne($c); if (!$c_field) { $field->field_options['calc'] = str_replace('[' . $c . ']', 0, $field->field_options['calc']); continue; } $c_id = $c_field->id; unset($c_field); } $c_val = trim($_POST['item_meta'][$c_id]); if (!is_numeric($c_val)) { preg_match_all('/[0-9,]*\\.?[0-9]+/', $c_val, $c_matches); $c_val = $c_matches ? end($c_matches[0]) : 0; unset($c_matches); } if ($c_val == '') { $c_val = 0; } $field->field_options['calc'] = str_replace('[' . $c . ']', $c_val, $field->field_options['calc']); unset($c); unset($c_id); } include FrmAppHelper::plugin_path() . '/pro/classes/helpers/FrmProMathHelper.php'; $m = new EvalMath(); if (strpos($field->field_options['calc'], ').toFixed(')) { $field->field_options['calc'] = str_replace(').toFixed(2', '', $field->field_options['calc']); $round = 2; } $result = $m->evaluate(str_replace('Math.', '', '(' . $field->field_options['calc'] . ')')); if (isset($round) and $round) { $result = sprintf('%.' . $round . 'f', $result); } unset($m); $_POST['item_meta'][$field->id] = $value = $result; unset($result); } unset($calc_matches); } //Don't validate the format if field is blank if ($value == '' or is_array($value)) { return $errors; } $value = trim($value); //validate the format if ($field->type == 'number' and !is_numeric($value) or $field->type == 'email' and !is_email($value) or ($field->type == 'website' or $field->type == 'url' or $field->type == 'image') and !preg_match('/^http(s)?:\\/\\/([\\da-z\\.-]+)\\.([\\da-z\\.-]+)/i', $value)) { $errors['field' . $field->id] = FrmProFieldsHelper::get_error_msg($field, 'invalid'); } if ($field->type == 'phone') { $pattern = (isset($field->field_options['format']) and !empty($field->field_options['format'])) ? $field->field_options['format'] : '^((\\+\\d{1,3}(-|.| )?\\(?\\d\\)?(-| |.)?\\d{1,5})|(\\(?\\d{2,6}\\)?))(-|.| )?(\\d{3,4})(-|.| )?(\\d{4})(( x| ext)\\d{1,5}){0,1}$'; $pattern = apply_filters('frm_phone_pattern', $pattern, $field); //check if format is already a regular expression if (strpos($pattern, '^') !== 0) { //if not, create a regular expression $pattern = preg_replace('/\\d/', '\\d', preg_quote($pattern)); $pattern = '/^' . $pattern . '$/'; } else { $pattern = '/' . $pattern . '/'; } if (!preg_match($pattern, $value)) { $errors['field' . $field->id] = FrmProFieldsHelper::get_error_msg($field, 'invalid'); } unset($pattern); } if ($field->type == 'date') { if (!preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $value)) { global $frmpro_settings; $formated_date = FrmProAppHelper::convert_date($value, $frmpro_settings->date_format, 'Y-m-d'); //check format before converting if ($value != date($frmpro_settings->date_format, strtotime($formated_date))) { $errors['field' . $field->id] = FrmProFieldsHelper::get_error_msg($field, 'invalid'); } $value = $formated_date; unset($formated_date); } $date = explode('-', $value); if (count($date) != 3 or !checkdate((int) $date[1], (int) $date[2], (int) $date[0])) { $errors['field' . $field->id] = FrmProFieldsHelper::get_error_msg($field, 'invalid'); } } return $errors; }
/** *Get ImageResource of the plot * *Generates ImageResource representation of the plot. * *@access private *@uses $Width *@uses EvalMath *@uses EvalMath::evaluate() *@uses GetCoordinatX() *@uses GetImageX() *@uses GetImageY() *@uses $Graphs *@uses Graph::$Color *@uses Graph::$LabelFont *@uses Graph::$EnableLabel *@uses Graph::$Label *@param ImageResource &$ImageResource ImageResource representation of the plot. */ function DrawPlots(&$ImageResource) { //Get a black Color $Black = imagecolorexact($ImageResource, 0, 0, 0); //Y position for Labels relative to Image $LabelY = 5; //Plot all graphs foreach ($this->Graphs as $key => $S) { //Get Color $Color = imagecolorexact($ImageResource, $S->Color[0], $S->Color[1], $S->Color[3]); //Set Expression $m = new EvalMath(); $m->evaluate("f(x) = " . $S->Exp); //Set OldCoordinat*, don't start with a line from 0,0 $OldCoordinatX = $this->GetCoordinatX(0); $OldCoordinatY = $m->evaluate("f(" . $OldCoordinatX . ")"); //Plot the graph for ($ImageX = 0; $ImageX < $this->Width; $ImageX++) { //Get some NewCoordinat* $NewCoordinatX = $this->GetCoordinatX($ImageX); $NewCoordinatY = $m->evaluate("f(" . $NewCoordinatX . ") "); //Draw a line from OldCoordinat* imageline($ImageResource, $this->GetImageX($OldCoordinatX), $this->GetImageY($OldCoordinatY), $this->GetImageX($NewCoordinatX), $this->GetImageY($NewCoordinatY), $Color); //Get some OldCoordinat* $OldCoordinatX = $NewCoordinatX; $OldCoordinatY = $NewCoordinatY; } //Draw label if it is enabled if ($S->EnableLabel) { //Draw label imagestring($ImageResource, $S->LabelFont, 5, $LabelY, "- " . $S->Label, $Color); //Add Label height to next Label X position $LabelY += imagefontheight($S->LabelFont); } } }
function check_condition($condition, $parameters, &$values, $question) { global $CFG; $values = ''; $interval = false; $operators = array('<=', '>=', '<', '>', '='); // ND : careful with operators relative positions here, see following foreach() foreach ($operators as $operator) { $operatorposition = strpos($condition, $operator); if ($operatorposition !== false) { $conditionsides = explode($operator, $condition); $left = trim($conditionsides[0]); $right = trim($conditionsides[1]); break; } } include_once "{$CFG->dirroot}/question/type/multinumerical/evalmath.class.php"; $math = new EvalMath(); $math->suppress_errors = true; // filling variables : foreach ($question->givenanswer as $param => $value) { $param = strtolower($param); // EvalMath n'aime pas les noms de variables avec majuscules $math->evaluate($param . '=' . $value); } $leftvalue = $math->evaluate($left); if ($operator == '=') { $operator = '=='; if (preg_match('/^\\s*([A-Z]*[a-z]*\\w*)\\s*=\\s*([\\[|\\]])(.+);(.+)([\\[|\\]])$/', $condition, $matches)) { $interval = true; $operator = ""; $rightvalue = $matches[2] == "[" ? ">=" : ">"; $val1 = $math->evaluate($matches[3]); $val2 = $math->evaluate($matches[4]); $rightvalue .= $val1 . " && " . $leftvalue; $rightvalue .= $matches[5] == "]" ? "<=" : "<"; $rightvalue .= $val2; } } if (!$interval) { $rightvalue = $math->evaluate($right); $values .= number_format($leftvalue, 2, '.', "'") . ' ' . $operator . ' ' . number_format($rightvalue, 2, '.', "'"); } else { $values .= $leftvalue . ' = ' . $matches[2] . number_format($val1, 3, '.', "'") . ';' . number_format($val2, 3, '.', "'") . $matches[5]; } if (eval('return(' . $leftvalue . $operator . $rightvalue . ');')) { $valuesspan = '<span'; $valuesspan .= $question->options->usecolorforfeedback ? ' style="color:#090"' : ''; $valuesspan .= '>' . get_string('conditionverified', 'qtype_multinumerical') . ' : ' . $values . '</span>'; $values = $valuesspan; return true; } $valuesspan = '<span'; $valuesspan .= $question->options->usecolorforfeedback ? ' style="color:#f00"' : ''; $valuesspan .= '>' . get_string('conditionnotverified', 'qtype_multinumerical') . ' : ' . $values . '</span>'; $values = $valuesspan; return false; }