protected function beforeCreate() { $this->setSid($_SESSION['admin_sid']); $this->setTs(NOW); $this->setIpLong(IP_LONG); $this->setAgent(USER_AGENT); $this->setRequestUri(SELF); $this->setReferer(REF); $this->setReferer(REF); $this->setUserId(USER_ID); $this->setP(P); $this->setDo(P_DO); $this->setPost($_POST ? sql_prepare(serialize($_POST)) : ''); }
public function get_user_options($user_id) { if (!$user_id) { throw new UnexpectedValueException(); } $out = array(); $res = sql_query("SELECT option_id id, option_value value FROM user_options_values WHERE user_id={$user_id}"); while ($r = sql_fetch_array($res)) { $out[$r['id']] = $r['value']; } //autovivify absent options sql_begin(); $ins = sql_prepare("INSERT INTO user_options_values VALUES(?, ?, ?)"); foreach ($this->options as $opt) { if (!in_array($opt->id, array_keys($out))) { $out[$opt->id] = $opt->default_value; sql_execute($ins, array($user_id, $opt->id, $opt->default_value)); } } sql_commit(); return $out; }
function get_ambiguity_stats_for_chart() { $chart = array(); $t = array(); $tchart = array(); $time = time(); $param_set = array(5, 35, 36, 37, 41, 45, 62, 64); $res = sql_prepare("SELECT timestamp, param_value FROM stats_values WHERE timestamp > ? AND param_id = ? ORDER BY timestamp"); foreach ($param_set as $param_id) { sql_execute($res, array($time - 90 * SEC_PER_DAY, $param_id)); while ($r = sql_fetch_array($res)) { $day = intval($r['timestamp'] / SEC_PER_DAY); $t[$day][$param_id] = $r['param_value']; } } ksort($t); foreach ($t as $day => $ar) { $tchart['disamb_sentences'][] = '[' . $day * MSEC_PER_DAY . ',' . $ar[41] . ']'; $tchart['disamb_sentences_strict'][] = '[' . $day * MSEC_PER_DAY . ',' . $ar[62] . ']'; if ($ar[45]) { $tchart['disamb_sent_length'][] = '[' . $day * MSEC_PER_DAY . ',' . sprintf("%.3f", $ar[45] / $ar[41]) . ']'; } if ($ar[64]) { $tchart['disamb_sent_strict_length'][] = '[' . $day * MSEC_PER_DAY . ',' . sprintf("%.3f", $ar[64] / $ar[62]) . ']'; } if ($ar[35] == 0) { continue; } $tchart['avg_parses'][] = '[' . $day * MSEC_PER_DAY . ',' . sprintf("%.3f", $ar[35] / $ar[5]) . ']'; $tchart['non_ambig'][] = '[' . $day * MSEC_PER_DAY . ',' . sprintf("%.3f", $ar[37] / $ar[5] * 100) . ']'; $tchart['unknown'][] = '[' . $day * MSEC_PER_DAY . ',' . sprintf("%.3f", $ar[36] / $ar[5] * 100) . ']'; $tchart['total_words'][] = '[' . $day * MSEC_PER_DAY . ',' . $ar[5] . ']'; } foreach ($tchart as $name => $ar) { $chart[$name] = join(',', $ar); } return $chart; }
function get_context_for_word($tf_id, $delta, $dir = 0, $include_self = 1) { // dir stands for direction (-1 => left, 1 => right, 0 => both) // delta <= 0 stands for infinity $t = array(); $tw = 0; $left_c = -1; //if there is left context to be added $right_c = 0; //same for right context $mw_pos = 0; static $query1 = NULL; // prepare the 1st query if ($query1 == NULL) { $query1 = sql_prepare("\n SELECT MAX(tokens.pos) AS maxpos, MIN(tokens.pos) AS minpos, sent_id, source, book_id\n FROM tokens\n JOIN sentences USING (sent_id)\n JOIN paragraphs USING (par_id)\n WHERE sent_id = (\n SELECT sent_id\n FROM tokens\n WHERE tf_id=? LIMIT 1\n )\n "); } sql_execute($query1, array($tf_id)); $res = sql_fetchall($query1); $r = $res[0]; $sent_id = $r['sent_id']; $sentence_text = $r['source']; $book_id = $r['book_id']; $maxpos = $r['maxpos']; $minpos = $r['minpos']; // prepare the 2nd query // this is really bad unreadable code, sorry static $query2 = NULL; if ($query2 == NULL) { $q = "SELECT tf_id, tf_text, pos FROM tokens WHERE sent_id = ?"; if ($dir != 0 || $delta > 0) { $q_left = $dir <= 0 ? $delta > 0 ? "(SELECT IF(pos > {$delta}, pos - {$delta}, 0) FROM tokens WHERE tf_id=? LIMIT 1)" : "0" : "(SELECT pos FROM tokens WHERE tf_id=? LIMIT 1)"; $q_right = $dir >= 0 ? $delta > 0 ? "(SELECT pos+{$delta} FROM tokens WHERE tf_id=? LIMIT 1)" : "1000" : "(SELECT pos FROM tokens WHERE tf_id=? LIMIT 1)"; $q .= " AND pos BETWEEN {$q_left} AND {$q_right}"; } $q .= " ORDER BY pos"; $query2 = sql_prepare($q); } // how many values should we provide? $bound = array($tf_id, $tf_id); if ($delta <= 0) { if ($dir == 0) { $bound = array(); } else { $bound = array($tf_id); } } sql_execute($query2, array_merge(array($sent_id), $bound)); foreach (sql_fetchall($query2) as $r) { if ($delta > 0) { if ($left_c == -1) { $left_c = $r['pos'] == $minpos ? 0 : $r['tf_id']; } if ($mw_pos) { if ($r['pos'] > $mw_pos) { $right_c = $r['tf_id']; } if ($right_c && $r['pos'] == $maxpos) { $right_c = 0; } } } if ($include_self || $r['tf_id'] != $tf_id) { $t[$r['tf_id']] = $r['tf_text']; } if ($include_self && $r['tf_id'] == $tf_id) { $mw_pos = $r['pos']; } } return array('context' => $t, 'mainword' => $tf_id, 'has_left_context' => $left_c, 'has_right_context' => $right_c, 'sentence_id' => $sent_id, 'sentence_text' => $sentence_text, 'book_id' => $book_id); }
function get_unknowns() { $res = sql_query("\n SELECT tf_id, tf_text, sent_id, ut.dict_revision\n FROM tokens t\n LEFT JOIN form2lemma f\n ON (t.tf_text = f.form_text)\n LEFT JOIN tf_revisions\n USING (tf_id)\n LEFT JOIN updated_tokens ut\n ON (t.tf_id = ut.token_id)\n WHERE is_last = 1\n AND rev_text LIKE '%UNKN%'\n AND f.lemma_id IS NOT NULL\n GROUP BY tf_id\n ORDER BY tf_id\n "); $res1 = sql_prepare("\n SELECT text, user_shown_name\n FROM morph_annot_comments\n LEFT JOIN morph_annot_samples\n USING (sample_id)\n LEFT JOIN users\n USING (user_id)\n WHERE tf_id = ?\n "); $out = array(); while ($r = sql_fetch_array($res)) { sql_execute($res1, array($r['tf_id'])); $comments = array(); while ($r1 = sql_fetch_array($res1)) { $comments[] = array('text' => $r1['text'], 'author' => $r1['user_shown_name']); } $out[] = array('sent_id' => $r['sent_id'], 'text' => $r['tf_text'], 'is_pending' => (bool) $r['dict_revision'], 'comments' => $comments); } return $out; }
<?php use TMCms\DB\SQL; use TMCms\Log\Errors; if (!defined('INC')) { define('INC', true); } if (!defined('MODE')) { define('MODE', 'site'); } if (stripos(USER_AGENT, 'bot') !== false) { return; } $msg = isset($_GET['msg']) ? $_GET['msg'] : ''; $stack = isset($_GET['stack']) ? $_GET['stack'] : ''; $url = isset($_GET['url']) ? $_GET['url'] : ''; $line = isset($_GET['line']) ? $_GET['line'] : ''; Errors::notify_devs(CFG_DOMAIN . ' JavaScript error', 'Message: ' . $msg . "\nClicks Stack: " . $stack . "\nURL: " . $url . "\nLine: " . $line); // Write log if DB available if (!SQL::getInstance()->getConnectionHandler()) { return; } q('INSERT INTO `cms_error_log` ( `ts`, `ip_long`, `agent`, `type`, `msg`, `file`, `line`, `vars` ) VALUES ( "' . NOW . '", "' . ip2long(IP) . '", "' . USER_AGENT . '", "JS", "' . sql_prepare($msg) . '", "' . sql_prepare($url) . '", "' . sql_prepare($line) . '", "' . sql_prepare($stack) . '" )');
<?php /** * Load CSV data (defined in datapackage.jsob) to the SQL database. * php src/php/prepare.php */ include 'packLoad.php'; // must be CONFIGURED for your database // // // // // // // // // // // CONFIGS: (complement to omLib) $basePath = realpath(__DIR__ . '/../..'); $reini = true; // re-init all SQL structures of the project (drop and refresh schema) $sqlMode = '1'; // // // // // // SQL PREPARE $sqlIni = ["::src/sql_mode{$sqlMode}/step1_libDefs.sql", "::src/sql_mode{$sqlMode}/step2_struct.sql", "::src/sql_mode{$sqlMode}/step3_lib.sql", "SELECT tStore.ns_upsert('test','pt','Test. Portuguese.')", "SELECT tStore.ns_upsert('wayta-pt','pt','Wayta SciELO reference-dataset, Portuguese.',true, '{\"group_unique\":false}'::jsonb)", "SELECT tStore.ns_upsert('wayta-code',' ','Wayta SciELO reference-dataset, no-lang')", "SELECT tStore.ns_upsert('wayta-en','en','Wayta SciELO reference-dataset, English.')", "SELECT tStore.ns_upsert('wayta-es','es','Wayta SciELO reference-dataset, Spanish.')", "UPDATE tStore.ns SET fk_partOf=tlib.nsget_nsid('wayta-pt') WHERE label!='wayta-pt' AND left(label,5)='wayta'", "SELECT tStore.ns_upsert('country-code', ' ', 'Country names reference-dataset, no-lang.', true, '{\"group_unique\":false}'::jsonb)", "SELECT tStore.ns_upsert('country-pt','pt','Country names reference-dataset, Portuguese.')", "SELECT tStore.ns_upsert('country-fr','fr','Country names reference-dataset, French.')", "SELECT tStore.ns_upsert('country-es','es','Country names reference-dataset, Spanish.')", "SELECT tStore.ns_upsert('country-en','en','Country names reference-dataset, English.')", "SELECT tStore.ns_upsert('country-de','de','Country names reference-dataset, Deutsch.')", "SELECT tStore.ns_upsert('country-it','it','Country names reference-dataset, Italian.')", "SELECT tStore.ns_upsert('country-nl','nl','Country names reference-dataset, Dutch.')", "UPDATE tStore.ns SET fk_partOf=tlib.nsget_nsid('country-code') WHERE label!='country-code' AND left(label,7)='country'", "INSERT INTO tstore.source (name,jinfo) VALUES\n\t\t('normalized_aff', tstore.source_add1('Scielo','Wayta institution','https://github.com/scieloorg/wayta/blob/master/processing/normalized_aff.csv') )\n\t\t,('normalized_country', tstore.source_add1('Scielo','Wayta country','https://github.com/scieloorg/wayta/blob/master/processing/normalized_country.csv') )\n\t\t,('country-names-multilang', tstore.source_add1('Unicode','UNICODE CLDR, core, territory','http://www.unicode.org/Public/cldr') )\n\t\t,('country-codes', tstore.source_add1('OKFN','Data Packaged Core Datasets, ISO and other Country Codes','https://raw.github.com/datasets/country-codes/master/data/country-codes.csv') )\n\t\t,('iso3166-1-alpha-2', tstore.source_add1('ISO','ISO-3166-1, Country Codes, Alpha-2','') )\n\t\t,('iso3166-1-alpha-3', tstore.source_add1('ISO','ISO-3166-1, Country Codes, Alpha-3','') )\n\t"]; // // // // // // MAKING DATA: sql_prepare($sqlIni, "SQL SCHEMAS with MODE{$sqlMode}", $basePath, $reini); if (!$reini) { sql_prepare("DELETE FROM tstore.term; DELETE FROM tstore.ns;", "DELETING MAIN TABLES"); } resourceLoad_run($basePath, ['test' => [['prepare_auto', "tlib.tmp_test"]], 'normalized_aff' => [['prepare_jsonb', "tlib.tmp_waytaff"]], 'normalized_country' => [['prepare_jsonb', "tlib.tmp_waytacountry"]], 'country-codes' => [['prepare_jsonb', "tlib.tmp_codes"]], 'country-names-multilang' => [['prepare_jsonb', "tlib.tmp_codes2"]]], "(MODE{$sqlMode})"); sql_prepare(["SELECT tStore.upsert(term, tlib.nsget_nsid('test')) FROM tlib.tmp_test;", "DROP TABLE tlib.tmp_test;", "::src/sql_mode{$sqlMode}/nsCountry_build.sql", "DROP TABLE tlib.tmp_waytacountry; DROP TABLE tlib.tmp_codes; DROP TABLE tlib.tmp_codes2;", "::src/sql_mode{$sqlMode}/nsWayta_build.sql", "DROP TABLE tlib.tmp_waytaff;", "::assert_bysql:data/assert1_mode{$sqlMode}.tsv"], "SQL FINALIZATION", $basePath);
die; } $save_ext = $params; break; case 'watermark': if (!$params) { break; } $check_size_allowed($params); if (!preg_match('/^[0-9]+$/', $params)) { if (!Settings::isProductionState()) { exit('Error processing params for action "watermark". Example: 1 or main'); } die; } $data = q_assoc_row('SELECT `image`, `image_pos` FROM `cms_img_proc_perms` WHERE `rule` = "&watermark=' . sql_prepare($params) . '" LIMIT 1'); if (!$data || !$data['image'] || !$data['image_pos']) { if (!Settings::isProductionState()) { exit('Error. Incorrect parameters for action "watermark"'); } die; } $image->watermark($data['image'], $data['image_pos']); break; } } FileSystem::mkdir(DIR_CACHE . 'images/' . $path); if (!$image->save(DIR_CACHE . 'images/' . QUERY, $ext, 90) && !Settings::isProductionState()) { dump('Not enough memory to resize and sharpen image "' . $path . $file . '".'); } unset($image);
/** * Set migration .sql file as already finished * @param string $filename * @return $this */ private function setMigrationFileAsCompleted($filename) { $migration = new MigrationEntity(); $migration->setFilename(sql_prepare($filename)); @$migration->save(); return $this; }
function find_ne_entity($annot_id, $e_id, $e_start_token, $e_length) { static $res = NULL; if ($res == NULL) { $res = sql_prepare("\n SELECT entity_id\n FROM ne_entities\n WHERE annot_id = ?\n AND start_token = ?\n AND length = ?\n "); } sql_execute($res, array($annot_id, $e_start_token, $e_length)); $rows = sql_fetchall($res); if (sizeof($rows) == 0) { return false; } // check tags $found_id = $rows[0]['entity_id']; $tags1 = get_ne_entity_tags($e_id, true); $tags2 = get_ne_entity_tags($found_id, true); if ($tags1 == $tags2) { return $found_id; } return false; }
function enqueue_updated_forms($forms, $revision_id) { $ins = sql_prepare("INSERT INTO `updated_forms` VALUES (?, ?)"); foreach (array_unique($forms) as $upd_form) { sql_execute($ins, array($upd_form, $revision_id)); } }
function addtext_add($text, $sentences, $book_id, $par_num) { check_permission(PERM_ADDER); if (!$text || !$book_id || !$par_num) { throw new UnexpectedValueException(); } if (sizeof(sql_pe("SELECT book_id FROM books WHERE parent_id=?", array($book_id))) > 0) { throw new UnexpectedValueException("Can't add paragraphs to a text having subtexts"); } sql_begin(); $revset_id = create_revset(); $sent_count = 0; $pars = split2paragraphs($text); // move the following paragraphs sql_query("UPDATE paragraphs SET pos=pos+" . sizeof($pars) . " WHERE book_id = {$book_id} AND pos >= {$par_num}"); $par_ins = sql_prepare("INSERT INTO `paragraphs` VALUES(NULL, ?, ?)"); $sent_ins = sql_prepare("INSERT INTO `sentences` VALUES(NULL, ?, ?, ?, 0)"); $token_ins = sql_prepare("INSERT INTO `tokens` VALUES(NULL, ?, ?, ?)"); foreach ($pars as $par) { //adding a paragraph sql_execute($par_ins, array($book_id, $par_num++)); $par_id = sql_insert_id(); $sent_num = 1; $sents = split2sentences($par); foreach ($sents as $sent) { if (!preg_match('/\\S/', $sent)) { continue; } //adding a sentence sql_execute($sent_ins, array($par_id, $sent_num++, trim($sent))); $sent_id = sql_insert_id(); sql_query("INSERT INTO sentence_authors VALUES({$sent_id}, " . $_SESSION['user_id'] . ", " . time() . ")"); $token_num = 1; $tokens = explode('^^', $sentences[$sent_count++]); foreach ($tokens as $token) { if (trim($token) === '') { continue; } //adding a textform sql_execute($token_ins, array($sent_id, $token_num++, trim($token))); $tf_id = sql_insert_id(); //adding a revision $parse = new MorphParseSet(false, trim($token)); create_tf_revision($revset_id, $tf_id, $parse->to_xml()); } } } sql_commit(); }
/** * @return string */ public function execute() { $results = []; preg_match_all('/\\%(' . implode('|', self::$replacements) . ')/', $this->sql, $results); $results = $results[1]; foreach ($this->params as $k => &$v) { if (!isset($results[$k])) { trigger_error('Incorrect parameter count'); } switch ($results[$k]) { case 's': case 'string': $v = '"' . sql_prepare($v) . '"'; break; case 'i': case 'int': $v = (int) $v; break; case 'ui': case 'uint': $v = abs((int) $v); break; case 'f': case 'float': $v = (double) $v; break; case 'l': case 'like': $v = '"' . sql_prepare($v) . '"'; break; case 'ai': case 'arrayint': foreach ($v as &$unit) { $unit = (int) $unit; } $v = implode(',', $v); unset($unit); break; case 'aui': case 'arrayuint': dump($v); if (!is_array($v)) { trigger_error('Parameter "' . ($k + 1) . '" must be an array becouse query contains "%' . $results[$k] . '".'); } foreach ($v as &$unit) { $unit = abs((int) $unit); } $v = implode(',', $v); unset($unit); break; case 'as': case 'arraystring': if (!is_array($v)) { trigger_error('Parameter "' . ($k + 1) . '" must be an array becouse query contains "%' . $results[$k] . '".'); } foreach ($v as &$unit) { $unit = '"' . sql_prepare($unit) . '"'; } $v = implode(',', $v); unset($unit); break; case 'af': case 'arrayfloat': if (!is_array($v)) { trigger_error('Parameter "' . ($k + 1) . '" must be an array becouse query contains "%' . $results[$k] . '".'); } foreach ($v as &$unit) { $unit = (double) $unit; } $v = implode(',', $v); unset($unit); break; case 'auf': case 'arrayufloat': if (!is_array($v)) { trigger_error('Parameter "' . ($k + 1) . '" must be an array becouse query contains "%' . $results[$k] . '".'); } foreach ($v as &$unit) { $unit = abs((double) $unit); } $v = implode(',', $v); unset($unit); break; default: trigger_error('Unknown Parameter'); } } unset($v); $tmp = []; foreach (self::$replacements as $v) { $tmp[] = '%' . $v; } return vsprintf(str_replace($tmp, '%s', $this->sql), $this->params); }
<?php use TMCms\Templates\VisualEdit; VisualEdit::getInstance()->init(); if (!VisualEdit::getInstance()->isEnabled()) { return; } if (!isset($_POST['content'], $_POST['component'], $_POST['page_id'])) { return; } q('UPDATE `cms_pages_components` SET `data` = "' . sql_prepare($_POST['content']) . '" WHERE `page_id` = "' . (int) $_POST['page_id'] . '" AND `component` = "' . sql_prepare($_POST['component']) . '" '); echo json_encode(['status' => true]);
/** * Basic webservice interface. */ include 'packLoad.php'; // must be CONFIGURED for your database //$db = new pdo($dsn,$PG_USER,$PG_PW); $basePath = '/var/www/xconv.local/xconv3/_relats'; //realpath(__DIR__ .'/../..'); $reini = true; // re-init all SQL structures of the project (drop and refresh schema) $sqlMode = '1'; $packs = ['packs' => ['aff2' => ['file' => "{$basePath}/data/aff2-2016-01-21.csv", 'sep' => ',']]]; $sqlIni = ["::assert_bysql:data/assert1_mode{$sqlMode}.tsv"]; sql_prepare($sqlIni, "teste de ASSERT", "/home/peter/gits/sql-term"); die("\nOK3232\n"); sql_prepare("\n CREATE TABLE IF NOT EXISTS tmp_aff2 (\n lang text,\n artigo_id int,\n p_aff xml\n );\n "); resourceLoad_run($basePath, ['aff2' => [['prepared_copy', "tmp_aff2"]]], "AFF2 test kit", $packs); // carregar asserts automaticamente, incluir "SELEC onde nao começar por SELECT ou WITH " # see table tstore.assert /* CREATE FUNCTION array_last( -- -- Returns the element of array_upper() -- anyarray, int DEFAULT 0 ) RETURNS anyelement AS $f$ SELECT $1[array_upper($1,1)-$2]; $f$ LANGUAGE SQL IMMUTABLE;
/** * Filter collection by value exclusive * @param $field * @param string $like_value * @param bool $left_any * @param bool $right_any * @param string $table * @return $this */ public function addWhereFieldIsNotLike($field, $like_value, $left_any = true, $right_any = true, $table = '') { if (!$table) { $table = $this->getDbTableName(); } $this->addWhereFieldAsString('`' . $table . '`.`' . $field . '` NOT LIKE "' . ($left_any ? '%' : '') . sql_prepare($like_value, true) . ($right_any ? '%' : '') . '"'); return $this; }
function merge_sentences($id1, $id2) { check_permission(PERM_ADDER); if ($id1 < 1 || $id2 < 1) { throw new UnexpectedValueException(); } // check same paragraph and adjacency $res = sql_pe("SELECT pos, par_id FROM sentences WHERE sent_id IN (?, ?) ORDER BY pos LIMIT 2", array($id1, $id2)); $r1 = $res[0]; $r2 = $res[1]; $res = sql_query("SELECT pos FROM sentences WHERE par_id = " . $r1['par_id'] . " AND pos > " . $r1['pos'] . " AND pos < " . $r2['pos'] . " LIMIT 1"); if ($r1['par_id'] != $r2['par_id'] || sql_num_rows($res) > 0) { throw new Exception(); } //moving tokens sql_begin(); $res = sql_pe("SELECT MAX(pos) AS maxpos FROM tokens WHERE sent_id=?", array($id1)); sql_pe("UPDATE tokens SET sent_id=?, pos=pos+? WHERE sent_id=?", array($id1, $res[0]['maxpos'], $id2)); //merging source text $res_src = sql_prepare("SELECT `source` FROM sentences WHERE sent_id=? LIMIT 1"); sql_execute($res_src, array($id1)); $r1 = sql_fetchall($res_src); sql_execute($res_src, array($id2)); $r2 = sql_fetchall($res_src); sql_pe("UPDATE sentences SET source=? WHERE sent_id=? LIMIT 1", array($r1[0]['source'] . ' ' . $r2[0]['source'], $id1)); //dropping status, moving comments sql_pe("UPDATE sentences SET check_status=0 WHERE sent_id=? LIMIT 1", array($id1)); sql_pe("UPDATE sentence_comments SET sent_id=? WHERE sent_id=?", array($id1, $id2)); sql_pe("DELETE FROM sentence_check WHERE sent_id=? OR sent_id=?", array($id1, $id2)); // change syntax markup accordingly sql_pe("UPDATE syntax_parses SET sent_id = ? WHERE sent_id = ?", array($id1, $id2)); //deleting sentence sql_pe("DELETE FROM sentence_authors WHERE sent_id=? LIMIT 1", array($id2)); sql_pe("DELETE FROM sentences WHERE sent_id=? LIMIT 1", array($id2)); sql_commit(); }
function sql_pe($query, $params) { // prepares and executes query, closes cursor // returns all the rows $res = sql_prepare($query); sql_execute($res, $params); try { return sql_fetchall($res); } catch (PDOException $e) { return array(); } }
function update_annot_instance($id, $answer, $user_id = 0) { if (!$user_id) { $user_id = $_SESSION['user_id']; } if (!$id || !$answer || !$user_id) { throw new UnexpectedValueException(); } global $config; static $res = NULL; if ($res == NULL) { $res = sql_prepare("\n SELECT pool_id, p.status, i.user_id, answer\n FROM morph_annot_instances i\n LEFT JOIN morph_annot_samples\n USING (sample_id)\n LEFT JOIN morph_annot_pools p\n USING (pool_id)\n WHERE instance_id = ?\n LIMIT 1\n "); } sql_execute($res, array($id)); $inst = sql_fetchall($res); if (!sizeof($inst)) { throw new Exception("Instance not found"); } $r = $inst[0]; // the pool should be editable if ($r['status'] != MA_POOLS_STATUS_IN_PROGRESS) { throw new Exception("Пул недоступен для разметки"); } $pool_id = $r['pool_id']; sql_begin(); static $res_rejected = NULL; // does the instance really belong to this user? $previous_answer = $r['answer'] > 0; if ($r['user_id'] != $user_id) { // if another user has taken it, no chance if ($r['user_id'] > 0) { throw new Exception(); } // or, perhaps, this user has rejected it before but has changed his mind if ($res_rejected == NULL) { $res_rejected = sql_prepare("SELECT sample_id FROM morph_annot_rejected_samples WHERE user_id=? AND sample_id = (SELECT sample_id FROM morph_annot_instances WHERE instance_id=? LIMIT 1) LIMIT 1"); } sql_execute($res_rejected, array($user_id, $id)); if (sql_num_rows($res_rejected) > 0) { $r = sql_fetch_array($res_rejected); sql_pe("DELETE FROM morph_annot_rejected_samples WHERE user_id=? AND sample_id=? LIMIT 1", array($user_id, $r['sample_id'])); sql_pe("UPDATE morph_annot_instances SET user_id=?, ts_finish=? WHERE instance_id=? LIMIT 1", array($user_id, time() + $config['misc']['morph_annot_timeout'], $id)); } } // a valid answer static $update = NULL; if ($update == NULL) { $update = sql_prepare("UPDATE morph_annot_instances SET user_id=?, answer=? WHERE instance_id=? LIMIT 1"); } if ($answer > 0) { sql_execute($update, array($user_id, $answer, $id)); } elseif ($answer == -1) { reject_annot_instance($id, $user_id); } sql_commit(); }
function find_all_words($name = NULL, $lang = NULL, $spart = NULL) { global $sql_stmts; $stmt = []; $params = [""]; if ($name !== NULL) { $stmt[] = "word_name"; $params[0] .= "s"; $params[] = $name; } if ($lang !== NULL) { $stmt[] = "word_lang"; $params[0] .= "s"; $params[] = $lang; } if ($spart !== NULL) { $stmt[] = "word_spart"; $params[0] .= "s"; $params[] = $spart; } if (!count($stmt)) { _die("bad arguments: need one non-NULL"); } $stmt = $sql_stmts["word_id<-" . implode(",", $stmt)]; $res = NULL; sql_getmany(sql_prepare($stmt), $res, $params); foreach ($res as &$r) { $r = WORD($this, $r); } return $res; }
function save_user_options($post) { if (!isset($post['options'])) { throw new UnexpectedValueException(); } check_logged(); sql_begin(); $upd = sql_prepare("UPDATE user_options_values SET option_value=? WHERE option_id=? AND user_id=? LIMIT 1"); foreach ($post['options'] as $id => $value) { if ($_SESSION['options'][$id]['value'] != $value) { sql_execute($upd, array($value, $id, $_SESSION['user_id'])); $_SESSION['options'][$id] = $value; } } sql_commit(); }
function revert_changeset($set_id, $comment) { if (!$set_id) { throw new UnexpectedValueException(); } check_permission(PERM_DICT); sql_begin(); $new_set_id = create_revset($comment); $dict_flag = 0; $res = sql_pe("SELECT tf_id FROM tf_revisions WHERE set_id=?", array($set_id)); $res_revtext = sql_prepare("SELECT rev_text FROM tf_revisions WHERE tf_id=? AND set_id<? ORDER BY rev_id DESC LIMIT 1"); foreach ($res as $r) { sql_execute($res_revtext, array($r[0], $set_id)); $arr = sql_fetch_array($res_revtext); create_tf_revision($new_set_id, $r[0], $arr[0]); } $res_revtext->closeCursor(); $res = sql_pe("SELECT lemma_id FROM dict_revisions WHERE set_id=?", array($set_id)); $res_revtext = sql_prepare("SELECT rev_text FROM dict_revisions WHERE lemma_id=? AND set_id<? ORDER BY rev_id DESC LIMIT 1"); foreach ($res as $r) { sql_execute($res_revtext, array($r[0], $set_id)); $arr = sql_fetch_array($res_revtext); new_dict_rev($r[0], $arr[0], $new_set_id); $dict_flag = 1; } $res_revtext->closeCursor(); sql_commit(); if ($dict_flag) { return 'dict_history.php'; } return 'history.php'; }
function sql_stmt($name) { global $sql_stmts; if (is_string($sql_stmts[$name])) { $sql_stmts[$name] = sql_prepare($sql_stmts[$name]); } return $sql_stmts[$name]; }
function set_ne_tags($entity_id, $tags, $annot_id = 0) { // overwrites old set of tags // TODO check that tags and annotation belong to the same tagset if (!$annot_id) { $res = sql_pe("SELECT annot_id FROM ne_entities WHERE entity_id = ?", array($entity_id)); $annot_id = $res[0]['annot_id']; } if (!check_ne_paragraph_status($annot_id, $_SESSION['user_id'])) { throw new Exception(); } sql_begin(); sql_pe("DELETE FROM ne_entity_tags WHERE entity_id = ?", array($entity_id)); $res = sql_prepare("INSERT INTO ne_entity_tags VALUES(?, ?)"); foreach ($tags as $tag) { sql_execute($res, array($entity_id, $tag)); } sql_commit(); }