query($query); $count = $db->query("SELECT FOUND_ROWS() as c")->current()->c; return array($count, new ORM_Iterator(ORM::factory("item"), $data)); } private static function _build_query_base($q, $where=array()) { $q = Database::instance()->escape($q); if (!identity::active_user()->admin) { foreach (identity::group_ids_for_active_user() as $id) { $fields[] = "`view_$id` = TRUE"; // access::ALLOW } $access_sql = " AND (" . join(" OR ", $fields) . ")"; } else { $access_sql = ""; } return "SELECT SQL_CALC_FOUND_ROWS {items}.*, " . " MATCH({search_records}.`data`) AGAINST ('$q') AS `score` " . "FROM {items} JOIN {search_records} ON ({items}.`id` = {search_records}.`item_id`) " . "WHERE MATCH({search_records}.`data`) AGAINST ('$q' IN BOOLEAN MODE) " . (empty($where) ? "" : " AND " . join(" AND ", $where)) . $access_sql; } /** * @return string An error message suitable for inclusion in the task log */ static function check_index() { list ($remaining) = search::stats(); if ($remaining) { site_status::warning( t('Your search index needs to be updated. Fix this now', array("url" => html::mark_clean(url::site("admin/maintenance/start/search_task::update_index?csrf=__CSRF__")))), "search_index_out_of_date"); } } static function update($item) { $data = new ArrayObject(); $record = ORM::factory("search_record")->where("item_id", "=", $item->id)->find(); if (!$record->loaded()) { $record->item_id = $item->id; } $item = $record->item(); module::event("item_index_data", $item, $data); $record->data = join(" ", (array)$data); $record->dirty = 0; $record->save(); } static function stats() { $remaining = db::build() ->from("items") ->join("search_records", "items.id", "search_records.item_id", "left") ->and_open() ->where("search_records.item_id", "IS", null) ->or_where("search_records.dirty", "=", 1) ->close() ->count_records(); $total = ORM::factory("item")->count_all(); $percent = round(100 * ($total - $remaining) / $total); return array($remaining, $total, $percent); } static function get_position($item, $q) { $page_size = module::get_var("gallery", "page_size", 9); $query = self::_build_query_base($q, array("{items}.id = " . $item->id)); $db = Database::instance(); // Truncate the score by two decimal places as this resolves the issues // that arise due to in exact numeric conversions. $score = $db->query($query)->current()->score; if (strlen($score) > 7) { $score = substr($score, 0, strlen($score) - 2); } $data = $db->query(self::_build_query_base($q) . " HAVING `score` >= " . $score); $data->seek($data->count() - 1); while ($data->get("id") != $item->id && $data->prev()->valid()) { } return $data->key() + 1; } }