Exemple #1
0
/**
 * function captialise()
 * this function captialises a string
 * @param string $text
 * @return string text
**/
function captialise($text)
{
    $otext = $text;
    $text = strtoupper($text);
    runDebug(__FILE__, __FUNCTION__, __LINE__, "In: {$otext} Out:{$text}", 4);
    return $text;
}
/**
 * function normalize_text
 * Transforms text to uppercase, removes all punctuation, and strips extra whitespace
 *
 * @param (string) $text - The text to perform the transformations on
 * @return mixed|string (string) $normalized_text - The completely transformed text
 */
function normalize_text($text)
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Begin normalization - text = '{$text}'", 4);
    $normalized_text = preg_replace('/[[:punct:]]/uis', ' ', $text);
    $normalized_text = preg_replace('/\\s\\s+/', ' ', $normalized_text);
    $normalized_text = IS_MB_ENABLED ? mb_strtoupper($normalized_text) : strtoupper($normalized_text);
    $normalized_text = trim($normalized_text);
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Normalization complete. Text = '{$normalized_text}'", 4);
    return $normalized_text;
}
/**
 * function make_conversation()
 * A controller function to run the instructions to make the conversation
 *
 * @link http://blog.program-o.com/?p=1209
 * @param  array $convoArr - the current state of the conversation array
 * @return array $convoArr (updated)
 */
function make_conversation($convoArr)
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Making conversation", 4);
    //get the user input and clean it
    $convoArr['aiml']['lookingfor'] = normalize_text($convoArr['user_say'][1]);
    //find an aiml match in the db
    $convoArr = get_aiml_to_parse($convoArr);
    $convoArr = parse_matched_aiml($convoArr, 'normal');
    //parse the aiml to build a response
    //store the conversation
    $convoArr = push_on_front_convoArr('parsed_template', $convoArr['aiml']['parsed_template'], $convoArr);
    $convoArr = push_on_front_convoArr('template', $convoArr['aiml']['template'], $convoArr);
    //display conversation vars to user.
    $convoArr['conversation']['totallines']++;
    return $convoArr;
}
/**
 * function normalize_text
 * Transforms text to uppercase, removes all punctuation, and strips extra whitespace
 *
 * @param (string) $text - The text to perform the transformations on
 * @return mixed|string (string) $normalized_text - The completely transformed text
 */
function normalize_text($text)
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Begin normalization - text = '{$text}'", 4);
    $normalized_text = preg_replace('/(\\d+) - (\\d+)/', '$1 MINUS $2', $text);
    $normalized_text = preg_replace('/(\\d+)-(\\d+)/', '$1 MINUS $2', $normalized_text);
    $normalized_text = preg_replace('/(\\d+) \\+ (\\d+)/', '$1 PLUS $2', $normalized_text);
    $normalized_text = preg_replace('/(\\d+)\\+(\\d+)/', '$1 PLUS $2', $normalized_text);
    $normalized_text = preg_replace('/(\\d+) \\* (\\d+)/', '$1 TIMES $2', $normalized_text);
    $normalized_text = preg_replace('/(\\d+) x (\\d+)/', '$1 TIMES $2', $normalized_text);
    $normalized_text = preg_replace('/(\\d+)x(\\d+)/', '$1 TIMES $2', $normalized_text);
    $normalized_text = preg_replace('/(\\d+)\\*(\\d+)/', '$1 TIMES $2', $normalized_text);
    $normalized_text = preg_replace('/(\\d+) \\/ (\\d+)/', '$1 DIVIDEDBY $2', $normalized_text);
    $normalized_text = preg_replace('/(\\d+)\\/(\\d+)/', '$1 DIVIDEDBY $2', $normalized_text);
    $normalized_text = preg_replace('/[[:punct:]]/uis', ' ', $normalized_text);
    $normalized_text = preg_replace('/\\s\\s+/', ' ', $normalized_text);
    $normalized_text = IS_MB_ENABLED ? mb_strtoupper($normalized_text) : strtoupper($normalized_text);
    $normalized_text = trim($normalized_text);
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Normalization complete. Text = '{$normalized_text}'", 4);
    return $normalized_text;
}
Exemple #5
0
function spellcheck($user_say)
{
    global $dbconn;
    $wordArr = make_wordArray($user_say);
    $limit_res = count($wordArr);
    $sqlwords = glue_words_for_sql($wordArr);
    $sql = "SELECT * FROM `{$dbn}`.`spellcheck` WHERE `missspelling` IN ({$sqlwords}) LIMIT {$limit_res}";
    $result = db_query($sql, $dbconn);
    if ($result) {
        if (db_res_count($result) > 0) {
            while ($row = db_res_array($result)) {
                $pattern = '/\\b' . $row['missspelling'] . '\\b/';
                $replacement = $row['correction'];
                if ($user_say = preg_replace($pattern, $replacement, $user_say)) {
                    runDebug(__FILE__, __FUNCTION__, __LINE__, "Replacing " . $row['missspelling'] . " with " . $row['correction'], 4);
                }
            }
        }
    }
}
Exemple #6
0
/**
 * function intisaliseUser()
 * This function gets data such as the referer to store in the db
 * @param string $convo_id - user session
 * @return int $user_id - the newly created user id
**/
function intisaliseUser($convo_id)
{
    //db globals
    global $con, $dbn, $default_bot_id;
    $sr = "";
    $sa = "";
    $sb = "unknown browser";
    if (isset($_SERVER['REMOTE_ADDR'])) {
        $sa = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
    }
    if (isset($_SERVER['HTTP_REFERER'])) {
        $sr = mysql_real_escape_string($_SERVER['HTTP_REFERER']);
    }
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $sb = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);
    }
    $sql = "INSERT INTO `{$dbn}`.`users` (`id` ,`session_id`, `bot_id`, `chatlines` ,`ip` ,`referer` ,`browser` ,`date_logged_on` ,`last_update`)\n\tVALUES ( NULL , '{$convo_id}', {$default_bot_id}, '0', '{$sa}', '{$sr}', '{$sb}', CURRENT_TIMESTAMP , '0000-00-00 00:00:00')";
    mysql_query($sql, $con);
    $user_id = mysql_insert_id($con);
    runDebug(__FILE__, __FUNCTION__, __LINE__, "intisaliseUser #{$user_id} SQL: {$sql}", 3);
    return $user_id;
}
/**
 * function foreignchar_replace()
 * A function to replace foreign characters with a string substitute 
 * So that nothing is broken during parsing/interpreting
 * @param  string $whichway - 'decode' or 'encode'
 * @param  sring $text - the text to decode or encode
 * @return the en/decoded string
**/
function foreignchar_replace($whichway, $text)
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, "{$whichway}", 4);
    $foreign_char_array = array('Š' => 'htmlentity_foreign_big_S_caron', 'š' => 'htmlentity_foreign_small_s_caron', 'À' => 'htmlentity_foreign_big_A_grave', 'Á' => 'htmlentity_foreign_small_a_acute', 'Â' => 'htmlentity_foreign_big_A_circ', 'Ã' => 'htmlentity_foreign_big_A_tilde', 'Ä' => 'htmlentity_foreign_big__A_uml', 'Å' => 'htmlentity_foreign_big_A_ring', 'Æ' => 'htmlentity_foreign_big_AE_lig', 'Ç' => 'htmlentity_foreign_big__C_cedil', 'È' => 'htmlentity_foreign_big_E_grave', 'É' => 'htmlentity_foreign_big_E_acute', 'Ê' => 'htmlentity_foreign_big_E_circ', 'Ë' => 'htmlentity_foreign_big_E_uml', 'Ì' => 'htmlentity_foreign_big_I_grave', 'Í' => 'htmlentity_foreign_big_I_acute', 'Î' => 'htmlentity_foreign_big_I_circ', 'Ï' => 'htmlentity_foreign_big_I_uml', 'Ñ' => 'htmlentity_foreign_big_N_tilde', 'Ò' => 'htmlentity_foreign_big_O_grave', 'Ó' => 'htmlentity_foreign_big_O_acuter', 'Ô' => 'htmlentity_foreign_big_O_circ', 'Õ' => 'htmlentity_foreign_big_O_tilde', 'Ö' => 'htmlentity_foreign_big_O_uml', 'Ø' => 'htmlentity_foreign_big_O_slash', 'Ù' => 'htmlentity_foreign_big_U_grave', 'Ú' => 'htmlentity_foreign_big_U_acute', 'Û' => 'htmlentity_foreign_big_U_circ', 'Ü' => 'htmlentity_foreign_big_U_uml', 'Ý' => 'htmlentity_foreign_big_Y_acute', 'Þ' => 'htmlentity_foreign_big_THORN', 'ß' => 'htmlentity_foreign_small_sz_lig', 'à' => 'htmlentity_foreign_small_a_grave', 'á' => 'htmlentity_foreign_small_a_acute', 'â' => 'htmlentity_foreign_small_a_circ', 'ã' => 'htmlentity_foreign_small_a_tilde', 'ä' => 'htmlentity_foreign_small_a_uml', 'å' => 'htmlentity_foreign_small_a_ring', 'æ' => 'htmlentity_foreign_small_ae_lig', 'ç' => 'htmlentity_foreign_small_c_cedil', 'è' => 'htmlentity_foreign_small_e_grave', 'é' => 'htmlentity_foreign_small_e_acute', 'ê' => 'htmlentity_foreign_small_e_circ', 'ë' => 'htmlentity_foreign_small_e_uml', 'ì' => 'htmlentity_foreign_small_i_grave', 'í' => 'htmlentity_foreign_small_i_acute', 'î' => 'htmlentity_foreign_small_i_circ', 'ï' => 'htmlentity_foreign_small_i_uml', 'ð' => 'htmlentity_foreign_small_e_th', 'ñ' => 'htmlentity_foreign_small_n_tilde', 'ò' => 'htmlentity_foreign_small_o_grave', 'ó' => 'htmlentity_foreign_small_o_acute', 'ô' => 'htmlentity_foreign_small_o_circ', 'õ' => 'htmlentity_foreign_small_o_tilde', 'ö' => 'htmlentity_foreign_small_o_uml', 'ø' => 'htmlentity_foreign_small_o_slash', 'ù' => 'htmlentity_foreign_small_u_grave', 'ú' => 'htmlentity_foreign_small_u_acute', 'û' => 'htmlentity_foreign_small_u_circ', 'ý' => 'htmlentity_foreign_small_y_acute', 'þ' => 'htmlentity_foreign_small_thorn', 'Α' => 'htmlentity_greek_capital_letter_alpha', 'Β' => 'htmlentity_greek_capital_letter_beta', 'Γ' => 'htmlentity_greek_capital_letter_gamma', 'Δ' => 'htmlentity_greek_capital_letter_delta', 'Ε' => 'htmlentity_greek_capital_letter_epsilon', 'Ζ' => 'htmlentity_greek_capital_letter_zeta', 'Η' => 'htmlentity_greek_capital_letter_eta', 'Θ' => 'htmlentity_greek_capital_letter_theta', 'Ι' => 'htmlentity_greek_capital_letter_iota', 'Κ' => 'htmlentity_greek_capital_letter_kappa', 'Λ' => 'htmlentity_greek_capital_letter_lambda', 'Μ' => 'htmlentity_greek_capital_letter_mu', 'Ν' => 'htmlentity_greek_capital_letter_nu', 'Ξ' => 'htmlentity_greek_capital_letter_xi', 'Ο' => 'htmlentity_greek_capital_letter_omicron', 'Π' => 'htmlentity_greek_capital_letter_pi', 'Ρ' => 'htmlentity_greek_capital_letter_rho', 'Σ' => 'htmlentity_greek_capital_letter_sigma', 'Τ' => 'htmlentity_greek_capital_letter_tau', 'Υ' => 'htmlentity_greek_capital_letter_upsilon', 'Φ' => 'htmlentity_greek_capital_letter_phi', 'Χ' => 'htmlentity_greek_capital_letter_chi', 'Ψ' => 'htmlentity_greek_capital_letter_psi', 'Ω' => 'htmlentity_greek_capital_letter_omega', 'α' => 'htmlentity_greek_small_letter_alpha', 'β' => 'htmlentity_greek_small_letter_beta', 'γ' => 'htmlentity_greek_small_letter_gamma', 'δ' => 'htmlentity_greek_small_letter_delta', 'ε' => 'htmlentity_greek_small_letter_epsilon', 'ζ' => 'htmlentity_greek_small_letter_zeta', 'η' => 'htmlentity_greek_small_letter_eta', 'θ' => 'htmlentity_greek_small_letter_theta', 'ι' => 'htmlentity_greek_small_letter_iota', 'κ' => 'htmlentity_greek_small_letter_kappa', 'λ' => 'htmlentity_greek_small_letter_lambda', 'μ' => 'htmlentity_greek_small_letter_mu', 'ν' => 'htmlentity_greek_small_letter_nu', 'ξ' => 'htmlentity_greek_small_letter_xi', 'ο' => 'htmlentity_greek_small_letter_omicron', 'π' => 'htmlentity_greek_small_letter_pi', 'ρ' => 'htmlentity_greek_small_letter_rho', 'ς' => 'htmlentity_greek_small_letter_final_sigma', 'σ' => 'htmlentity_greek_small_letter_sigma', 'τ' => 'htmlentity_greek_small_letter_tau', 'υ' => 'htmlentity_greek_small_letter_upsilon', 'φ' => 'htmlentity_greek_small_letter_phi', 'χ' => 'htmlentity_greek_small_letter_chi', 'ψ' => 'htmlentity_greek_small_letter_psi', 'ω' => 'htmlentity_greek_small_letter_omega', 'ϑ' => 'htmlentity_greek_small_letter_theta_symbol', 'ϒ' => 'htmlentity_greek_upsilon_with_hook_symbol', 'ϖ' => 'htmlentity_greek_pi_symbol', 'À' => 'htmlentity_capital_A_grave_accent', 'Á' => 'htmlentity_capital_A_acute_accent', 'Â' => 'htmlentity_capital_A_circumflex_accent', 'Ã' => 'htmlentity_capital_A_tilde', 'Ä' => 'htmlentity_capital_A_dieresis_or_umlaut_mark', 'Å' => 'htmlentity_capital_A_ring', 'Æ' => 'htmlentity_capital_AE_diphthong_ligature', 'Ç' => 'htmlentity_capital_C_cedilla', 'È' => 'htmlentity_capital_E_grave_accent', 'É' => 'htmlentity_capital_E_acute_accent', 'Ê' => 'htmlentity_capital_E_circumflex_accent', 'Ë' => 'htmlentity_capital_E_dieresis_or_umlaut_mark', 'Ì' => 'htmlentity_capital_I_grave_accent', 'Í' => 'htmlentity_capital_I_acute_accent', 'Î' => 'htmlentity_capital_I_circumflex_accent', 'Ï' => 'htmlentity_capital_I_dieresis_or_umlaut_mark', 'Ð' => 'htmlentity_capital_Eth_Icelandic', 'Ñ' => 'htmlentity_capital_N_tilde', 'Ò' => 'htmlentity_capital_O_grave_accent', 'Ó' => 'htmlentity_capital_O_acute_accent', 'Ô' => 'htmlentity_capital_O_circumflex_accent', 'Õ' => 'htmlentity_capital_O_tilde', 'Ö' => 'htmlentity_capital_O_dieresis_or_umlaut_mark', 'Ø' => 'htmlentity_capital_O_slash', 'Ù' => 'htmlentity_capital_U_grave_accent', 'Ú' => 'htmlentity_capital_U_acute_accent', 'Û' => 'htmlentity_capital_U_circumflex_accent', 'Ü' => 'htmlentity_capital_U_dieresis_or_umlaut_mark', 'Ý' => 'htmlentity_capital_Y_acute_accent', 'Þ' => 'htmlentity_capital_THORN_Icelandic', 'ß' => 'htmlentity_small_sharp_s_German_sz_ligature', 'à' => 'htmlentity_small_a_grave_accent', 'á' => 'htmlentity_small_a_acute_accent', 'â' => 'htmlentity_small_a_circumflex_accent', 'ã' => 'htmlentity_small_a_tilde', 'ä' => 'htmlentity_small_a_dieresis_or_umlaut_mark', 'å' => 'htmlentity_small_a_ring', 'æ' => 'htmlentity_small_ae_diphthong_ligature', 'ç' => 'htmlentity_small_c_cedilla', 'è' => 'htmlentity_small_e_grave_accent', 'é' => 'htmlentity_small_e_acute_accent', 'ê' => 'htmlentity_small_e_circumflex_accent', 'ë' => 'htmlentity_small_e_dieresis_or_umlaut_mark', 'ì' => 'htmlentity_small_i_grave_accent', 'í' => 'htmlentity_small_i_acute_accent', 'î' => 'htmlentity_small_i_circumflex_accent', 'ï' => 'htmlentity_small_i_dieresis_or_umlaut_mark', 'ð' => 'htmlentity_small_eth_Icelandic', 'ñ' => 'htmlentity_small_n_tilde', 'ò' => 'htmlentity_small_o_grave_accent', 'ó' => 'htmlentity_small_o_acute_accent', 'ô' => 'htmlentity_small_o_circumflex_accent', 'õ' => 'htmlentity_small_o_tilde', 'ö' => 'htmlentity_small_o_dieresis_or_umlaut_mark', 'ø' => 'htmlentity_small_o_slash', 'ù' => 'htmlentity_small_u_grave_accent', 'ú' => 'htmlentity_small_u_acute_accent', 'û' => 'htmlentity_small_u_circumflex_accent', 'ü' => 'htmlentity_small_u_dieresis_or_umlaut_mark', 'ý' => 'htmlentity_small_y_acute_accent', 'þ' => 'htmlentity_small_thorn_Icelandic', 'ƒ' => 'htmlentity_latin_small_f_with_hook', 'Œ' => 'htmlentity_latin_capital_ligature_oe', 'œ' => 'htmlentity_latin_small_ligature_oe', 'Š' => 'htmlentity_latin_capital_letter_s_with_caron', 'š' => 'htmlentity_latin_small_letter_s_with_caron', 'Ÿ' => 'htmlentity_latin_capital_letter_y_with_diaeresis');
    //number of replacements to check
    $total_replacements = count($foreign_char_array) - 1;
    //get the keys from the array
    $keys = array_keys($foreign_char_array);
    //get the values from the array
    $values = array_values($foreign_char_array);
    //do the replacement
    for ($i = 0; $i <= $total_replacements; $i++) {
        $k = $keys[$i];
        $v = $values[$i];
        $t = htmlentities($text, ENT_QUOTES);
        if ($whichway == "encode") {
            $t = str_replace($k, $v, $t);
        } else {
            $t = str_replace($v, $k, $t);
        }
        $text = html_entity_decode($t, ENT_QUOTES);
    }
    return $text;
}
/**
 * function clean_condition()
 * This function cleans an item to be used in conditional checks
 * @param  string $condition - item to be cleaned
 * @return string $condition - item after clean
**/
function clean_condition($condition)
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Cleaning condition - {$condition} ", 4);
    return trim($condition);
}
/**
 * function check_set_format(()
 * A function to check and set the conversation return type
 * @param  array $convoArr - the current state of the conversation array
 * @return $convoArr (updated)
**/
function check_set_format($convoArr)
{
    global $default_format;
    $formatsArr = array('html', 'xml', 'json');
    //at thsi point we can overwrite the conversation format.
    if (isset($_REQUEST['format']) && trim($_REQUEST['format']) != "") {
        $format = trim($_REQUEST['format']);
    } else {
        $format = $default_format;
    }
    $convoArr['conversation']['format'] = strtolower($format);
    if (!in_array($convoArr['conversation']['format'], $formatsArr)) {
        $convoArr['debug']['intialisation_error'] = "Incompatible return type: {$format}";
        runDebug(__FILE__, __FUNCTION__, __LINE__, "ERROR - bad return type: {$format}", 1);
    } else {
        runDebug(__FILE__, __FUNCTION__, __LINE__, "Using format: {$format}", 2);
    }
    return $convoArr;
}
Exemple #10
0
/**
 * Function parseInput
 *
 * * @param $msg
 * @return mixed
 */
function parseInput($msg)
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Pre-parsing input. Setting Timestamp. msg = |{$msg}|", 4);
    $smilieArray = file(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'inputEmotes.dat');
    rsort($smilieArray);
    $out = str_replace($smilieArray, 'emoteshown', $msg);
    // Edit the input to deal with multiple punctuation marks
    $emSearch = '/^\\!+/';
    // Exclamation mark search string
    $out = preg_replace($emSearch, 'emonly', $out);
    //
    $qmSearch = '/^\\?+/';
    // Question mark search string
    $out = preg_replace($qmSearch, 'qmonly', $out);
    //
    $periodSearch = '/^\\.+/';
    // Period search string
    $out = preg_replace($periodSearch, 'periodonly', $out);
    //
    runDebug(__FILE__, __FUNCTION__, __LINE__, "msg now = |{$out}|", 4);
    return $out;
    // Send back the processed image
}
Exemple #11
0
/**
 * function find_aiml_matches()
 * This function builds the sql to use to get a match from the tbl
 * @param array $convoArr - conversation array
 * @return array $convoArr
 **/
function find_aiml_matches($convoArr)
{
    global $dbConn, $dbn, $error_response, $use_parent_bot;
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Finding the aiml matches from the DB", 4);
    $i = 0;
    //TODO convert to get_it
    $bot_id = $convoArr['conversation']['bot_id'];
    $bot_parent_id = $convoArr['conversation']['bot_parent_id'];
    $default_aiml_pattern = $convoArr['conversation']['default_aiml_pattern'];
    #$lookingfor = get_convo_var($convoArr,"aiml","lookingfor");
    $convoArr['aiml']['lookingfor'] = str_replace('  ', ' ', $convoArr['aiml']['lookingfor']);
    $lookingfor = trim(strtoupper($convoArr['aiml']['lookingfor']));
    //get the first and last words of the cleaned user input
    $lastInputWord = get_last_word($lookingfor);
    $firstInputWord = get_first_word($lookingfor);
    //get the stored topic
    $storedtopic = get_topic($convoArr);
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Stored topic = '{$storedtopic}'", 4);
    //get the cleaned user input
    $lastthat = isset($convoArr['that'][1][1]) ? $convoArr['that'][1][1] : '';
    //build like patterns
    if ($lastthat != '') {
        $thatPatternSQL = " OR " . make_like_pattern($lastthat, 'thatpattern');
        $thatPatternSQL = rtrim($thatPatternSQL, ' OR');
    } else {
        $thatPattern = '';
        $thatPatternSQL = '';
    }
    //get the word count
    $word_count = wordsCount_inSentence($lookingfor);
    if ($bot_parent_id != 0 and $bot_parent_id != $bot_id) {
        $sql_bot_select = " (bot_id = '{$bot_id}' OR bot_id = '{$bot_parent_id}') ";
    } else {
        $sql_bot_select = " bot_id = '{$bot_id}' ";
    }
    if (!empty($storedtopic)) {
        $topic_select = "AND (`topic`='' OR `topic`='{$storedtopic}')";
    } else {
        $topic_select = '';
    }
    if ($word_count == 1) {
        //if there is one word do this
        $sql = "SELECT `id`, `pattern`, `thatpattern`, `topic` FROM `{$dbn}`.`aiml` WHERE\n  {$sql_bot_select} AND (\n  `pattern` = '_' OR\n  `pattern` = '*' OR\n  `pattern` = '{$lookingfor}' OR\n  `pattern` = '{$default_aiml_pattern}'\n  {$thatPatternSQL}\n  ) {$topic_select} order by `topic` desc, `pattern` asc, `thatpattern` asc,`id` asc;";
    } else {
        //otherwise do this
        $sql_add = make_like_pattern($lookingfor, 'pattern');
        $sql = "SELECT `id`, `bot_id`, `pattern`, `thatpattern`, `topic` FROM `{$dbn}`.`aiml` WHERE\n  {$sql_bot_select} AND (\n  `pattern` = '_' OR\n  `pattern` = '*' OR\n  `pattern` = '{$lookingfor}' OR {$sql_add} OR\n  `pattern` = '{$default_aiml_pattern}'\n  {$thatPatternSQL}\n  ) {$topic_select}\n  order by `topic` desc, `pattern` asc, `thatpattern` asc,`id` asc;";
    }
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Core Match AIML sql: {$sql}", 3);
    $result = db_fetchAll($sql, null, __FILE__, __FUNCTION__, __LINE__);
    $num_rows = count($result);
    if ($result && $num_rows > 0) {
        $tmp_rows = number_format($num_rows);
        runDebug(__FILE__, __FUNCTION__, __LINE__, "FOUND: ({$num_rows}) potential AIML matches", 2);
        $tmp_content = date('H:i:s') . ": SQL:\n{$sql}\nRows = {$tmp_rows}\n\n";
        //loop through results
        foreach ($result as $row) {
            $row['aiml_id'] = $row['id'];
            $row['bot_id'] = $bot_id;
            $row['score'] = 0;
            $row['track_score'] = '';
            $allrows[] = $row;
            $mu = memory_get_usage(true);
            if ($mu >= MEM_TRIGGER) {
                runDebug(__FILE__, __FUNCTION__, __LINE__, 'Current operation exceeds memory threshold. Aborting data retrieval.', 0);
                break;
            }
        }
    } else {
        runDebug(__FILE__, __FUNCTION__, __LINE__, "Error: FOUND NO AIML matches in DB", 1);
        $allrows[$i]['aiml_id'] = "-1";
        $allrows[$i]['bot_id'] = $bot_id;
        $allrows[$i]['pattern'] = "no results";
        $allrows[$i]['thatpattern'] = '';
        $allrows[$i]['topic'] = '';
    }
    return $allrows;
}
Exemple #12
0
function db_write($sql, $params = null, $multi = false, $file = 'unknown', $function = 'unknown', $line = 'unknown')
{
    global $dbConn;
    try {
        $sth = $dbConn->prepare($sql);
        switch (true) {
            case $params === null:
                $sth->execute();
                break;
            case $multi === true:
                foreach ($params as $row) {
                    $sth->execute($row);
                }
                break;
            default:
                $sth->execute($params);
        }
        return $sth->rowCount();
    } catch (Exception $e) {
        $pdoError = print_r($dbConn->errorInfo(), true);
        $psError = print_r($sth->errorInfo(), true);
        error_log("bad SQL encountered in file {$file}, line #{$line}. SQL:\n{$sql}\nPDO Error:\n{$pdoError}\nSTH Error:\n{$psError}\nException Message:\n" . $e->getMessage() . "\n", 3, _LOG_PATH_ . 'db_write.txt');
        runDebug(__FILE__, __FUNCTION__, __LINE__, "An error was generated while writing to the database in file {$file} at line {$line}, in the function {$function} - SQL:\n{$sql}\nPDO error: {$pdoError}\nPDOStatement error: {$psError}", 0);
        return false;
    }
}
/**
 * function load_that(()
 * A function to load the previous bot responses into the convoArr['that'] array
 *
 * @link http://blog.program-o.com/?p=1283
 * @param  array $convoArr - the current state of the conversation array
 * @return array $convoArr (updated)
 */
function load_that($convoArr)
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, 'Loading the THAT array.', 2);
    global $dbConn, $dbn, $remember_up_to, $bot_id;
    $remember_up_to = !empty($convoArr['conversation']['remember_up_to']) ? $convoArr['conversation']['remember_up_to'] : $remember_up_to;
    $user_id = $convoArr['conversation']['user_id'];
    $bot_id = !empty($convoArr['conversation']['bot_id']) ? $convoArr['conversation']['bot_id'] : $bot_id;
    $limit = $remember_up_to;
    $sql = "select `input`, `response` from `{$dbn}`.`conversation_log` where `user_id` = {$user_id} and `bot_id` = {$bot_id} order by `id` desc limit {$limit};";
    // desc
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Getting conversation log entries for the current user. SQL:\n{$sql}", 3);
    $result = db_fetchAll($sql, null, __FILE__, __FUNCTION__, __LINE__);
    if ($result) {
        $tmpThatRows = array();
        $tmpInputRows = array();
        $tmpThat = array();
        $tmpInput = array();
        $puncuation = array(',', '?', ';', '!');
        foreach ($result as $row) {
            $tmpThatRows[] = $row['response'];
            $tmpInputRows[] = $row['input'];
        }
        runDebug(__FILE__, __FUNCTION__, __LINE__, 'Inputs returned:' . print_r($tmpInputRows, true), 1);
        runDebug(__FILE__, __FUNCTION__, __LINE__, 'Loading previous responses into the ~THAT~ array.', 4);
        runDebug(__FILE__, __FUNCTION__, __LINE__, 'Responses returned:' . print_r($tmpThatRows, true), 1);
        $tmpThatRows = array_reverse($tmpThatRows);
        foreach ($tmpThatRows as $row) {
            $row = str_replace($puncuation, '.', $row);
            $tmpThat[] = explode('.', $row);
        }
        array_unshift($tmpThat, NULL);
        unset($tmpThat[0]);
        foreach ($tmpThat as $index => $value) {
            $value = implode_recursive(' ', $value, __FILE__, __FUNCTION__, __LINE__);
            $value = clean_that($value, __FILE__, __FUNCTION__, __LINE__);
            $convoArr = push_on_front_convoArr('that', $value, $convoArr);
        }
        runDebug(__FILE__, __FUNCTION__, __LINE__, 'Loading previous user inputs into the ~INPUT~ array.', 4);
        $tmpInputRows = array_reverse($tmpInputRows);
        foreach ($tmpInputRows as $row) {
            $row = str_replace($puncuation, '.', $row);
            $tmpInput[] = explode('.', $row);
        }
        array_unshift($tmpThat, NULL);
        unset($tmpThat[0]);
        foreach ($tmpInput as $index => $value) {
            $value = implode_recursive(' ', $value, __FILE__, __FUNCTION__, __LINE__);
            $value = clean_that($value, __FILE__, __FUNCTION__, __LINE__);
            $convoArr = push_on_front_convoArr('input', $value, $convoArr);
        }
    } else {
        runDebug(__FILE__, __FUNCTION__, __LINE__, 'Couldn\'t find any previous inputs or responses.', 4);
    }
    return $convoArr;
}
Exemple #14
0
/**
 * function math_functions()
 * This function runs the system math operations
 *
 * @param string       $operator - maths operator
 * @param int        $num_1    - the first number
 * @param int|string $num_2    - the second number
 * @internal param int $output - the result of the math operation
 *
 * @return float|int|number|string
 */
function math_functions($operator, $num_1, $num_2 = "")
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Running system tag math {$num_1} {$operator} {$num_2}", 4);
    $operator = IS_MB_ENABLED ? mb_strtolower($operator) : strtolower($operator);
    switch ($operator) {
        case "add":
            $output = $num_1 + $num_2;
            break;
        case "subtract":
            $output = $num_1 - $num_2;
            break;
        case "multiply":
            $output = $num_1 * $num_2;
            break;
        case "divide":
            if ($num_2 == 0) {
                $output = "You can't divide by 0!";
            } else {
                $output = $num_1 / $num_2;
            }
            break;
        case "sqrt":
            $output = sqrt($num_1);
            break;
        case "power":
            $output = pow($num_1, $num_2);
            break;
        default:
            $output = $operator . "?";
    }
    return $output;
}
/**
 * Converts the contents of the AIML tag to a string.
 *
 * @param array            $convoArr
 * @param SimpleXMLElement $element
 * @param string           $parentName
 * @param int              $level
 * @param string           $type
 * @return string
 */
function tag_to_string(&$convoArr, $element, $parentName, $level, $type = 'element')
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, "converting the {$parentName} tag into text.", 2);
    $response = array();
    $children = $element->children();
    if (!empty($children)) {
        foreach ($children as $child) {
            $response[] = parseTemplateRecursive($convoArr, $child, $level + 1);
        }
    } else {
        switch ($type) {
            case 'element':
                $response[] = (string) $element;
                break;
            default:
                $response[] = $convoArr['star'][1];
        }
    }
    $response_string = implode_recursive(' ', $response, __FILE__, __FUNCTION__, __LINE__);
    // do something here
    return $response_string;
}
        $convoArr['conversation']['totallines'] = 0;
        $convoArr = get_user_id($convoArr);
    }
    $convoArr['aiml'] = array();
    //add the latest thing the user said
    $convoArr = add_new_conversation_vars($say, $convoArr);
    //parse the aiml
    $convoArr = make_conversation($convoArr);
    $convoArr = run_mid_level_addons($convoArr);
    $convoArr = log_conversation($convoArr);
    #$convoArr = log_conversation_state($convoArr);
    $convoArr = write_to_session($convoArr);
    $convoArr = get_conversation($convoArr);
    $convoArr = run_post_response_useraddons($convoArr);
    //return the values to display
    $display = $convoArr['send_to_user'];
    $time_start = $convoArr['time_start'];
    unset($convoArr['nounList']);
    $final_convoArr = $convoArr;
} else {
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Conversation intialised waiting user", 2);
    $convoArr['send_to_user'] = '';
}
runDebug(__FILE__, __FUNCTION__, __LINE__, "Closing Database", 2);
$dbConn = db_close();
$time_end = microtime(true);
$time = number_format(round(($time_end - $script_start) * 1000, 7), 3);
display_conversation($convoArr);
runDebug(__FILE__, __FUNCTION__, __LINE__, "Conversation Ending. Elapsed time: {$time} milliseconds.", 0);
$convoArr = handleDebug($convoArr, $time);
// Make sure this is the last line in the file, so that all debug entries are captured.
<?php

/***************************************
* http://www.program-o.com
* PROGRAM O 
* Version: 2.0.9
* FILE: chatbot/core/aiml/load_convofunctions.php
* AUTHOR: ELIZABETH PERREAU
* DATE: MAY 4TH 2011
* DETAILS: this file contains all the includes that are needed to process the return/display of the conversation
***************************************/
include_once "intialise_conversation.php";
include_once "display_conversation.php";
include_once "make_conversation.php";
runDebug(__FILE__, __FUNCTION__, __LINE__, "Convofunction include files loaded", 4);
Exemple #18
0
* PROGRAM O 
* Version: 2.0.9
* FILE: install/upgrade.php
* AUTHOR: ELIZABETH PERREAU AND DAVE MORTON
* DATE: JUNE 4TH 2012
* DETAILS: PLEASE RUN THIS FILE TO UPGRADE THE DATABASE FROM VERSION 1 TO VERSION 2
***************************************/
$thisFile = __FILE__;
if (!file_exists('../config/global_config.php')) {
    header('location: ../install/install_programo.php');
}
require_once '../config/global_config.php';
//load shared files
include_once _LIB_PATH_ . "db_functions.php";
include_once _LIB_PATH_ . "error_functions.php";
runDebug(__FILE__, __FUNCTION__, __LINE__, "Starting upgrade");
create_bots_tbl();
update_aiml_tbl();
//open db connection
$con = db_open();
function create_bots_tbl()
{
    global $con, $dbn;
    $sql = "CREATE TABLE IF NOT EXISTS `{$dbn}`.`bots` (\n\t\t  `bot_id` int(11) NOT NULL AUTO_INCREMENT,\n\t\t  `bot_name` varchar(255) NOT NULL,\n\t\t  `bot_desc` varchar(255) NOT NULL,\n\t\t  `bot_active` int(11) NOT NULL DEFAULT '1',\n\t\t  `format` varchar(10) NOT NULL DEFAULT 'html',\n\t\t  `use_aiml_code` int(11) NOT NULL DEFAULT '1',\n\t\t  `update_aiml_code` int(11) NOT NULL DEFAULT '1',\n\t\t  `save_state` enum('session','database') NOT NULL DEFAULT 'session',\n\t\t  `conversation_lines` int(11) NOT NULL DEFAULT '7',\n\t\t  `remember_up_to` int(11) NOT NULL DEFAULT '10',\n\t\t  `debugemail` int(11) NOT NULL,\n\t\t  `debugshow` int(11) NOT NULL DEFAULT '1',\n\t\t  `debugmode` int(11) NOT NULL DEFAULT '1',\n\t\t  `default_aiml_pattern` varchar(255) NOT NULL DEFAULT 'RANDOM PICKUP LINE',\n\t\t  PRIMARY KEY (`bot_id`)\n\t\t)";
    $result = mysql_query($sql, $con);
    if ($result) {
        outputDebug(__FILE__, __FUNCTION__, __LINE__, "Created bot table");
    } else {
        outputDebug(__FILE__, __FUNCTION__, __LINE__, "Errorwhile creating bot table - Exiting");
        exit;
    }
<?php

/***************************************
 * www.program-o.com
 * PROGRAM O
 * Version: 2.4.3
 * FILE: chatbot/core/user/load_userfunctions.php
 * AUTHOR: Elizabeth Perreau and Dave Morton
 * DATE: MAY 17TH 2014
 * DETAILS: this file contains the includes to load all user function files
 ***************************************/
include_once "handle_user.php";
runDebug(__FILE__, __FUNCTION__, __LINE__, "userfunctions include files loaded", 4);
/**
 * function get_xml()
 * This function formats the response as xml
 * @link http://blog.program-o.com/?p=1238
 * @param  array $convoArr - the conversation array
 * @param  array $conversation - the conversation lines to format
 * @return array $convoArr
 **/
function get_xml($convoArr, $conversation)
{
    $addTags = array('bot_id', 'bot_name', 'user_id', 'user_name');
    $program_o = new SimpleXMLElement('<program_o/>');
    $program_o->addChild('version', VERSION);
    $program_o->addChild('status');
    $status = $program_o->status;
    $status->addChild('success', true);
    foreach ($addTags as $tag_name) {
        $tmpVal = $convoArr['conversation'][$tag_name];
        $program_o->addChild($tag_name, $tmpVal);
    }
    $program_o->addChild('chat');
    $chat = $program_o->chat;
    foreach ($conversation as $index => $conversation_subarray) {
        if (empty($conversation_subarray)) {
            continue;
        }
        $line = $chat->addChild('line');
        $line->addChild('input', $conversation_subarray['input']);
        $line->addChild('response', $conversation_subarray['response']);
    }
    $responseXML = $program_o->asXML();
    libxml_use_internal_errors(true);
    $dom = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = true;
    $dom->formatOutput = true;
    $dom->loadXML($responseXML);
    $send_to_user = $dom->saveXML();
    $convoArr['send_to_user'] = $send_to_user;
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Returning XML", 4);
    return $convoArr;
}
/**
 * function db_close()
 * Close the connection to the database
 *
 * @link     http://blog.program-o.com/?p=1343
 * @internal param resource $dbConn - the open connection
 *
 * @return null
 */
function db_close()
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, 'This DB is now closed. You don\'t have to go home, but you can\'t stay here.', 2);
    return null;
}
/**
 * function aiml_to_phpfunctions()
 * This function performs a big find and replace on the aiml to convert it to php code
 * @param  array $convoArr - the existing conversation array
 * @return array $convoArr
**/
function aiml_to_phpfunctions($convoArr)
{
    //TODO do we need this still?
    global $botsay, $srai_iterations, $error_response;
    //TODO read from bot vars
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Converting the AIML to PHP code", 4);
    //extra debug info
    $msg = "";
    $useStoredPHP = $convoArr['conversation']['use_aiml_code'];
    $uac = $convoArr['conversation']['update_aiml_code'];
    #$uac = 0;
    if ($convoArr['aiml']['aiml_to_php'] == "") {
        $msg .= " php code does not exist,";
    } else {
        $msg .= " php code exists,";
    }
    if ($useStoredPHP == 1) {
        $msg .= " Use stored php code is set to YES({$useStoredPHP})";
    } else {
        $msg .= " Use stored php code is set to NO({$useStoredPHP})";
    }
    if ($uac == 1) {
        $msg .= " update aiml to php is set to YES({$uac})";
    } else {
        $msg .= " update aiml to php is set to NO({$uac})";
    }
    //THIS MAY already have the code contained in the db in which case we can skip all of this
    //UNLESS - update_aiml_code is set to 1 this means we want to re-write it each time
    if ($convoArr['aiml']['aiml_to_php'] != "" and $uac == 0 and $useStoredPHP == 1) {
        runDebug(__FILE__, __FUNCTION__, __LINE__, "Using existing AIML to PHP code - {$msg}", 2);
        $parsed_template = get_convo_var($convoArr, 'aiml', 'aiml_to_php');
    } else {
        runDebug(__FILE__, __FUNCTION__, __LINE__, "Generating new AIML to PHP code - {$msg}", 2);
        //load the existing aiml template
        $template = get_convo_var($convoArr, 'aiml', 'template');
        //make stars, apostrophes and encode foriegn chars just to make everything safe before the big replace
        $template = str_replace("*", "\\*", $template);
        $template = str_replace("'", '~apos~', $template);
        $template = foreignchar_replace('encode', $template);
        $template = entity_replace('encode', $template);
        $i = 0;
        //to do this is in the add custom tags thing
        //start the find and replace
        $template = preg_replace('#<bot name="([^"]*)"/>#ie', "\$convoArr['bot_properties']['\$1']", $template);
        runDebug(__FILE__, __FUNCTION__, __LINE__, "Made initial bot property replacements", 4);
        $find[$i] = '#</say>#i';
        $replace[$i] = '\';';
        $i++;
        $find[$i] = '#<template>(\\s)*?</template>#i';
        $replace[$i] = '';
        $i++;
        $find[$i] = '#<template/>#i';
        $replace[$i] = '';
        $i++;
        $find[$i] = '#<say>#i';
        $replace[$i] = '$tmp_botsay .= \'';
        $i++;
        $find[$i] = '#<bot name="([^"]*)"/>#i';
        $replace[$i] = '\'.call_user_func(\'get_convo_var\',$convoArr,\'bot_properties\',\'$1\').\'';
        $i++;
        $find[$i] = '#<date format="([^"]*)"/>#i';
        $replace[$i] = '\'.call_user_func(\'get_formatted_date\',\'$1\').\'';
        $i++;
        $find[$i] = '#<bigthink></bigthink>#i';
        $replace[$i] = '; $tmp_botsay = ""; ';
        $i++;
        $find[$i] = '#<pushstack>(.*)([^<]*)</pushstack>#';
        $replace[$i] = '\'.call_user_func(\'push_stack\',$convoArr,\'$1\').\'';
        $i++;
        $find[$i] = '#PUSH\\s?<([^>]*)>#';
        $replace[$i] = '\'.call_user_func(\'push_stack\',$convoArr,\'<$1>\').\'';
        $i++;
        $find[$i] = '#POP\\s?<([^>]*)>#';
        $replace[$i] = '\'.call_user_func(\'pop_stack\',$convoArr).\'';
        $i++;
        $find[$i] = '#<popstack></popstack>#';
        $replace[$i] = '\'.call_user_func(\'pop_stack\',$convoArr).\'';
        $i++;
        $find[$i] = '#<personf/>#i';
        $replace[$i] = '\'.call_user_func(\'url_encode_star\',$convoArr).\'';
        $i++;
        $find[$i] = '#<topic name=\\"(A-Z0-9)\\">#i';
        $replace[$i] = '\'.call_user_func(\'set_topicname\',$convoArr,\'$1\').\'';
        $i++;
        $find[$i] = '#<star index="([^"]*?)"/>#i';
        $replace[$i] = '\'.call_user_func(\'get_convo_var\',$convoArr,\'star\',\'\',\'$1\').\'';
        $i++;
        $find[$i] = '#<that index="(.*?),(.*?)"/>#i';
        $replace[$i] = '\'.call_user_func(\'get_convo_var\',$convoArr,\'that\',\'\',\'$1\',\'$2\').\'';
        $i++;
        $find[$i] = '#<input index="([^"]*)"/>#i';
        $replace[$i] = '\'.call_user_func(\'get_convo_var\',$convoArr,\'input\',\'\',\'$1\').\'';
        $i++;
        $find[$i] = '#<thatstar index="([^"]*)"/>#i';
        $replace[$i] = '\'.call_user_func(\'get_convo_var\',$convoArr,\'that_star\',\'\',\'$1\').\'';
        $i++;
        $find[$i] = '#<topicstar index="([^"]*)"/>#i';
        $replace[$i] = '\'.call_user_func(\'get_convo_var\',$convoArr,\'topic_star\',\'\',\'$1\').\'';
        $i++;
        $find[$i] = '#<get name="topic"(\\s)?(/)?>#i';
        $replace[$i] = '\'.call_user_func(\'get_convo_var\',$convoArr,\'topic\').\'';
        $i++;
        $find[$i] = '#<get name="([^"]*)"(/)?>#i';
        $replace[$i] = '\'.call_user_func(\'get_convo_var\',$convoArr,\'client_properties\',\'$1\').\'';
        $i++;
        $find[$i] = '#<id/>#i';
        $replace[$i] = '\'.call_user_func(\'get_convo_var\',$convoArr,\'client_properties\',\'id\').\'';
        $i++;
        $find[$i] = '#<uppercase>([^<]*)</uppercase>#i';
        $replace[$i] = '\'.call_user_func(\'format\',\'uppercase\',\'$1\').\'';
        $i++;
        $find[$i] = '#<lowercase>([^<]*)</lowercase>#i';
        $replace[$i] = '\'.call_user_func(\'format\',\'lowercase\',\'$1\').\'';
        $i++;
        $find[$i] = '#<formal>([^<]*)</formal>#i';
        $replace[$i] = '\'.call_user_func(\'format\',\'formal\',\'$1\').\'';
        $i++;
        $find[$i] = '#<sentence>([^<]*)</sentence>#i';
        $replace[$i] = '\'.call_user_func(\'format\',\'sentence\',\'$1\').\'';
        $i++;
        $find[$i] = '#<srai>#i';
        $replace[$i] = '\'.call_user_func(\'run_srai\',$convoArr,\'';
        $i++;
        $find[$i] = '#</srai>#i';
        $replace[$i] = '\').\'';
        $i++;
        $find[$i] = '#<think>#i';
        $replace[$i] = '\'.call_user_func(\'make_null\',\'';
        $i++;
        $find[$i] = '#</think>#i';
        $replace[$i] = '\').\'';
        $i++;
        $find[$i] = '#<person>([^<]*)</person>#i';
        $replace[$i] = '\'.call_user_func(\'transform_prounoun\',$convoArr,\'3\',\'$1\').\'';
        $i++;
        $find[$i] = '#<person2>([^<]*)</person2>#i';
        $replace[$i] = '\'.call_user_func(\'transform_prounoun\',$convoArr,\'2\',\'$1\').\'';
        $i++;
        $find[$i] = '#<condition>[\\s]?<li name="([^"]*)" value="([^"]*)">#i';
        $replace[$i] = "';\r\n" . ' if( ((isset($convoArr[\'$1\'])) && (strtoupper($convoArr[\'$1\']) === strtoupper(\'$2\'))) || ((isset($convoArr[\'client_properties\'][\'$1\'])) && (strtoupper($convoArr[\'client_properties\'][\'$1\']) === strtoupper(\'$2\')))  )' . "\r\n" . ' { $tmp_botsay .= \'';
        $i++;
        $find[$i] = '#<condition name="([^"]*)">#i';
        $replace[$i] = "\r\n" . '; $condition = call_user_func(\'clean_condition\',\'$1\'); ';
        $i++;
        $find[$i] = '#<li name="([0-9a-z]*)" value="([0-9a-z]*)">#i';
        $replace[$i] = "\r\n" . ' elseif( ((isset($convoArr[\'$1\'])) && (strtoupper($convoArr[\'$1\']) === strtoupper(\'$2\'))) || ((isset($convoArr[\'client_properties\'][\'$1\'])) && (strtoupper($convoArr[\'client_properties\'][\'$1\']) === strtoupper(\'$2\')))  )' . "\r\n" . ' { $tmp_botsay .= \'';
        $i++;
        $find[$i] = '#<li value="([^"]*)">#i';
        $replace[$i] = "\r\n" . ' elseif( ((isset($convoArr[$condition])) && (strtoupper($convoArr[$condition]) === strtoupper(\'$1\'))) || ((isset($convoArr[\'client_properties\'][$condition])) && (strtoupper($convoArr[\'client_properties\'][$condition]) === strtoupper(\'$1\')))  )' . "\r\n" . ' { $tmp_botsay .= \'';
        $i++;
        $find[$i] = '#;(\\s|\\s+)?elseif#i';
        $replace[$i] = ";\r\nif";
        $i++;
        $find[$i] = "#<\random>(\\?|\\.|\\!\\s)?</li>#eis";
        $replace[$i] = '</random>$1\';}';
        //this has to be be evalutated immeditately as nothing will change we are just collecting a random value
        $i++;
        $find[$i] = "#<random>([^<]*)</random>#eis";
        $replace[$i] = 'call_user_func(\'select_random\',\'$1\')';
        // this needs a second attempt before i work out a proper fix
        // the first removes the out random but if there is a nested random it wont work
        $i++;
        $find[$i] = "#<random>(.*)</random>#eis";
        $replace[$i] = 'call_user_func(\'select_random\',\'$1\')';
        $i++;
        $find[$i] = '#<li>(.*)</li>#i';
        $replace[$i] = "\r\n" . 'else { $tmp_botsay .=\'$1\'; } ';
        $i++;
        $find[$i] = '#</li>#i';
        $replace[$i] = '\'; } ';
        $i++;
        $find[$i] = '#</condition>#i';
        $replace[$i] = "\r\n" . '$condition = ""; ';
        //TODO WORK OUT WHY THIS OCCURES
        $i++;
        $find[$i] = '#</conditio#i';
        $replace[$i] = "\r\n" . '$condition = ""; ';
        $i++;
        $find[$i] = '#<set name="([^"]*)">#i';
        $replace[$i] = '\'.call_user_func(\'set_simple\',$convoArr,\'$1\',\'';
        $i++;
        $find[$i] = '#<set name=\\\\"([^\\\\]*)\\\\">#i';
        $replace[$i] = '\'.call_user_func(\'set_simple\',$convoArr,\'$1\',\'';
        $i++;
        $find[$i] = '#</set>#i';
        $replace[$i] = '\').\'';
        $i++;
        $find[$i] = '#</get>#i';
        $replace[$i] = '';
        $i++;
        $find[$i] = '#<system>\\s?(add|power|sqrt|divide|multiply|subtract)\\s?(.*)[\\s?](.*)</system>#i';
        $replace[$i] = '\'.call_user_func(\'run_system\',\'$1\',\'$2\',\'$3\').\'';
        $i++;
        $find[$i] = '#<learn>\\s+?<category>\\s+?<pattern>\\s+?<eval>([^<]*)</eval>\\s+?</pattern>\\s+?<template>\\s+?<eval>([^<]*)</eval>\\s+?</template>\\s+?</category>\\s+?</learn>#ius';
        $replace[$i] = '\'; call_user_func(\'make_learn\',$convoArr,\'$1\',\'$2\');';
        runDebug(__FILE__, __FUNCTION__, __LINE__, "Built core tag array to make replacements", 4);
        //custom tags handled here
        $custom_tag_handle = custom_aiml_to_phpfunctions($find, $replace, $i);
        $find = $custom_tag_handle['find'];
        $replace = $custom_tag_handle['replace'];
        runDebug(__FILE__, __FUNCTION__, __LINE__, "Built custom tag array to make replacements", 4);
        runDebug(__FILE__, __FUNCTION__, __LINE__, "Looking to replace: " . print_r($find, true), 4);
        runDebug(__FILE__, __FUNCTION__, __LINE__, "With replacements: " . print_r($replace, true), 4);
        //actually do the find and replace here
        $parsed_template = preg_replace($find, $replace, $template);
        //clean up the find/replace code so that it can actaully evaluate as real php code
        $parsed_template = clean_for_eval($parsed_template, 0);
        //decode back before sending
        $parsed_template = entity_replace('decode', $parsed_template);
        $parsed_template = foreignchar_replace('decode', $parsed_template);
        //write to convoArr
        $convoArr['aiml']['aiml_to_php'] = $parsed_template;
        //update the aiml table
        $convoArr = add_aiml_to_php($convoArr);
    }
    //evaluate the generated code
    $botsay = eval_aiml_to_php_code($convoArr, $parsed_template);
    //if it works it works if not display error message
    //write the result (what the bot said) to the convoArr
    $convoArr['aiml']['parsed_template'] = $botsay . " ";
    runDebug(__FILE__, __FUNCTION__, __LINE__, "The bot will say: {$botsay}", 2);
    return $convoArr;
}
/**
 * function get_xml()
 * This function formats the response as xml
 * @param  array $convoArr - the conversation array
 * @param  array $conversation - the conversation lines to format
 * @return array $convoArr
**/
function get_xml($convoArr, $conversation)
{
    $user_name = $convoArr['conversation']['user_name'];
    $user_id = $convoArr['conversation']['user_id'];
    $bot_name = $convoArr['conversation']['bot_name'];
    $conversation_lines = $convoArr['conversation']['conversation_lines'];
    $convo_xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n  <conversation convo_id=\"" . $convoArr['conversation']['convo_id'] . "\">\n";
    $convo_xml .= "    <bot_name>{$bot_name}</bot_name>\n";
    $convo_xml .= "    <user_name>{$user_name}</user_name>\n";
    $convo_xml .= "    <user_id value='{$user_id}' />\n";
    /*
    	$convo_xml .= "    <chat>\n";
    */
    foreach ($conversation as $index => $conversation_subarray) {
        $convo_xml .= "      <usersay>" . stripslashes($conversation_subarray['input']) . "</usersay>\n      <botsay>" . stripslashes($conversation_subarray['response']) . "</botsay>\n";
    }
    $convo_xml .= "  </conversation>\n";
    #$convo_xml .= "    </chat>\n  </conversation>\n";
    $convoArr['send_to_user'] = $convo_xml;
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Returning XML", 4);
    return $convoArr;
}
Exemple #24
0
/**
 * function run_aiml_to_php()
 * @param  array $convoArr - the current state of the conversation array
 * @param  string $evalthis - string to make safe
 * @return string $result (-botsay)
**/
function run_aiml_to_php($convoArr, $evalthis)
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Evaluating Stored PHP Code from the Database", 4);
    global $botsay;
    global $error_response;
    //this must be NULL if it is FALSE then its failed but  if its NULL its a success
    $error_flag = eval($evalthis);
    if ($error_flag === NULL) {
        //success
        runDebug(__FILE__, __FUNCTION__, __LINE__, "EVALUATED: {$evalthis} ", 4);
        $result = $botsay;
    } else {
        //error
        runDebug(__FILE__, __FUNCTION__, __LINE__, "ERROR TRYING TO EVAL: {$evalthis} ", 1);
        runDebug(__FILE__, __FUNCTION__, __LINE__, "ERROR TRYING TO EVAL: " . print_r($convoArr['aiml'], true), 1);
        $result = $error_response;
    }
    return $result;
}
Exemple #25
0
* www.program-o.com
* PROGRAM O 
* Version: 2.4.8
* FILE: chatbot/addons/load_addons.php
* AUTHOR: Elizabeth Perreau and Dave Morton
* DATE: MAY 17TH 2014
* DETAILS: this file contains the calls to include addon functions
***************************************/
//load the word censor functions
include "custom_tags/custom_tags.php";
include "word_censor/word_censor.php";
include 'spell_checker/spell_checker.php';
include "parseBBCode/parseBBCode.php";
// A new addon to allow parsing of output that's consistent with BBCode tags
//include("checkForBan/checkForBan.php"); // A new addon for verifying that a user has not been banned by IP address
runDebug(__FILE__, __FUNCTION__, __LINE__, "Loading addons", 4);
/**
 * Function run_pre_input_addons
 *
 * * @param $convoArr
 * @param $say
 * @return string
 */
function run_pre_input_addons(&$convoArr, $say)
{
    global $format;
    $say = USE_SPELL_CHECKER ? run_spell_checker_say($say) : $say;
    //$convoArr = checkIP($convoArr);
    #if ($format == 'html') $say =  parseInput($say);
    return $say;
}
Exemple #26
0
/**
 * Function parse_wiki_tag
 *
 * * @param $convoArr
 * @param $element
 * @param $parentName
 * @param $level
 * @return string
 */
function parse_wiki_tag($convoArr, $element, $parentName, $level)
{
    global $debugemail;
    runDebug(__FILE__, __FUNCTION__, __LINE__, 'Parsing custom WIKI tag.', 2);
    $response = array();
    $children = $element->children();
    if (!empty($children)) {
        $response = parseTemplateRecursive($convoArr, $children, $level + 1);
    } else {
        $response[] = (string) $element;
    }
    $response_string = implode_recursive(' ', $response);
    // do something here
    $wikiURL = 'http://en.wikipedia.org/w/api.php?action=opensearch&format=xml&limit=1&search=' . urlencode($response_string);
    $options = array(CURLOPT_HTTPGET => TRUE, CURLOPT_POST => FALSE, CURLOPT_HEADER => false, CURLOPT_NOBODY => FALSE, CURLOPT_VERBOSE => FALSE, CURLOPT_REFERER => "", CURLOPT_USERAGENT => "Program O version " . VERSION . " - Please contact {$debugemail} regarding any queries or complaints.", CURLOPT_SSL_VERIFYPEER => FALSE, CURLOPT_FOLLOWLOCATION => TRUE, CURLOPT_MAXREDIRS => 4);
    $wikiText = get_cURL($wikiURL, $options);
    #save_file(_DEBUG_PATH_ . 'wiki_return.txt', $wikiText);
    $xml = simplexml_load_string($wikiText, 'SimpleXMLElement', LIBXML_NOCDATA);
    if ((string) $xml->Section->Item->Description) {
        $description = (string) $xml->Section->Item->Description;
        $image = (string) $xml->Section->Item->Image->asXML();
        $image = str_replace('<Image source', '<img src', $image);
        $linkHref = (string) $xml->Section->Item->Url;
        $linkText = (string) $xml->Section->Item->Text;
        $link = "<a href=\"{$linkHref}\" target=\"_blank\">{$linkText}</a>";
        $output = "{$link}<br/>\n{$image}<br/>\n{$description}";
    } else {
        $output = 'Wikipedia returned no results!';
    }
    //$output = '<![CDATA[' . $output . ']]>'; // Uncomment this line when using the XHTML doctype
    return $output;
}
/** reduceConvoArr()
 *  A small function to create a smaller convoArr just for debuggin!
 *
 * @param array $convoArr - the big array to be reduced
 * @return array
 */
function reduceConvoArr($convoArr)
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, 'Reducing the conversation array.', 0);
    $showConvoArr = array();
    $showConvoArr['conversation'] = isset($convoArr['conversation']) ? $convoArr['conversation'] : '';
    $showConvoArr['aiml'] = isset($convoArr['aiml']) ? $convoArr['aiml'] : '';
    $showConvoArr['topic'][1] = isset($convoArr['topic'][1]) ? $convoArr['topic'][1] : '';
    $showConvoArr['that'][1] = isset($convoArr['that'][1]) ? $convoArr['that'][1] : '';
    if (isset($convoArr['star'])) {
        foreach ($convoArr['star'] as $index => $star) {
            if (!empty($star)) {
                $showConvoArr['star'][$index] = $star;
            }
        }
    }
    $showConvoArr['input'][1] = isset($convoArr['input'][1]) ? $convoArr['input'][1] : '';
    $showConvoArr['stack']['top'] = isset($convoArr['stack']['top']) ? $convoArr['stack']['top'] : '';
    $showConvoArr['stack']['last'] = isset($convoArr['stack']['last']) ? $convoArr['stack']['last'] : '';
    $showConvoArr['client_properties'] = isset($convoArr['client_properties']) ? $convoArr['client_properties'] : '';
    $showConvoArr['aiml']['user_raw'] = isset($convoArr['aiml']['user_raw']) ? $convoArr['aiml']['user_raw'] : '';
    $showConvoArr['aiml']['lookingfor'] = isset($convoArr['aiml']['lookingfor']) ? $convoArr['aiml']['lookingfor'] : '';
    $showConvoArr['aiml']['pattern'] = isset($convoArr['aiml']['pattern']) ? $convoArr['aiml']['pattern'] : '';
    $showConvoArr['aiml']['thatpattern'] = isset($convoArr['aiml']['thatpattern']) ? $convoArr['aiml']['thatpattern'] : '';
    $showConvoArr['aiml']['topic'] = isset($convoArr['aiml']['topic']) ? $convoArr['aiml']['topic'] : '';
    $showConvoArr['aiml']['score'] = isset($convoArr['aiml']['score']) ? $convoArr['aiml']['score'] : '';
    $showConvoArr['aiml']['aiml_id'] = isset($convoArr['aiml']['aiml_id']) ? $convoArr['aiml']['aiml_id'] : '';
    $showConvoArr['aiml']['parsed_template'] = isset($convoArr['aiml']['parsed_template']) ? $convoArr['aiml']['parsed_template'] : '';
    $showConvoArr['user_say'][1] = isset($convoArr['aiml']['parsed_template']) ? $convoArr['user_say'][1] : '';
    $showConvoArr['that_raw'][1] = isset($convoArr['that_raw'][1]) ? $convoArr['that_raw'][1] : '';
    $showConvoArr['parsed_template'][1] = isset($convoArr['parsed_template'][1]) ? $convoArr['parsed_template'][1] : '';
    return $showConvoArr;
}
/**
 * function load_spelling_list
 * Gets all missspelled words and their corrections from the DB, loading them into a session variable.
 *
 * @internal param $ (none)
 * @return void (void)
 */
function load_spelling_list()
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, 'Loading the spellcheck list from the DB.', 2);
    global $dbConn, $dbn;
    $_SESSION['spellcheck'] = array();
    $sql = "SELECT `missspelling`, `correction` FROM `{$dbn}`.`spellcheck`;";
    $sth = $dbConn->prepare($sql);
    $sth->execute();
    $result = $sth->fetchAll();
    $num_rows = count($result);
    if ($num_rows > 0) {
        foreach ($result as $row) {
            $missspelling = IS_MB_ENABLED ? mb_strtolower($row['missspelling']) : strtolower($row['missspelling']);
            $correction = $row['correction'];
            $_SESSION['spellcheck'][$missspelling] = $correction;
        }
    }
}
Exemple #29
0
/**
 * function intisaliseUser()
 * This function gets data such as the referer to store in the db
 *
 * @param $convoArr
 * @internal param string $convo_id - user session
 * @return int $user_id - the newly created user id
 */
function intisaliseUser($convoArr)
{
    runDebug(__FILE__, __FUNCTION__, __LINE__, 'Initializing user.', 2);
    //db globals
    global $dbConn, $dbn, $bot_id, $unknown_user;
    $convo_id = $convoArr['conversation']['convo_id'];
    $sr = "";
    $sa = "";
    $sb = "unknown browser";
    if (isset($_SERVER['REMOTE_ADDR'])) {
        $sa = $_SERVER['REMOTE_ADDR'];
    }
    if (isset($_SERVER['HTTP_REFERER'])) {
        $sr = $_SERVER['HTTP_REFERER'];
    }
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $sb = $_SERVER['HTTP_USER_AGENT'];
    }
    $sql = "INSERT INTO `{$dbn}`.`users` (`id`, `user_name`, `session_id`, `bot_id`, `chatlines` ,`ip` ,`referer` ,`browser` ,`date_logged_on` ,`last_update`, `state`)\n  VALUES ( NULL , '{$unknown_user}', '{$convo_id}', {$bot_id}, '0', '{$sa}', '{$sr}', '{$sb}', CURRENT_TIMESTAMP , CURRENT_TIMESTAMP, '')";
    $sth = $dbConn->prepare($sql);
    $sth->execute();
    $user_id = $dbConn->lastInsertId();
    $convoArr['conversation']['user_id'] = $user_id;
    $convoArr['conversation']['totallines'] = 0;
    runDebug(__FILE__, __FUNCTION__, __LINE__, "intisaliseUser #{$user_id} SQL: {$sql}", 3);
    //add the username to the client properties....
    $sql = "INSERT INTO `{$dbn}`.`client_properties` (`id`,`user_id`,`bot_id`,`name`,`value`)\n  VALUES ( NULL , '{$user_id}', {$bot_id}, 'name', '{$unknown_user}')";
    $sth = $dbConn->prepare($sql);
    $sth->execute();
    return $convoArr;
}
    $convoArr = add_new_conversation_vars($say, $convoArr);
    //parse the aiml
    $convoArr = make_conversation($convoArr);
    $convoArr = log_conversation($convoArr);
    $convoArr = log_conversation_state($convoArr);
    $convoArr = write_to_session($convoArr);
    $convoArr = get_conversation($convoArr);
    $convoArr = run_post_response_useraddons($convoArr);
    //return the values to display
    $display = $convoArr['send_to_user'];
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Conversation Ending", 4);
    $convoArr = handleDebug($convoArr);
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Returning " . $convoArr['conversation']['format'], 4);
    if ($convoArr['conversation']['format'] == "html") {
        //TODO what if it is ajax call
        $time_start = $convoArr['time_start'];
        $time_end = microtime(true);
        $time = $time_end - $time_start;
        runDebug(__FILE__, __FUNCTION__, __LINE__, "Script took {$time} seconds", 2);
        return $convoArr['send_to_user'];
    } else {
        echo $convoArr['send_to_user'];
    }
} else {
    runDebug(__FILE__, __FUNCTION__, __LINE__, "Conversation intialised waiting user", 2);
}
runDebug(__FILE__, __FUNCTION__, __LINE__, "Closing Database", 2);
$time_end = microtime(true);
$time = $time_end - $time_start;
runDebug(__FILE__, __FUNCTION__, __LINE__, "Script took {$time} seconds", 2);