Beispiel #1
0
 private function eval_route()
 {
     $route = URI::current();
     $formula = $this->get_formula($route, $action_count);
     $m = new EvalMath();
     $result = $m->e($formula);
     if ($action_count <= 10 && $result !== false) {
         return round($result, 0, PHP_ROUND_HALF_UP);
     } else {
         return 'Incorrect arithmetic route';
     }
 }
Beispiel #2
0
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());
    }
}
Beispiel #3
0
Datei: lib.php Projekt: 0-php/AI
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);
}
 /**
  * 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);
 }
Beispiel #5
0
 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);
 }
 /**
  * Check input, strip slashes etc. set alert, if input is not ok.
  *
  * @return	boolean		Input ok, true/false
  */
 function checkInput()
 {
     global $lng;
     $_POST[$this->getPostVar()] = ilUtil::stripSlashes($_POST[$this->getPostVar()]);
     if ($this->getRequired() && trim($_POST[$this->getPostVar()]) == "") {
         $this->setAlert($lng->txt("msg_input_is_required"));
         return false;
     } else {
         $eval = new EvalMath();
         $eval->suppress_errors = true;
         $result = $eval->e(str_replace(",", ".", ilUtil::stripSlashes($_POST[$this->getPostVar()], FALSE)));
         if ($result === false) {
             $this->setAlert($lng->txt("form_msg_formula_is_required"));
             return false;
         }
     }
     return $this->checkSubItemsInput();
 }
    function check_permissions($userid, $context) {
        global $DB, $CFG, $USER;

        if (has_capability('block/cobalt_reports:manageownreports', $context, $userid) && $this->config->ownerid == $userid)
            return true;

        if (has_capability('block/cobalt_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/cobalt_reports:viewreports', $context);
        } else {
            $i = 1;
            $cond = array();
            foreach ($permissions['elements'] as $p) {
                require_once($CFG->dirroot . '/blocks/cobalt_reports/plugin.class.php');
                require_once($CFG->dirroot . '/blocks/cobalt_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;
                }
            }
        }
    }
 /**
  * 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->pfx($this->evalmath->nfx($expression));
     if (false === $result) {
         return '!ERROR! ' . $this->evalmath->last_error;
     } else {
         return $result;
     }
 }
Beispiel #9
0
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;
}
 /**
  * Returns a QTI xml representation of the question
  *
  * Returns a QTI xml representation of the question and sets the internal
  * domxml variable with the DOM XML representation of the QTI xml representation
  *
  * @return string The QTI xml representation of the question
  * @access public
  */
 function toXML($a_include_header = true, $a_include_binary = true, $a_shuffle = false, $test_output = false, $force_image_references = false)
 {
     global $ilias;
     include_once "./Services/Math/classes/class.EvalMath.php";
     $eval = new EvalMath();
     $eval->suppress_errors = TRUE;
     include_once "./Services/Xml/classes/class.ilXmlWriter.php";
     $a_xml_writer = new ilXmlWriter();
     // set xml header
     $a_xml_writer->xmlHeader();
     $a_xml_writer->xmlStartTag("questestinterop");
     $attrs = array("ident" => "il_" . IL_INST_ID . "_qst_" . $this->object->getId(), "title" => $this->object->getTitle(), "maxattempts" => $this->object->getNrOfTries());
     $a_xml_writer->xmlStartTag("item", $attrs);
     // add question description
     $a_xml_writer->xmlElement("qticomment", NULL, $this->object->getComment());
     // add estimated working time
     $workingtime = $this->object->getEstimatedWorkingTime();
     $duration = sprintf("P0Y0M0DT%dH%dM%dS", $workingtime["h"], $workingtime["m"], $workingtime["s"]);
     $a_xml_writer->xmlElement("duration", NULL, $duration);
     // add ILIAS specific metadata
     $a_xml_writer->xmlStartTag("itemmetadata");
     $a_xml_writer->xmlStartTag("qtimetadata");
     $a_xml_writer->xmlStartTag("qtimetadatafield");
     $a_xml_writer->xmlElement("fieldlabel", NULL, "ILIAS_VERSION");
     $a_xml_writer->xmlElement("fieldentry", NULL, $ilias->getSetting("ilias_version"));
     $a_xml_writer->xmlEndTag("qtimetadatafield");
     $a_xml_writer->xmlStartTag("qtimetadatafield");
     $a_xml_writer->xmlElement("fieldlabel", NULL, "QUESTIONTYPE");
     $a_xml_writer->xmlElement("fieldentry", NULL, CLOZE_TEST_IDENTIFIER);
     $a_xml_writer->xmlEndTag("qtimetadatafield");
     $a_xml_writer->xmlStartTag("qtimetadatafield");
     $a_xml_writer->xmlElement("fieldlabel", NULL, "AUTHOR");
     $a_xml_writer->xmlElement("fieldentry", NULL, $this->object->getAuthor());
     $a_xml_writer->xmlEndTag("qtimetadatafield");
     // additional content editing information
     $this->addAdditionalContentEditingModeInformation($a_xml_writer);
     $this->addGeneralMetadata($a_xml_writer);
     $a_xml_writer->xmlStartTag("qtimetadatafield");
     $a_xml_writer->xmlElement("fieldlabel", NULL, "textgaprating");
     $a_xml_writer->xmlElement("fieldentry", NULL, $this->object->getTextgapRating());
     $a_xml_writer->xmlEndTag("qtimetadatafield");
     $a_xml_writer->xmlStartTag("qtimetadatafield");
     $a_xml_writer->xmlElement("fieldlabel", NULL, "fixedTextLength");
     $a_xml_writer->xmlElement("fieldentry", NULL, $this->object->getFixedTextLength());
     $a_xml_writer->xmlEndTag("qtimetadatafield");
     $a_xml_writer->xmlStartTag("qtimetadatafield");
     $a_xml_writer->xmlElement("fieldlabel", NULL, "identicalScoring");
     $a_xml_writer->xmlElement("fieldentry", NULL, $this->object->getIdenticalScoring());
     $a_xml_writer->xmlEndTag("qtimetadatafield");
     $a_xml_writer->xmlStartTag("qtimetadatafield");
     $a_xml_writer->xmlElement("fieldlabel", NULL, "combinations");
     $a_xml_writer->xmlElement("fieldentry", NULL, base64_encode(json_encode($this->object->getGapCombinations())));
     $a_xml_writer->xmlEndTag("qtimetadatafield");
     $a_xml_writer->xmlEndTag("qtimetadata");
     $a_xml_writer->xmlEndTag("itemmetadata");
     // PART I: qti presentation
     $attrs = array("label" => $this->object->getTitle());
     $a_xml_writer->xmlStartTag("presentation", $attrs);
     // add flow to presentation
     $a_xml_writer->xmlStartTag("flow");
     $questionText = $this->object->getQuestion() ? $this->object->getQuestion() : '&nbsp;';
     $this->object->addQTIMaterial($a_xml_writer, $questionText);
     $text_parts = preg_split("/\\[gap.*?\\[\\/gap\\]/", $this->object->getClozeText());
     // add material with question text to presentation
     for ($i = 0; $i <= $this->object->getGapCount(); $i++) {
         $this->object->addQTIMaterial($a_xml_writer, $text_parts[$i]);
         if ($i < $this->object->getGapCount()) {
             // add gap
             $gap = $this->object->getGap($i);
             switch ($gap->getType()) {
                 case CLOZE_SELECT:
                     // comboboxes
                     $attrs = array("ident" => "gap_{$i}", "rcardinality" => "Single");
                     $a_xml_writer->xmlStartTag("response_str", $attrs);
                     $solution = $this->object->getSuggestedSolution($i);
                     if (count($solution)) {
                         if (preg_match("/il_(\\d*?)_(\\w+)_(\\d+)/", $solution["internal_link"], $matches)) {
                             $attrs = array("label" => "suggested_solution");
                             $a_xml_writer->xmlStartTag("material", $attrs);
                             $intlink = "il_" . IL_INST_ID . "_" . $matches[2] . "_" . $matches[3];
                             if (strcmp($matches[1], "") != 0) {
                                 $intlink = $solution["internal_link"];
                             }
                             $a_xml_writer->xmlElement("mattext", NULL, $intlink);
                             $a_xml_writer->xmlEndTag("material");
                         }
                     }
                     $attrs = array("shuffle" => $gap->getShuffle() ? "Yes" : "No");
                     $a_xml_writer->xmlStartTag("render_choice", $attrs);
                     // add answers
                     foreach ($gap->getItems() as $answeritem) {
                         $attrs = array("ident" => $answeritem->getOrder());
                         $a_xml_writer->xmlStartTag("response_label", $attrs);
                         $a_xml_writer->xmlStartTag("material");
                         $a_xml_writer->xmlElement("mattext", NULL, $answeritem->getAnswertext());
                         $a_xml_writer->xmlEndTag("material");
                         $a_xml_writer->xmlEndTag("response_label");
                     }
                     $a_xml_writer->xmlEndTag("render_choice");
                     $a_xml_writer->xmlEndTag("response_str");
                     break;
                 case CLOZE_TEXT:
                     // text fields
                     $attrs = array("ident" => "gap_{$i}", "rcardinality" => "Single");
                     $a_xml_writer->xmlStartTag("response_str", $attrs);
                     $solution = $this->object->getSuggestedSolution($i);
                     if (count($solution)) {
                         if (preg_match("/il_(\\d*?)_(\\w+)_(\\d+)/", $solution["internal_link"], $matches)) {
                             $attrs = array("label" => "suggested_solution");
                             $a_xml_writer->xmlStartTag("material", $attrs);
                             $intlink = "il_" . IL_INST_ID . "_" . $matches[2] . "_" . $matches[3];
                             if (strcmp($matches[1], "") != 0) {
                                 $intlink = $solution["internal_link"];
                             }
                             $a_xml_writer->xmlElement("mattext", NULL, $intlink);
                             $a_xml_writer->xmlEndTag("material");
                         }
                     }
                     $attrs = array("fibtype" => "String", "prompt" => "Box", "columns" => $gap->getGapSize());
                     $a_xml_writer->xmlStartTag("render_fib", $attrs);
                     $a_xml_writer->xmlEndTag("render_fib");
                     $a_xml_writer->xmlEndTag("response_str");
                     break;
                 case CLOZE_NUMERIC:
                     // numeric fields
                     $attrs = array("ident" => "gap_{$i}", "numtype" => "Decimal", "rcardinality" => "Single");
                     $a_xml_writer->xmlStartTag("response_num", $attrs);
                     $solution = $this->object->getSuggestedSolution($i);
                     if (count($solution)) {
                         if (preg_match("/il_(\\d*?)_(\\w+)_(\\d+)/", $solution["internal_link"], $matches)) {
                             $attrs = array("label" => "suggested_solution");
                             $a_xml_writer->xmlStartTag("material", $attrs);
                             $intlink = "il_" . IL_INST_ID . "_" . $matches[2] . "_" . $matches[3];
                             if (strcmp($matches[1], "") != 0) {
                                 $intlink = $solution["internal_link"];
                             }
                             $a_xml_writer->xmlElement("mattext", NULL, $intlink);
                             $a_xml_writer->xmlEndTag("material");
                         }
                     }
                     $answeritem = $gap->getItem(0);
                     $attrs = array("fibtype" => "Decimal", "prompt" => "Box", "columns" => $gap->getGapSize());
                     if (is_object($answeritem)) {
                         if ($eval->e($answeritem->getLowerBound()) !== FALSE) {
                             $attrs["minnumber"] = $answeritem->getLowerBound();
                         }
                         if ($eval->e($answeritem->getUpperBound()) !== FALSE) {
                             $attrs["maxnumber"] = $answeritem->getUpperBound();
                         }
                     }
                     $a_xml_writer->xmlStartTag("render_fib", $attrs);
                     $a_xml_writer->xmlEndTag("render_fib");
                     $a_xml_writer->xmlEndTag("response_num");
                     break;
             }
         }
     }
     $a_xml_writer->xmlEndTag("flow");
     $a_xml_writer->xmlEndTag("presentation");
     // PART II: qti resprocessing
     $a_xml_writer->xmlStartTag("resprocessing");
     $a_xml_writer->xmlStartTag("outcomes");
     $a_xml_writer->xmlStartTag("decvar");
     $a_xml_writer->xmlEndTag("decvar");
     $a_xml_writer->xmlEndTag("outcomes");
     // add response conditions
     for ($i = 0; $i < $this->object->getGapCount(); $i++) {
         $gap = $this->object->getGap($i);
         switch ($gap->getType()) {
             case CLOZE_SELECT:
                 foreach ($gap->getItems() as $answer) {
                     $attrs = array("continue" => "Yes");
                     $a_xml_writer->xmlStartTag("respcondition", $attrs);
                     // qti conditionvar
                     $a_xml_writer->xmlStartTag("conditionvar");
                     $attrs = array("respident" => "gap_{$i}");
                     $a_xml_writer->xmlElement("varequal", $attrs, $answer->getAnswertext());
                     $a_xml_writer->xmlEndTag("conditionvar");
                     // qti setvar
                     $attrs = array("action" => "Add");
                     $a_xml_writer->xmlElement("setvar", $attrs, $answer->getPoints());
                     // qti displayfeedback
                     $linkrefid = "";
                     $linkrefid = "{$i}" . "_Response_" . $answer->getOrder();
                     $attrs = array("feedbacktype" => "Response", "linkrefid" => $linkrefid);
                     $a_xml_writer->xmlElement("displayfeedback", $attrs);
                     $a_xml_writer->xmlEndTag("respcondition");
                 }
                 break;
             case CLOZE_TEXT:
                 foreach ($gap->getItems() as $answer) {
                     $attrs = array("continue" => "Yes");
                     $a_xml_writer->xmlStartTag("respcondition", $attrs);
                     // qti conditionvar
                     $a_xml_writer->xmlStartTag("conditionvar");
                     $attrs = array("respident" => "gap_{$i}");
                     $a_xml_writer->xmlElement("varequal", $attrs, $answer->getAnswertext());
                     $a_xml_writer->xmlEndTag("conditionvar");
                     // qti setvar
                     $attrs = array("action" => "Add");
                     $a_xml_writer->xmlElement("setvar", $attrs, $answer->getPoints());
                     // qti displayfeedback
                     $linkrefid = "{$i}" . "_Response_" . $answer->getOrder();
                     $attrs = array("feedbacktype" => "Response", "linkrefid" => $linkrefid);
                     $a_xml_writer->xmlElement("displayfeedback", $attrs);
                     $a_xml_writer->xmlEndTag("respcondition");
                 }
                 break;
             case CLOZE_NUMERIC:
                 foreach ($gap->getItems() as $answer) {
                     $attrs = array("continue" => "Yes");
                     $a_xml_writer->xmlStartTag("respcondition", $attrs);
                     // qti conditionvar
                     $a_xml_writer->xmlStartTag("conditionvar");
                     $attrs = array("respident" => "gap_{$i}");
                     $a_xml_writer->xmlElement("varequal", $attrs, $answer->getAnswertext());
                     $a_xml_writer->xmlEndTag("conditionvar");
                     // qti setvar
                     $attrs = array("action" => "Add");
                     $a_xml_writer->xmlElement("setvar", $attrs, $answer->getPoints());
                     // qti displayfeedback
                     $linkrefid = "{$i}" . "_Response_" . $answer->getOrder();
                     $attrs = array("feedbacktype" => "Response", "linkrefid" => $linkrefid);
                     $a_xml_writer->xmlElement("displayfeedback", $attrs);
                     $a_xml_writer->xmlEndTag("respcondition");
                 }
                 break;
         }
     }
     $feedback_allcorrect = $this->object->feedbackOBJ->getGenericFeedbackExportPresentation($this->object->getId(), true);
     if (strlen($feedback_allcorrect)) {
         $attrs = array("continue" => "Yes");
         $a_xml_writer->xmlStartTag("respcondition", $attrs);
         // qti conditionvar
         $a_xml_writer->xmlStartTag("conditionvar");
         for ($i = 0; $i < $this->object->getGapCount(); $i++) {
             $gap = $this->object->getGap($i);
             $indexes = $gap->getBestSolutionIndexes();
             if ($i > 0) {
                 $a_xml_writer->xmlStartTag("and");
             }
             switch ($gap->getType()) {
                 case CLOZE_SELECT:
                     $k = 0;
                     foreach ($indexes as $key) {
                         if ($k > 0) {
                             $a_xml_writer->xmlStartTag("or");
                         }
                         $attrs = array("respident" => "gap_{$i}");
                         $answer = $gap->getItem($key);
                         $a_xml_writer->xmlElement("varequal", $attrs, $answer->getAnswertext());
                         if ($k > 0) {
                             $a_xml_writer->xmlEndTag("or");
                         }
                         $k++;
                     }
                     break;
                 case CLOZE_TEXT:
                     $k = 0;
                     foreach ($indexes as $key) {
                         if ($k > 0) {
                             $a_xml_writer->xmlStartTag("or");
                         }
                         $attrs = array("respident" => "gap_{$i}");
                         $answer = $gap->getItem($key);
                         $a_xml_writer->xmlElement("varequal", $attrs, $answer->getAnswertext());
                         if ($k > 0) {
                             $a_xml_writer->xmlEndTag("or");
                         }
                         $k++;
                     }
                     break;
                 case CLOZE_NUMERIC:
                     $k = 0;
                     foreach ($indexes as $key) {
                         if ($k > 0) {
                             $a_xml_writer->xmlStartTag("or");
                         }
                         $attrs = array("respident" => "gap_{$i}");
                         $answer = $gap->getItem($key);
                         $a_xml_writer->xmlElement("varequal", $attrs, $answer->getAnswertext());
                         if ($k > 0) {
                             $a_xml_writer->xmlEndTag("or");
                         }
                         $k++;
                     }
                     break;
             }
             if ($i > 0) {
                 $a_xml_writer->xmlEndTag("and");
             }
         }
         $a_xml_writer->xmlEndTag("conditionvar");
         // qti displayfeedback
         $attrs = array("feedbacktype" => "Response", "linkrefid" => "response_allcorrect");
         $a_xml_writer->xmlElement("displayfeedback", $attrs);
         $a_xml_writer->xmlEndTag("respcondition");
     }
     $feedback_onenotcorrect = $this->object->feedbackOBJ->getGenericFeedbackExportPresentation($this->object->getId(), false);
     if (strlen($feedback_onenotcorrect)) {
         $attrs = array("continue" => "Yes");
         $a_xml_writer->xmlStartTag("respcondition", $attrs);
         // qti conditionvar
         $a_xml_writer->xmlStartTag("conditionvar");
         $a_xml_writer->xmlStartTag("not");
         for ($i = 0; $i < $this->object->getGapCount(); $i++) {
             $gap = $this->object->getGap($i);
             $indexes = $gap->getBestSolutionIndexes();
             if ($i > 0) {
                 $a_xml_writer->xmlStartTag("and");
             }
             switch ($gap->getType()) {
                 case CLOZE_SELECT:
                     $k = 0;
                     foreach ($indexes as $key) {
                         if ($k > 0) {
                             $a_xml_writer->xmlStartTag("or");
                         }
                         $attrs = array("respident" => "gap_{$i}");
                         $answer = $gap->getItem($key);
                         $a_xml_writer->xmlElement("varequal", $attrs, $answer->getAnswertext());
                         if ($k > 0) {
                             $a_xml_writer->xmlEndTag("or");
                         }
                         $k++;
                     }
                     break;
                 case CLOZE_TEXT:
                     $k = 0;
                     foreach ($indexes as $key) {
                         if ($k > 0) {
                             $a_xml_writer->xmlStartTag("or");
                         }
                         $attrs = array("respident" => "gap_{$i}");
                         $answer = $gap->getItem($key);
                         $a_xml_writer->xmlElement("varequal", $attrs, $answer->getAnswertext());
                         if ($k > 0) {
                             $a_xml_writer->xmlEndTag("or");
                         }
                         $k++;
                     }
                     break;
                 case CLOZE_NUMERIC:
                     $k = 0;
                     foreach ($indexes as $key) {
                         if ($k > 0) {
                             $a_xml_writer->xmlStartTag("or");
                         }
                         $attrs = array("respident" => "gap_{$i}");
                         $answer = $gap->getItem($key);
                         $a_xml_writer->xmlElement("varequal", $attrs, $answer->getAnswertext());
                         if ($k > 0) {
                             $a_xml_writer->xmlEndTag("or");
                         }
                         $k++;
                     }
                     break;
             }
             if ($i > 0) {
                 $a_xml_writer->xmlEndTag("and");
             }
         }
         $a_xml_writer->xmlEndTag("not");
         $a_xml_writer->xmlEndTag("conditionvar");
         // qti displayfeedback
         $attrs = array("feedbacktype" => "Response", "linkrefid" => "response_onenotcorrect");
         $a_xml_writer->xmlElement("displayfeedback", $attrs);
         $a_xml_writer->xmlEndTag("respcondition");
     }
     $a_xml_writer->xmlEndTag("resprocessing");
     // PART III: qti itemfeedback
     for ($i = 0; $i < $this->object->getGapCount(); $i++) {
         $gap = $this->object->getGap($i);
         switch ($gap->getType()) {
             case CLOZE_SELECT:
                 break;
             case CLOZE_TEXT:
                 break;
             case CLOZE_NUMERIC:
                 break;
         }
         /*foreach ($gap->getItems() as $answer)
         			{
         				$linkrefid = "$i" . "_Response_" . $answer->getOrder();
         				$attrs = array(
         					"ident" => $linkrefid,
         					"view" => "All"
         				);
         				$a_xml_writer->xmlStartTag("itemfeedback", $attrs);
         				// qti flow_mat
         				$a_xml_writer->xmlStartTag("flow_mat");
         //				$a_xml_writer->xmlStartTag("material");
         //				$a_xml_writer->xmlElement("mattext");
         //				$a_xml_writer->xmlEndTag("material");
         				$fb = $this->object->feedbackOBJ->getSpecificAnswerFeedbackExportPresentation(
         					$this->object->getId(), $index
         				);
         				$this->object->addQTIMaterial($a_xml_writer, $fb);
         				$a_xml_writer->xmlEndTag("flow_mat");
         				$a_xml_writer->xmlEndTag("itemfeedback");
         			}*/
         $attrs = array("ident" => $i, "view" => "All");
         $a_xml_writer->xmlStartTag("itemfeedback", $attrs);
         // qti flow_mat
         $a_xml_writer->xmlStartTag("flow_mat");
         //				$a_xml_writer->xmlStartTag("material");
         //				$a_xml_writer->xmlElement("mattext");
         //				$a_xml_writer->xmlEndTag("material");
         $fb = $this->object->feedbackOBJ->getSpecificAnswerFeedbackExportPresentation($this->object->getId(), $i);
         $this->object->addQTIMaterial($a_xml_writer, $fb);
         $a_xml_writer->xmlEndTag("flow_mat");
         $a_xml_writer->xmlEndTag("itemfeedback");
     }
     if (strlen($feedback_allcorrect)) {
         $attrs = array("ident" => "response_allcorrect", "view" => "All");
         $a_xml_writer->xmlStartTag("itemfeedback", $attrs);
         // qti flow_mat
         $a_xml_writer->xmlStartTag("flow_mat");
         $this->object->addQTIMaterial($a_xml_writer, $feedback_allcorrect);
         $a_xml_writer->xmlEndTag("flow_mat");
         $a_xml_writer->xmlEndTag("itemfeedback");
     }
     if (strlen($feedback_onenotcorrect)) {
         $attrs = array("ident" => "response_onenotcorrect", "view" => "All");
         $a_xml_writer->xmlStartTag("itemfeedback", $attrs);
         // qti flow_mat
         $a_xml_writer->xmlStartTag("flow_mat");
         $this->object->addQTIMaterial($a_xml_writer, $feedback_onenotcorrect);
         $a_xml_writer->xmlEndTag("flow_mat");
         $a_xml_writer->xmlEndTag("itemfeedback");
     }
     $a_xml_writer->xmlEndTag("item");
     $a_xml_writer->xmlEndTag("questestinterop");
     $xml = $a_xml_writer->xmlDumpMem(FALSE);
     if (!$a_include_header) {
         $pos = strpos($xml, "?>");
         $xml = substr($xml, $pos + 2);
     }
     return $xml;
 }
 /**
  * Checks for a given value within the range
  *
  * Checks for a given value within the range
  *
  * @param double $value The value to check
  *
  * @return boolean TRUE if the value is in the range, FALSE otherwise
  *
  * @see $upperlimit
  * @see $lowerlimit
  */
 public function contains($value)
 {
     require_once './Services/Math/classes/class.EvalMath.php';
     $eval = new EvalMath();
     $eval->suppress_errors = TRUE;
     $result = $eval->e($value);
     if ($result === FALSE || $result === TRUE) {
         return FALSE;
     }
     if ($result >= $eval->e($this->lowerlimit) && $result <= $eval->e($this->upperlimit)) {
         return TRUE;
     } else {
         return FALSE;
     }
 }
Beispiel #12
0
$lang = array('en' => array('help' => 'Usage: %CMD% <expression>. Evaluate a mathematical expression and print results. Use _ and $ to referr to the last result.', '00' => '1 ... No ... 0 ... No ... UNDEFINED!', 'err_in' => 'Error in expression.', 'err_lib' => 'The "EvalMath" class by Miles Kaufmann is missing.'));
$plugin = Dog::getPlugin();
if ('' === ($message = $plugin->msg())) {
    return $plugin->showHelp();
}
if (false !== ($last = Dog_Conf_Plug_User::getConf($plugin->getName(), Dog::getUID(), 'last', false))) {
    $message = str_replace(array('_', '$'), $last, $message);
}
if ($message === '0^0') {
    return $plugin->rply('00');
}
if ($message === 'pi') {
    return $plugin->reply('4');
}
$path = GWF_PATH . 'core/inc/3p/EvalMath.php';
if (!Common::isFile($path)) {
    return $plugin->rply('err_lib');
}
require_once $path;
$eval = new EvalMath();
if (false === ($result = $eval->e($message))) {
    return $plugin->rply('err_in');
}
$result = sprintf('%.09f', $result);
if (strpos($result, '.') !== false) {
    $result = rtrim($result, '0');
    $result = rtrim($result, '.');
}
Dog_Conf_Plug_User::setConf($plugin->getName(), Dog::getUID(), 'last', $result);
Dog::reply($result);
Beispiel #13
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");
    // $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
}
 public function checkInput()
 {
     $error = false;
     $json = json_decode(ilUtil::stripSlashes($_POST['gap_json_post']));
     $_POST['gap'] = ilUtil::stripSlashesRecursive($_POST['gap']);
     $gaps_used_in_combination = array();
     if (array_key_exists('gap_combination', $_POST)) {
         $_POST['gap_combination'] = ilUtil::stripSlashesRecursive($_POST['gap_combination']);
         $_POST['gap_combination_values'] = ilUtil::stripSlashesRecursive($_POST['gap_combination_values']);
         $gap_with_points = array();
         for ($i = 0; $i < count($_POST['gap_combination']['select']); $i++) {
             foreach ($_POST['gap_combination']['select'][$i] as $key => $item) {
                 if ($item == 'none_selected_minus_one') {
                     return false;
                 }
                 $gaps_used_in_combination[$item] = $item;
                 $check_points_for_best_scoring = false;
                 foreach ($_POST['gap_combination_values'][$i] as $index => $answeritems) {
                     foreach ($answeritems as $answeritem) {
                         if ($answeritem == 'none_selected_minus_one') {
                             return false;
                         }
                     }
                     $points = $_POST['gap_combination']['points'][$i][$index];
                     if ($points > 0) {
                         $check_points_for_best_scoring = true;
                     }
                 }
                 if (!$check_points_for_best_scoring) {
                     return false;
                 }
             }
         }
     }
     if (isset($_POST['gap']) && is_array($_POST['gap'])) {
         foreach ($_POST['gap'] as $key => $item) {
             $_POST['clozetype_' . $key] = ilUtil::stripSlashes($_POST['clozetype_' . $key]);
             $getType = $_POST['clozetype_' . $key];
             $gapsize = $_POST['gap_' . $key . '_gapsize'];
             $json[0][$key]->text_field_length = $gapsize > 0 ? $gapsize : '';
             if ($getType == CLOZE_TEXT || $getType == CLOZE_SELECT) {
                 $_POST['gap_' . $key] = ilUtil::stripSlashesRecursive($_POST['gap_' . $key]);
                 $gapText = $_POST['gap_' . $key];
                 foreach ($gapText['answer'] as $row => $answer) {
                     if (!isset($answer) || $answer == '') {
                         $error = true;
                     }
                 }
                 $points_sum = 0;
                 if (array_key_exists('points', $gapText)) {
                     foreach ($gapText['points'] as $row => $points) {
                         if (isset($points) && $points != '' && is_numeric($points)) {
                             $points_sum += $points;
                         } else {
                             $error = true;
                         }
                     }
                     if (is_array($gap_with_points) && array_key_exists($key, $gap_with_points)) {
                         $points_sum += $gap_with_points[$key];
                     }
                     if ($points_sum == 0) {
                         if (!array_key_exists($key, $gaps_used_in_combination)) {
                             $error = true;
                         }
                     }
                     if ($getType == CLOZE_SELECT) {
                         $_POST['shuffle_' . $key] = ilUtil::stripSlashes($_POST['shuffle_' . $key]);
                         if (!isset($_POST['shuffle_' . $key])) {
                             $error = true;
                         }
                     }
                 } else {
                     $error = true;
                 }
             }
             if ($getType == CLOZE_NUMERIC) {
                 $_POST['gap_' . $key . 'numeric'] = ilUtil::stripSlashes($_POST['gap_' . $key . 'numeric'], FALSE);
                 $_POST['gap_' . $key . 'numeric_lower'] = ilUtil::stripSlashes($_POST['gap_' . $key . 'numeric_lower'], FALSE);
                 $_POST['gap_' . $key . 'numeric_upper'] = ilUtil::stripSlashes($_POST['gap_' . $key . 'numeric_upper'], FALSE);
                 $_POST['gap_' . $key . 'numeric_points'] = ilUtil::stripSlashes($_POST['gap_' . $key . 'numeric_points']);
                 $mark_errors = array('answer' => false, 'lower' => false, 'upper' => false, 'points' => false);
                 $eval = new EvalMath();
                 $eval->suppress_errors = true;
                 $formula = $_POST['gap_' . $key . '_numeric'];
                 $result = $eval->e(str_replace(',', '.', $_POST['gap_' . $key . '_numeric'], $formula));
                 if ($result === false) {
                     $error = true;
                 }
                 $lower = $_POST['gap_' . $key . '_numeric_lower'];
                 $assClozeTestObject = new assClozeTest();
                 $has_valid_chars = $assClozeTestObject->checkForValidFormula($lower);
                 $result = $eval->e(str_replace(',', '.', $lower), FALSE);
                 if ($result === false || !$has_valid_chars) {
                     $error = true;
                 }
                 $_POST['gap_' . $key . '_numeric_lower'] = $result;
                 $result = $eval->e(str_replace(',', '.', $_POST['gap_' . $key . '_numeric_upper']), FALSE);
                 if ($result === false) {
                     $error = true;
                 }
                 $_POST['gap_' . $key . '_numeric_upper'] = $result;
                 $points = $_POST['gap_' . $key . '_numeric_points'];
                 if (is_array($gap_with_points) && array_key_exists($key, $gap_with_points)) {
                     $points += $gap_with_points[$key];
                 }
                 if (!isset($points) || $points == '' || !is_numeric($points) || $points == 0) {
                     if (!array_key_exists($key, $gaps_used_in_combination)) {
                         $error = true;
                     }
                 }
                 $json[0][$key]->values[0]->error = $mark_errors;
             }
         }
     }
     $_POST['gap_json_post'] = json_encode($json);
     return !$error;
 }
Beispiel #15
0
include $_SERVER['DOCUMENT_ROOT'] . '/TBSIM/Core/Config/SessionStart.php';
include $_SERVER['DOCUMENT_ROOT'] . '/TBSIM/Core/Config/Config.php';
$DBM = $_SESSION['DB'];
$iname = $_REQUEST['iname'];
$equation = $_REQUEST['equation'];
$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);
Beispiel #16
0
 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);
 }
 /**
  * Returns the points, a learner has reached answering the question.
  * The points are calculated from the given answers.
  * 
  * @access public
  * @param integer $active_id
  * @param integer $pass
  * @param boolean $returndetails (deprecated !!)
  * @return integer/array $points/$details (array $details is deprecated !!)
  */
 public function calculateReachedPoints($active_id, $pass = NULL, $returndetails = FALSE)
 {
     global $ilDB;
     $found_value1 = array();
     $found_value2 = array();
     $detailed = array();
     if (is_null($pass)) {
         $pass = $this->getSolutionMaxPass($active_id);
     }
     $result = $ilDB->queryF("SELECT * FROM tst_solutions WHERE active_fi = %s AND question_fi = %s AND pass = %s", array("integer", "integer", "integer"), array($active_id, $this->getId(), $pass));
     $user_result = array();
     while ($data = $ilDB->fetchAssoc($result)) {
         if (strcmp($data["value2"], "") != 0) {
             $user_result[$data["value1"]] = array("gap_id" => $data["value1"], "value" => $data["value2"]);
         }
     }
     $points = 0;
     $counter = 0;
     $solution_values_text = array();
     // for identical scoring checks
     $solution_values_select = array();
     // for identical scoring checks
     $solution_values_numeric = array();
     // for identical scoring checks
     foreach ($user_result as $gap_id => $value) {
         if (array_key_exists($gap_id, $this->gaps)) {
             switch ($this->gaps[$gap_id]->getType()) {
                 case CLOZE_TEXT:
                     $gappoints = 0;
                     for ($order = 0; $order < $this->gaps[$gap_id]->getItemCount(); $order++) {
                         $answer = $this->gaps[$gap_id]->getItem($order);
                         $gotpoints = $this->getTextgapPoints($answer->getAnswertext(), $value["value"], $answer->getPoints());
                         if ($gotpoints > $gappoints) {
                             $gappoints = $gotpoints;
                         }
                     }
                     if (!$this->getIdenticalScoring()) {
                         // check if the same solution text was already entered
                         if (in_array($value["value"], $solution_values_text) && $gappoints > 0) {
                             $gappoints = 0;
                         }
                     }
                     $points += $gappoints;
                     $detailed[$gap_id] = array("points" => $gappoints, "best" => $this->getMaximumGapPoints($gap_id) == $gappoints ? TRUE : FALSE, "positive" => $gappoints > 0 ? TRUE : FALSE);
                     array_push($solution_values_text, $value["value"]);
                     break;
                 case CLOZE_NUMERIC:
                     $gappoints = 0;
                     for ($order = 0; $order < $this->gaps[$gap_id]->getItemCount(); $order++) {
                         $answer = $this->gaps[$gap_id]->getItem($order);
                         $gotpoints = $this->getNumericgapPoints($answer->getAnswertext(), $value["value"], $answer->getPoints(), $answer->getLowerBound(), $answer->getUpperBound());
                         if ($gotpoints > $gappoints) {
                             $gappoints = $gotpoints;
                         }
                     }
                     if (!$this->getIdenticalScoring()) {
                         // check if the same solution value was already entered
                         include_once "./Services/Math/classes/class.EvalMath.php";
                         $eval = new EvalMath();
                         $eval->suppress_errors = TRUE;
                         $found_value = FALSE;
                         foreach ($solution_values_numeric as $solval) {
                             if ($eval->e($solval) == $eval->e($value["value"])) {
                                 $found_value = TRUE;
                             }
                         }
                         if ($found_value && $gappoints > 0) {
                             $gappoints = 0;
                         }
                     }
                     $points += $gappoints;
                     $detailed[$gap_id] = array("points" => $gappoints, "best" => $this->getMaximumGapPoints($gap_id) == $gappoints ? TRUE : FALSE, "positive" => $gappoints > 0 ? TRUE : FALSE);
                     array_push($solution_values_numeric, $value["value"]);
                     break;
                 case CLOZE_SELECT:
                     if ($value["value"] >= 0) {
                         for ($order = 0; $order < $this->gaps[$gap_id]->getItemCount(); $order++) {
                             $answer = $this->gaps[$gap_id]->getItem($order);
                             if ($value["value"] == $answer->getOrder()) {
                                 $answerpoints = $answer->getPoints();
                                 if (!$this->getIdenticalScoring()) {
                                     // check if the same solution value was already entered
                                     if (in_array($answer->getAnswertext(), $solution_values_select) && $answerpoints > 0) {
                                         $answerpoints = 0;
                                     }
                                 }
                                 $points += $answerpoints;
                                 $detailed[$gap_id] = array("points" => $answerpoints, "best" => $this->getMaximumGapPoints($gap_id) == $answerpoints ? TRUE : FALSE, "positive" => $answerpoints > 0 ? TRUE : FALSE);
                                 array_push($solution_values_select, $answer->getAnswertext());
                             }
                         }
                     }
                     break;
             }
         }
     }
     if ($returndetails) {
         return $detailed;
     } else {
         return $points;
     }
 }
 protected function getNumericValueFromAnswerText()
 {
     include_once "./Services/Math/classes/class.EvalMath.php";
     $eval = new EvalMath();
     $eval->suppress_errors = true;
     return $eval->e(str_replace(",", ".", ilUtil::stripSlashes($this->getAnswertext(), FALSE)));
 }
Beispiel #19
0
 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);
 }
Beispiel #20
0
 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;
 }
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);
}
 /**
  *	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"];
 }
 /**
  * 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;
 }
 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;
 }
Beispiel #25
0
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
}
 /**
  * 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();
         }
     }
 }
 /**
  *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);
         }
     }
 }
 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;
 }
 /**
  * Checks the range limits
  *
  * Checks the Range limits Upper and Lower for their correctness
  *
  * @return boolean 
  */
 public function checkRange()
 {
     include_once "./Services/Math/classes/class.EvalMath.php";
     $eval = new EvalMath();
     $eval->suppress_errors = TRUE;
     if ($eval->e($_POST["rang_lower_limit"]) !== FALSE and $eval->e($_POST["range_upper_limit"]) !== FALSE) {
         if ($eval->e($_POST["rang_lower_limit"]) < $eval->e($_POST["range_upper_limit"])) {
             return TRUE;
         } else {
             return FALSE;
         }
     }
     return FALSE;
 }
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;
    }
}