FINAL suepr merge step : added all modules to this super repos

This commit is contained in:
Bachir Soussi Chiadmi
2015-04-19 16:46:59 +02:00
7585 changed files with 1723356 additions and 18 deletions

View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,52 @@
Ajaxify Search API pages.
1. INSTALLATION AND CONFIGURATION
This Ajax module does not understand your theme CSS id's by default. You must
implement a custom module hook to let it know about your theme.
For example, create and enable a custom mymodule.module containing this code:
<?php
/**
* Implements hook_search_api_ajax_settings().
*/
function mymodule_search_api_ajax_settings() {
$settings = array(
// CSS id for main content (search results html)
// format: content => CSS id
'content' => '#content .content',
// CSS id's for regions containing search blocks
// check your region names in mytheme.info
// format: region_name => CSS id
'regions' => array(
'sidebar_first' => '#sidebar-first',
'sidebar_second' => '#sidebar-second',
),
// OPTIONAL: if you want to provide an AJAX spinner
// this paht is for a default spinner path provided with this module
// @note: see the search_api_ajax.css
'spinner' => drupal_get_path('module', 'search_api_ajax') .'/spinner.gif',
// OPTIONAL: if you want to use scroll-to-top functionality when paging
// scroll target div
'scrolltarget' => '#main-content',
'scrollspeed' => 1000,
// OPTIONAL: if you want to fade search results when Ajaxing
// please set to 1 for TRUE
'fade' => 1,
'opacity' => 0.3,
);
return $settings;
}
2. OPTIONAL: customize YUI3 jquery
If you want to use your custom YUI3 logic, you can override:
theme_search_api_ajax_js()
See search_api_ajax.module

View File

@@ -0,0 +1,228 @@
/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
* Dual licensed under the MIT (MIT_LICENSE.txt)
* and GPL Version 2 (GPL_LICENSE.txt) licenses.
*
* Version: 1.1.1
* Requires jQuery 1.3+
* Docs: http://docs.jquery.com/Plugins/livequery
*/
(function($) {
$.extend($.fn, {
livequery: function(type, fn, fn2) {
var self = this, q;
// Handle different call patterns
if ($.isFunction(type))
fn2 = fn, fn = type, type = undefined;
// See if Live Query already exists
$.each($.livequery.queries, function(i, query) {
if (self.selector == query.selector && self.context == query.context && type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid))
// Found the query, exit the each loop
return ( q = query) && false;
});
// Create new Live Query if it wasn't found
q = q || new $.livequery(this.selector, this.context, type, fn, fn2);
// Make sure it is running
q.stopped = false;
// Run it immediately for the first time
q.run();
// Contnue the chain
return this;
},
expire: function(type, fn, fn2) {
var self = this;
// Handle different call patterns
if ($.isFunction(type))
fn2 = fn, fn = type, type = undefined;
// Find the Live Query based on arguments and stop it
$.each($.livequery.queries, function(i, query) {
if (self.selector == query.selector && self.context == query.context && (!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped)
$.livequery.stop(query.id);
});
// Continue the chain
return this;
}
});
$.livequery = function(selector, context, type, fn, fn2) {
this.selector = selector;
this.context = context;
this.type = type;
this.fn = fn;
this.fn2 = fn2;
this.elements = [];
this.stopped = false;
// The id is the index of the Live Query in $.livequery.queries
this.id = $.livequery.queries.push(this) - 1;
// Mark the functions for matching later on
fn.$lqguid = fn.$lqguid || $.livequery.guid++;
if (fn2)
fn2.$lqguid = fn2.$lqguid || $.livequery.guid++;
// Return the Live Query
return this;
};
$.livequery.prototype = {
stop: function() {
var query = this;
if (this.type)
// Unbind all bound events
this.elements.unbind(this.type, this.fn);
else if (this.fn2)
// Call the second function for all matched elements
this.elements.each(function(i, el) {
query.fn2.apply(el);
});
// Clear out matched elements
this.elements = [];
// Stop the Live Query from running until restarted
this.stopped = true;
},
run: function() {
// Short-circuit if stopped
if (this.stopped)
return;
var query = this;
var oEls = this.elements, els = $(this.selector, this.context), nEls = els.not(oEls);
// Set elements to the latest set of matched elements
this.elements = els;
if (this.type) {
// Bind events to newly matched elements
nEls.bind(this.type, this.fn);
// Unbind events to elements no longer matched
if (oEls.length > 0)
$.each(oEls, function(i, el) {
if ($.inArray(el, els) < 0)
$.event.remove(el, query.type, query.fn);
});
}
else {
// Call the first function for newly matched elements
nEls.each(function() {
query.fn.apply(this);
});
// Call the second function for elements no longer matched
if (this.fn2 && oEls.length > 0)
$.each(oEls, function(i, el) {
if ($.inArray(el, els) < 0)
query.fn2.apply(el);
});
}
}
};
$.extend($.livequery, {
guid: 0,
queries: [],
queue: [],
running: false,
timeout: null,
checkQueue: function() {
if ($.livequery.running && $.livequery.queue.length) {
var length = $.livequery.queue.length;
// Run each Live Query currently in the queue
while (length--)
$.livequery.queries[ $.livequery.queue.shift()].run();
}
},
pause: function() {
// Don't run anymore Live Queries until restarted
$.livequery.running = false;
},
play: function() {
// Restart Live Queries
$.livequery.running = true;
// Request a run of the Live Queries
$.livequery.run();
},
registerPlugin: function() {
$.each(arguments, function(i, n) {
// Short-circuit if the method doesn't exist
if (!$.fn[n])
return;
// Save a reference to the original method
var old = $.fn[n];
// Create a new method
$.fn[n] = function() {
// Call the original method
var r = old.apply(this, arguments);
// Request a run of the Live Queries
$.livequery.run();
// Return the original methods result
return r;
}
});
},
run: function(id) {
if (id != undefined) {
// Put the particular Live Query in the queue if it doesn't already exist
if ($.inArray(id, $.livequery.queue) < 0)
$.livequery.queue.push(id);
}
else
// Put each Live Query in the queue if it doesn't already exist
$.each($.livequery.queries, function(id) {
if ($.inArray(id, $.livequery.queue) < 0)
$.livequery.queue.push(id);
});
// Clear timeout if it already exists
if ($.livequery.timeout)
clearTimeout($.livequery.timeout);
// Create a timeout to check the queue and actually run the Live Queries
$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);
},
stop: function(id) {
if (id != undefined)
// Stop are particular Live Query
$.livequery.queries[id].stop();
else
// Stop all Live Queries
$.each($.livequery.queries, function(id) {
$.livequery.queries[id].stop();
});
}
});
// Register core DOM manipulation methods
$.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove', 'html');
// Run Live Queries when the Document is ready
$(function() {
$.livequery.play();
});
})(jQuery);

View File

@@ -0,0 +1,8 @@
#search-api-ajax-spinner {
width: 100%;
position: absolute;
top: 0;
left: 0;
text-align: center;
padding-top: 150px;
}

View File

@@ -0,0 +1,12 @@
name = Search ajaxified
description = "Ajaxifies Search API pages with jQuery Livequery and Yahoo! iFrame."
dependencies[] = search_api
core = 7.x
package = Search
; Information added by drupal.org packaging script on 2012-07-02
version = "7.x-1.x-dev"
core = "7.x"
project = "search_api_ajax"
datestamp = "1341225683"

View File

@@ -0,0 +1,224 @@
(function($) {
var history;
Drupal.search_api_ajax = {};
if (Drupal.settings.search_api_ajax) {
var blocks = Drupal.settings.search_api_ajax.blocks;
var content = Drupal.settings.search_api_ajax.content;
var regions = Drupal.settings.search_api_ajax.regions;
var spinner = Drupal.settings.search_api_ajax.spinner;
var target = Drupal.settings.search_api_ajax.scrolltarget;
var fade = Drupal.settings.search_api_ajax.fade;
var opacity = Drupal.settings.search_api_ajax.opacity;
var speed = Drupal.settings.search_api_ajax.scrollspeed;
// notice the "search_api_ajax_path" instead of
// "search_api_ajax.path" for magic reasons
var ajaxPath = Drupal.settings.search_api_ajax_path;
var qPath = Drupal.settings.search_api_ajax_qpath;
var isView = Drupal.settings.search_api_ajax.view;
// initialize listeners
Drupal.search_api_ajax.initialize = function() {
if (content) {
Drupal.search_api_ajax.ajax(content);
}
if (blocks) {
for (var block in blocks) {
Drupal.search_api_ajax.ajax(blocks[block]);
}
}
};
// extract url for ajax history
Drupal.search_api_ajax.url_to_state = function(url) {
var state = '';
if (isView) {
var query = Drupal.search_api_ajax.get_url_state(url)["query"];
}
state = url.replace(new RegExp('^.*' + Drupal.settings.basePath + ajaxPath + '/' + '?'), '');
if (query) {
state = query + state.replace('?query=' + query, '');
}
else {
state = state.replace('?query=', '');
state = state.replace('?', '&');
}
return state;
};
Drupal.search_api_ajax.get_url_state = function(url) {
var vars = [], hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// prepare and perform ajax search request
Drupal.search_api_ajax.request_callback = function(state) {
if (content) {
if (fade) {
$(content + ':first').fadeTo('fast', opacity);
}
if (spinner) {
$('#content').append('<div id="search-api-ajax-spinner"><img class="spinner" src="' + Drupal.settings.basePath + spinner + '" /></div>')
}
}
// Scroll back to top, when top is out of view. Inspired by views module.
if (target) {
var offset = $(target).offset();
var scrollTarget = target;
while ($(scrollTarget).scrollTop() == 0 && $(scrollTarget).parent()) {
scrollTarget = $(scrollTarget).parent()
}
if (offset.top - 10 < $(scrollTarget).scrollTop()) {
$(scrollTarget).animate({
scrollTop: (offset.top - 10)
}, speed);
}
}
// post ajax, read json
var keysPath = '/' + state;
if (isView) {
keysPath = '?query=' + state;
}
$.post(Drupal.settings.basePath + 'search_api_ajax/' + ajaxPath + keysPath, {
js: 1
}, Drupal.search_api_ajax.response_callback, 'json');
};
// update search page with ajax, based on the json we read
Drupal.search_api_ajax.response_callback = function(data) {
if (content) {
if (fade) {
$(content + ':first').fadeTo('fast', 1);
}
if (spinner) {
$('#search-api-ajax-spinner').remove();
}
}
for (var setting in data.settings) {
Drupal.settings[setting] = data.settings[setting];
}
var list = [];
// we have to add the new blocks, that have come into existence
// @see search_api_ajax.pages.inc where we add this blocks variable
if (data.blocks) {
for (var new_block in data.blocks) {
blocks[new_block] = data.blocks[new_block];
}
}
// schedule items for removal to reduce page jumpiness.
if (blocks) {
for (var block in blocks) {
list.push($(blocks[block]));
}
for (var i = 0, l = list.length; i < l; i++) {
list[i].remove();
}
}
for (var region in data.regions) {
if (region == 'search_api_ajax') {
if (content) {
$(content + ':first').html(data.regions[region]);
}
}
else {
for (var block in data.regions[region]) {
if (regions[region] && blocks[block]) {
$(regions[region]).append(data.regions[region][block]);
}
}
}
}
// re-attach Drupal behaviors for whole document
Drupal.attachBehaviors('body');
};
Drupal.search_api_ajax.navigate = function(url) {
if (url !== undefined) {
YUI().use('history', function(Y) {
history.add({
q: Drupal.search_api_ajax.url_to_state(url)
});
});
}
return false;
};
Drupal.search_api_ajax.ajax = function(selector) {
// observe regular facet and sorts links ^ starts with * contains
// check two paths: ^basePath/ajaxPath OR ^search_api_ajax/basePath/ajaxPath
// @see http://api.jquery.com/category/selectors/attribute-selectors/
// Create an array of selectors for readability.
var selectors = [selector + ' a[href^="' + Drupal.settings.basePath + ajaxPath + '"]', selector + ' a[href^="' + Drupal.settings.basePath + 'search_api_ajax/' + ajaxPath + '"]'];
$(selectors.join(', ')).livequery('click', function() {
return Drupal.search_api_ajax.navigate($(this).attr('href'));
});
// Add support for facetapi checkboxes widget.
// Unbind facetapi click event.
$(selector + ' .facetapi-checkbox').unbind('click');
$(selector + ' .facetapi-checkbox').livequery('click', function() {
return Drupal.search_api_ajax.navigate($(this).next('a').attr('href'));
})
// observe search keys forms (or views input forms, must be custom set)
$(selector + ' form[action^="' + Drupal.settings.basePath + ajaxPath + '"], ' + selector + ' form[action^="' + Drupal.settings.basePath + 'search_api_ajax/' + ajaxPath + '"]').livequery('submit', function() {
return Drupal.search_api_ajax.navigate($(this).find('input[name*="keys"]').val());
});
// observe facet range sliders
$(selector + ' .search-api-ranges-widget form[action^="' + Drupal.settings.basePath + ajaxPath + '"], ' + selector + ' .search-api-ranges-widget form[action^="' + Drupal.settings.basePath + 'search_api_ajax/' + ajaxPath + '"]').livequery('submit', function() {
var separator = '?';
if ($(this).find('input[name="range-ajax-target"]').val().indexOf("?") !== -1) {
separator = '&';
}
// add a filter in the form of &f[n]=field_name:[A B]
// instead of actually knowing what "n" is, we just f[]
// @todo Facet API can have different 'f', how to know which?
var addFilter = 'f[]=' + $(this).find('input[name="range-field"]').val() + ':' + '[' + $(this).find('input[name="range-from"]').val() + ' TO ' + $(this).find('input[name="range-to"]').val() + ']';
return Drupal.search_api_ajax.navigate($(this).find('input[name="range-ajax-target"]').val() + separator + addFilter);
});
};
}
// we initiate YUI3's History extension
YUI().use('history', function(Y) {
// initialize
history = new Y.HistoryHash();
if (history.get('q')) {
Drupal.search_api_ajax.request_callback(history.get('q'));
}
// listen to changes
// @todo when going from /page#q= to /page it should also trigger
Y.on('history:change', function(e) {
var changed = e.changed;
if (changed.q) {
Drupal.search_api_ajax.request_callback(history.get('q'));
}
});
});
Drupal.behaviors.search_api_ajax = {
attach: function(context, settings) {
// initialize livequery() event only if there is an active search
// only needed for search api pages, not for views paths
if (Drupal.search_api_ajax.url_to_state(window.location.href) != '' || isView === 1) {
Drupal.search_api_ajax.initialize();
}
}
};
})(jQuery);

View File

@@ -0,0 +1,258 @@
<?php
/**
* @file AJAXifies the Search API search pages, links, ranges, sorts and forms.
*/
/**
* Implements hook_search_api_ajax_settings().
*/
function search_api_ajax_search_api_ajax_settings() {
global $theme_key;
$settings = array();
// get all drupal blocks
$settings['blocks'] = &drupal_static(__FUNCTION__);
if (!isset($settings['blocks'])) {
$blocks = array();
// Drupal blocks
// @todo cache this?
$regions = system_region_list($theme_key);
foreach ($regions as $region_key => $region_name) {
$settings['regions'][] = $region_key;
$block_list = block_list($region_key);
// remove inactive blocks (status=0)
foreach ($block_list as $key => $block) {
if ($block->status == 0) {
unset($block_list[$key]);
}
}
$blocks = array_merge(block_list($region_key), $blocks);
if (module_exists('context')) {
$blocks = array_merge(context_get_plugin('reaction', 'block')->block_list($region_key), $blocks);
}
}
$modules = search_api_ajax_modules();
foreach ($blocks as $block) {
if (in_array($block->module, $modules)) {
// facetapi block names are strtolowered in html, so do same here
if (in_array($block->module, array(
'facetapi',
'facetapi_tagcloud'
))) {
$block->delta = strtolower($block->delta);
}
$settings['blocks'][$block->module . '_' . $block->delta] = str_replace('_', '-', '#block-' . $block->module . '-' . $block->delta);
}
}
}
// need to make the current search api page path available as jQuery setting
// @see search_api_ajax.js
$current_search = search_api_current_search();
foreach ($current_search as $key => $search) {
// break on facet blocks - $path is only useful for pages, avoid blocks
if (strpos($key, 'facets_block') !== FALSE || arg(0) == 'admin') {
break;
}
$path_parts = explode(':', $key);
// is it a view path or a search_api_page?
// views paths have 3 parts, search pages only 2
if ($path_parts[0] == 'search_api_views') {
$trail = menu_set_active_trail();
// process last entry
end($trail);
$key = key($trail);
$views_path = isset($trail[$key]['link_path']) ? $trail[$key]['link_path'] : $trail[$key]['path'];
$path = search_api_ajax_get_views_path($views_path);
$settings['view'] = 1;
}
else {
$path = $path_parts[1];
$settings['view'] = 0;
}
if (!empty($path)) {
// needed to add current page path to ajax
drupal_add_js(array('search_api_ajax_path' => $path), 'setting');
}
$settings['path'] = $path;
}
return $settings;
}
/**
* Implementation of hook_menu().
*/
function search_api_ajax_menu() {
$items = array();
// during uninstallation, this would lead to a fatal error otherwise.
if (module_exists('search_api_page')) {
foreach (search_api_page_load_multiple(FALSE, array('enabled' => TRUE)) as $page) {
$items['search_api_ajax/' . $page->path] = array(
'title' => $page->name,
'description' => $page->description ? $page->description : '',
'page callback' => 'search_api_ajax_proxy',
'page arguments' => array((string)$page->id),
'access arguments' => array('access search_api_page'),
'type' => MENU_CALLBACK,
'file' => 'search_api_ajax.pages.inc',
);
}
}
// similarly, walk through search_api_views with a path (pages)
if (module_exists('search_api_views') && function_exists('views_get_enabled_views')) {
foreach (views_get_enabled_views() as $view) {
if (strpos($view->base_table, 'search_api_index') !== FALSE) {
foreach ($view->display as $display_name => $display) {
if (isset($display->display_options['path']) && !(empty($display->display_options['path']))) {
$items['search_api_ajax/' . $display->display_options['path']] = array(
'title' => isset($display->display_title) ? $display->display_title : '',
'description' => (string)$view->human_name,
'page callback' => 'search_api_ajax_proxy_views',
'page arguments' => array(
(string)$view->name,
(string)$display_name
),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
'file' => 'search_api_ajax.pages.inc',
);
}
}
}
}
}
return $items;
}
/**
* Returns the list of modules whose blocks are search api-related.
*
* @see search_api_ajax_proxy()
*/
function search_api_ajax_modules() {
static $modules = NULL;
if (is_null($modules)) {
$modules = array(
'search_api_facets',
'search_api_ranges',
'search_api_sorts',
'search_api_widgets',
'facetapi',
'facetapi_tagcloud',
);
drupal_alter('search_api_ajax_modules', $modules);
}
return $modules;
}
/**
* Implementation of hook_preprocess_page().
*
* Adds JavaScript files and settings. To successfully configure this module,
* another module must implement hook_search_api_ajax_settings(), which must
* return an array with the required keys "content", "blocks", "regions" and
* the optional key "spinner".
*
* "content" must be the CSS selector for the HTML node in which the page
* content is displayed. In the Zen theme, this is '#content-area'.
*
* "blocks" must be a map between the block keys and the CSS selectors for
* the blocks. Block keys follow the pattern: MODULE_DELTA. In the Zen theme,
* this may be: array('node_0' => '#block-node-0', ...). You need only do this
* for search-related blocks. If you don't know your blocks, run:
*
* <pre>
* $modules = search_api_ajax_modules();
* foreach ($modules as $module) {
* if (module_exists($module)) {
* if ($list = module_invoke($module, 'block', 'list')) {
* foreach (array_keys($list) as $delta) {
* print $module .'_'. $delta;
* }
* }
* }
* }
* </pre>
*
* "regions" must be a map between the theme regions and the CSS selectors
* for the regions. In the Zen theme, this may be: array('content_top' =>
* '.region-content-top'). If you don't know your theme's regions, run:
* <code>system_region_list('mytheme');</code>
*
* (Optional) "spinner" is the path to an animated image to be displayed
* while content is loading via AJAX, e.g.: <code>base_path() .
* drupal_get_path('module', 'mymodule') .'/images/spinner.gif'</code>
*
* @see http://developer.yahoo.com/yui/history/
*/
function search_api_ajax_preprocess_page(&$vars, $hook) {
if (!search_api_current_search()) {
return;
}
drupal_add_css(drupal_get_path('module', 'search_api_ajax') . '/search_api_ajax.css');
drupal_add_js(array('search_api_ajax' => module_invoke_all('search_api_ajax_settings')), 'setting');
drupal_add_js(drupal_get_path('module', 'search_api_ajax') . '/jquery.livequery.js', array('scope' => 'footer'));
if (module_exists('libraries') && $library = libraries_get_path('yui')) {
drupal_add_js($library . '/build/yui/yui-min.js', array('scope' => 'footer'));
}
else {
drupal_add_js('http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js', 'external');
}
drupal_add_js(drupal_get_path('module', 'search_api_ajax') . '/search_api_ajax.js', array('scope' => 'footer'));
}
/**
* Collects debug data to send to the browser with the AJAX response.
*
* @param mixed $data Debug data you want to send to the browser.
*/
function search_api_ajax_debug($data = NULL) {
static $debug = array();
if (isset($data)) {
$debug[] = $data;
}
return $debug;
}
/**
* Get the actual views path
* Filling in '%' arguments in the path with the correct values from arg()
*
* @param string $views_path
* The views page path, e.g. 'mynodes', 'mynodes/%'
*
* @param int $skip
* The number of arguments to skip (usually only needed on
* search_api_ajax/* pages).
*/
function search_api_ajax_get_views_path($views_path, $skip = 0) {
$path = array();
$current_path = arg();
// fill in % paths: we know the views_path, which may contain % arguments
// so we need to fill in those % with the current page from arg()
// @todo is there a 'Drupal way' to do this?
$path = explode('/', $views_path);
foreach (arg(NULL, $views_path) as $key => $piece) {
if ($piece == '%') {
$path[$key] = $current_path[$key + $skip];
}
}
$path = implode('/', $path);
return $path;
}

View File

@@ -0,0 +1,123 @@
<?php
/**
* Checks incoming AJAX requests for Search API pages paths
*/
function search_api_ajax_proxy($id, $keys = NULL) {
$page = search_api_page_load((int)$id);
if (!$page) {
return MENU_NOT_FOUND;
}
$return = menu_execute_active_handler($page->path . '/' . $keys, FALSE);
search_api_ajax_return_json($return);
}
/**
* Checks incoming AJAX requests for Search API views paths
*/
function search_api_ajax_proxy_views($name, $display, $keys = NULL) {
$view = views_get_view($name);
if (!$view) {
return MENU_NOT_FOUND;
}
$path = search_api_ajax_get_views_path($view->display[$display]->display_options['path'], 1);
if ($keys) {
$path = $path . '/' . $keys;
}
$return = menu_execute_active_handler($path, FALSE);
search_api_ajax_return_json($return);
}
/**
* Performs a search request and returns page & block content html as JSON
*
* If the incoming request is not an AJAX request, user/bot is redirected
* to the non-Ajax URL.
*
* @see search_api_ajax_modules()
*/
function search_api_ajax_return_json($return) {
// check request source type: non-ajax is redirect back to non-ajax URL
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$params = drupal_get_query_parameters();
$path = str_replace('search_api_ajax/', '', $_GET['q']);
drupal_goto($path, array('query' => $params), 301);
exit ;
}
if (is_int($return)) {
switch ($return) {
case MENU_NOT_FOUND :
drupal_add_http_header('Status', '404 Not Found');
break;
case MENU_ACCESS_DENIED :
drupal_add_http_header('Status', '403 Forbidden');
break;
case MENU_SITE_OFFLINE :
drupal_add_http_header('Status', '503 Service unavailable');
break;
}
}
elseif (isset($return)) {
global $theme;
if (!isset($theme)) {
init_theme();
}
// render JSON (views are already rendered)
if (is_array($return)) {
$return = drupal_render($return);
}
$json = array('regions' => array('search_api_ajax' => $return));
// add new blocks
$blocks = array();
// Drupal blocks
// @todo cache this?
$regions = system_region_list($theme);
foreach ($regions as $region_key => $region_name) {
$settings['regions'][] = $region_key;
$block_list = block_list($region_key);
// remove inactive blocks (status=0)
foreach ($block_list as $key => $block) {
if ($block->status == 0) {
unset($block_list[$key]);
}
}
$blocks = array_merge(block_list($region_key), $blocks);
if (module_exists('context')) {
$blocks = array_merge(context_get_plugin('reaction', 'block')->block_list($region_key), $blocks);
}
}
$modules = search_api_ajax_modules();
foreach ($blocks as $block) {
if (in_array($block->module, $modules)) {
$rendered_block = _block_render_blocks(array($block));
$rendered_block = _block_get_renderable_array($rendered_block);
$json['regions'][$block->region][$block->module . '_' . $block->delta] = drupal_render($rendered_block);
// new blocks may have come into existence, we notify about them
// otherwise they would never be displayed to the user
// @see search_api_ajax.js
$block_delta = strtolower($block->delta);
$json['blocks'][$block->module . '_' . $block->delta] = str_replace('_', '-', '#block-' . $block->module . '-' . $block->delta);
}
}
// merge all scopes and settings
$javascript = drupal_add_js(NULL, NULL, NULL);
$scopes = call_user_func_array('array_merge_recursive', $javascript);
$json['settings'] = call_user_func_array('array_merge_recursive', array($scopes['data']));
$json['debug'] = search_api_ajax_debug();
drupal_add_http_header('Content-Type', 'application/json; charset=utf-8');
print drupal_json_encode($json);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,54 @@
Search API autocomplete
-----------------------
Adds autocomplete capabilities for Search API searches.
Information for users
---------------------
- Necessary server feature
The server on which the search will be executed has to support the
"search_api_autocomplete" feature in order for autocompletion to work. Searches
on other servers won't be affected by this module.
Currently, only the Solr service class [1] is known to support this feature.
[1] http://drupal.org/project/search_api_solr
- Necessary setup
After having installed and enabled the module, you have to do some
administrative steps to activate the autocomplete functionality. Autocompletion
can be enabled and configured for each search separately.
To activate autocompletion for an index's searches, go to the index's
„Autocomplete“ tab. There, you see all available searches for the index and can
enable (and afterwards configure) autocompletion for each of them. All fulltext
key fields on the searches should then become autocompletion fields.
- Supported searches
Currently, only search forms built by search pages or search views are
supported directly. However, other modules can easily also use this
functionality. See the "Information for developers" for details.
Information for developers
--------------------------
- Supporting autocompletion with a service class
To support autocompletion with a service class, the class has to support the
"search_api_autocomplete" feature. This will necessitate the service class to
have a getAutocompleteSuggestions() method as detailed in the interface in
search_api_autocomplete.interface.php.
- Supporting autocompletion on a search form
If you have a search form not generated by the Search views or Search pages
modules, you can use hook_search_api_autocomplete_types() to tell this module
about it. For details, see the hook documentation in the
search_api_autocomplete.api.php file, or look at the existing implementations
in search_api_autocomplete.search_api_page.inc and
search_api_autocomplete.search_api_views.inc.

View File

@@ -0,0 +1,316 @@
<?php
/**
* @file
* Contains page callbacks and related functions for the admin UI.
*/
/**
* Form displaying an overview over all searches available for autocompletion.
*
* @param SearchApiIndex $index
* The index for which autocompletion searches should be configured.
*
* @see search_api_autocomplete_admin_overview_submit()
* @see search_api_autocomplete_admin_overview_submit_delete()
* @ingroup forms
*/
function search_api_autocomplete_admin_overview(array $form, array &$form_state, SearchApiIndex $index) {
$form = array();
$form_state['index'] = $index;
$index_id = $index->machine_name;
$server = $index->server();
if (!$server || !$server->supportsFeature('search_api_autocomplete')) {
drupal_set_message(t("The server this index currently lies on doesn't support autocompletion. " .
'To use autocompletion, you will have to move this index to a server supporting this feature.'), 'error');
if (search_api_autocomplete_search_load_multiple(FALSE, array('index_id' => $index_id))) {
$form['description'] = array(
'#type' => 'item',
'#title' => t('Delete autocompletion settings'),
'#description' => t("If you won't use autocompletion with this index anymore, you can delete all autocompletion settings associated with it. " .
"This will delete all autocompletion settings on this index. Settings on other indexes won't be influenced."),
);
$form['button'] = array(
'#type' => 'submit',
'#value' => t('Delete autocompletion settings'),
'#submit' => array('search_api_autocomplete_admin_overview_submit_delete'),
);
}
return $form;
}
$form['#tree'] = TRUE;
$types = search_api_autocomplete_get_types();
$searches = search_api_autocomplete_search_load_multiple(FALSE, array('index_id' => $index_id));
$show_status = FALSE;
foreach ($types as $type => $info) {
if (empty($info['list searches'])) {
continue;
}
$t_searches = $info['list searches']($index);
if (empty($t_searches)) {
$t_searches = array();
}
foreach ($t_searches as $id => $search) {
if (isset($searches[$id])) {
$types[$type]['searches'][$id] = $searches[$id];
$show_status |= $searches[$id]->hasStatus(ENTITY_IN_CODE);
unset($searches[$id]);
}
else {
$search += array(
'machine_name' => $id,
'index_id' => $index_id,
'type' => $type,
'enabled' => 0,
'options' => array(),
);
$search['options'] += array(
'result count' => TRUE,
);
$types[$type]['searches'][$id] = entity_create('search_api_autocomplete_search', $search);
}
}
}
foreach ($searches as $id => $search) {
$search->unavailable = TRUE;
$type = isset($types[$search->type]) ? $search->type : '';
$types[$type]['searches'][$id] = $search;
$show_status |= $search->hasStatus(ENTITY_IN_CODE);
}
$base_path = 'admin/config/search/search_api/index/' . $index_id . '/autocomplete/';
foreach ($types as $type => $info) {
if (empty($info['searches'])) {
continue;
}
if (!$type) {
$info += array(
'name' => t('Unavailable search types'),
'description' => t('The modules providing these searches were disabled or uninstalled. ' .
"If you won't use them anymore, you can delete their settings."),
);
}
$form[$type] = array(
'#type' => 'fieldset',
'#title' => $info['name'],
);
if (!empty($info['description'])) {
$form[$type]['#description'] = '<p>' . $info['description'] . '</p>';
}
$form[$type]['searches']['#theme'] = 'tableselect';
$form[$type]['searches']['#header'] = array();
if ($show_status) {
$form[$type]['searches']['#header']['status'] = t('Status');
}
$form[$type]['searches']['#header'] += array(
'name' => t('Name'),
'operations' => t('Operations'),
);
$form[$type]['searches']['#empty'] = '';
$form[$type]['searches']['#js_select'] = TRUE;
foreach ($info['searches'] as $id => $search) {
$form[$type]['searches'][$id] = array(
'#type' => 'checkbox',
'#default_value' => $search->enabled,
'#parents' => array('searches', $id),
);
if (!empty($search->unavailabe)) {
$form[$type]['searches'][$id]['#default_value'] = FALSE;
$form[$type]['searches'][$id]['#disabled'] = TRUE;
}
$form_state['searches'][$id] = $search;
$options = &$form[$type]['searches']['#options'][$id];
if ($show_status) {
$options['status'] = isset($search->status) ? theme('entity_status', array('status' => $search->status)) : '';;
}
$options['name'] = $search->name;
$items = array();
if (empty($search->unavailabe) && !empty($search->id)) {
$items[] = l(t('edit'), $base_path . $id . '/edit');
}
if (!empty($search->status) && ($search->hasStatus(ENTITY_CUSTOM))) {
$title = $search->hasStatus(ENTITY_IN_CODE) ? t('revert') : t('delete');
$items[] = l($title, $base_path . $id . '/delete');
}
if ($items) {
$variables = array(
'items' => $items,
'attributes' => array('class' => array('inline')),
);
$options['operations'] = theme('item_list', $variables);
}
else {
$options['operations'] = '';
}
unset($options);
}
}
if (empty($form)) {
$form['message']['#markup'] = '<p>' . t('There are currently no searches known for this index.') . '</p>';
}
else {
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
}
return $form;
}
/**
* Submit callback for search_api_autocomplete_admin_overview().
*
* @see search_api_autocomplete_admin_overview()
*/
function search_api_autocomplete_admin_overview_submit(array $form, array &$form_state) {
foreach ($form_state['values']['searches'] as $id => $enabled) {
$search = $form_state['searches'][$id];
if ($search->enabled != $enabled) {
$search->enabled = $enabled;
$search->save();
}
}
drupal_set_message(t('The settings have been saved.'));
}
/**
* Submit callback for search_api_autocomplete_admin_overview(), when all
* settings for the index should be deleted.
*
* @see search_api_autocomplete_admin_overview()
*/
function search_api_autocomplete_admin_overview_submit_delete(array $form, array &$form_state) {
$index = $form_state['index'];
$ids = array_keys(search_api_autocomplete_search_load_multiple(FALSE, array('index_id' => $index->machine_name)));
if ($ids) {
entity_delete_multiple('search_api_autocomplete_search', $ids);
drupal_set_message(t('All autocompletion settings stored for this index were deleted.'));
}
else {
drupal_set_message(t('There were no settings to delete.'), 'warning');
}
$form_state['redirect'] = 'admin/config/search/search_api/index/' . $index->machine_name;
}
/**
* Form for editing the autocompletion settings for a search.
*
* @param SearchApiAutocompleteSearch $search
* The search whose settings should be edited.
*
* @see search_api_autocomplete_admin_search_edit_validate()
* @see search_api_autocomplete_admin_search_edit_submit()
* @ingroup forms
*/
function search_api_autocomplete_admin_search_edit(array $form, array &$form_state, SearchApiAutocompleteSearch $search) {
drupal_set_title(t('Edit %search', array('%search' => $search->name)), PASS_THROUGH);
$form_state['search'] = $search;
$form_state['type'] = $type = search_api_autocomplete_get_types($search->type);
if (!$type) {
drupal_set_message(t('No information about the type of this search was found.'), 'error');
return array();
}
$form['#tree'] = TRUE;
$form['enabled'] = array(
'#type' => 'checkbox',
'#title' => t('Enabled'),
'#default_value' => $search->enabled,
);
$form['options']['results'] = array(
'#type' => 'checkbox',
'#title' => t('Display result count estimates'),
'#description' => t('Display the estimated number of result for each suggestion. ' .
'This option might not have an effect for some servers or types of suggestion.'),
'#default_value' => !empty($search->options['results']),
);
$custom_form = empty($form['options']['custom']) ? array() : $form['options']['custom'];
if (!empty($type['config form']) && function_exists($type['config form']) && is_array($custom_form = $type['config form']($custom_form, $form_state, $search))) {
$form['options']['custom'] = $custom_form;
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
return $form;
}
/**
* Validate callback for search_api_autocomplete_admin_search_edit().
*
* @see search_api_autocomplete_admin_search_edit()
* @see search_api_autocomplete_admin_search_edit_submit()
*/
function search_api_autocomplete_admin_search_edit_validate(array $form, array &$form_state) {
if (empty($form_state['type']['config form'])) {
return;
}
$f = $form_state['type']['config form'] . '_validate';
if (function_exists($f)) {
$custom_form = empty($form['options']['custom']) ? array() : $form['options']['custom'];
$f($form['options']['custom'], $form_state, $form_state['values']['options']['custom']);
}
}
/**
* Submit callback for search_api_autocomplete_admin_search_edit().
*
* @see search_api_autocomplete_admin_search_edit()
* @see search_api_autocomplete_admin_search_edit_validate()
*/
function search_api_autocomplete_admin_search_edit_submit(array $form, array &$form_state) {
$values = &$form_state['values'];
if (!empty($form_state['type']['config form'])) {
$f = $form_state['type']['config form'] . '_submit';
if (function_exists($f)) {
$custom_form = empty($form['options']['custom']) ? array() : $form['options']['custom'];
$f($form['options']['custom'], $form_state, $values['options']['custom']);
}
}
$search = $form_state['search'];
$search->enabled = $values['enabled'];
$search->options['results'] = $values['options']['results'];
if (isset($values['options']['custom'])) {
// Take care of custom options that aren't changed in the config form.
$old = empty($search->options['custom']) ? array() : $search->options['custom'];
$search->options['custom'] = $values['options']['custom'] + $old;
}
$search->save();
drupal_set_message(t('The autocompletion settings for the search have been saved.'));
$form_state['redirect'] = 'admin/config/search/search_api/index/' . $search->index_id . '/autocomplete';
}
/**
* Form for deleting the autocompletion settings of a search.
*
* @param SearchApiAutocompleteSearch $search
* The search whose settings should be deleted.
*
* @see search_api_autocomplete_admin_search_delete_submit()
* @ingroup forms
*/
function search_api_autocomplete_admin_search_delete(array $form, array &$form_state, SearchApiAutocompleteSearch $search) {
$form_state['search'] = $search;
return confirm_form(
$form,
t('Do you really want to delete the autocompletion settings for search %search?', array('%search' => $search->name)),
'admin/config/search/search_api/index/' . $search->index_id . '/autocomplete'
);
}
/**
* Submit callback for search_api_autocomplete_admin_search_delete().
*
* @see search_api_autocomplete_admin_search_delete()
*/
function search_api_autocomplete_admin_search_delete_submit(array $form, array &$form_state) {
$form_state['search']->delete();
drupal_set_message(t('The autocompletion settings for the search have been deleted.'));
$form_state['redirect'] = 'admin/config/search/search_api/index/' . $form_state['search']->index_id . '/autocomplete';
}

View File

@@ -0,0 +1,343 @@
<?php
/**
* @file
* Hooks provided by the Search API autocomplete module.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Inform the module about types of searches for which autocompletion is available.
*
* The implementation has to take care of altering the search form accordingly
* itself. This should be done by loading the appropriate
* SearchApiAutocompleteSearch entity and calling its alterElement() method with
* the textfield element to which autocompletion should be added. See
* example_form_example_search_form_alter() for an example.
*
* @return array
* An array with search types as the keys, mapped to arrays containing the
* following entries:
* - name: The category name for searches of this type.
* - description: A short description of this type (may contain HTML).
* - list searches: Callback function that returns a list of all known
* searches of this type for a given index. See
* example_list_autocomplete_searches() for the expected function signature.
* - create query: Callback function to create a search query for a search of
* this type and some user input. See example_create_autocomplete_query()
* for the expected function signature.
* - config form: (optional) Callback function for adding a form for
* type-specific options to a search's autocomplete settings form. See
* example_autocomplete_config_form() for the expected function signature.
* This function name will also be the base for custom validation and submit
* callbacks, with "_validate" or "_submit" appended, respectively.
*
* @see example_list_autocomplete_searches()
* @see example_create_autocomplete_query()
* @see example_autocomplete_config_form()
* @see example_autocomplete_config_form_validate()
* @see example_autocomplete_config_form_submit()
* @see example_form_example_search_form_alter()
*/
function hook_search_api_autocomplete_types() {
$types['example'] = array(
'name' => t('Example searches'),
'description' => t('Searches provided by the <em>Example</em> module.'),
'list searches' => 'example_list_autocomplete_searches',
'create query' => 'example_create_autocomplete_query',
'config form' => 'example_autocomplete_config_form',
);
return $types;
}
/**
* Acts on searches being loaded from the database.
*
* This hook is invoked during search loading, which is handled by
* entity_load(), via the EntityCRUDController.
*
* @param array $searches
* An array of search entities being loaded, keyed by machine name.
*
* @see hook_entity_load()
*/
function hook_search_api_autocomplete_search_load(array $searches) {
$result = db_query('SELECT pid, foo FROM {mytable} WHERE pid IN(:ids)', array(':ids' => array_keys($entities)));
foreach ($result as $record) {
$entities[$record->pid]->foo = $record->foo;
}
}
/**
* Responds when a search is inserted.
*
* This hook is invoked after the search is inserted into the database.
*
* @param SearchApiAutocompleteSearch $search
* The search that is being inserted.
*
* @see hook_entity_insert()
*/
function hook_search_api_autocomplete_search_insert(SearchApiAutocompleteSearch $search) {
db_insert('mytable')
->fields(array(
'id' => entity_id('search_api_autocomplete_search', $search),
'extra' => print_r($search, TRUE),
))
->execute();
}
/**
* Acts on a search being inserted or updated.
*
* This hook is invoked before the search is saved to the database.
*
* @param SearchApiAutocompleteSearch $search
* The search that is being inserted or updated.
*
* @see hook_entity_presave()
*/
function hook_search_api_autocomplete_search_presave(SearchApiAutocompleteSearch $search) {
$search->name = 'foo';
}
/**
* Responds to a search being updated.
*
* This hook is invoked after the search has been updated in the database.
*
* @param SearchApiAutocompleteSearch $search
* The search that is being updated.
*
* @see hook_entity_update()
*/
function hook_search_api_autocomplete_search_update(SearchApiAutocompleteSearch $search) {
db_update('mytable')
->fields(array('extra' => print_r($search, TRUE)))
->condition('id', entity_id('search_api_autocomplete_search', $search))
->execute();
}
/**
* Responds to search deletion.
*
* This hook is invoked after the search has been removed from the database.
*
* @param SearchApiAutocompleteSearch $search
* The search that is being deleted.
*
* @see hook_entity_delete()
*/
function hook_search_api_autocomplete_search_delete(SearchApiAutocompleteSearch $search) {
db_delete('mytable')
->condition('pid', entity_id('search_api_autocomplete_search', $search))
->execute();
}
/**
* Define default search configurations.
*
* @return
* An array of default searches, keyed by machine names.
*
* @see hook_default_search_api_autocomplete_search_alter()
*/
function hook_default_search_api_autocomplete_search() {
$defaults['main'] = entity_create('search_api_autocomplete_search', array(
// …
));
return $defaults;
}
/**
* Alter default search configurations.
*
* @param array $defaults
* An array of default searches, keyed by machine names.
*
* @see hook_default_search_api_autocomplete_search()
*/
function hook_default_search_api_autocomplete_search_alter(array &$defaults) {
$defaults['main']->name = 'custom name';
}
/**
* @} End of "addtogroup hooks".
*/
/**
* Returns a list of searches for the given index.
*
* All searches returned must have a unique and well-defined machine name. The
* implementing module for this type is responsible for being able to map a
* specific search always to the same distinct machine name.
* Since the machine names have to be globally unique, they should be prefixed
* with the search type / module name.
*
* Also, name and machine name have to respect the length constraints from
* search_api_autocomplete_schema().
*
* @param SearchApiIndex $index
* The index whose searches should be returned.
*
* @return array
* An array of searches, keyed by their machine name. The values are arrays
* with the following keys:
* - name: A human-readable name for this search.
* - options: (optional) An array of options to use for this search.
* Type-specific options should go into the "custom" nested key in these
* options.
*/
function example_list_autocomplete_searches(SearchApiIndex $index) {
$ret = array();
$result = db_query('SELECT name, machine_name, extra FROM {example_searches} WHERE index_id = :id', array($index->machine_name));
foreach ($result as $row) {
$id = 'example_' . $row->machine_name;
$ret[$id] = array(
'name' => $row->name,
);
if ($row->extra) {
$ret[$id]['options']['custom']['extra'] = $row->extra;
}
}
return $ret;
}
/**
* Create the query that would be issued for the given search for the complete keys.
*
* @param SearchApiAutocompleteSearch $search
* The search for which to create the query.
* @param $complete
* A string containing the complete search keys.
* @param $incomplete
* A string containing the incomplete last search key.
*
* @return SearchApiQueryInterface
* The query that would normally be executed when only $complete was entered
* as the search keys for the given search.
*/
function example_create_autocomplete_query(SearchApiAutocompleteSearch $search, $complete, $incomplete) {
$query = search_api_query($search->index_id);
if ($complete) {
$query->keys($complete);
}
if (!empty($search->options['custom']['extra'])) {
list($f, $v) = explode('=', $search->options['custom']['extra'], 2);
$query->condition($f, $v);
}
if (!empty($search->options['custom']['user_filters'])) {
foreach (explode("\n", $search->options['custom']['user_filters']) as $line) {
list($f, $v) = explode('=', $line, 2);
$query->condition($f, $v);
}
}
return $query;
}
/**
* Form callback for configuring autocompletion for searches of the "example" type.
*
* The returned form array will be nested into an outer form, so you should not
* rely on knowing the array structure (like the elements' parents) and should
* not set "#tree" to FALSE for any element.
*
* @param SearchApiAutocompleteSearch $search
* The search whose config form should be presented.
*
* @see example_autocomplete_config_form_validate()
* @see example_autocomplete_config_form_submit()
*/
function example_autocomplete_config_form(array $form, array &$form_state, SearchApiAutocompleteSearch $search) {
$form['user_filters'] = array(
'#type' => 'textarea',
'#title' => t('Custom filters'),
'#description' => t('Enter additional filters set on the autocompletion search. ' .
'Write one filter on each line, the field and its value separated by an equals sign (=).'),
'#default_value' => empty($search->options['custom']['user_filters']) ? '' : $search->options['custom']['user_filters'],
);
return $form;
}
/**
* Validation callback for example_autocomplete_config_form().
*
* The configured SearchApiAutocompleteSearch object can be found in
* $form_state['search'].
*
* @param array $form
* The type-specific config form, as returned by the "config form" callback.
* @param array $form_state
* The complete form state of the form.
* @param array $values
* The portion of $form_state['values'] that corresponds to the type-specific
* config form.
*
* @see example_autocomplete_config_form()
* @see example_autocomplete_config_form_submit()
*/
function example_autocomplete_config_form_validate(array $form, array &$form_state, array &$values) {
$f = array();
foreach (explode("\n", $values['user_filters']) as $line) {
if (preg_match('/^\s*([a-z0-9_:]+)\s*=\s*(.*\S)\s*$/i', $line, $m)) {
$f[] = $m[1] . '=' . $m[2];
}
else {
form_error($form, t('Write one filter on each line, the field and its value separated by an equals sign (=).'));
}
}
$values['user_filters'] = $f;
}
/**
* Submit callback for example_autocomplete_config_form().
*
* After calling this function, the value of $values (if set) will automatically
* be written to $search->options['custom']. This function just has to take care
* of sanitizing the data as necessary. Also, values already present in
* $search->options['custom'], but not in the form, will automatically be
* protected from being overwritten.
*
* The configured SearchApiAutocompleteSearch object can be found in
* $form_state['search'].
*
* @param array $form
* The type-specific config form, as returned by the "config form" callback.
* @param array $form_state
* The complete form state of the form.
* @param array $values
* The portion of $form_state['values'] that corresponds to the type-specific
* config form.
*
* @see example_autocomplete_config_form()
* @see example_autocomplete_config_form_validate()
*/
function example_autocomplete_config_form_submit(array $form, array &$form_state, array &$values) {
$values['user_filters'] = implode("\n", $values['user_filters']);
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Alters the example_search_form form to add autocompletion, if enabled by the
* user.
*/
function example_form_example_search_form_alter(array &$form, array &$form_state) {
// Compute the machine name that would be generated for this search in the
// 'list searches' callback.
$search_id = 'example_' . $form_state['search id'];
// Look up the corresponding autocompletion configuration, if it exists.
$search = search_api_autocomplete_search_load($search_id);
// Check whether autocompletion for the search is enabled.
if (!empty($search->enabled)) {
// If it is, pass the textfield for the search keywords to the
// alterElement() method of the search object.
$search->alterElement($form['keys']);
}
}

View File

@@ -0,0 +1,16 @@
.search-api-autocomplete-suggestion {
position: relative;
}
.search-api-autocomplete-suggestion .autocomplete-suggestion-note {
font-size: 90%;
}
.search-api-autocomplete-suggestion .autocomplete-user-input {
font-weight: bold;
}
.search-api-autocomplete-suggestion .autocomplete-suggestion-results {
position: absolute;
right: 0.2em;
}

View File

@@ -0,0 +1,178 @@
<?php
/**
* @file
* Contains the SearchApiAutocompleteSearch class.
*/
/**
* Class describing the settings for a certain search for which autocompletion
* is available.
*/
class SearchApiAutocompleteSearch extends Entity {
// Entity properties, loaded from the database:
/**
* @var integer
*/
public $id;
/**
* @var string
*/
public $machine_name;
/**
* @var string
*/
public $name;
/**
* @var integer
*/
public $index_id;
/**
* @var string
*/
public $type;
/**
* @var boolean
*/
public $enabled;
/**
* An array of options for this search, containing any of the following:
* - results: Boolean indicating whether to also list the estimated number of
* results for each suggestion (if possible).
* - custom: An array of type-specific settings.
*
* @var array
*/
public $options = array();
// Inferred properties, for caching:
/**
* @var SearchApiIndex
*/
protected $index;
/**
* @var SearchApiServer
*/
protected $server;
/**
* Constructor.
*
* @param array $values
* The entity properties.
*/
public function __construct(array $values = array()) {
parent::__construct($values, 'search_api_autocomplete_search');
}
/**
* @return SearchApiIndex
* The index this search belongs to.
*/
public function index() {
if (!isset($this->index)) {
$this->index = search_api_index_load($this->index_id);
if (!$this->index) {
$this->index = FALSE;
}
}
return $this->index;
}
/**
* @return SearchApiServer
* The server this search would at the moment be executed on.
*/
public function server() {
if (!isset($this->server)) {
if (!$this->index() || !$this->index()->server) {
$this->server = FALSE;
}
else {
$this->server = $this->index()->server();
if (!$this->server) {
$this->server = FALSE;
}
}
}
return $this->server;
}
/**
* @return boolean
* TRUE if the server this search is currently associated with supports the
* autocompletion feature; FALSE otherwise.
*/
public function supportsAutocompletion() {
return $this->server() && $this->server()->supportsFeature('search_api_autocomplete');
}
/**
* Helper method for altering a textfield form element to use autocompletion.
*/
public function alterElement(array &$element, array $fields = array()) {
if (user_access('use search_api_autocomplete') && $this->supportsAutocompletion()) {
$element['#attached']['css'][] = drupal_get_path('module', 'search_api_autocomplete') . '/search_api_autocomplete.css';
$element['#autocomplete_path'] = 'search_api_autocomplete/' . $this->machine_name . '/' . implode(' ', $fields);
}
}
/**
* Split a string with search keywords into two parts.
*
* The first part consists of all words the user has typed completely, the
* second one contains the beginning of the last, possibly incomplete word.
*
* @return array
* An array with $keys split into exactly two parts, both of which may be
* empty.
*/
public function splitKeys($keys) {
$keys = ltrim($keys);
// If there is whitespace or a quote on the right, all words have been
// completed.
if (rtrim($keys, " \t\n\r\0\x0B\"") != $keys) {
return array(rtrim($keys), '');
}
if (preg_match('/^(.*?)\s*"?([\S]*)$/', $keys, $m)) {
return array($m[1], $m[2]);
}
return array('', $keys);
}
/**
* Create the query that would be issued for this search for the complete keys.
*
* @param $complete
* A string containing the complete search keys.
* @param $incomplete
* A string containing the incomplete last search key.
*
* @return SearchApiQueryInterface
* The query that would normally be executed when only $complete was entered
* as the search keys for this search.
*/
public function getQuery($complete, $incomplete) {
$info = search_api_autocomplete_get_types($this->type);
if (empty($info['create query'])) {
return NULL;
}
$query = $info['create query']($this, $complete, $incomplete);
if ($complete && !$query->getKeys()) {
$query->keys($complete);
}
return $query;
}
}

View File

@@ -0,0 +1,14 @@
name = Search API autocomplete
description = "Adds autocomplete functionality to most searches on servers supportings this feature."
dependencies[] = search_api
core = 7.x
package = Search
files[] = search_api_autocomplete.entity.php
; Information added by drupal.org packaging script on 2012-06-22
version = "7.x-1.0-beta2+4-dev"
core = "7.x"
project = "search_api_autocomplete"
datestamp = "1340325570"

View File

@@ -0,0 +1,81 @@
<?php
/**
* @file
* Install, update and uninstall functions for the Search API autocomplete module.
*/
/**
* Implements hook_schema().
*/
function search_api_autocomplete_schema() {
$schema['search_api_autocomplete_search'] = array(
'description' => 'Stores autocomplete settings for searches on Search API indexes.',
'fields' => array(
'id' => array(
'description' => 'The primary identifier for a search.',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'machine_name' => array(
'description' => 'A string identifier for a search.',
'type' => 'varchar',
'length' => 100,
'not null' => TRUE,
),
'name' => array(
'description' => 'A human-readable name for the search.',
'type' => 'varchar',
'length' => 50,
),
'index_id' => array(
'description' => 'The {search_api_index}.machine_name this search belongs to.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
),
'type' => array(
'description' => 'The type of search, usually a module name.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
),
'enabled' => array(
'description' => 'A flag indicating whether autocompletion for this search is enabled.',
'type' => 'int',
'size' => 'tiny',
'not null' => TRUE,
'default' => 1,
),
'options' => array(
'description' => 'The options used to configure autocompletion for this search.',
'type' => 'text',
'serialize' => TRUE,
'not null' => TRUE,
),
'status' => array(
'description' => 'The exportable status of the entity.',
'type' => 'int',
'not null' => TRUE,
'default' => 0x01,
'size' => 'tiny',
),
'module' => array(
'description' => 'The name of the providing module if the entity has been defined in code.',
'type' => 'varchar',
'length' => 255,
'not null' => FALSE,
),
),
'primary key' => array('id'),
'unique keys' => array(
'machine_name' => array('machine_name'),
),
'indexes' => array(
'enabled' => array('enabled'),
),
);
return $schema;
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* @file
* Contains the SearchApiAutocompleteInterface.
*/
/**
* Interface describing the method a service class has to add to support autocompletion.
*
* Please note that this interface is purely documentational. You shouldn't, and
* can't, implement it explicitly.
*/
interface SearchApiAutocompleteInterface extends SearchApiServiceInterface {
/**
* Get autocompletion suggestions for some user input.
*
* For example, when given the user input "teach us", with "us" being
* considered incomplete, the following might be returned:
* @code
* array(
* array(
* 'prefix' => t('Did you mean:'),
* 'user_input' => 'reach us',
* ),
* array(
* 'user_input' => 'teach us',
* 'suggestion_suffix' => 'ers',
* ),
* array(
* 'user_input' => 'teach us',
* 'suggestion_suffix' => ' swimming',
* ),
* 'teach users swimming',
* );
* @endcode
*
* @param SearchApiQueryInterface $query
* A query representing the completed user input so far.
* @param SearchApiAutocompleteSearch $search
* An object containing details about the search the user is on, and
* settings for the autocompletion. See the class documentation for details.
* Especially $search->options should be checked for settings, like whether
* to try and estimate result counts for returned suggestions.
* @param string $incomplete_key
* The start of another fulltext keyword for the search, which should be
* completed. Might be empty, in which case all user input up to now was
* considered completed. Then, additional keywords for the search could be
* suggested.
* @param string $user_input
* The complete user input for the fulltext search keywords so far.
*
* @return array
* An array of suggestion. Each suggestion is either a simple string
* containing the whole suggested keywords, or an array containing the
* following keys:
* - prefix: For special suggestions, some kind of prefix describing them.
* - suggestion_prefix: A suggested prefix for the entered input.
* - user_input: The input entered by the user. Defaults to $user_input.
* - suggestion_suffix: A suggested suffix for the entered input.
* - results: If available, the estimated number of results for these keys.
* One of "suggestion_prefix" and "suggestion_suffix" has to be present, all
* other keys are optional. The search keys inserted for the suggestion will
* be a direct concatenation (no spaces in between) of "suggestion_prefix",
* "user_input" and "suggestion_suffix".
*/
public function getAutocompleteSuggestions(SearchApiQueryInterface $query, SearchApiAutocompleteSearch $search, $incomplete_key, $user_input);
}

View File

@@ -0,0 +1,208 @@
<?php
/**
* @file
* Adds autocomplete capabilities for Search API searches.
*/
// Include the files with the module-specific implementations.
require_once('search_api_autocomplete.search_api_page.inc');
require_once('search_api_autocomplete.search_api_views.inc');
/**
* Implements hook_search_api_autocomplete_types().
*
* Adds search types for search pages and views. The actual implementations lie
* in the above include files.
*/
function search_api_autocomplete_search_api_autocomplete_types() {
$types = array();
if (module_exists('search_api_page')) {
$types['search_api_page'] = array(
'name' => t('Search pages'),
'description' => t('Searches provided by the <em>Search pages</em> module.'),
'list searches' => 'search_api_autocomplete_pages_searches',
'create query' => 'search_api_autocomplete_pages_query',
);
}
if (module_exists('search_api_views')) {
$types['search_api_views'] = array(
'name' => t('Search views'),
'description' => t('Searches provided by the <em>Search views</em> module.'),
'list searches' => 'search_api_autocomplete_views_searches',
'create query' => 'search_api_autocomplete_views_query',
);
}
return $types;
}
/**
* Implements hook_menu().
*/
function search_api_autocomplete_menu() {
// Autocompletion path
$items['search_api_autocomplete/%search_api_autocomplete_search'] = array(
'title' => 'Search API autocomplete',
'page callback' => 'search_api_autocomplete_autocomplete',
'page arguments' => array(1),
'access arguments' => array('use search_api_autocomplete'),
'type' => MENU_CALLBACK,
'file' => 'search_api_autocomplete.pages.inc',
);
// Admin UI
$items['admin/config/search/search_api/index/%search_api_index/autocomplete'] = array(
'title' => 'Autocomplete',
'description' => 'Add autocompletion to searches for this index.',
'page callback' => 'drupal_get_form',
'page arguments' => array('search_api_autocomplete_admin_overview', 5),
'access arguments' => array('administer search_api'),
'weight' => -1,
'type' => MENU_LOCAL_TASK,
'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
'file' => 'search_api_autocomplete.admin.inc',
);
$items['admin/config/search/search_api/index/%/autocomplete/%search_api_autocomplete_search/edit'] = array(
'title' => 'Edit autocompletion settings',
'description' => 'Edit the autocompletion settings of a search.',
'page callback' => 'drupal_get_form',
'page arguments' => array('search_api_autocomplete_admin_search_edit', 7),
'access arguments' => array('administer search_api'),
'file' => 'search_api_autocomplete.admin.inc',
);
$items['admin/config/search/search_api/index/%/autocomplete/%search_api_autocomplete_search/delete'] = array(
'title' => 'Delete autocompletion settings',
'description' => 'Delete the autocompletion settings of a search.',
'page callback' => 'drupal_get_form',
'page arguments' => array('search_api_autocomplete_admin_search_delete', 7),
'access arguments' => array('administer search_api'),
'file' => 'search_api_autocomplete.admin.inc',
);
return $items;
}
/**
* Implements hook_theme().
*/
function search_api_autocomplete_theme() {
$themes['search_api_autocomplete_suggestion'] = array(
'variables' => array(
'prefix' => NULL,
'suggestion_prefix' => '',
'user_input' => '',
'suggestion_suffix' => '',
'results' => NULL,
),
'file' => 'search_api_autocomplete.pages.inc',
);
return $themes;
}
/**
* Implements hook_entity_info().
*/
function search_api_autocomplete_entity_info() {
$info['search_api_autocomplete_search'] = array(
'label' => t('Autocomplete search'),
'controller class' => 'EntityAPIControllerExportable',
'entity class' => 'SearchApiAutocompleteSearch',
'base table' => 'search_api_autocomplete_search',
'uri callback' => 'search_api_autocomplete_search_url',
'module' => 'search_api_autocomplete',
'exportable' => TRUE,
'entity keys' => array(
'id' => 'id',
'name' => 'machine_name',
'label' => 'name',
),
);
return $info;
}
/**
* Implements hook_permission().
*/
function search_api_autocomplete_permission() {
return array(
'use search_api_autocomplete' => array(
'title' => t('Use search autocomplete'),
),
);
}
/**
* Implements hook_search_api_index_delete().
*/
function search_api_autocomplete_search_api_index_delete(SearchApiIndex $index) {
if (!$index->hasStatus(ENTITY_IN_CODE)) {
$ids = db_query('SELECT id FROM {search_api_autocomplete_search} WHERE index_id = :id',
array(':id' => $index->machine_name))->fetchCol();
if ($ids) {
entity_delete_multiple('search_api_autocomplete_search', $ids);
}
}
}
/**
* Get information about all search types, or a specific one.
*
* @param $type
* (optional) The name of a type.
*
* @return
* If $type was not given, an array containing information about all search
* types. Otherwise, either information about the specified type, or NULL if
* the type is not known.
*
* @see hook_search_api_autocomplete_types()
*/
function search_api_autocomplete_get_types($type = NULL) {
$types = &drupal_static(__FUNCTION__);
if (!isset($types)) {
$types = module_invoke_all('search_api_autocomplete_types');
}
if (isset($type)) {
return isset($types[$type]) ? $types[$type] : NULL;
}
return $types;
}
/**
* Loads an autocomplete search entity.
*
* @param $id
* Either the ID or machine name of an autocomplete search.
* @param $reset
* Whether to reset the internal cache.
*
* @return SearchApiAutocompleteSearch
* The specified autocomplete search entity, or FALSE if it doesn't exist.
*/
function search_api_autocomplete_search_load($id, $reset = FALSE) {
$ret = search_api_autocomplete_search_load_multiple(array($id), array(), $reset);
return $ret ? reset($ret) : FALSE;
}
/**
* Loads autocomplete search entities.
*
* @param $ids
* An array of IDs or machine names, or FALSE to load all searches.
* @param $conditions
* An associative array of conditions on the {search_api_autocomplete_search}
* table.
* @param $reset
* Whether to reset the internal cache.
*
* @return array
* An array of all autocomplete search entities that meet the criteria.
*
* @see entity_load()
*/
function search_api_autocomplete_search_load_multiple($ids = FALSE, array $conditions = array(), $reset = FALSE) {
return entity_load_multiple_by_name('search_api_autocomplete_search', $ids, $conditions, $reset);
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* @file
* Contains page callbacks and theme functions for the frontend UI.
*/
/**
* Page callback for getting autocomplete suggestions.
*/
function search_api_autocomplete_autocomplete(SearchApiAutocompleteSearch $search, $fields, $keys = '') {
$ret = array();
if ($search->supportsAutocompletion()) {
$server = $search->server();
list($complete, $incomplete) = $search->splitKeys($keys);
$keys = preg_replace('/\s+/', ' ', trim($keys));
$query = $search->getQuery($complete, $incomplete);
if ($query) {
// @todo Maybe make range configurable?
$query->range(0, 10);
$query->setOption('search id', 'search_api_autocomplete');
if ($fields) {
$fields = explode(' ', $fields);
$query->fields($fields);
}
$query->preExecute();
$suggestions = $server->getAutocompleteSuggestions($query, $search, $incomplete, $keys);
if ($suggestions) {
foreach ($suggestions as $suggestion) {
// Convert suggestion strings into an array.
if (is_string($suggestion)) {
$pos = strpos($suggestion, $keys);
if ($pos === FALSE) {
$suggestion = array(
'user_input' => '',
'suggestion_suffix' => $suggestion,
);
}
else {
$suggestion = array(
'suggestion_prefix' => substr($suggestion, 0, $pos),
'user_input' => $keys,
'suggestion_suffix' => substr($suggestion, $pos + strlen($keys)),
);
}
}
// Add defaults.
$suggestion += array(
'prefix' => NULL,
'suggestion_prefix' => '',
'user_input' => $keys,
'suggestion_suffix' => '',
'results' => NULL,
);
if (empty($search->options['results'])) {
unset($suggestion['results']);
}
$key = $suggestion['suggestion_prefix'] . $suggestion['user_input'] . $suggestion['suggestion_suffix'];
if (!isset($ret[$key])) {
$ret[$key] = theme('search_api_autocomplete_suggestion', $suggestion);
}
}
}
}
}
drupal_json_output($ret);
}
/**
*
*
* @param array $variables
* An associative array containing:
* - prefix: For special suggestions, some kind of prefix describing them.
* - suggestion_prefix: A suggested prefix for the entered input.
* - user_input: The input entered by the user.
* - suggestion_suffix: A suggested suffix for the entered input.
* - results: If available, the estimated number of results for these keys.
*/
function theme_search_api_autocomplete_suggestion(array $variables) {
extract($variables);
$output = '';
if ($prefix) {
$output .= "<span class=\"autocomplete-suggestion-note\">$prefix</span> ";
}
if ($suggestion_prefix) {
$output .= "<span class=\"autocomplete-suggestion-prefix\">$suggestion_prefix</span>";
}
if ($user_input) {
$output .= "<span class=\"autocomplete-user-input\">$user_input</span>";
}
if ($suggestion_suffix) {
$output .= "<span class=\"autocomplete-suggestion-suffix\">$suggestion_suffix</span>";
}
if ($results) {
$output .= " <span class=\"autocomplete-suggestion-results\">$results</span>";
}
return "<div class=\"search-api-autocomplete-suggestion\">$output</div>";
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* @file
* Contains code for integrating with the "Search pages" module.
*/
/**
* Implements hook_form_FORM_ID_alter().
*
* Adds autocompletion to the keywords field on search pages, if enabled by the
* user.
*/
function search_api_autocomplete_form_search_api_page_search_form_alter(array &$form, array &$form_state) {
if (isset($form['form'])) {
$form = &$form['form'];
}
$id = 'search_api_page_' . $form['id']['#value'];
$search = search_api_autocomplete_search_load($id);
if ($search && $search->enabled) {
$search->alterElement($form['keys_' . $form['id']['#value']]);
}
}
/**
* Returns a list of search pages for the given index.
*
* @param SearchApiIndex $index
* The index whose searches should be returned.
*
* @return array
* An array of searches, keyed by their machine name. The values are arrays
* with the following keys:
* - name: A human-readable name for this search.
* - options: (optional) An array of options to use for this search.
* Type-specific options should go into the "custom" nested key in these
* options.
*/
function search_api_autocomplete_pages_searches(SearchApiIndex $index) {
$ret = array();
foreach (search_api_page_load_multiple(FALSE, array('index_id' => $index->machine_name)) as $page) {
$id = 'search_api_page_' . $page->id;
$ret[$id]['name'] = $page->name;
$ret[$id]['options']['custom']['page_id'] = $page->id;
}
return $ret;
}
/**
* Create the query that would be issued for the given search for the complete keys.
*
* @param SearchApiAutocompleteSearch $search
* The search for which to create the query.
* @param $complete
* A string containing the complete search keys.
* @param $incomplete
* A string containing the incomplete last search key.
*
* @return SearchApiQueryInterface
* The query that would normally be executed when only $complete was entered
* as the search keys for the given search.
*/
function search_api_autocomplete_pages_query(SearchApiAutocompleteSearch $search, $complete, $incomplete) {
$page = search_api_page_load($search->options['custom']['page_id']);
// Copied from search_api_page_search_execute().
$query = search_api_query($page->index_id, array('parse mode' => $page->options['mode']))
->keys($complete);
if (!empty($page->options['fields'])) {
$query->fields($page->options['fields']);
}
return $query;
}

View File

@@ -0,0 +1,104 @@
<?php
/**
* @file
* Contains code for integrating with the "Search views" module.
*/
/**
* Implements hook_form_FORM_ID_alter().
*
* Adds autocompletion to input fields for fulltext keywords on views with
* exposed filters.
*/
function search_api_autocomplete_form_views_exposed_form_alter(array &$form, array &$form_state) {
$view = $form_state['view'];
if (substr($view->base_table, 0, 17) != 'search_api_index_') {
return;
}
$search_id = 'search_api_views_' . $view->name;
$search = search_api_autocomplete_search_load($search_id);
if (empty($search->enabled)) {
return;
}
$index_id = substr($view->base_table, 17);
$index = search_api_index_load($index_id);
if (empty($index->options['fields'])) {
return;
}
$fields = $index->getFulltextFields(TRUE);
// Add the "Search: Fulltext search" filter as another text field.
$fields[] = 'search_api_views_fulltext';
// We need the _entity_views_field_identifier() function to translate Search
// API field names into Views identifiers.
module_load_include('views.inc', 'entity', 'views/entity');
foreach ($fields as $search_field) {
$field = _entity_views_field_identifier($search_field, array());
if (!empty($view->filter[$field]->options['expose']['identifier'])) {
$key = $view->filter[$field]->options['expose']['identifier'];
if (isset($form[$key]) && $form[$key]['#type'] == 'textfield') {
if ($field == 'search_api_views_fulltext') {
$fields = $view->filter[$field]->options['fields'];
}
else {
$fields = array($search_field);
}
$search->alterElement($form[$key], $fields);
}
}
}
}
/**
* Returns a list of search views for the given index.
*
* @param SearchApiIndex $index
* The index whose searches should be returned.
*
* @return array
* An array of searches, keyed by their machine name. The values are arrays
* with the following keys:
* - name: A human-readable name for this search.
* - options: (optional) An array of options to use for this search.
* Type-specific options should go into the "custom" nested key in these
* options.
*/
function search_api_autocomplete_views_searches(SearchApiIndex $index) {
$ret = array();
foreach (views_get_all_views() as $name => $view) {
if (substr($view->base_table, 0, 17) == 'search_api_index_') {
// @todo Check whether there is an exposed fulltext filter
$ret['search_api_views_' . $name] = array(
'name' => $view->human_name,
);
}
}
return $ret;
}
/**
* Create the query that would be issued for the given search for the complete keys.
*
* @param SearchApiAutocompleteSearch $search
* The search for which to create the query.
* @param $complete
* A string containing the complete search keys.
* @param $incomplete
* A string containing the incomplete last search key.
*
* @return SearchApiQueryInterface
* The query that would normally be executed when only $complete was entered
* as the search keys for the given search.
*/
function search_api_autocomplete_views_query(SearchApiAutocompleteSearch $search, $complete, $incomplete) {
$views_id = substr($search->machine_name, 17);
$view = views_get_view($views_id);
// @todo Let users select display
$view->set_display();
// @todo Determine arguments
$view->pre_execute();
$view->build();
$query = $view->query->getSearchApiQuery();
$query->keys($complete);
return $query;
}

View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,59 @@
INSTALLATION
Simply save this module's subdir in your contrib module directory,
and enable the module.
USAGE
Simply configure your search api index(es) to index the field
"Multilingual full text". Now, all of your selected entity's translations will
be included in your index(es) and the search.
MODULE DESCRIPTION
Search API Entity Translation is a minimalist approach of making multilingual
content managed via entity translations searchable via Search API.
The current approach simply offers a new search API field named
"Multilingual full text" which indexes all of your entity translations.
This is, of course, not very intelligent (since the translations/languages of
content cannot be properly distinguished in the search, let alone searched
language _specificly_ or independently) - but it's a first simply approach.
Search API Entity Translation is written for Drupal 7 and used in production
environments. It is currently only thouroughly tested and used with node based
indexes, though.
Requirements:
* Search API is obviously required, as well as
a compatible search module (e.g. apachesolr, search_api).
Similar projects:
* Currently (2012-01-02) there does not seem to be other similar modules.
TODOS
* Make different language versions of a content distinguishable for search.
MODULE URL
More information and issues, see the module page, currently at:
http://drupal.org/project/search_api_et

View File

@@ -0,0 +1,13 @@
core = "7.x"
dependencies[] = "search_api"
dependencies[] = "entity_translation"
description = "Add support to search API for searching multilingual content managed via entity translation module."
name = "Search API Entity Translation"
package = Search
; Information added by drupal.org packaging script on 2012-02-08
version = "7.x-1.x-dev"
core = "7.x"
project = "search_api_et"
datestamp = "1328704472"

View File

@@ -0,0 +1,105 @@
<?php
/**
* @file
* Offers simple support for search api for searching in multilingual nodes
* translated with the entity translation module.
*
* ToDos:
* - Make different language versions of a content distinguishable for search.
*/
/**
* Implements hook_entity_property_info_alter().
*
* Adds entity property for handling
* field-translation based multi-language indexing
*/
function search_api_et_entity_property_info_alter(&$info) {
foreach (search_api_et_entity_types() as $etype => $einfo) {
$info[$etype]['properties']['unified_fulltext'] = array(
'type' => 'text',
'label' => t('Multilingual full text (all languages via entity translation)'),
'sanitized' => TRUE,
'getter callback' => 'search_api_et_fulltext_get',
);
}
}
/**
* Getter callback for fulltext property.
*
* Concatenate the entity rendering for all its language versions/translations.
*/
function search_api_et_fulltext_get($item, $options, $name, $type, $info) {
$view_mode = variable_get('search_api_et_fulltext_get_viewmode_' . $type, 'search_index');
// If no translations are managed for this entity (i.e. ET is not activated),
// do nothing.
if (!is_array($item->translations->data)) {
return;
}
// Iterate through the $item->translations to render the entity in each lang.
$fulltext = '';
foreach ($item->translations->data as $langcode => $translation) {
if ($translation['status']) {
$render = entity_view($type, array($item), $view_mode, $langcode);
$context = array('item' => $item, 'options' => $options, 'name' => $name, 'type' => $type, 'view_mode' => $view_mode, 'language' => $langcode);
// Invoke some hooks, before or after the rendering, for alterations.
drupal_alter('search_api_et_fulltext_prerender', $render, $context);
$render = drupal_render($render);
drupal_alter('search_api_et_fulltext_postrender', $render, $context);
$fulltext .= $render;
}
}
// watchdog('search_api_et', $fulltext, null, WATCHDOG_INFO);
return $fulltext;
}
/**
* Implements hook_entity_translation_save().
*
* Trigger re-indexing of content when translation changes.
*/
function search_api_et_entity_translation_save($entity_type, $entity, $langcode) {
search_api_entity_update($entity, $entity_type);
}
/**
* Implements hook_entity_info_alter().
*
* (re-) declare search_index view mode
* (which is not available when core search is disabled (as it can be here)
*/
function search_api_et_entity_info_alter(&$entity_info) {
foreach (search_api_et_entity_types() as $etype => $einfo) {
$entity_info[$etype]['view modes']['search_index']
= array(
'label' => t('Search index'),
'custom settings' => FALSE,
);
}
}
/**
* Helper function to list all entity types supported by entity translation.
*
*/
function search_api_et_entity_types() {
$entity_types = array();
foreach (entity_get_info() as $entity_type => $entity_data) {
if (entity_translation_enabled($entity_type)) {
$entity_types[$entity_type] = $entity_data;
}
}
return $entity_types;
}
/* END OF FILE marker for fewer merge conflicts. */

View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,38 @@
Multi-index searches
--------------------
This module allows you to create search queries on multiple indexes that lie on
the same server. The only thing you'll need is a search service class that
supports the "search_api_multi" feature. Currently, only the "Solr search"
supports this.
Information for users
---------------------
Enable the Search views (search_api_views) module along with this one to make
instant use of the multi-index searching facilities. You'll get a new base table
in Views for each server supporting the "search_api_multi" feature.
You can then add filters, arguments, fields and sorts (although the last one
might work rather poorly, depending on the sorted field and the implementation)
from all enabled indexes on this server.
- Issues
If you find any bugs or shortcomings while using this module, please file an
issue in the project's issue queue [1].
[1] http://drupal.org/project/issues/search_api_multi
Information for developers
--------------------------
If you are the developer of a SearchApiServiceInterface implementation and want
to support searches on multiple indexes with your service class, too, you'll
have to support the "search_api_multi" feature by implementing the
SearchApiMultiServiceInterface interface documented in
search_api_multi.service.inc.

View File

@@ -0,0 +1,25 @@
<?php
/**
* @file
* Hooks provided by the Search API multi-index searches module.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Lets modules alter a search query before executing it.
*
* @param SearchApiMultiQueryInterface $query
* The executed search query.
*/
function hook_search_api_multi_query_alter(SearchApiMultiQueryInterface $query) {
$query->condition('#', 0, '!=');
}
/**
* @} End of "addtogroup hooks".
*/

View File

@@ -0,0 +1,19 @@
name = Multi-index searches
description = Small extension for the Search API that allows searches across several indexes on the same server.
dependencies[] = search_api
core = 7.x
package = Search
files[] = search_api_multi.query.inc
files[] = search_api_multi.service.inc
files[] = views/handler_argument_fulltext.inc
files[] = views/handler_filter_fulltext.inc
files[] = views/query.inc
; Information added by drupal.org packaging script on 2012-06-22
version = "7.x-1.0-beta3+2-dev"
core = "7.x"
project = "search_api_multi"
datestamp = "1340325572"

View File

@@ -0,0 +1,148 @@
<?php
/**
* Implements hook_views_api().
*/
function search_api_multi_views_api() {
if (module_exists('search_api_views')) {
return array(
'api' => '3.0-alpha1',
'path' => drupal_get_path('module', 'search_api_multi') . '/views',
);
}
}
/**
* Implements hook_search_api_server_enabled().
*/
function search_api_multi_search_api_server_enabled(array $servers) {
if (!module_exists('search_api_views')) {
return;
}
foreach ($servers as $server) {
if ($server->supportsFeature('search_api_multi')) {
// Make the new server(s) available for views.
views_invalidate_cache();
break;
}
}
}
/**
* Implements hook_search_api_server_update().
*/
function search_api_multi_search_api_server_update(SearchApiServer $server) {
if (module_exists('search_api_views') && $server->supportsFeature('search_api_multi') && !$server->enabled && $server->original->enabled) {
_search_api_multi_server_unavailable($server);
}
}
/**
* Implements hook_search_api_server_delete().
*/
function search_api_multi_search_api_server_delete(SearchApiServer $server) {
if (module_exists('search_api_views') && $server->supportsFeature('search_api_multi')) {
_search_api_multi_server_unavailable($server);
}
}
/**
* Function for reacting to a disabled or deleted search server.
*/
function _search_api_multi_server_unavailable(SearchApiServer $server) {
$names = array();
$table = 'search_api_server_' . $server->machine_name;
foreach (views_get_all_views() as $name => $view) {
if (empty($view->disabled) && $view->base_table == $table) {
$names[] = $name;
// @todo: if ($server_deleted) $view->delete()?
}
}
if ($names) {
views_invalidate_cache();
drupal_set_message(t('The following views were using the server %name: @views. You should disable or delete them.', array('%name' => $server->name, '@views' => implode(', ', $names))), 'warning');
}
}
/**
* Creates a multi-index search query on a specified search server.
*
* @param $id
* The ID or machine name of the index to execute the search on.
* @param array $options
* Associative array of options configuring this query. Recognized options
* are:
* - conjunction: The type of conjunction to use for this query - either
* 'AND' or 'OR'. 'AND' by default. This only influences the search keys,
* filters will always use AND by default.
* - 'parse mode': The mode with which to parse the $keys variable, if it
* is set and not already an array. See SearchApiMultiQuery::parseModes() for
* recognized parse modes.
* - languages: The languages to search for, as an array of language IDs.
* If not specified, all languages will be searched. Language-neutral
* content (LANGUAGE_NONE) is always searched.
* - offset: The position of the first returned search results relative to
* the whole result on the server.
* - limit: The maximum number of search results to return. -1 means no
* limit.
* - 'filter class': Can be used to change the SearchApiQueryFilterInterface
* implementation to use.
* - 'search id': A string that will be used as the identifier when storing
* this search in the static cache.
* All options are optional.
*
* @return SearchApiMultiQueryInterface
* An object for searching on the specified server.
*/
function search_api_multi_query($id, array $options = array()) {
$server = search_api_server_load($id);
if (!$server) {
throw new SearchApiException(t('Unknown server with ID @id.', array('@id' => $id)));
}
if (!$server->supportsFeature('search_api_multi')) {
throw new SearchApiException(t("The search server @name doesn't support multi-index searches.", array('@name' => $server->name)));
}
return $server->queryMultiple($options);
}
/**
* Static store for the multi-index searches executed on the current page. Can
* either be used to store an executed search, or to retrieve a previously
* stored search.
*
* @param $search_id
* For pages displaying multiple searches, an optional ID identifying the
* search in questions. When storing a search, this is filled automatically,
* unless it is manually set.
* @param SearchApiMultiQuery $query
* When storing an executed search, the query that was executed. NULL
* otherwise.
* @param array $results
* When storing an executed search, the returned results as specified by
* SearchApiMultiQueryInterface::execute(). An empty array, otherwise.
*
* @return array
* If a search with the specified ID was executed, an array containing
* ($query, $results) as used in this function's parameters. If $search_id is
* NULL, an array of all executed searches will be returned, keyed by ID.
*/
function search_api_multi_current_search($search_id = NULL, SearchApiMultiQuery $query = NULL, array $results = array()) {
$searches = &drupal_static(__FUNCTION__, array());
if (isset($query)) {
if (!isset($search_id)) {
$search_id = $query->getOption('search id');
}
$base = $search_id;
$i = 0;
while (isset($searches[$search_id])) {
$search_id = $base . '-' . ++$i;
}
$searches[$search_id] = array($query, $results);
}
if (isset($searches[$search_id])) {
return $searches[$search_id];
}
return $searches;
}

View File

@@ -0,0 +1,863 @@
<?php
/**
* Interface representing a search query on multiple Search API indexes on the
* same server. The server has to support the "search_api_multi" feature.
*
* For discerning from which index a certain field should be used (for filtering
* or specifying the fulltext fields, fr instance), all field identifiers have
* to be prefixed with their index' machine name, seperated by a colon.
* For example, to filter on the "author:name" field from the index with the
* machine name "default_node_index", use "default_node_index:author:name" as
* the identifier.
*
* Methods not returning something else will return the object itself, so calls
* can be chained.
*/
interface SearchApiMultiQueryInterface {
/**
* Constructor used when creating SearchApiMultiQueryInterface objects.
*
* @param SearchApiServer $server
* The server this search will be executed on.
* @param array $options
* Associative array of options configuring this query. Recognized options
* are:
* - conjunction: The type of conjunction to use for this query - either
* 'AND' or 'OR'. 'AND' by default. This only influences the search keys,
* filters will always use AND by default.
* - 'parse mode': The mode with which to parse the $keys variable, if it
* is set and not already an array. See SearchApiMultiQuery::parseModes() for
* recognized parse modes.
* - languages: The languages to search for, as an array of language IDs.
* If not specified, all languages will be searched. Language-neutral
* content (LANGUAGE_NONE) is always searched.
* - offset: The position of the first returned search results relative to
* the whole result on the server.
* - limit: The maximum number of search results to return. -1 means no
* limit.
* - 'filter class': Can be used to change the SearchApiQueryFilterInterface
* implementation to use.
* - 'search id': A string that will be used as the identifier when storing
* this search in the static cache.
* All options are optional.
*
* @throws SearchApiException
* If a search with these options won't be possible.
*/
public function __construct(SearchApiServer $server, array $options = array());
/**
* @return array
* An associative array of parse modes recognized by objects of this class.
* The keys are the parse modes' ids, values are associative arrays
* containing the following entries:
* - name: The translated name of the parse mode.
* - description: (optional) A translated text describing the parse mode.
*/
public function parseModes();
/**
* Method for creating a filter to use with this query object.
*
* @param $conjunction
* The conjunction to use for the filter - either 'AND' or 'OR'.
*
* @return SearchApiQueryFilterInterface
* A filter object that is set to use the specified conjunction.
*/
public function createFilter($conjunction = 'AND');
/**
* Sets the keys to search for. If this method is not called on the query
* before execution, this will be a filter-only query.
*
* @param $keys
* A string with the unparsed search keys, or NULL to use no search keys.
*
* @return SearchApiMultiQueryInterface
* The called object.
*/
public function keys($keys = NULL);
/**
* Sets the fields that will be searched for the search keys. If this is not
* called, all fulltext fields should be searched.
*
* @param array $fields
* An array containing fulltext fields that should be searched.
*
* @throws SearchApiException
* If one of the fields isn't of type "text".
*
* @return SearchApiMultiQueryInterface
* The called object.
*/
public function fields(array $fields);
/**
* Adds a subfilter to this query's filter.
*
* @param SearchApiQueryFilterInterface $filter
* A SearchApiQueryFilter object that should be added as a subfilter.
*
* @return SearchApiMultiQueryInterface
* The called object.
*/
public function filter(SearchApiQueryFilterInterface $filter);
/**
* Add a new ($field $operator $value) condition filter.
*
* @param $field
* The field to filter on. Either a field specification as detailed in the
* class comment, or the special field "search_api_multi_index" which means
* a filter on the searched indexes.
* @param $value
* The value the field should have (or be related to by the operator).
* @param $operator
* The operator to use for checking the constraint. The following operators
* are supported for primitive types: "=", "<>", "<", "<=", ">=", ">". They
* have the same semantics as the corresponding SQL operators.
* If $field is a fulltext field, $operator can only be "=" or "<>", which
* are in this case interpreted as "contains" or "doesn't contain",
* respectively.
* If $value is NULL, $operator also can only be "=" or "<>", meaning the
* field must have no or some value, respectively.
*
* @return SearchApiMultiQueryInterface
* The called object.
*/
public function condition($field, $value, $operator = '=');
/**
* Add a sort directive to this search query. If no sort is manually set, the
* results will be sorted descending by relevance.
*
* How sorts on index-specific fields are handled may differ between service
* backends.
*
* @param $field
* The field to sort by. The special field "search_api_relevance" may be
* used to sort by relevance.
* @param $order
* The order to sort items in - either 'ASC' or 'DESC'.
*
* @throws SearchApiException
* If the field is multi-valued or of a fulltext type.
*
* @return SearchApiMultiQueryInterface
* The called object.
*/
public function sort($field, $order = 'ASC');
/**
* Adds a range of results to return. This will be saved in the query's
* options. If called without parameters, this will remove all range
* restrictions previously set.
*
* @param $offset
* The zero-based offset of the first result returned.
* @param $limit
* The number of results to return.
*
* @return SearchApiMultiQueryInterface
* The called object.
*/
public function range($offset = NULL, $limit = NULL);
/**
* Executes this search query.
*
* @return array
* An associative array containing the search results. The following keys
* are standardized:
* - 'result count': The overall number of results for this query, without
* range restrictions. Might be approximated, for large numbers.
* - results: An array of results, ordered as specified. The array keys are
* the items' IDs, values are arrays containing the following keys:
* - id: The item's ID.
* - index_id: The machine name of the index this item was found on.
* - score: A float measuring how well the item fits the search.
* - entity (optional): If set, the fully loaded result item. This field
* should always be used by modules using search results, to avoid
* duplicate item loads.
* - excerpt (optional): If set, an HTML text containing highlighted
* portions of the fulltext that match the query.
* - warnings: A numeric array of translated warning messages that may be
* displayed to the user.
* - ignored: A numeric array of search keys that were ignored for this
* search (e.g., because of being too short or stop words).
* - performance: An associative array with the time taken (as floats, in
* seconds) for specific parts of the search execution:
* - complete: The complete runtime of the query.
* - hooks: Hook invocations and other client-side preprocessing.
* - preprocessing: Preprocessing of the service class.
* - execution: The actual query to the search server, in whatever form.
* - postprocessing: Preparing the results for returning.
* Additional metadata may be returned in other keys. Only 'result count'
* and 'result' always have to be set, all other entries are optional.
*/
public function execute();
/**
* @return SearchApiServer
* The search server this query should be executed on.
*/
public function getServer();
/**
* @return array
* An array of SearchApiIndex objects representing all indexes that will be
* searched.
*/
public function getIndexes();
/**
* @return
* This object's search keys - either a string or an array specifying a
* complex search expression.
* An array will contain a '#conjunction' key specifying the conjunction
* type, and search strings or nested expression arrays at numeric keys.
* Additionally, a '#negation' key might be present, which means unless it
* maps to a FALSE value that the search keys contained in that array
* should be negated, i.e. not be present in returned results.
*/
public function &getKeys();
/**
* @return
* The unprocessed search keys, exactly as passed to this object. Has the
* same format as getKeys().
*/
public function getOriginalKeys();
/**
* @return array
* An array containing the fields that should be searched for the search
* keys.
*/
public function &getFields();
/**
* @return SearchApiQueryFilterInterface
* This object's associated filter object.
*/
public function getFilter();
/**
* @return array
* An array specifying the sort order for this query. Array keys are the
* field names in order of importance, the values are the respective order
* in which to sort the results according to the field.
*/
public function &getSort();
/**
* @param $name string
* The name of an option.
*
* @return mixed
* The value of the option with the specified name, if set. NULL otherwise.
*/
public function getOption($name);
/**
* @param string $name
* The name of an option.
* @param mixed $value
* The new value of the option.
*
* @return The option's previous value.
*/
public function setOption($name, $value);
/**
* @return array
* An associative array of query options.
*/
public function &getOptions();
}
/**
* Standard implementation of SearchApiMultiQueryInterface.
*/
class SearchApiMultiQuery implements SearchApiMultiQueryInterface {
/**
* The server.
*
* @var SearchApiServer
*/
protected $server;
/**
* The searched indexes.
*
* @var array
*/
protected $indexes;
/**
* The search keys. If NULL, this will be a filter-only search.
*
* @var mixed
*/
protected $keys;
/**
* The unprocessed search keys, as passed to the keys() method.
*
* @var mixed
*/
protected $orig_keys;
/**
* The fields that will be searched for the keys.
*
* @var array
*/
protected $fields;
/**
* The search filter associated with this query.
*
* @var SearchApiQueryFilterInterface
*/
protected $filter;
/**
* The sort associated with this query.
*
* @var array
*/
protected $sort;
/**
* Search options configuring this query.
*
* @var array
*/
protected $options;
/**
* Count for providing a unique ID.
*/
protected static $count = 0;
/**
* Constructor for SearchApiMultiQuery objects.
*
* @param SearchApiIndex $server
* The server the query should be executed on.
* @param array $options
* Associative array of options configuring this query. Recognized options
* are:
* - conjunction: The type of conjunction to use for this query - either
* 'AND' or 'OR'. 'AND' by default. This only influences the search keys,
* filters will always use AND by default.
* - 'parse mode': The mode with which to parse the $keys variable, if it
* is set and not already an array. See SearchApiMultiQuery::parseModes() for
* recognized parse modes.
* - languages: The languages to search for, as an array of language IDs.
* If not specified, all languages will be searched. Language-neutral
* content (LANGUAGE_NONE) is always searched.
* - offset: The position of the first returned search results relative to
* the whole result on the server.
* - limit: The maximum number of search results to return. -1 means no
* limit.
* - 'filter class': Can be used to change the SearchApiQueryFilterInterface
* implementation to use.
* - 'search id': A string that will be used as the identifier when storing
* this search in the Search API's static cache.
* All options are optional.
*
* @throws SearchApiException
* If a search with these options won't be possible.
*/
public function __construct(SearchApiServer $server, array $options = array()) {
if (!$server->supportsFeature('search_api_multi')) {
throw new SearchApiException(t("The search server @name doesn't support multi-index searches.", array('@name' => $server->name)));
}
$this->server = $server;
$this->indexes = search_api_index_load_multiple(FALSE, array('server' => $server->machine_name, 'enabled' => 1));
if (empty($this->indexes)) {
throw new SearchApiException(t('There are no enabled indexes on the searched server @name.', array('@name' => $server->name)));
}
foreach ($this->indexes as $index) {
if (empty($index->options['fields'])) {
throw new SearchApiException(t("Can't search an index which hasn't got any fields defined."));
}
if (isset($options['parse mode'])) {
$modes = $this->parseModes();
if (!isset($modes[$options['parse mode']])) {
throw new SearchApiException(t('Unknown parse mode: @mode.', array('@mode' => $options['parse mode'])));
}
}
}
$this->options = $options + array(
'conjunction' => 'AND',
'parse mode' => 'terms',
'filter class' => 'SearchApiQueryFilter',
'search id' => __CLASS__,
);
$this->filter = $this->createFilter('AND');
$this->sort = array();
}
/**
* @return array
* An associative array of parse modes recognized by objects of this class.
* The keys are the parse modes' ids, values are associative arrays
* containing the following entries:
* - name: The translated name of the parse mode.
* - description: (optional) A translated text describing the parse mode.
*/
public function parseModes() {
$modes['direct'] = array(
'name' => t('Direct query'),
'description' => t("Don't parse the query, just hand it to the search server unaltered. " .
"Might fail if the query contains syntax errors in regard to the specific server's query syntax."),
);
$modes['single'] = array(
'name' => t('Single term'),
'description' => t('The query is interpreted as a single keyword, maybe containing spaces or special characters.'),
);
$modes['terms'] = array(
'name' => t('Multiple terms'),
'description' => t('The query is interpreted as multiple keywords seperated by spaces. ' .
'Keywords containing spaces may be "quoted". Quoted keywords must still be seperated by spaces.'),
);
return $modes;
}
/**
* Parses the keys string according to the $mode parameter.
*
* @return
* The parsed keys. Either a string or an array.
*/
protected function parseKeys($keys, $mode) {
if ($keys == NULL || is_array($keys)) {
return $keys;
}
$keys = '' . $keys;
switch ($mode) {
case 'direct':
return $keys;
case 'single':
return array('#conjunction' => $this->options['conjunction'], $keys);
case 'terms':
$ret = explode(' ', $keys);
$ret['#conjunction'] = $this->options['conjunction'];
$quoted = FALSE;
$str = '';
foreach ($ret as $k => $v) {
if (!$v) {
continue;
}
if ($quoted) {
if ($v[drupal_strlen($v)-1] == '"') {
$v = substr($v, 0, -1);
$str .= ' ' . $v;
$ret[$k] = $str;
$quoted = FALSE;
}
else {
$str .= ' ' . $v;
unset($ret[$k]);
}
}
elseif ($v[0] == '"') {
$len = drupal_strlen($v);
if ($len > 1 && $v[$len-1] == '"') {
$ret[$k] = substr($v, 1, -1);
}
else {
$str = substr($v, 1);
$quoted = TRUE;
unset($ret[$k]);
}
}
}
if ($quoted) {
$ret[] = $str;
}
return array_filter($ret);
}
}
/**
* Method for creating a filter to use with this query object.
*
* @param $conjunction
* The conjunction to use for the filter - either 'AND' or 'OR'.
*
* @return SearchApiQueryFilterInterface
* A filter object that is set to use the specified conjunction.
*/
public function createFilter($conjunction = 'AND') {
$filter_class = $this->options['filter class'];
return new $filter_class($conjunction);
}
/**
* Sets the keys to search for. If this method is not called on the query
* before execution, this will be a filter-only query.
*
* @param $keys
* A string with the unparsed search keys, or NULL to use no search keys.
*
* @return SearchApiMultiQuery
* The called object.
*/
public function keys($keys = NULL) {
$this->orig_keys = $keys;
if (isset($keys)) {
$this->keys = $this->parseKeys($keys, $this->options['parse mode']);
}
else {
$this->keys = NULL;
}
return $this;
}
/**
* Sets the fields that will be searched for the search keys. If this is not
* called, all fulltext fields should be searched.
*
* @param array $fields
* An array containing fulltext fields that should be searched.
*
* @throws SearchApiException
* If one of the fields isn't of type "text".
*
* @return SearchApiMultiQueryInterface
* The called object.
*/
public function fields(array $fields) {
foreach ($fields as $spec) {
list($index_id, $field) = explode(':', $spec, 2);
if (!isset($this->indexes[$index_id])) {
throw new SearchApiException(t("Trying to search on fields of index @index which doesn't lie on server @server.", array('@index' => $index_id, '@server' => $this->server->name)));
}
if (empty($this->indexes[$index_id]->options['fields'][$field]) || !search_api_is_text_type($this->indexes[$index_id]->options['fields'][$field]['type'])) {
throw new SearchApiException(t('Trying to search on field @field which is no indexed fulltext field.', array('@field' => $field)));
}
}
$this->fields = $fields;
return $this;
}
/**
* Adds a subfilter to this query's filter.
*
* @param SearchApiQueryFilterInterface $filter
* A SearchApiQueryFilter object that should be added as a subfilter.
*
* @return SearchApiMultiQuery
* The called object.
*/
public function filter(SearchApiQueryFilterInterface $filter) {
$this->filter->filter($filter);
return $this;
}
/**
* Add a new ($field $operator $value) condition filter.
*
* @param $field
* The field to filter on, e.g. 'title'.
* @param $value
* The value the field should have (or be related to by the operator).
* @param $operator
* The operator to use for checking the constraint. The following operators
* are supported for primitive types: "=", "<>", "<", "<=", ">=", ">". They
* have the same semantics as the corresponding SQL operators.
* If $field is a fulltext field, $operator can only be "=" or "<>", which
* are in this case interpreted as "contains" or "doesn't contain",
* respectively.
* If $value is NULL, $operator also can only be "=" or "<>", meaning the
* field must have no or some value, respectively.
*
* @return SearchApiMultiQuery
* The called object.
*/
public function condition($field, $value, $operator = '=') {
$this->filter->condition($field, $value, $operator);
return $this;
}
/**
* Add a sort directive to this search query. If no sort is manually set, the
* results will be sorted descending by relevance.
*
* @param $field
* The field to sort by. The special fields 'search_api_relevance' (sort by
* relevance) and 'search_api_id' (sort by item id) may be used.
* @param $order
* The order to sort items in - either 'ASC' or 'DESC'.
*
* @throws SearchApiException
* If the field is multi-valued or of a fulltext type.
*
* @return SearchApiMultiQuery
* The called object.
*/
public function sort($field, $order = 'ASC') {
if ($field != 'search_api_relevance' && $field != 'search_api_id') {
list($index_id, $f) = explode(':', $field, 2);
if (!isset($this->indexes[$index_id])) {
throw new SearchApiException(t("Trying to search on fields of index @index which doesn't lie on server @server.", array('@index' => $index_id, '@server' => $this->server->name)));
}
$fields = $this->indexes[$index_id]->options['fields'];
$fields += array(
'search_api_relevance' => array('type' => 'decimal'),
'search_api_id' => array('type' => 'integer'),
);
if (empty($fields[$f])) {
throw new SearchApiException(t('Trying to sort on unknown field @field.', array('@field' => $f)));
}
$type = $fields[$f]['type'];
if (search_api_is_list_type($type) || search_api_is_text_type($type)) {
throw new SearchApiException(t('Trying to sort on field @field of illegal type @type.', array('@field' => $f, '@type' => $type)));
}
}
$order = strtoupper(trim($order)) == 'DESC' ? 'DESC' : 'ASC';
$this->sort[$field] = $order;
return $this;
}
/**
* Adds a range of results to return. This will be saved in the query's
* options. If called without parameters, this will remove all range
* restrictions previously set.
*
* @param $offset
* The zero-based offset of the first result returned.
* @param $limit
* The number of results to return.
*
* @return SearchApiMultiQueryInterface
* The called object.
*/
public function range($offset = NULL, $limit = NULL) {
$this->options['offset'] = $offset;
$this->options['limit'] = $limit;
return $this;
}
/**
* Executes this search query.
*
* @return array
* An associative array containing the search results. The following keys
* are standardized:
* - 'result count': The overall number of results for this query, without
* range restrictions. Might be approximated, for large numbers.
* - results: An array of results, ordered as specified. The array keys are
* the items' IDs, values are arrays containing the following keys:
* - id: The item's ID.
* - index_id: The machine name of the index this item was found on.
* - score: A float measuring how well the item fits the search.
* - entity (optional): If set, the fully loaded result item. This field
* should always be used by modules using search results, to avoid
* duplicate item loads.
* - excerpt (optional): If set, an HTML text containing highlighted
* portions of the fulltext that match the query.
* - warnings: A numeric array of translated warning messages that may be
* displayed to the user.
* - ignored: A numeric array of search keys that were ignored for this
* search (e.g., because of being too short or stop words).
* - performance: An associative array with the time taken (as floats, in
* seconds) for specific parts of the search execution:
* - complete: The complete runtime of the query.
* - hooks: Hook invocations and other client-side preprocessing.
* - preprocessing: Preprocessing of the service class.
* - execution: The actual query to the search server, in whatever form.
* - postprocessing: Preparing the results for returning.
* Additional metadata may be returned in other keys. Only 'result count'
* and 'result' always have to be set, all other entries are optional.
*/
public final function execute() {
$start = microtime(TRUE);
// Add filter for languages.
if (isset($this->options['languages'])) {
$this->addLanguages($this->options['languages']);
}
// Add fulltext fields, unless set
if ($this->fields === NULL) {
$this->fields = array();
foreach ($this->indexes as $index) {
$prefix = $index->machine_name . ':';
foreach ($index->getFulltextFields() as $f) {
$this->fields[] = $prefix . $f;
}
}
}
// Call pre-execute hook.
$this->preExecute();
// Let modules alter the query.
drupal_alter('search_api_multi_query', $this);
$pre_search = microtime(TRUE);
// Execute query.
$response = $this->server->searchMultiple($this);
$post_search = microtime(TRUE);
// Call post-execute hook.
$this->postExecute($response);
$end = microtime(TRUE);
$response['performance']['complete'] = $end - $start;
$response['performance']['hooks'] = $response['performance']['complete'] - ($post_search - $pre_search);
// Store search for later retrieval for facets, etc.
search_api_multi_current_search(NULL, $this, $response);
return $response;
}
/**
* Helper method for adding a language filter.
*/
protected function addLanguages(array $languages) {
if (array_search(LANGUAGE_NONE, $languages) === FALSE) {
$languages[] = LANGUAGE_NONE;
}
if (count($languages) == 1) {
$this->condition('search_api_language', reset($languages));
}
else {
$filter = $this->createFilter('OR');
foreach ($languages as $lang) {
$filter->condition('search_api_language', $lang);
}
$this->filter($filter);
}
}
/**
* Pre-execute hook for modifying search behaviour.
*/
protected function preExecute() {}
/**
* Post-execute hook for modifying search behaviour.
*
* @param array $results
* The results returned by the server, which may be altered.
*/
protected function postExecute(array &$results) {}
/**
* @return SearchApiIndex
* The search index this query will be executed on.
*/
public function getServer() {
return $this->server;
}
/**
* @return array
* An array of SearchApiIndex objects representing all indexes that will be
* searched.
*/
public function getIndexes() {
return $this->indexes;
}
/**
* @return
* This object's search keys - either a string or an array specifying a
* complex search expression.
* An array will contain a '#conjunction' key specifying the conjunction
* type, and search strings or nested expression arrays at numeric keys.
* Additionally, a '#negation' key might be present, which means unless it
* maps to a FALSE value that the search keys contained in that array
* should be negated, i.e. not be present in returned results.
*/
public function &getKeys() {
return $this->keys;
}
/**
* @return
* The unprocessed search keys, exactly as passed to this object. Has the
* same format as getKeys().
*/
public function getOriginalKeys() {
return $this->orig_keys;
}
/**
* @return array
* An array containing the fields that should be searched for the search
* keys.
*/
public function &getFields() {
return $this->fields;
}
/**
* @return SearchApiQueryFilterInterface
* This object's associated filter object.
*/
public function getFilter() {
return $this->filter;
}
/**
* @return array
* An array specifying the sort order for this query. Array keys are the
* field names in order of importance, the values are the respective order
* in which to sort the results according to the field.
*/
public function &getSort() {
return $this->sort;
}
/**
* @param $name string
* The name of an option.
*
* @return mixed
* The option with the specified name, if set, or NULL otherwise.
*/
public function getOption($name) {
return isset($this->options[$name]) ? $this->options[$name] : NULL;
}
/**
* @param string $name
* The name of an option.
* @param mixed $value
* The new value of the option.
*
* @return The option's previous value.
*/
public function setOption($name, $value) {
$old = $this->getOption($name);
$this->options[$name] = $value;
return $old;
}
/**
* @return array
* An associative array of query options.
*/
public function &getOptions() {
return $this->options;
}
}

View File

@@ -0,0 +1,117 @@
<?php
/**
* Interface defining the additional methods a service has to implement in order
* to support the "search_api_multi" feature.
*
* The interface shouldn't be implemented directly (i.e., with a proper
* "implements" statement) since this would introduce a needless dependency.
*/
interface SearchApiMultiServiceInterface extends SearchApiServiceInterface {
//
// Additional methods
//
/**
* Create a query object for searching on this server.
*
* @param $options
* Associative array of options configuring this query. See
* SearchApiMultiQueryInterface::__construct().
*
* @throws SearchApiException
* If the server is currently disabled.
*
* @return SearchApiMultiQueryInterface
* An object for searching this server.
*/
public function queryMultiple(array $options = array());
/**
* Executes a search on the server represented by this object.
*
* @param SearchApiMultiQueryInterface $query
* The search query to execute.
*
* @throws SearchApiException
* If an error prevented the search from completing.
*
* @return array
* An associative array containing the search results, as required by
* SearchApiMultiQueryInterface::execute().
*/
public function searchMultiple(SearchApiMultiQueryInterface $query);
//
// Changed documentation / post-conditions
//
/**
* Determines whether this service class implementation supports a given
* feature. Features are optional extensions to Search API functionality and
* usually defined and used by third-party modules.
* Currently, the only feature specified directly in the search_api project is
* "search_api_facets", defined by the module of the same name.
*
* @param string $feature
* The name of the optional feature.
*
* @return boolean
* TRUE if this service knows and supports the specified feature. FALSE
* otherwise.
* Must return TRUE if $feature is "search_api_multi".
*/
public function supportsFeature($feature);
/**
* Add a new index to this server.
*
* If the index was already added to the server, the object should treat this
* as if removeIndex() and then addIndex() were called.
*
* The implementation of this method should call views_invalidate_cache(), if
* the search_api_views and search_api_multi modules are enabled.
*
* @param SearchApiIndex $index
* The index to add.
*/
public function addIndex(SearchApiIndex $index);
/**
* Notify the server that the indexed field settings for the index have
* changed.
* If any user action is necessary as a result of this, the method should
* use drupal_set_message() to notify the user.
*
* The implementation of this method should call views_invalidate_cache(), if
* the search_api_views and search_api_multi modules are enabled.
*
* @param SearchApiIndex $index
* The updated index.
*
* @return
* TRUE, if this change affected the server in any way that forces it to
* re-index the content. FALSE otherwise.
*/
public function fieldsUpdated(SearchApiIndex $index);
/**
* Remove an index from this server.
*
* This might mean that the index has been deleted, or reassigned to a
* different server. If you need to distinguish between these cases, inspect
* $index->server.
*
* If the index wasn't added to the server, the method call should be ignored.
*
* The implementation of this method should call views_invalidate_cache(), if
* the search_api_views and search_api_multi modules are enabled.
*
* @param $index
* Either an object representing the index to remove, or its machine name
* (if the index was completely deleted).
*/
public function removeIndex($index);
}

View File

@@ -0,0 +1,46 @@
<?php
/**
* Views argument handler class for handling fulltext fields.
*/
class SearchApiMultiHandlerArgumentFulltext extends SearchApiViewsHandlerArgumentFulltext {
/**
* Extend the options form a bit.
*/
public function options_form(array &$form, array &$form_state) {
parent::options_form($form, $form_state);
$fields = array();
$server_id = substr($this->table, 18);
$indexes = search_api_index_load_multiple(FALSE, array('enabled' => TRUE, 'server' => $server_id));
foreach ($indexes as $index) {
if (!empty($index->options['fields'])) {
$prefix = $index->machine_name . ':';
$prefix_name = $index->name . ' » ';
$f = $index->options['fields'];
foreach ($index->getFulltextFields() as $name) {
$fields[$prefix . $name] = $prefix_name . $f[$name]['name'];
}
}
}
if (!empty($fields)) {
$form['fields'] = array(
'#type' => 'select',
'#title' => t('Searched fields'),
'#description' => t('Select the fields that will be searched. If no fields are selected, all available fulltext fields will be searched.'),
'#options' => $fields,
'#size' => min(4, count($fields)),
'#multiple' => TRUE,
'#default_value' => $this->options['fields'],
);
}
else {
$form['fields'] = array(
'#type' => 'value',
'#value' => array(),
);
}
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Views filter handler class for handling fulltext fields.
*/
class SearchApiMultiHandlerFilterFulltext extends SearchApiViewsHandlerFilterFulltext {
/**
* Helper method to get an option list of all available fulltext fields.
*/
protected function getFulltextFields() {
$fields = array();
$server_id = substr($this->table, 18);
$indexes = search_api_index_load_multiple(FALSE, array('enabled' => TRUE, 'server' => $server_id));
foreach ($indexes as $index) {
if (!empty($index->options['fields'])) {
$prefix = $index->machine_name . ':';
$prefix_name = $index->name . ' » ';
$f = $index->options['fields'];
foreach ($index->getFulltextFields() as $name) {
$fields[$prefix . $name] = $prefix_name . $f[$name]['name'];
}
}
}
return $fields;
}
}

View File

@@ -0,0 +1,148 @@
<?php
/**
* Views query class using a Search API index as the data source.
*/
class SearchApiMultiViewsQuery extends SearchApiViewsQuery {
/**
* The server this view accesses.
*
* @var SearchApiServer
*/
protected $server;
/**
* Create the basic query object and fill with default values.
*/
public function init($base_table, $base_field, $options) {
try {
parent::init($base_table, $base_field, $options);
if (substr($base_table, 0, 18) == 'search_api_server_') {
$id = substr($base_table, 18);
$this->server = search_api_server_load($id);
$this->query = $this->server->queryMultiple(array(
'parse mode' => 'terms',
));
}
}
catch (Exception $e) {
$this->errors[] = $e->getMessage();
}
}
/**
* Helper function for adding results to a view in the format expected by the view.
*/
protected function addResults(array $results, $view) {
$index_types = array();
$view_result = array();
$items = array();
$ids = array();
// First we extract the involved indexes, and which entities need to be
// loaded for each entity type.
foreach ($results as $result) {
$id = $result['id'];
$index_id = $result['index_id'];
if (!isset($index_types[$index_id])) {
$index_types[$index_id] = search_api_index_load($index_id)->item_type;
}
// Maybe the service class or a postprocessor already set the entities.
if (!empty($result['entity'])) {
$items[$index_types[$index_id]][$id] = $result['entity'];
}
else {
$ids[$index_types[$index_id]][$id] = $id;
}
}
// Then extract the needed fields for each involved entity type.
$type_fields = array();
foreach ($this->fields as $field => $true) {
if (strpos($field, ':') !== FALSE) {
list($index_id, $field) = explode(':', $field, 2);
if (isset($index_types[$index_id])) {
$type_fields[$index_types[$index_id]][$field] = TRUE;
}
}
}
// Extract the field values for entities that were already loaded.
foreach ($items as $type => $objs) {
foreach ($objs as $id => $item) {
try {
$key = $type . '-' . $id;
$wrapper = search_api_get_datasource_controller($type)->getMetadataWrapper($item);
$view_result[$key] = (object) $this->extractFields($wrapper, $type_fields[$type]);
$view_result[$key]->entity = $item;
unset($objs[$id]);
}
catch (Exception $e) {
continue;
}
}
// If the values of some items couldn't be extracted, try it again with
// freshly loaded ones.
if ($objs) {
$ids[$type] = array_merge($ids[$type], array_keys($objs));
}
}
// Load remaining items and extract their field values.
foreach ($ids as $type => $item_ids) {
if (empty($type_fields[$type])) {
continue;
}
$datasource = search_api_get_datasource_controller($type);
$items = $datasource->loadItems($item_ids);
foreach ($items as $id => $item) {
try {
$key = $type . '-' . $id;
$wrapper = $datasource->getMetadataWrapper($item);
$view_result[$key] = (object) $this->extractFields($wrapper, $type_fields[$type]);
$view_result[$key]->entity = $item;
}
catch (Exception $e) {
continue;
}
}
}
// Finally, add the extracted values in the correct order to $view->result.
foreach ($results as $result) {
$key = $index_types[$result['index_id']] . '-' . $result['id'];
if (isset($view_result[$key])) {
$prefix = $result['index_id'] . ':';
$view->result[$key] = new stdClass();
foreach ($view_result[$key] as $k => $v) {
if ($k != 'entity') {
$k = $prefix . $k;
}
$view->result[$key]->$k = $v;
}
$view->result[$key]->search_api_relevance = $result['score'];
$view->result[$key]->search_api_multi_index = $result['index_id'];
foreach ($this->fields as $field => $true) {
if (!isset($view->result[$key]->$field)) {
$view->result[$key]->$field = '';
}
}
}
}
}
//
// Query interface methods (proxy to $this->query)
//
public function getServer() {
return $this->server;
}
public function getIndexes() {
if (!$this->errors) {
return $this->query->getIndexes();
}
}
}

View File

@@ -0,0 +1,190 @@
<?php
/**
* Implements hook_views_data().
*/
// This is largely copied from search_api_views_views_data(), including the
// "This is largely copied from _search_api_admin_get_fields()." comment.
function search_api_multi_views_data() {
$data = array();
$servers = array();
foreach (search_api_index_load_multiple(FALSE) as $index) {
if (!($server = $index->server()) || !$server->supportsFeature('search_api_multi')) {
continue;
}
$servers[$server->machine_name][$index->machine_name] = $index->name;
// We need the complete indexed data.
$array = array();
$index->dataAlter($array);
// Base data
$key = 'search_api_server_' . $server->machine_name;
$table = &$data[$key];
$table['table']['base'] = array(
'field' => 'search_api_id',
'index' => $server->machine_name,
'title' => $server->name,
'help' => t('Use search indexes on the %name search server for filtering and retrieving data.', array('%name' => $server->name)),
'query class' => 'search_api_multi_query',
);
// Add all available fields
// This is largely copied from _search_api_admin_get_fields().
$max_depth = variable_get('search_api_multi_max_fields_depth', 2);
$orig_wrapper = $index->entityWrapper(NULL, FALSE);
$fields = empty($index->options['fields']) ? array() : $index->options['fields'];
// A wrapper for a specific field name prefix, e.g. 'user:' mapped to the user wrapper
$wrappers = array('' => $orig_wrapper);
// Display names for the prefixes
$prefix_names = array('' => '');
// The list nesting level for entities with a certain prefix
$nesting_levels = array('' => 0);
$types = search_api_field_types();
$types['options'] = t('Options');
while ($wrappers) {
foreach ($wrappers as $prefix => $wrapper) {
$prefix_name = $prefix_names[$prefix];
$depth = substr_count($prefix, ':');
// Deal with lists.
$nesting_level = $nesting_levels[$prefix];
$type_prefix = str_repeat('list<', $nesting_level);
$type_suffix = str_repeat('>', $nesting_level);
if ($nesting_level) {
$info = $wrapper->info();
// The real nesting level of the wrapper, not the accumulated one.
$level = search_api_list_nesting_level($info['type']);
for ($i = 0; $i < $level; ++$i) {
$wrapper = $wrapper[0];
}
}
// Now look at all properties.
foreach ($wrapper as $property => $value) {
$info = $value->info();
$type = $type_prefix . $info['type'] . $type_suffix;
$inner_type = search_api_extract_inner_type($info['type']);
if ($inner_type == 'token') {
$inner_type = 'string';
$type = search_api_nest_type('string', $type);
}
$key = $index->machine_name . ':' . $prefix . $property;
if (isset($types[$inner_type])) {
if ($value->optionsList()) {
$inner_type = 'options';
$type = search_api_nest_type('options', $type);
}
// Add field handler.
$table[$key]['group'] = $prefix_name ? $index->name . ' » ' . $prefix_name : $index->name;
$table[$key]['title'] = $info['label'];
$table[$key]['help'] = empty($info['description']) ? t('(No information available)') : $info['description'];
$table[$key]['type'] = $type;
$table[$key]['field']['handler'] = _search_api_views_field_handler($type, $inner_type);
if ($inner_type == 'options') {
$table[$key]['field']['options'] = $value->optionsList();
}
// If field is indexed, also add additional handlers.
if (!empty($fields[$prefix . $property])) {
// Discern between original and indexed type
$table[$key]['field']['type'] = $table[$key]['type'];
$table[$key]['type'] = $fields[$prefix . $property]['type'];
$table[$key] += _search_api_views_add_handlers($fields[$prefix . $property], $value);
if (!empty($table[$key]['sort'])) {
$table[$key]['field']['click sortable'] = TRUE;
}
}
unset($fields[$prefix . $property]);
}
elseif ($depth < $max_depth) {
// Visit this entity/struct in a later iteration.
$key = $prefix . $property . ':';
$wrappers[$key] = $value;
$prefix_names[$key] = $prefix_name ? $prefix_name . ' » ' . $info['label'] : $info['label'];
$nesting_levels[$key] = search_api_list_nesting_level($type);
}
}
unset($wrappers[$prefix]);
}
}
// Add handlers for all indexed fields which weren't processed yet.
foreach ($fields as $key => $field) {
$tmp = $orig_wrapper;
$group = '';
$name = $index->name;
$parts = explode(':', $key);
foreach ($parts as $i => $part) {
if (!isset($tmp->$part)) {
continue 2;
}
$tmp = $tmp->$part;
$info = $tmp->info();
$group = ($group ? $group . ' » ' . $name : ($name ? $name : ''));
$name = $info['label'];
if ($i < count($parts) - 1) {
// Unwrap lists.
$level = search_api_list_nesting_level($info['type']);
for ($j = 0; $j < $level; ++$j) {
$tmp = $tmp[0];
}
}
}
$key = $index->machine_name . ':' . $key;
if ($group) {
$table[$key]['group'] = $group;
}
$table[$key]['title'] = $name;
$table[$key]['help'] = empty($info['description']) ? t('(No information available)') : $info['description'];
$table[$key]['type'] = $field['type'];
$table[$key] += _search_api_views_add_handlers($field, $tmp);
}
// Special handlers
$table['search_api_relevance']['group'] = t('Search');
$table['search_api_relevance']['title'] = t('Relevance');
$table['search_api_relevance']['help'] = t('The relevance of this search result with respect to the query.');
$table['search_api_relevance']['type'] = 'decimal';
$table['search_api_relevance']['field']['handler'] = _search_api_views_field_handler('decimal', 'decimal');
$table['search_api_relevance']['field']['click sortable'] = TRUE;
$table['search_api_relevance']['sort']['handler'] = 'SearchApiViewsHandlerSort';
$table['search_api_multi_fulltext']['group'] = t('Search');
$table['search_api_multi_fulltext']['title'] = t('Fulltext search');
$table['search_api_multi_fulltext']['help'] = t('Search several or all fulltext fields at once.');
$table['search_api_multi_fulltext']['type'] = 'text';
$table['search_api_multi_fulltext']['filter']['handler'] = 'SearchApiMultiHandlerFilterFulltext';
$table['search_api_multi_fulltext']['argument']['handler'] = 'SearchApiMultiHandlerArgumentFulltext';
}
foreach ($servers as $server_id => $indexes) {
$key = 'search_api_server_' . $server_id;
$table = &$data[$key];
$table['search_api_multi_index']['group'] = t('Search');
$table['search_api_multi_index']['title'] = t('Index');
$table['search_api_multi_index']['help'] = t('The search indexes that will be searched.');
$table['search_api_multi_index']['type'] = 'options';
$table['search_api_multi_index']['field']['handler'] = _search_api_views_field_handler('options', 'options');
$table['search_api_multi_index']['field']['options'] = $indexes;
$table['search_api_multi_index']['argument']['handler'] = 'SearchApiViewsHandlerArgument';
$table['search_api_multi_index']['filter']['handler'] = 'SearchApiViewsHandlerFilterOptions';
$table['search_api_multi_index']['filter']['options'] = $indexes;
}
return $data;
}
/**
* Implements hook_views_plugins().
*/
function search_api_multi_views_plugins() {
return array(
'query' => array(
'search_api_multi_query' => array(
'title' => t('Search API Query'),
'help' => t('Query will be generated and run using the Search API.'),
'handler' => 'SearchApiMultiViewsQuery'
),
),
);
}

View File

@@ -0,0 +1,457 @@
diff --git a/search-api-page-result.tpl.php b/search-api-page-result.tpl.php
new file mode 100644
index 0000000..bf56e48
--- /dev/null
+++ b/search-api-page-result.tpl.php
@@ -0,0 +1,56 @@
+<?php
+/**
+ * @file
+ * Default theme implementation for displaying a single search result.
+ *
+ * This template renders a single search result and is collected into
+ * search_api_page-results.tpl.php. This and the parent template are
+ * dependent to one another sharing the markup for definition lists.
+ *
+ * View Mode is set in the Search page settings. If you select
+ * "Themed as search results", then the child template will be used for
+ * theming the individual result. Any other view mode will bypass the
+ * child template.
+ *
+ * Available variables:
+ * - $url: URL of the result.
+ * - $title: Title of the result.
+ * - $snippet: A small preview of the result. Does not apply to user searches.
+ * - $info: String of all the meta information ready for print. Does not apply
+ * to user searches.
+ * - $info_split: Contains same data as $info, split into a keyed array.
+ * - $list_classes: CSS classes for this list element.
+ *
+ * Default keys within $info_split:
+ * - $info_split['user']: Author of the node linked to users profile. Depends
+ * on permission.
+ * - $info_split['date']: Last update of the node. Short formatted.
+ *
+ * Since $info_split is keyed, a direct print of the item is possible.
+ * This array does not apply to user searches so it is recommended to check
+ * for its existence before printing. The default keys of 'user' and
+ * 'date' always exist for node searches.
+ *
+ * To check for all available data within $info_split, use the code below.
+ * @code
+ * <?php print '<pre>'. check_plain(print_r($info_split, 1)) .'</pre>'; ?>
+ * @endcode
+ *
+ * @see template_preprocess()
+ * @see template_preprocess_search_result()
+ * @see template_process()
+ */
+?>
+<li<?php print $list_classes; ?>>
+ <h3 class="title">
+ <?php print $url ? l($title, $url['path'], $url['options']) : check_plain($title); ?>
+ </h3>
+ <div class="search-snippet-info">
+ <?php if ($snippet) : ?>
+ <p class="search-snippet"><?php print $snippet; ?></p>
+ <?php endif; ?>
+ <?php if ($info) : ?>
+ <p class="search-info"><?php print $info; ?></p>
+ <?php endif; ?>
+ </div>
+</li>
diff --git a/search-api-page-results.tpl.php b/search-api-page-results.tpl.php
new file mode 100644
index 0000000..9bbf343
--- /dev/null
+++ b/search-api-page-results.tpl.php
@@ -0,0 +1,53 @@
+<?php
+/**
+ * @file
+ * Default theme implementation for displaying search results.
+ *
+ * This template collects each invocation of theme_search_result(). This and
+ * the child template are dependent to one another sharing the markup for
+ * definition lists.
+ *
+ * Note that modules and themes may implement their own search type and theme
+ * function completely bypassing this template.
+ *
+ * Available variables:
+ * - $result_count: Number of results.
+ * - $spellcheck: Possible spelling suggestions from Search spellcheck module.
+ * - $search_results: All results rendered as list items in a single HTML string.
+ * - $items: All results as it is rendered through search-result.tpl.php.
+ * - $search_performance: The number of results and how long the query took.
+ * - $sec: The number of seconds it took to run the query.
+ * - $pager: Row of control buttons for navigating between pages of results.
+ * - $index:
+ * - $keys: The keywords of the executed search.
+ * - $page_machine_name: Machine name of the current Search API Page.
+ *
+ * View Mode is set in the Search page settings. If you select
+ * "Themed as search results", then the child template will be used for
+ * theming the individual result. Any other view mode will bypass the
+ * child template.
+ *
+ * @see template_preprocess_search_api_page_results()
+ */
+
+?>
+<?php if (!empty($result_count)) : ?>
+ <div class="search-api-page <?php print 'search-api-page-' . $page_machine_name . ' view-mode-' . $variables['view_mode'];?>">
+ <?php if ($result_count) : ?>
+ <?php print render($search_performance); ?>
+ <?php print render($spellcheck); ?>
+ <h2><?php print t('Search results');?></h2>
+
+ <?php if ($variables['view_mode'] == 'search_api_page_result') : // Uses child template. ?>
+ <?php print render($search_results); ?>
+ <? else : // All other view modes (Teaser, Full content, RSS and so forth). ?>
+ <div class="search-results">
+ <?php print render(entity_view($index->item_type, $items, $variables['view_mode'])); ?>
+ </div>
+ <?php endif; ?>
+ <?php print $pager; ?>
+ <?php else : ?>
+ <h2><?php print t('Your search yielded no results.');?></h2>
+ <?php endif; ?>
+ </div>
+<?php endif; ?>
diff --git a/search_api_page.info b/search_api_page.info
index 148c481..263ce24 100644
--- a/search_api_page.info
+++ b/search_api_page.info
@@ -4,5 +4,6 @@ description = "Create search pages using Search API indexes."
dependencies[] = search_api
core = 7.x
package = Search
+stylesheets[all][] = search_api_page.css
configure = admin/config/search/search_api/page
diff --git a/search_api_page.module b/search_api_page.module
index a9a00cb..6e15c45 100755
--- a/search_api_page.module
+++ b/search_api_page.module
@@ -60,8 +60,12 @@ function search_api_page_theme() {
'items' => array(),
'view_mode' => 'search_api_page_result',
'keys' => '',
+ 'page_machine_name' => NULL,
+ 'spellcheck' => NULL,
+ 'pager' => NULL,
),
'file' => 'search_api_page.pages.inc',
+ 'template' => 'search-api-page-results',
);
$themes['search_api_page_result'] = array(
'variables' => array(
@@ -69,14 +73,99 @@ function search_api_page_theme() {
'result' => NULL,
'item' => NULL,
'keys' => '',
+ 'list_classes' => '',
),
'file' => 'search_api_page.pages.inc',
+ 'template' => 'search-api-page-result',
+ );
+ $themes['search_performance'] = array(
+ 'render element' => 'element',
+ );
+ $themes['search_results_list'] = array(
+ 'render element' => 'element',
);
return $themes;
}
/**
+ * Implements theme for rendering search-performance
+ */
+function theme_search_performance($variables) {
+ $element = array_shift($variables);
+
+ return $element['#markup'];
+}
+
+/**
+ * Returns HTML for a list of search results.
+ * Taken from theme_item_list().
+ *
+ * @param $variables
+ * An associative array containing:
+ * - items: An array of items to be displayed in the list. If an item is a
+ * string, then it is used as is. If an item is an array, then the "data"
+ * element of the array is used as the contents of the list item. If an item
+ * is an array with a "children" element, those children are displayed in a
+ * nested list. All other elements are treated as attributes of the list
+ * item element.
+ * - type: The type of list to return (e.g. "ul", "ol").
+ * - attributes: The attributes applied to the list element.
+ */
+function theme_search_results_list($variables) {
+ // Pull Element array from the $variables array.
+ $variables = $variables['element'];
+
+ $items = $variables['items']; // Full data
+ $type = $variables['type'];
+
+ // CSS classes for ul
+ $attributes = (!empty($variables['attributes'])) ? $variables['attributes'] : array();
+ $attributes['class'] = array_merge(
+ array('item-list', 'search-results-list'),
+ (isset($attributes['class'])) ? $attributes['class'] : array()
+ );
+
+ // Render items within a list
+ if (!empty($items)) {
+ $output = "<$type" . drupal_attributes($attributes) . '>';
+ $num_items = count($items);
+
+ // Parse search results as tokens to access items with full data.
+ $i = 0;
+ foreach ($variables['results'] as $result) {
+ // Set css classes.
+ $item_attributes = array();
+ if ($i == 0) {
+ $item_attributes['class'][] = 'first';
+ }
+ if ($i == $num_items - 1) {
+ $item_attributes['class'][] = 'last';
+ }
+ (($i+1)%2) ? $item_attributes['class'][] = 'odd': $item_attributes['class'][] = 'even';
+
+ // Define render array.
+ $data = theme(
+ 'search_api_page_result', array(
+ 'index' => $variables['index'], // Use full results index.
+ 'result' => $result,
+ 'item' => isset($items[$result['id']]) ?
+ $items[$result['id']] :
+ NULL,
+ 'keys' => $variables['keys'],
+ 'list_classes' => drupal_attributes($item_attributes),
+ )
+ );
+ $output .= $data . "\n";
+ $i++;
+ }
+ $output .= "</$type>";
+
+ return $output;
+ }
+}
+
+/**
* Implements hook_permission().
*/
function search_api_page_permission() {
diff --git a/search_api_page.pages.inc b/search_api_page.pages.inc
index 7b72a0d..c514909 100644
--- a/search_api_page.pages.inc
+++ b/search_api_page.pages.inc
@@ -33,14 +33,18 @@ function search_api_page_view($id, $keys = NULL) {
watchdog('search_api_page', 'An error occurred while executing a search: !msg.', array('!msg' => $e->getMessage()), WATCHDOG_ERROR, l(t('search page'), $_GET['q']));
}
- // If spellcheck results are returned then add them to the render array.
+ // Load spellcheck.
if (isset($results['search_api_spellcheck'])) {
- $ret['search_api_spellcheck']['#theme'] = 'search_api_spellcheck';
- $ret['search_api_spellcheck']['#spellcheck'] = $results['search_api_spellcheck'];
+ $ret['results']['#spellcheck'] = array(
+ '#theme' => 'search_api_spellcheck',
+ '#spellcheck' => $results['search_api_spellcheck'],
// Let the theme function know where the key is stored by passing its arg
// number. We can work this out from the number of args in the page path.
- $ret['search_api_spellcheck']['#options'] = array(
- 'arg' => array(count(arg(NULL, $page->path))),
+ '#options' => array(
+ 'arg' => array(count(arg(NULL, $page->path))),
+ ),
+ '#prefix' => '<p class="search-api-spellcheck suggestion">',
+ '#suffix' => '</p>',
);
}
@@ -49,11 +53,12 @@ function search_api_page_view($id, $keys = NULL) {
$ret['results']['#results'] = $results;
$ret['results']['#view_mode'] = isset($page->options['view_mode']) ? $page->options['view_mode'] : 'search_api_page_result';
$ret['results']['#keys'] = $keys;
+ $ret['results']['#page_machine_name'] = $page->machine_name;
+ // Load pager.
if ($results['result count'] > $page->options['per_page']) {
pager_default_initialize($results['result count'], $page->options['per_page']);
- $ret['pager']['#theme'] = 'pager';
- $ret['pager']['#quantity'] = 9;
+ $ret['results']['#pager'] = theme('pager');
}
if (!empty($results['ignored'])) {
@@ -108,96 +113,66 @@ function search_api_page_search_execute(Entity $page, $keys) {
/**
* Function for preprocessing the variables for the search_api_page_results
- * theme.
+ * template.
*
* @param array $variables
* An associative array containing:
- * - index: The index this search was executed on.
- * - results: An array of search results, as returned by
+ * - $index: The index this search was executed on.
+ * - $results: An array of search results, as returned by
* SearchApiQueryInterface::execute().
- * - keys: The keywords of the executed search.
- */
-function template_preprocess_search_api_page_results(array &$variables) {
- if (!empty($variables['results']['results'])) {
- $variables['items'] = $variables['index']->loadItems(array_keys($variables['results']['results']));
- }
-}
-
-/**
- * Theme function for displaying search results.
+ * - $keys: The keywords of the executed search.
*
- * @param array $variables
- * An associative array containing:
- * - index: The index this search was executed on.
- * - results: An array of search results, as returned by
- * SearchApiQueryInterface::execute().
- * - items: The loaded items for all results, in an array keyed by ID.
- * - view_mode: The view mode to use for displaying the individual results,
- * or the special mode "search_api_page_result" to use the theme function
- * of the same name.
- * - keys: The keywords of the executed search.
+ * @see search_api_page-results.tpl.php
*/
-function theme_search_api_page_results(array $variables) {
- drupal_add_css(drupal_get_path('module', 'search_api_page') . '/search_api_page.css');
-
- $index = $variables['index'];
+function template_preprocess_search_api_page_results(array &$variables) {
$results = $variables['results'];
- $items = $variables['items'];
$keys = $variables['keys'];
- $output = '<p class="search-performance">' . format_plural($results['result count'],
- 'The search found 1 result in @sec seconds.',
- 'The search found @count results in @sec seconds.',
- array('@sec' => round($results['performance']['complete'], 3))) . '</p>';
-
- if (!$results['result count']) {
- $output .= "\n<h2>" . t('Your search yielded no results') . "</h2>\n";
- return $output;
- }
-
- $output .= "\n<h2>" . t('Search results') . "</h2>\n";
-
- if ($variables['view_mode'] == 'search_api_page_result') {
- $output .= '<ol class="search-results">';
- foreach ($results['results'] as $item) {
- $output .= '<li class="search-result">' . theme('search_api_page_result', array('index' => $index, 'result' => $item, 'item' => isset($items[$item['id']]) ? $items[$item['id']] : NULL, 'keys' => $keys)) . '</li>';
- }
- $output .= '</ol>';
- }
- else {
- // This option can only be set when the items are entities.
- $output .= '<div class="search-results">';
- $render = entity_view($index->item_type, $items, $variables['view_mode']);
- $output .= render($render);
- $output .= '</div>';
- }
+ $variables['items'] = $variables['index']->loadItems(array_keys($variables['results']['results']));
+ $variables['result_count'] = $results['result count'];
+ $variables['sec'] = round($results['performance']['complete'], 3);
+ $variables['search_performance'] = array(
+ '#theme' => 'search_performance',
+ '#markup' => format_plural(
+ $results['result count'],
+ 'The search found 1 result in @sec seconds.',
+ 'The search found @count results in @sec seconds.',
+ array('@sec' => $variables['sec'])
+ ),
+ '#prefix' => '<p class="search-performance">',
+ '#suffix' => '</p>',
+ );
- return $output;
+ $variables['search_results'] = array(
+ '#theme' => 'search_results_list',
+ 'results' => $variables['results']['results'],
+ 'items' => $variables['items'],
+ 'index' => $variables['index'],
+ 'type' => 'ul',
+ );
}
/**
- * Theme function for displaying search results.
+ * Process variables for search-result.tpl.php.
*
- * @param array $variables
- * An associative array containing:
- * - index: The index this search was executed on.
- * - result: One item of the search results, an array containing the keys
- * 'id' and 'score'.
- * - item: The loaded item corresponding to the result.
- * - keys: The keywords of the executed search.
+ * The $variables array contains the following arguments:
+ * - $result
+ *
+ * @see search_api_page-result.tpl.php
*/
-function theme_search_api_page_result(array $variables) {
+function template_preprocess_search_api_page_result(&$variables) {
$index = $variables['index'];
- $id = $variables['result']['id'];
+ $variables['id'] = $variables['result']['id'];
+ $variables['excerpt'] = $variables['result']['excerpt'];
$item = $variables['item'];
$wrapper = $index->entityWrapper($item, FALSE);
- $url = $index->datasource()->getItemUrl($item);
- $name = $index->datasource()->getItemLabel($item);
+ $variables['url'] = $index->datasource()->getItemUrl($item);
+ $variables['title'] = $index->datasource()->getItemLabel($item);
- if (!empty($variables['result']['excerpt'])) {
- $text = $variables['result']['excerpt'];
+ if (!empty($variables['excerpt'])) {
+ $text = $variables['excerpt'];
}
else {
$fields = $index->options['fields'];
@@ -239,10 +214,24 @@ function theme_search_api_page_result(array $variables) {
}
}
- $output = '<h3>' . ($url ? l($name, $url['path'], $url['options']) : check_plain($name)) . "</h3>\n";
- if ($text) {
- $output .= $text;
+ // Check for existence. User search does not include snippets.
+ $variables['snippet'] = isset($text) ? $text : '';
+
+ // Meta information
+ global $language;
+ if (isset($item->language) && $item->language != $language->language && $item->language != LANGUAGE_NONE) {
+ $variables['title_attributes_array']['xml:lang'] = $item->language;
+ $variables['content_attributes_array']['xml:lang'] = $item->language;
}
- return $output;
+ $info = array();
+ if (!empty($item->name)) {
+ $info['user'] = $item->name;
+ }
+ if (!empty($item->created)) {
+ $info['date'] = format_date($item->created, 'short');
+ }
+ // Provide separated and grouped meta information..
+ $variables['info_split'] = $info;
+ $variables['info'] = implode(' - ', $info);
}

View File

@@ -0,0 +1,53 @@
diff --git a/search_api_page.admin.inc b/search_api_page.admin.inc
old mode 100644
new mode 100755
index 013672e..a08ee06
--- a/search_api_page.admin.inc
+++ b/search_api_page.admin.inc
@@ -177,6 +177,14 @@ function search_api_page_admin_add(array $form, array &$form_state) {
'#default_value' => 10,
);
+ $form['result_page_search_form'] = array(
+ '#type' => 'radios',
+ '#title' => t('Search form on result page'),
+ '#default_value' => 1,
+ '#options' => array('1' => t('Enabled'), '0' => t('Disabled')),
+ '#description' => t('Enable or disable the search form on the result page'),
+ );
+
$form['get_per_page'] = array(
'#type' => 'checkbox',
'#title' => t('Allow GET override'),
@@ -359,6 +367,14 @@ function search_api_page_admin_edit(array $form, array &$form_state, Entity $pag
'#default_value' => $page->options['per_page'],
);
+ $form['result_page_search_form'] = array(
+ '#type' => 'radios',
+ '#title' => t('Search form on result page'),
+ '#default_value' => $page->options['per_page'],
+ '#options' => array('1' => t('Enabled'), '0' => t('Disabled')),
+ '#description' => t('Enable or disable the search form on the result page'),
+ );
+
$form['options']['get_per_page'] = array(
'#type' => 'checkbox',
'#title' => t('Allow GET override'),
diff --git a/search_api_page.pages.inc b/search_api_page.pages.inc
old mode 100644
new mode 100755
index 23f7b30..d43a465
--- a/search_api_page.pages.inc
+++ b/search_api_page.pages.inc
@@ -22,7 +22,9 @@ function search_api_page_view($id, $keys = NULL) {
$page->options['per_page'] = (int) $_GET['per_page'];
}
- $ret['form'] = drupal_get_form('search_api_page_search_form', $page, $keys);
+ if ($page->options['result_page_search_form']) {
+ $ret['form'] = drupal_get_form('search_api_page_search_form', $page, $keys);
+ }
if ($keys) {
$results = search_api_page_search_execute($page, $keys);

View File

@@ -0,0 +1,26 @@
diff --git search_api_page.admin.inc search_api_page.admin.inc
index a08ee0609ac55a7456cc7496272fbfb96714d299..d0f541d12f39f7b93ce4b00723302364feea89aa 100644
--- search_api_page.admin.inc
+++ search_api_page.admin.inc
@@ -370,7 +370,7 @@ function search_api_page_admin_edit(array $form, array &$form_state, Entity $pag
$form['result_page_search_form'] = array(
'#type' => 'radios',
'#title' => t('Search form on result page'),
- '#default_value' => $page->options['per_page'],
+ '#default_value' => isset($page->options['result_page_search_form']) ? $page->options['result_page_search_form'] : 1,
'#options' => array('1' => t('Enabled'), '0' => t('Disabled')),
'#description' => t('Enable or disable the search form on the result page'),
);
diff --git search_api_page.module search_api_page.module
index a9a00cb0de7cdcbc084a304682180a5f1448b847..16179de63cdd7ad9babdc872814ad7efa1d121af 100755
--- search_api_page.module
+++ search_api_page.module
@@ -364,7 +364,7 @@ function search_api_page_insert(array $values) {
*/
function search_api_page_edit($id, array $fields) {
$page = search_api_page_load($id, TRUE);
- $changeable = array('name' => 1, 'description' => 1, 'path' => 1, 'options' => 1, 'enabled' => 1);
+ $changeable = array('name' => 1, 'description' => 1, 'path' => 1, 'options' => 1, 'enabled' => 1, 'result_page_search_form'=>1);
foreach ($fields as $field => $value) {
if (isset($changeable[$field]) || $value === $page->$field) {
$page->$field = $value;

View File

@@ -0,0 +1,56 @@
<?php
/**
* @file
* Default theme implementation for displaying a single search result.
*
* This template renders a single search result and is collected into
* search_api_page-results.tpl.php. This and the parent template are
* dependent to one another sharing the markup for definition lists.
*
* View Mode is set in the Search page settings. If you select
* "Themed as search results", then the child template will be used for
* theming the individual result. Any other view mode will bypass the
* child template.
*
* Available variables:
* - $url: URL of the result.
* - $title: Title of the result.
* - $snippet: A small preview of the result. Does not apply to user searches.
* - $info: String of all the meta information ready for print. Does not apply
* to user searches.
* - $info_split: Contains same data as $info, split into a keyed array.
* - $list_classes: CSS classes for this list element.
*
* Default keys within $info_split:
* - $info_split['user']: Author of the node linked to users profile. Depends
* on permission.
* - $info_split['date']: Last update of the node. Short formatted.
*
* Since $info_split is keyed, a direct print of the item is possible.
* This array does not apply to user searches so it is recommended to check
* for its existence before printing. The default keys of 'user' and
* 'date' always exist for node searches.
*
* To check for all available data within $info_split, use the code below.
* @code
* <?php print '<pre>'. check_plain(print_r($info_split, 1)) .'</pre>'; ?>
* @endcode
*
* @see template_preprocess()
* @see template_preprocess_search_result()
* @see template_process()
*/
?>
<li<?php print $list_classes; ?>>
<h3 class="title">
<?php print $url ? l($title, $url['path'], $url['options']) : check_plain($title); ?>
</h3>
<div class="search-snippet-info">
<?php if ($snippet) : ?>
<p class="search-snippet"><?php print $snippet; ?></p>
<?php endif; ?>
<?php if ($info) : ?>
<p class="search-info"><?php print $info; ?></p>
<?php endif; ?>
</div>
</li>

View File

@@ -0,0 +1,53 @@
<?php
/**
* @file
* Default theme implementation for displaying search results.
*
* This template collects each invocation of theme_search_result(). This and
* the child template are dependent to one another sharing the markup for
* definition lists.
*
* Note that modules and themes may implement their own search type and theme
* function completely bypassing this template.
*
* Available variables:
* - $result_count: Number of results.
* - $spellcheck: Possible spelling suggestions from Search spellcheck module.
* - $search_results: All results rendered as list items in a single HTML string.
* - $items: All results as it is rendered through search-result.tpl.php.
* - $search_performance: The number of results and how long the query took.
* - $sec: The number of seconds it took to run the query.
* - $pager: Row of control buttons for navigating between pages of results.
* - $index:
* - $keys: The keywords of the executed search.
* - $page_machine_name: Machine name of the current Search API Page.
*
* View Mode is set in the Search page settings. If you select
* "Themed as search results", then the child template will be used for
* theming the individual result. Any other view mode will bypass the
* child template.
*
* @see template_preprocess_search_api_page_results()
*/
?>
<?php if (!empty($result_count)) : ?>
<div class="search-api-page <?php print 'search-api-page-' . $page_machine_name . ' view-mode-' . $variables['view_mode'];?>">
<?php if ($result_count) : ?>
<?php print render($search_performance); ?>
<?php print render($spellcheck); ?>
<h2><?php print t('Search results');?></h2>
<?php if ($variables['view_mode'] == 'search_api_page_result') : // Uses child template. ?>
<?php print render($search_results); ?>
<?php else : // All other view modes (Teaser, Full content, RSS and so forth). ?>
<div class="search-results">
<?php print render(entity_view($index->item_type, $items, $variables['view_mode'])); ?>
</div>
<?php endif; ?>
<?php print $pager; ?>
<?php else : ?>
<h2><?php print t('Your search yielded no results.');?></h2>
<?php endif; ?>
</div>
<?php endif; ?>

View File

@@ -0,0 +1,493 @@
<?php
/**
* Displays an overview of all defined search pages.
*/
function search_api_page_admin_overview() {
$base_path = drupal_get_path('module', 'search_api') . '/';
drupal_add_css($base_path . 'search_api.admin.css');
$header = array(t('Status'), t('Configuration'), t('Name'), t('Path'), t('Index'), t('Operations'));
$rows = array();
$t_enabled['data'] = array(
'#theme' => 'image',
'#path' => $base_path . 'enabled.png',
'#alt' => t('enabled'),
'#title' => t('enabled'),
);
$t_enabled['class'] = array('search-api-status');
$t_disabled['data'] = array(
'#theme' => 'image',
'#path' => $base_path . 'disabled.png',
'#alt' => t('disabled'),
'#title' => t('disabled'),
);
$t_disabled['class'] = array('search-api-status');
$t_enable = t('enable');
$t_disable = t('disable');
$t_edit = t('edit');
$t_delete = t('delete');
$pre = 'admin/config/search/search_api/page/';
$pre_index = 'admin/config/search/search_api/index/';
$enable = '/enable';
$disable = '/disable';
$edit = '/edit';
$delete = '/delete';
foreach (search_api_page_load_multiple() as $page) {
$url = $pre . $page->machine_name;
$index = search_api_index_load($page->index_id);
$rows[] = array(
$page->enabled ? $t_enabled : $t_disabled,
theme('entity_status', array('status' => $page->status)),
l($page->name, $page->path),
l($page->path, $page->path),
l($index->name, $pre_index . $index->machine_name),
l($t_edit, $url . $edit),
);
}
return array(
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => t('There are no search pages defined yet.'),
);
}
/**
* Displays a form for adding a search page.
*/
function search_api_page_admin_add(array $form, array &$form_state) {
$form = array();
if (empty($form_state['step_one'])) {
$indexes = search_api_index_load_multiple(FALSE);
if (!$indexes) {
drupal_set_message(t('There are no searches indexes which can be searched. Please <a href="@url">create an index</a> first.', array('@url' => url('admin/config/search/search_api/add_index'))), 'warning');
return array();
}
$index_options = array();
foreach ($indexes as $index) {
if ($index->enabled) {
$index_options[$index->machine_name] = $index->name;
}
}
foreach ($indexes as $index) {
if (!$index->enabled) {
$index_options[$index->machine_name] = $index->name . ' (' . t('disabled') . ')';
}
}
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Search name'),
'#maxlength' => 50,
'#required' => TRUE,
);
$form['machine_name'] = array(
'#type' => 'machine_name',
'#maxlength' => 51,
'#machine_name' => array(
'exists' => 'search_api_index_load',
),
);
$form['index_id'] = array(
'#type' => 'select',
'#title' => t('Index'),
'#description' => t('Select the index this page should search. This cannot be changed later.'),
'#options' => $index_options,
'#required' => TRUE,
);
$form['enabled'] = array(
'#type' => 'checkbox',
'#title' => t('Enabled'),
'#description' => t('This will only take effect if the selected index is also enabled.'),
'#default_value' => TRUE,
);
$form['description'] = array(
'#type' => 'textarea',
'#title' => t('Search description'),
);
$form['path'] = array(
'#type' => 'textfield',
'#title' => t('Path'),
'#description' => t('Set the path under which the search page will be accessible, when enabled.'),
'#maxlength' => 50,
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Create page'),
);
return $form;
}
$index = search_api_index_load($form_state['step_one']['index_id']);
if ($index->enabled) {
$modes = array();
foreach ($index->query()->parseModes() as $mode => $info) {
$modes[$mode] = $info['name'];
}
}
else {
$modes = array();
$modes['direct'] = t('Direct query');
$modes['single'] = t('Single term');
$modes['terms'] = t('Multiple terms');
}
$form['mode'] = array(
'#type' => 'select',
'#title' => t('Query type'),
'#description' => t('Select how the query will be parsed.'),
'#options' => $modes,
'#default_value' => 'terms',
);
$fields = array();
$index_fields = $index->getFields();
foreach ($index->getFulltextFields() as $name) {
$fields[$name] = $index_fields[$name]['name'];
}
if (count($fields) > 1) {
$form['fields'] = array(
'#type' => 'select',
'#title' => t('Searched fields'),
'#description' => t('Select the fields that will be searched. If no fields are selected, all available fulltext fields will be searched.'),
'#options' => $fields,
'#size' => min(4, count($fields)),
'#multiple' => TRUE,
);
}
else {
$form['fields'] = array(
'#type' => 'value',
'#value' => array(),
);
}
$form['per_page'] = array(
'#type' => 'select',
'#title' => t('Results per page'),
'#description' => t('Select how many items will be displayed on one page of the search result.'),
'#options' => drupal_map_assoc(array(5, 10, 20, 30, 40, 50, 60, 80, 100)),
'#default_value' => 10,
);
$form['result_page_search_form'] = array(
'#type' => 'radios',
'#title' => t('Search form on result page'),
'#default_value' => 1,
'#options' => array('1' => t('Enabled'), '0' => t('Disabled')),
'#description' => t('Enable or disable the search form on the result page'),
);
$form['get_per_page'] = array(
'#type' => 'checkbox',
'#title' => t('Allow GET override'),
'#description' => t('Allow the „Results per page“ setting to be overridden from the URL, using the "per_page" GET parameter.<br />' .
'Example: http://example.com/search_results?per_page=7'),
'#default_value' => TRUE,
);
$view_modes = array(
'search_api_page_result' => t('Themed as search results'),
);
// For entities, we also add all entity view modes.
if ($entity_info = entity_get_info($index->item_type)) {
foreach ($entity_info['view modes'] as $mode => $mode_info) {
$view_modes[$mode] = $mode_info['label'];
}
}
if (count($view_modes) > 1) {
$form['view_mode'] = array(
'#type' => 'select',
'#title' => t('View mode'),
'#options' => $view_modes,
'#description' => t('Select how search results will be displayed.'),
'#size' => 1,
'#default_value' => 'search_api_page_result',
);
}
else {
$form['view_mode'] = array(
'#type' => 'value',
'#value' => reset($view_modes),
);
}
if (module_exists('search_api_spellcheck') && ($server = $index->server()) && $server->supportsFeature('search_api_spellcheck')) {
$form['search_api_spellcheck'] = array(
'#type' => 'checkbox',
'#title' => t('Enable spell check'),
'#description' => t('Display "Did you mean … ?" above search results.'),
'#default_value' => TRUE,
);
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Create page'),
);
return $form;
}
/**
* Validation callback for search_api_page_admin_add().
*/
function search_api_page_admin_add_validate(array $form, array &$form_state) {
if (empty($form_state['step_one'])) {
$form_state['values']['path'] = drupal_strtolower(trim($form_state['values']['path']));
if (search_api_page_load_multiple(FALSE, array('path' => $form_state['values']['path']))) {
form_set_error('path', t('The entered path is already in use. Please enter a unique path.'));
}
}
}
/**
* Submit callback for search_api_page_admin_add().
*/
function search_api_page_admin_add_submit(array $form, array &$form_state) {
form_state_values_clean($form_state);
if (empty($form_state['step_one'])) {
$form_state['step_one'] = $form_state['values'];
$form_state['rebuild'] = TRUE;
return;
}
$values = $form_state['step_one'];
$values['options'] = $form_state['values'];
search_api_page_insert($values);
drupal_set_message(t('The search page was successfully created.'));
$form_state['redirect'] = 'admin/config/search/search_api/page';
}
/**
* Displays a form for editing or deleting a search page.
*/
function search_api_page_admin_edit(array $form, array &$form_state, Entity $page) {
$index = search_api_index_load($page->index_id);
$form_state['page'] = $page;
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Search name'),
'#maxlength' => 50,
'#required' => TRUE,
'#default_value' => $page->name,
);
$form['enabled'] = array(
'#type' => 'checkbox',
'#title' => t('Enabled'),
'#description' => t('This will only take effect if the selected index is also enabled.'),
'#default_value' => $page->enabled,
'#disabled' => !$index->enabled,
);
$form['description'] = array(
'#type' => 'textarea',
'#title' => t('Search description'),
'#default_value' => $page->description,
);
$form['index'] = array(
'#type' => 'item',
'#title' => t('Index'),
'#description' => l($index->name, 'admin/config/search/search_api/index/' . $index->machine_name),
);
$form['path'] = array(
'#type' => 'textfield',
'#title' => t('Path'),
'#description' => t('Set the path under which the search page will be accessible, when enabled.'),
'#maxlength' => 50,
'#default_value' => $page->path,
);
if ($index->enabled) {
$modes = array();
foreach ($index->query()->parseModes() as $mode => $info) {
$modes[$mode] = $info['name'];
}
}
else {
$modes = array();
$modes['direct'] = array(
'name' => t('Direct query'),
'description' => t("Don't parse the query, just hand it to the search server unaltered. " .
"Might fail if the query contains syntax errors in regard to the specific server's query syntax."),
);
$modes['single'] = array(
'name' => t('Single term'),
'description' => t('The query is interpreted as a single keyword, maybe containing spaces or special characters.'),
);
$modes['terms'] = array(
'name' => t('Multiple terms'),
'description' => t('The query is interpreted as multiple keywords seperated by spaces. ' .
'Keywords containing spaces may be "quoted". Quoted keywords must still be seperated by spaces.'),
);
}
$form['options']['#tree'] = TRUE;
$form['options']['mode'] = array(
'#type' => 'select',
'#title' => t('Query type'),
'#description' => t('Select how the query will be parsed.'),
'#options' => $modes,
'#default_value' => $page->options['mode'],
);
$fields = array();
$index_fields = $index->getFields();
foreach ($index->getFulltextFields() as $name) {
$fields[$name] = $index_fields[$name]['name'];
}
if (count($fields) > 1) {
$form['options']['fields'] = array(
'#type' => 'select',
'#title' => t('Searched fields'),
'#description' => t('Select the fields that will be searched. If no fields are selected, all available fulltext fields will be searched.'),
'#options' => $fields,
'#size' => min(4, count($fields)),
'#multiple' => TRUE,
'#default_value' => $page->options['fields'],
);
}
else {
$form['options']['fields'] = array(
'#type' => 'value',
'#value' => array(),
);
}
$form['options']['per_page'] = array(
'#type' => 'select',
'#title' => t('Results per page'),
'#description' => t('Select how many items will be displayed on one page of the search result.'),
'#options' => drupal_map_assoc(array(5, 10, 20, 30, 40, 50, 60, 80, 100)),
'#default_value' => $page->options['per_page'],
);
$form['result_page_search_form'] = array(
'#type' => 'radios',
'#title' => t('Search form on result page'),
'#default_value' => isset($page->options['result_page_search_form']) ? $page->options['result_page_search_form'] : 1,
'#options' => array('1' => t('Enabled'), '0' => t('Disabled')),
'#description' => t('Enable or disable the search form on the result page'),
);
$form['options']['get_per_page'] = array(
'#type' => 'checkbox',
'#title' => t('Allow GET override'),
'#description' => t('Allow the „Results per page“ setting to be overridden from the URL, using the "per_page" GET parameter.<br />' .
'Example: <code>http://example.com/search_results?per_page=7</code>'),
'#default_value' => !empty($page->options['get_per_page']),
);
$view_modes = array(
'search_api_page_result' => t('Themed as search results'),
);
// For entities, we also add all entity view modes.
if ($entity_info = entity_get_info($index->item_type)) {
foreach ($entity_info['view modes'] as $mode => $mode_info) {
$view_modes[$mode] = $mode_info['label'];
}
}
if (count($view_modes) > 1) {
$form['options']['view_mode'] = array(
'#type' => 'select',
'#title' => t('View mode'),
'#options' => $view_modes,
'#description' => t('Select how search results will be displayed.'),
'#size' => 1,
'#default_value' => isset($page->options['view_mode']) ? $page->options['view_mode'] : 'search_api_page_result',
);
}
else {
$form['options']['view_mode'] = array(
'#type' => 'value',
'#value' => reset($view_modes),
);
}
if (module_exists('search_api_spellcheck') && ($server = $index->server()) && $server->supportsFeature('search_api_spellcheck')) {
$form['options']['search_api_spellcheck'] = array(
'#type' => 'checkbox',
'#title' => t('Enable spell check'),
'#description' => t('Display "Did you mean … ?" above search results.'),
'#default_value' => !empty($page->options['search_api_spellcheck']),
);
}
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Save changes'),
);
if ($page->hasStatus(ENTITY_OVERRIDDEN)) {
$form['actions']['revert'] = array(
'#type' => 'fieldset',
'#title' => t('Revert search page'),
'#description' => t('This will revert all settings on this search page back to the defaults. This action cannot be undone.'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'revert' => array(
'#type' => 'submit',
'#value' => t('Revert search page'),
),
);
}
elseif ($page->hasStatus(ENTITY_CUSTOM)) {
$form['actions']['delete'] = array(
'#type' => 'fieldset',
'#title' => t('Delete search page'),
'#description' => t('This will delete the search page along with all of its settings.'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'delete' => array(
'#type' => 'submit',
'#value' => t('Delete search page'),
),
);
}
return $form;
}
/**
* Validation callback for search_api_page_admin_edit().
*/
function search_api_page_admin_edit_validate(array $form, array &$form_state) {
if ($form_state['values']['op'] == t('Save changes')) {
$form_state['values']['path'] = drupal_strtolower(trim($form_state['values']['path']));
$pages = search_api_page_load_multiple(FALSE, array('path' => $form_state['values']['path']));
if (count($pages) > 1 || (($page = array_shift($pages)) && $page->machine_name != $form_state['page']->machine_name)) {
form_set_error('path', t('The entered path is already in use. Please enter a unique path.'));
}
}
}
/**
* Submit callback for search_api_page_admin_edit().
*/
function search_api_page_admin_edit_submit(array $form, array &$form_state) {
$op = $form_state['values']['op'];
form_state_values_clean($form_state);
$form_state['redirect'] = 'admin/config/search/search_api/page';
if ($op == t('Delete search page') || $op == t('Revert search page')) {
$form_state['page']->delete();
if ($op == t('Revert search page')) {
drupal_set_message(t('The search page was successfully reverted.'));
}
else {
drupal_set_message(t('The search page was successfully deleted.'));
}
return;
}
search_api_page_edit($form_state['page']->machine_name, $form_state['values']);
drupal_set_message(t('The changes were successfully saved.'));
}

View File

@@ -0,0 +1,12 @@
.search-performance {
font-size: 80%;
}
ol.search-results {
display: block;
}
li.search-result {
display: block;
}

View File

@@ -0,0 +1,16 @@
name = Search pages
description = "Create search pages using Search API indexes."
dependencies[] = search_api
core = 7.x
package = Search
stylesheets[all][] = search_api_page.css
configure = admin/config/search/search_api/page
; Information added by drupal.org packaging script on 2012-06-26
version = "7.x-1.0-beta2+5-dev"
core = "7.x"
project = "search_api_page"
datestamp = "1340671392"

View File

@@ -0,0 +1,15 @@
name = Search pages
description = "Create search pages using Search API indexes."
dependencies[] = search_api
core = 7.x
package = Search
configure = admin/config/search/search_api/page
; Information added by drupal.org packaging script on 2012-06-26
version = "7.x-1.0-beta2+5-dev"
core = "7.x"
project = "search_api_page"
datestamp = "1340671392"

View File

@@ -0,0 +1,193 @@
<?php
/**
* Implements hook_schema().
*/
function search_api_page_schema() {
$schema['search_api_page'] = array(
'description' => '',
'fields' => array(
'id' => array(
'description' => 'The primary identifier for a search page.',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'index_id' => array(
'description' => 'The {search_api_index}.machine_name this page will search on.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
),
'path' => array(
'description' => 'The path at which this search page can be viewed.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
),
'name' => array(
'description' => 'The displayed name for a search page.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
),
'machine_name' => array(
'description' => 'The machine name for a search page.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
),
'description' => array(
'description' => 'The displayed description for a search page.',
'type' => 'text',
'not null' => FALSE,
),
'options' => array(
'description' => 'The options used to configure the search page.',
'type' => 'text',
'serialize' => TRUE,
'not null' => TRUE,
),
'enabled' => array(
'description' => 'A flag indicating whether the search page is enabled.',
'type' => 'int',
'size' => 'tiny',
'not null' => TRUE,
'default' => 1,
),
'status' => array(
'description' => 'The exportable status of the entity.',
'type' => 'int',
'not null' => TRUE,
'default' => 0x01,
'size' => 'tiny',
),
'module' => array(
'description' => 'The name of the providing module if the entity has been defined in code.',
'type' => 'varchar',
'length' => 255,
'not null' => FALSE,
),
),
'indexes' => array(
'enabled' => array('enabled'),
'index_id' => array('index_id'),
),
'unique' => array(
'path' => array('path'),
'machine_name' => array('machine_name'),
),
'primary key' => array('id'),
);
return $schema;
}
/**
* Implements hook_update_dependencies().
*/
function search_api_page_update_dependencies() {
// This update should run after primary IDs have been changed to machine names in the framework.
$dependencies['search_api_page'][7101] = array(
'search_api' => 7102,
);
return $dependencies;
}
/**
* Make {search_api_page}.index_id the index' machine name.
*/
function search_api_page_update_7101() {
// Update of search_api_page:
db_drop_index('search_api_page', 'index_id');
$spec = array(
'description' => 'The {search_api_index}.machine_name this page will search on.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
);
db_change_field('search_api_page', 'index_id', 'index_id', $spec);
db_add_index('search_api_page', 'index_id', array('index_id'));
foreach (db_query('SELECT id, machine_name FROM {search_api_index}') as $index) {
// We explicitly forbid numeric machine names, therefore we don't have to worry about conflicts here.
db_update('search_api_page')
->fields(array(
'index_id' => $index->machine_name,
))
->condition('index_id', $index->id)
->execute();
}
}
/**
* Add a {search_api_page}.machine_name column.
*/
function search_api_page_update_7102() {
$tx = db_transaction();
try {
// Add the machine_name field, along with its unique key index.
$spec = array(
'description' => 'The machine name for a search page.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
'default' => '',
);
db_add_field('search_api_page', 'machine_name', $spec);
$names = array();
foreach (db_query('SELECT id, name FROM {search_api_page}')->fetchAllKeyed() as $id => $name) {
$base = $name = drupal_strtolower(preg_replace('/[^a-z0-9]+/i', '_', $name));
$i = 0;
while (isset($names[$name])) {
$name = $base . '_' . ++$i;
if (drupal_strlen($name) > 50) {
$suffix_len = drupal_strlen('_' . $i);
$base = drupal_substr($base, 0, 50 - $suffix_len);
$name = $base . '_' . ++$i;
}
}
$names[$name] = TRUE;
db_update('search_api_page')
->fields(array(
'machine_name' => $name,
))
->condition('id', $id)
->execute();
}
db_add_unique_key('search_api_page', 'machine_name', array('machine_name'));
// Add the status field.
$spec = array(
'description' => 'The exportable status of the entity.',
'type' => 'int',
'not null' => TRUE,
'default' => 0x01,
'size' => 'tiny',
);
db_add_field('search_api_page', 'status', $spec);
// Add the module field.
$spec = array(
'description' => 'The name of the providing module if the entity has been defined in code.',
'type' => 'varchar',
'length' => 255,
'not null' => FALSE,
);
db_add_field('search_api_page', 'module', $spec);
}
catch (Exception $e) {
$tx->rollback();
try {
db_drop_field('search_api_page', 'machine_name');
db_drop_field('search_api_page', 'status');
db_drop_field('search_api_page', 'module');
}
catch (Exception $e1) {
// Ignore.
}
throw new DrupalUpdateException(t('An exception occurred during the update: @msg.', array('@msg' => $e->getMessage())));
}
}

View File

@@ -0,0 +1,565 @@
<?php
/**
* Implements hook_menu().
*/
function search_api_page_menu() {
$pre = 'admin/config/search/search_api/page';
$items[$pre] = array(
'title' => 'Search pages',
'description' => 'Create and configure search pages.',
'page callback' => 'search_api_page_admin_overview',
'access arguments' => array('administer search_api'),
'file' => 'search_api_page.admin.inc',
'type' => MENU_LOCAL_TASK,
);
$items[$pre . '/add'] = array(
'title' => 'Add search page',
'description' => 'Add a new search page.',
'page callback' => 'drupal_get_form',
'page arguments' => array('search_api_page_admin_add'),
'access arguments' => array('administer search_api'),
'file' => 'search_api_page.admin.inc',
'type' => MENU_LOCAL_ACTION,
);
$items[$pre . '/%search_api_page'] = array(
'title' => 'Edit search page',
'description' => 'Configure or delete a search page.',
'page callback' => 'drupal_get_form',
'page arguments' => array('search_api_page_admin_edit', 5),
'access arguments' => array('administer search_api'),
'file' => 'search_api_page.admin.inc',
);
// During uninstallation, this would lead to a fatal error otherwise.
if (module_exists('search_api_page')) {
foreach (search_api_page_load_multiple(FALSE, array('enabled' => TRUE)) as $page) {
$items[$page->path] = array(
'title' => $page->name,
'description' => $page->description ? $page->description : '',
'page callback' => 'search_api_page_view',
'page arguments' => array((string) $page->machine_name),
'access arguments' => array('access search_api_page'),
'file' => 'search_api_page.pages.inc',
'type' => MENU_SUGGESTED_ITEM,
);
}
}
$ret['results']['#theme'] = 'materiobase_results';
$ret['results']['#index'] = search_api_index_load($page->index_id);
$ret['results']['#results'] = $results;
$ret['results']['#view_mode'] = isset($page->options['view_mode']) ? $page->options['view_mode'] : 'search_api_page_result';
$ret['results']['#keys'] = $keys;
$ret['results']['#page_machine_name'] = $page->machine_name;
return $items;
}
/**
* Implements hook_theme().
*/
function search_api_page_theme() {
$themes['search_api_page_results'] = array(
'variables' => array(
'index' => NULL,
'results' => array('result count' => 0),
'items' => array(),
'view_mode' => 'search_api_page_result',
'keys' => '',
'page_machine_name' => NULL,
'spellcheck' => NULL,
'pager' => NULL,
),
'file' => 'search_api_page.pages.inc',
'template' => 'search-api-page-results',
);
$themes['search_api_page_result'] = array(
'variables' => array(
'index' => NULL,
'result' => NULL,
'item' => NULL,
'keys' => '',
'list_classes' => '',
),
'file' => 'search_api_page.pages.inc',
'template' => 'search-api-page-result',
);
$themes['search_performance'] = array(
'render element' => 'element',
);
$themes['search_results_list'] = array(
'render element' => 'element',
);
return $themes;
}
/**
* Implements theme for rendering search-performance
*/
function theme_search_performance($variables) {
$element = array_shift($variables);
return $element['#markup'];
}
/**
* Returns HTML for a list of search results.
* Taken from theme_item_list().
*
* @param $variables
* An associative array containing:
* - items: An array of items to be displayed in the list. If an item is a
* string, then it is used as is. If an item is an array, then the "data"
* element of the array is used as the contents of the list item. If an item
* is an array with a "children" element, those children are displayed in a
* nested list. All other elements are treated as attributes of the list
* item element.
* - type: The type of list to return (e.g. "ul", "ol").
* - attributes: The attributes applied to the list element.
*/
function theme_search_results_list($variables) {
// Pull Element array from the $variables array.
$variables = $variables['element'];
$items = $variables['items']; // Full data
$type = $variables['type'];
// CSS classes for ul
$attributes = (!empty($variables['attributes'])) ? $variables['attributes'] : array();
$attributes['class'] = array_merge(
array('item-list', 'search-results-list'),
(isset($attributes['class'])) ? $attributes['class'] : array()
);
// Render items within a list
if (!empty($items)) {
$output = "<$type" . drupal_attributes($attributes) . '>';
$num_items = count($items);
// Parse search results as tokens to access items with full data.
$i = 0;
foreach ($variables['results'] as $result) {
// Set css classes.
$item_attributes = array();
if ($i == 0) {
$item_attributes['class'][] = 'first';
}
if ($i == $num_items - 1) {
$item_attributes['class'][] = 'last';
}
(($i+1)%2) ? $item_attributes['class'][] = 'odd': $item_attributes['class'][] = 'even';
// Define render array.
$data = theme(
'search_api_page_result', array(
'index' => $variables['index'], // Use full results index.
'result' => $result,
'item' => isset($items[$result['id']]) ?
$items[$result['id']] :
NULL,
'keys' => $variables['keys'],
'list_classes' => drupal_attributes($item_attributes),
)
);
$output .= $data . "\n";
$i++;
}
$output .= "</$type>";
return $output;
}
}
/**
* Implements hook_permission().
*/
function search_api_page_permission() {
return array(
'access search_api_page' => array(
'title' => t('Access search pages'),
'description' => t('Execute searches using the Search pages module.'),
),
);
}
/**
* Implements hook_block_info().
*/
function search_api_page_block_info() {
$blocks = array();
foreach (search_api_page_load_multiple(FALSE, array('enabled' => TRUE)) as $page) {
$blocks[$page->machine_name] = array(
'info' => t('Search block: !name', array('!name' => $page->name)),
);
}
return $blocks;
}
/**
* Implements hook_block_view().
*/
function search_api_page_block_view($delta) {
$page = search_api_page_load($delta);
if ($page) {
$block = array();
$block['subject'] = t($page->name);
$block['content'] = drupal_get_form('search_api_page_search_form_' . $page->machine_name, $page, NULL, TRUE);
return $block;
}
}
/**
* Implements hook_forms().
*/
function search_api_page_forms($form_id, $args) {
$forms = array();
foreach (search_api_page_load_multiple(FALSE, array('enabled' => TRUE)) as $page) {
$forms['search_api_page_search_form_' . $page->machine_name] = array(
'callback' => 'search_api_page_search_form',
'callback arguments' => array(),
);
}
return $forms;
}
/**
* Implements hook_entity_info().
*/
function search_api_page_entity_info() {
$info['search_api_page'] = array(
'label' => t('Search page'),
'controller class' => 'EntityAPIControllerExportable',
'metadata controller class' => FALSE,
'entity class' => 'Entity',
'base table' => 'search_api_page',
'uri callback' => 'search_api_page_url',
'module' => 'search_api_page',
'exportable' => TRUE,
'entity keys' => array(
'id' => 'id',
'label' => 'name',
'name' => 'machine_name',
),
);
return $info;
}
/**
* Implements hook_entity_property_info().
*/
function search_api_page_entity_property_info() {
$info['search_api_page']['properties'] = array(
'id' => array(
'label' => t('ID'),
'type' => 'integer',
'description' => t('The primary identifier for a search page.'),
'schema field' => 'id',
'validation callback' => 'entity_metadata_validate_integer_positive',
),
'index_id' => array(
'label' => t('Index ID'),
'type' => 'token',
'description' => t('The machine name of the index this search page uses.'),
'schema field' => 'index_id',
),
'index' => array(
'label' => t('Index'),
'type' => 'search_api_index',
'description' => t('The index this search page uses.'),
'getter callback' => 'search_api_page_get_index',
),
'name' => array(
'label' => t('Name'),
'type' => 'text',
'description' => t('The displayed name for a search page.'),
'schema field' => 'name',
'required' => TRUE,
),
'machine_name' => array(
'label' => t('Machine name'),
'type' => 'token',
'description' => t('The internally used machine name for a search page.'),
'schema field' => 'machine_name',
'required' => TRUE,
),
'description' => array(
'label' => t('Description'),
'type' => 'text',
'description' => t('The displayed description for a search page.'),
'schema field' => 'description',
'sanitize' => 'filter_xss',
),
'enabled' => array(
'label' => t('Enabled'),
'type' => 'boolean',
'description' => t('A flag indicating whether the search page is enabled.'),
'schema field' => 'enabled',
),
);
return $info;
}
/**
* Implements hook_search_api_index_update().
*/
function search_api_page_search_api_index_update(SearchApiIndex $index) {
if (!$index->enabled && $index->original->enabled) {
foreach (search_api_page_load_multiple(FALSE, array('index_id' => $index->machine_name, 'enabled' => 1)) as $page) {
search_api_page_edit($page->id, array('enabled' => 0));
}
}
}
/**
* Implements hook_search_api_index_delete().
*/
function search_api_page_search_api_index_delete(SearchApiIndex $index) {
// Only react on real delete, not revert.
if ($index->hasStatus(ENTITY_IN_CODE)) {
return;
}
foreach (search_api_page_load_multiple(FALSE, array('index_id' => $index->machine_name)) as $page) {
search_api_page_delete($page->id);
}
}
/**
* Implements hook_search_api_page_insert().
*
* Rebuilds the menu table if a search page is created.
*/
function search_api_page_search_api_page_insert(Entity $page) {
menu_rebuild();
}
/**
* Implements hook_search_api_page_update().
*
* Rebuilds the menu table if a search page is edited.
*/
function search_api_page_search_api_page_update(Entity $page) {
if ($page->enabled != $page->original->enabled || $page->path != $page->original->path) {
menu_rebuild();
}
}
/**
* Implements hook_search_api_page_delete().
*
* Rebuilds the menu table if a search page is removed.
*/
function search_api_page_search_api_page_delete(Entity $page) {
menu_rebuild();
}
/**
* Entity URI callback.
*/
function search_api_page_url(Entity $page) {
return array('path' => $page->path);
}
/**
* Entity property getter callback.
*/
function search_api_page_get_index(Entity $page) {
return search_api_index_load($page->index_id);
}
/**
* Loads a search page.
*
* @param $id
* The page's id or machine name.
* @param $reset
* Whether to reset the internal cache.
*
* @return Entity
* A completely loaded page object, or NULL if no such page exists.
*/
function search_api_page_load($id, $reset = FALSE) {
$ret = entity_load_multiple_by_name('search_api_page', array($id), array(), $reset);
return $ret ? reset($ret) : FALSE;
}
/**
* Load multiple search pages at once.
*
* @see entity_load()
*
* @param $ids
* An array of page IDs or machine names, or FALSE to load all pages.
* @param $conditions
* An array of conditions on the {search_api_page} table in the form
* 'field' => $value.
* @param $reset
* Whether to reset the internal entity_load cache.
*
* @return array
* An array of page objects keyed by machine name.
*/
function search_api_page_load_multiple($ids = FALSE, array $conditions = array(), $reset = FALSE) {
return entity_load_multiple_by_name('search_api_page', $ids, $conditions, $reset);
}
/**
* Inserts a new search page into the database.
*
* @param array $values
* An array containing the values to be inserted.
*
* @return
* The newly inserted page's id, or FALSE on error.
*/
function search_api_page_insert(array $values) {
foreach (array('name', 'machine_name', 'index_id', 'path') as $var) {
if (!isset($values[$var])) {
throw new SearchApiException(t('Property @field has to be set for the new search page.', array('@field' => $var)));
}
}
if (empty($values['description'])) {
$values['description'] = NULL;
}
if (empty($values['options'])) {
$values['options'] = array();
}
$fields = array(
'name' => $values['name'],
'machine_name' => $values['machine_name'],
'description' => $values['description'],
'enabled' => empty($values['enabled']) ? 0 : 1,
'index_id' => $values['index_id'],
'path' => $values['path'],
'options' => $values['options'],
);
if (isset($values['id'])) {
$fields['id'] = $values['id'];
}
$page = entity_create('search_api_page', $fields);
$page->save();
return $page->id;
}
/**
* Changes a page's settings.
*
* @param $id
* The edited page's ID.
* @param array $fields
* The new field values to set.
*
* @return
* 1 if fields were changed, 0 if the fields already had the desired values.
*/
function search_api_page_edit($id, array $fields) {
$page = search_api_page_load($id, TRUE);
$changeable = array('name' => 1, 'description' => 1, 'path' => 1, 'options' => 1, 'enabled' => 1, 'result_page_search_form'=>1);
foreach ($fields as $field => $value) {
if (isset($changeable[$field]) || $value === $page->$field) {
$page->$field = $value;
$new_values = TRUE;
}
}
// If there are no new values, just return 0.
if (empty($new_values)) {
return 0;
}
$page->save();
return 1;
}
/**
* Deletes a search page.
*
* @param $id
* The ID of the search page to delete.
*
* @return
* TRUE on success, FALSE on failure.
*/
function search_api_page_delete($id) {
$page = search_api_page_load($id, TRUE);
if (!$page) {
return FALSE;
}
$page->delete();
menu_rebuild();
return TRUE;
}
/**
* Display a search form.
*
* @param Entity $page
* The search page for which this form is displayed.
* @param $keys
* The search keys.
* @param $compact
* Whether to display a compact form (e.g. for blocks) instead of a normal one.
*/
function search_api_page_search_form(array $form, array &$form_state, Entity $page, $keys = NULL, $compact = FALSE) {
$form['keys_' . $page->id] = array(
'#type' => 'textfield',
'#title' => t('Enter your keywords'),
'#title_display' => $compact ? 'invisible' : 'before',
'#default_value' => $keys,
'#size' => $compact ? 15 : 30,
);
$form['base_' . $page->id] = array(
'#type' => 'value',
'#value' => $page->path,
);
$form['id'] = array(
'#type' => 'hidden',
'#value' => $page->id,
);
$form['submit_' . $page->id] = array(
'#type' => 'submit',
'#value' => t('Search'),
);
if (!$compact) {
$form = array(
'#type' => 'fieldset',
'#title' => $page->name,
'form' => $form,
);
if ($page->description) {
$form['text']['#markup'] = '<p>' . nl2br(check_plain($page->description)) . '</p>';
$form['text']['#weight'] = -5;
}
}
return $form;
}
/**
* Validation callback for search_api_page_search_form().
*/
function search_api_page_search_form_validate(array $form, array &$form_state) {
if (!trim($form_state['values']['keys_' . $form_state['values']['id']])) {
form_set_error('keys_' . $form_state['values']['id'], t('Please enter at least one keyword.'));
}
}
/**
* Submit callback for search_api_page_search_form().
*/
function search_api_page_search_form_submit(array $form, array &$form_state) {
$keys = trim($form_state['values']['keys_' . $form_state['values']['id']]);
// @todo Take care of "/"s in the keys
$form_state['redirect'] = $form_state['values']['base_' . $form_state['values']['id']] . '/' . $keys;
}

View File

@@ -0,0 +1,239 @@
<?php
/**
* Displays a search page.
*
* @param $id
* The search page's machine name.
* @param $keys
* The keys to search for.
*/
function search_api_page_view($id, $keys = NULL) {
$page = search_api_page_load($id);
if (!$page) {
return MENU_NOT_FOUND;
}
// Override per_page setting with GET parameter.
if (!empty($_GET['per_page']) && !empty($page->options['get_per_page']) && ((int) $_GET['per_page']) > 0) {
// Remember and later restore the true setting value so we don't
// accidentally permanently save the altered one.
$page->options['original_per_page'] = $page->options['per_page'];
$page->options['per_page'] = (int) $_GET['per_page'];
}
if (isset($page->options['result_page_search_form']) && $page->options['result_page_search_form']) {
$ret['form'] = drupal_get_form('search_api_page_search_form', $page, $keys);
}
if ($keys) {
try {
$results = search_api_page_search_execute($page, $keys);
}
catch (SearchApiException $e) {
$ret['message'] = t('An error occurred while executing the search. Please try again or contact the site administrator if the problem persists.');
watchdog('search_api_page', 'An error occurred while executing a search: !msg.', array('!msg' => $e->getMessage()), WATCHDOG_ERROR, l(t('search page'), $_GET['q']));
}
// Load spellcheck.
if (isset($results['search_api_spellcheck'])) {
$ret['results']['#spellcheck'] = array(
'#theme' => 'search_api_spellcheck',
'#spellcheck' => $results['search_api_spellcheck'],
// Let the theme function know where the key is stored by passing its arg
// number. We can work this out from the number of args in the page path.
'#options' => array(
'arg' => array(count(arg(NULL, $page->path))),
),
'#prefix' => '<p class="search-api-spellcheck suggestion">',
'#suffix' => '</p>',
);
}
$ret['results']['#theme'] = 'search_api_page_results';
$ret['results']['#index'] = search_api_index_load($page->index_id);
$ret['results']['#results'] = $results;
$ret['results']['#view_mode'] = isset($page->options['view_mode']) ? $page->options['view_mode'] : 'search_api_page_result';
$ret['results']['#keys'] = $keys;
$ret['results']['#page_machine_name'] = $page->machine_name;
// Load pager.
if ($results['result count'] > $page->options['per_page']) {
pager_default_initialize($results['result count'], $page->options['per_page']);
$ret['results']['#pager'] = theme('pager');
}
if (!empty($results['ignored'])) {
drupal_set_message(t('The following search keys are too short or too common and were therefore ignored: "@list".', array('@list' => implode(t('", "'), $results['ignored']))), 'warning');
}
if (!empty($results['warnings'])) {
foreach ($results['warnings'] as $warning) {
drupal_set_message($warning, 'warning');
}
}
}
if (isset($page->options['original_per_page'])) {
$page->options['per_page'] = $page->options['original_per_page'];
unset($page->options['original_per_page']);
}
return $ret;
}
/**
* Executes a search.
*
* @param Entity $page
* The page for which a search should be executed.
* @param $keys
* The keywords to search for.
*
* @return array
* The search results as returned by SearchApiQueryInterface::execute().
*/
function search_api_page_search_execute(Entity $page, $keys) {
$limit = $page->options['per_page'];
$offset = pager_find_page() * $limit;
$options = array(
'search id' => 'search_api_page:' . $page->path,
'parse mode' => $page->options['mode'],
);
if (!empty($page->options['search_api_spellcheck'])) {
$options['search_api_spellcheck'] = TRUE;
}
$query = search_api_query($page->index_id, $options)
->keys($keys)
->range($offset, $limit);
if (!empty($page->options['fields'])) {
$query->fields($page->options['fields']);
}
return $query->execute();
}
/**
* Function for preprocessing the variables for the search_api_page_results
* template.
*
* @param array $variables
* An associative array containing:
* - $index: The index this search was executed on.
* - $results: An array of search results, as returned by
* SearchApiQueryInterface::execute().
* - $keys: The keywords of the executed search.
*
* @see search_api_page-results.tpl.php
*/
function template_preprocess_search_api_page_results(array &$variables) {
$results = $variables['results'];
$keys = $variables['keys'];
$variables['items'] = $variables['index']->loadItems(array_keys($variables['results']['results']));
$variables['result_count'] = $results['result count'];
$variables['sec'] = round($results['performance']['complete'], 3);
$variables['search_performance'] = array(
'#theme' => 'search_performance',
'#markup' => format_plural(
$results['result count'],
'The search found 1 result in @sec seconds.',
'The search found @count results in @sec seconds.',
array('@sec' => $variables['sec'])
),
'#prefix' => '<p class="search-performance">',
'#suffix' => '</p>',
);
$variables['search_results'] = array(
'#theme' => 'search_results_list',
'results' => $variables['results']['results'],
'items' => $variables['items'],
'index' => $variables['index'],
'type' => 'ul',
);
}
/**
* Process variables for search-result.tpl.php.
*
* The $variables array contains the following arguments:
* - $result
*
* @see search_api_page-result.tpl.php
*/
function template_preprocess_search_api_page_result(&$variables) {
$index = $variables['index'];
$variables['id'] = $variables['result']['id'];
$variables['excerpt'] = $variables['result']['excerpt'];
$item = $variables['item'];
$wrapper = $index->entityWrapper($item, FALSE);
$variables['url'] = $index->datasource()->getItemUrl($item);
$variables['title'] = $index->datasource()->getItemLabel($item);
if (!empty($variables['excerpt'])) {
$text = $variables['excerpt'];
}
else {
$fields = $index->options['fields'];
$fields = array_intersect_key($fields, drupal_map_assoc($index->getFulltextFields()));
$fields = search_api_extract_fields($wrapper, $fields);
$text = '';
$length = 0;
foreach ($fields as $field_name => $field) {
if (search_api_is_list_type($field['type']) || !isset($field['value'])) {
continue;
}
$val_length = drupal_strlen($field['value']);
if ($val_length > $length) {
$text = $field['value'];
$length = $val_length;
$format = NULL;
if (($pos = strrpos($field_name, ':')) && substr($field_name, $pos + 1) == 'value') {
$tmp = $wrapper;
try {
foreach (explode(':', substr($field_name, 0, $pos)) as $part) {
if (!isset($tmp->$part)) {
$tmp = NULL;
}
$tmp = $tmp->$part;
}
}
catch (EntityMetadataWrapperException $e) {
$tmp = NULL;
}
if ($tmp && $tmp->type() == 'text_formatted' && isset($tmp->format)) {
$format = $tmp->format->value();
}
}
}
}
if ($text && function_exists('text_summary')) {
$text = text_summary($text, $format);
}
}
// Check for existence. User search does not include snippets.
$variables['snippet'] = isset($text) ? $text : '';
// Meta information
global $language;
if (isset($item->language) && $item->language != $language->language && $item->language != LANGUAGE_NONE) {
$variables['title_attributes_array']['xml:lang'] = $item->language;
$variables['content_attributes_array']['xml:lang'] = $item->language;
}
$info = array();
if (!empty($item->name)) {
$info['user'] = $item->name;
}
if (!empty($item->created)) {
$info['date'] = format_date($item->created, 'short');
}
// Provide separated and grouped meta information..
$variables['info_split'] = $info;
$variables['info'] = implode(' - ', $info);
}

View File

@@ -0,0 +1,250 @@
<?php
/**
* Displays a search page.
*
* @param $id
* The search page's machine name.
* @param $keys
* The keys to search for.
*/
function search_api_page_view($id, $keys = NULL) {
$page = search_api_page_load($id);
if (!$page) {
return MENU_NOT_FOUND;
}
// Override per_page setting with GET parameter.
if (!empty($_GET['per_page']) && !empty($page->options['get_per_page']) && ((int) $_GET['per_page']) > 0) {
// Remember and later restore the true setting value so we don't
// accidentally permanently save the altered one.
$page->options['original_per_page'] = $page->options['per_page'];
$page->options['per_page'] = (int) $_GET['per_page'];
}
if (isset($page->options['result_page_search_form']) && $page->options['result_page_search_form']) {
$ret['form'] = drupal_get_form('search_api_page_search_form', $page, $keys);
}
if ($keys) {
try {
$results = search_api_page_search_execute($page, $keys);
}
catch (SearchApiException $e) {
$ret['message'] = t('An error occurred while executing the search. Please try again or contact the site administrator if the problem persists.');
watchdog('search_api_page', 'An error occurred while executing a search: !msg.', array('!msg' => $e->getMessage()), WATCHDOG_ERROR, l(t('search page'), $_GET['q']));
}
// If spellcheck results are returned then add them to the render array.
if (isset($results['search_api_spellcheck'])) {
$ret['search_api_spellcheck']['#theme'] = 'search_api_spellcheck';
$ret['search_api_spellcheck']['#spellcheck'] = $results['search_api_spellcheck'];
// Let the theme function know where the key is stored by passing its arg
// number. We can work this out from the number of args in the page path.
$ret['search_api_spellcheck']['#options'] = array(
'arg' => array(count(arg(NULL, $page->path))),
);
}
$ret['results']['#theme'] = 'search_api_page_results';
$ret['results']['#index'] = search_api_index_load($page->index_id);
$ret['results']['#results'] = $results;
$ret['results']['#view_mode'] = isset($page->options['view_mode']) ? $page->options['view_mode'] : 'search_api_page_result';
$ret['results']['#keys'] = $keys;
if ($results['result count'] > $page->options['per_page']) {
pager_default_initialize($results['result count'], $page->options['per_page']);
$ret['pager']['#theme'] = 'pager';
$ret['pager']['#quantity'] = 9;
}
if (!empty($results['ignored'])) {
drupal_set_message(t('The following search keys are too short or too common and were therefore ignored: "@list".', array('@list' => implode(t('", "'), $results['ignored']))), 'warning');
}
if (!empty($results['warnings'])) {
foreach ($results['warnings'] as $warning) {
drupal_set_message($warning, 'warning');
}
}
}
if (isset($page->options['original_per_page'])) {
$page->options['per_page'] = $page->options['original_per_page'];
unset($page->options['original_per_page']);
}
return $ret;
}
/**
* Executes a search.
*
* @param Entity $page
* The page for which a search should be executed.
* @param $keys
* The keywords to search for.
*
* @return array
* The search results as returned by SearchApiQueryInterface::execute().
*/
function search_api_page_search_execute(Entity $page, $keys) {
$limit = $page->options['per_page'];
$offset = pager_find_page() * $limit;
$options = array(
'search id' => 'search_api_page:' . $page->path,
'parse mode' => $page->options['mode'],
);
if (!empty($page->options['search_api_spellcheck'])) {
$options['search_api_spellcheck'] = TRUE;
}
$query = search_api_query($page->index_id, $options)
->keys($keys)
->range($offset, $limit);
if (!empty($page->options['fields'])) {
$query->fields($page->options['fields']);
}
return $query->execute();
}
/**
* Function for preprocessing the variables for the search_api_page_results
* theme.
*
* @param array $variables
* An associative array containing:
* - index: The index this search was executed on.
* - results: An array of search results, as returned by
* SearchApiQueryInterface::execute().
* - keys: The keywords of the executed search.
*/
function template_preprocess_search_api_page_results(array &$variables) {
if (!empty($variables['results']['results'])) {
$variables['items'] = $variables['index']->loadItems(array_keys($variables['results']['results']));
}
}
/**
* Theme function for displaying search results.
*
* @param array $variables
* An associative array containing:
* - index: The index this search was executed on.
* - results: An array of search results, as returned by
* SearchApiQueryInterface::execute().
* - items: The loaded items for all results, in an array keyed by ID.
* - view_mode: The view mode to use for displaying the individual results,
* or the special mode "search_api_page_result" to use the theme function
* of the same name.
* - keys: The keywords of the executed search.
*/
function theme_search_api_page_results(array $variables) {
drupal_add_css(drupal_get_path('module', 'search_api_page') . '/search_api_page.css');
$index = $variables['index'];
$results = $variables['results'];
$items = $variables['items'];
$keys = $variables['keys'];
$output = '<p class="search-performance">' . format_plural($results['result count'],
'The search found 1 result in @sec seconds.',
'The search found @count results in @sec seconds.',
array('@sec' => round($results['performance']['complete'], 3))) . '</p>';
if (!$results['result count']) {
$output .= "\n<h2>" . t('Your search yielded no results') . "</h2>\n";
return $output;
}
$output .= "\n<h2>" . t('Search results') . "</h2>\n";
if ($variables['view_mode'] == 'search_api_page_result') {
$output .= '<ol class="search-results">';
foreach ($results['results'] as $item) {
$output .= '<li class="search-result">' . theme('search_api_page_result', array('index' => $index, 'result' => $item, 'item' => isset($items[$item['id']]) ? $items[$item['id']] : NULL, 'keys' => $keys)) . '</li>';
}
$output .= '</ol>';
}
else {
// This option can only be set when the items are entities.
$output .= '<div class="search-results">';
$render = entity_view($index->item_type, $items, $variables['view_mode']);
$output .= render($render);
$output .= '</div>';
}
return $output;
}
/**
* Theme function for displaying search results.
*
* @param array $variables
* An associative array containing:
* - index: The index this search was executed on.
* - result: One item of the search results, an array containing the keys
* 'id' and 'score'.
* - item: The loaded item corresponding to the result.
* - keys: The keywords of the executed search.
*/
function theme_search_api_page_result(array $variables) {
$index = $variables['index'];
$id = $variables['result']['id'];
$item = $variables['item'];
$wrapper = $index->entityWrapper($item, FALSE);
$url = $index->datasource()->getItemUrl($item);
$name = $index->datasource()->getItemLabel($item);
if (!empty($variables['result']['excerpt'])) {
$text = $variables['result']['excerpt'];
}
else {
$fields = $index->options['fields'];
$fields = array_intersect_key($fields, drupal_map_assoc($index->getFulltextFields()));
$fields = search_api_extract_fields($wrapper, $fields);
$text = '';
$length = 0;
foreach ($fields as $field_name => $field) {
if (search_api_is_list_type($field['type']) || !isset($field['value'])) {
continue;
}
$val_length = drupal_strlen($field['value']);
if ($val_length > $length) {
$text = $field['value'];
$length = $val_length;
$format = NULL;
if (($pos = strrpos($field_name, ':')) && substr($field_name, $pos + 1) == 'value') {
$tmp = $wrapper;
try {
foreach (explode(':', substr($field_name, 0, $pos)) as $part) {
if (!isset($tmp->$part)) {
$tmp = NULL;
}
$tmp = $tmp->$part;
}
}
catch (EntityMetadataWrapperException $e) {
$tmp = NULL;
}
if ($tmp && $tmp->type() == 'text_formatted' && isset($tmp->format)) {
$format = $tmp->format->value();
}
}
}
}
if ($text && function_exists('text_summary')) {
$text = text_summary($text, $format);
}
}
$output = '<h3>' . ($url ? l($name, $url['path'], $url['options']) : check_plain($name)) . "</h3>\n";
if ($text) {
$output .= $text;
}
return $output;
}

View File

@@ -0,0 +1,37 @@
Search API Saved Searches 1.x, dev (xx/xx/xxxx):
------------------------------------------------
Search API Saved Searches 1.2 (07/21/2013):
-------------------------------------------
- #2040469 by drunken monkey: Fixed Views display of saved search results.
- #2027441 by drunken monkey: Added option to filter by date instead of IDs.
- #2027449 by drunken monkey: Fixed loading of new result items.
- #1398300 by Leksat, drunken monkey: Added option for disabling notifications.
- #2018983 by drunken monkey: Fixed error after deleting last saved search.
- #2012714 by drunken monkey: Fixed the $reset parameter for load functions.
Search API Saved Searches 1.1 (03/27/2013):
-------------------------------------------
- #1371344 by leeomara, drunken monkey: Added a README.txt file.
- #1888140 by drunken monkey: Added extended Views integration.
- #1941934 by drunken monkey: Added possibility to edit the notification
interval.
- #1885036 by mh86: Added custom interval labels to saved searches overview
page.
- #1888146 by drunken monkey: Added an option to allow registered users
logged-out deleting of their searches.
- #1447004 by fago, drunken monkey, mh86: Added i18n support.
- #1888126 by drunken monkey: Fixed "Cancel" link in delete forms for anonymous
users.
- #1881704 by drunken monkey: Added option to limit number of results sent per
mail.
- #1874132 by drunken monkey: Added automatic reactions for saved searches when
users are created, edited or deleted.
- #1868488 by drunken monkey: Fixed logic for whether to activate a saved search
right away.
- #1398310 by drunken monkey: Fixed visibility of "custom time" field.
- #1857822 by sepgil: Added quantity tokens.
Search API Saved Searches 1.0 (10/04/2012):
-------------------------------------------
First stable release of the Search API Saved Searches project.

View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,27 @@
Search API Saved Searches
-------------------------
This module offers users the ability to save searches executed with the
Search API module and be notified of new results. Notifications are done
via mails with token-replacement, their frequency can be configured both by
admins and/or users and saved searches can also be created without first
executing the search.
Facet, Views or other filters set for the search will also be included in a
saved search, thus reflecting exactly the same search results as displayed.
Bug reports, feature suggestions and latest developments:
http://drupal.org/project/issues/search_api_saved_searches
Installation
------------
* Install the module as usual.
See http://drupal.org/documentation/install/modules-themes/modules-7
for further information.
* Set the module's permissions (Administer saved searches, Use saved searches).
* You can now configure saved searches for each index by going to its
"Saved searches" tab.
* For being able to actually save searches, you have to enable the
"[Index Name]: Save search" block. This block will only appear on pages which
contain a Search API search and allow users to save the executed search.

View File

@@ -0,0 +1,557 @@
<?php
/**
* @file
* Admin UI functions and form callbacks for saved searches.
*/
/**
* Form builder for editing the saved search settings for an index.
*
* @param SearchApiIndex $index
* The index for which to edit settings.
*
* @see search_api_saved_searches_index_edit_validate()
* @see search_api_saved_searches_index_edit_submit()
* @ingroup forms
*/
function search_api_saved_searches_index_edit(array $form, array &$form_state, SearchApiIndex $index) {
if (!$index->enabled) {
$form = array(
'note' => array(
'#markup' => t('Saved searches cannot be enabled for a disabled search index. Enable the index first.'),
),
);
return $form;
}
$settings = search_api_saved_searches_settings_load_multiple(FALSE, array('index_id' => $index->machine_name));
if (!$settings) {
$delta = $index->machine_name;
if (strlen($delta) > 32) {
$delta = substr($delta, 0, 32);
}
$base = $delta;
for ($i = 1; search_api_saved_searches_settings_load($delta); ++$i) {
$suffix = '_' . $i;
$delta = substr($base, 0, 32 - strlen($suffix)) . $suffix;
}
$settings = entity_create('search_api_saved_searches_settings', array(
'delta' => $delta,
'index_id' => $index->machine_name,
'enabled' => FALSE,
'options' => array(),
));
}
else {
$settings = reset($settings);
}
// Set default options.
$settings->options += array(
'date_field' => NULL,
'description' => '',
'default_true' => TRUE,
'ids_list' => array(),
'registered_choose_mail' => FALSE,
'choose_name' => FALSE,
'registered_user_delete_key' => FALSE,
'show_empty_list' => FALSE,
'user_select_interval' => TRUE,
'interval_options' => array(
60 * 60 * 24 => t('Daily'),
60 * 60 * 24 * 7 => t('Weekly'),
),
'set_interval' => 60 * 60 * 24,
'mail' => array(),
'manual' => array(),
);
$settings->options['mail'] += array(
'activate' => array(),
'notify' => array(),
);
$settings->options['mail']['activate'] += array(
'send' => TRUE,
'title' => t('Activate your saved search at [site:name]'),
'body' => t("A saved search on [site:name] with this e-mail address was created.
To activate this saved search, click the following link:
[search-api-saved-search:activate-url]
If you didn't create this saved search, just ignore this mail and it will be deleted.
-- [site:name] team"),
);
$settings->options['mail']['notify'] += array(
'title' => t('New results for your saved search at [site:name]'),
'body' => t('[user:name],
There are new results for your saved search on [site:name]:
[search-api-saved-searches:results]
You can configure your saved searches at the following address:
[user:search-api-saved-searches-url]
-- [site:name] team'),
'results' => t('New results for search "!name_token"', array('!name_token' => '[search-api-saved-search:name]')) .
":\n[search-api-saved-search:items]\n[search-api-saved-search:results-capped]",
'result' => '[search-api-saved-search-result:label] ([search-api-saved-search-result:url])',
'max_results' => 0,
'results_capped' => "\n" . t('View all results') . ': [search-api-saved-search:view-url]',
);
$settings->options['manual'] += array(
'allow' => FALSE,
'fulltext' => FALSE,
'fields' => array(),
'page' => array(),
);
$settings->options['manual']['page'] += array(
'path' => '',
'fulltext' => '',
'direct_filter_params' => FALSE,
);
$form_state['settings'] = $settings;
$options = $settings->options;
$form['#tree'] = TRUE;
$form['#attached']['css'][] = drupal_get_path('module', 'search_api') . '/search_api.admin.css';
$form['enabled'] = array(
'#type' => 'checkbox',
'#title' => t('Enable'),
'#description' => t('Enable saved searches for this index.'),
'#default_value' => $settings->enabled,
);
$form['options'] = array(
'#type' => 'fieldset',
'#title' => t('Settings'),
'#states' => array(
'invisible' => array(
':input[name="enabled"]' => array('checked' =>FALSE),
),
),
);
$form['options']['misc'] = array(
'#type' => 'fieldset',
'#title' => t('Miscellaneous'),
'#collapsible' => TRUE,
'#collapsed' => $settings->enabled,
);
$fields = array();
foreach ($index->getFields() as $key => $field) {
if ($field['type'] == 'date') {
$fields[$key] = t('Determine by @name', array('@name' => $field['name']));
}
}
if ($fields) {
$fields = array(NULL => t('Determine by result ID')) + $fields;
$form['options']['misc']['date_field'] = array(
'#type' => 'select',
'#title' => t('Method for determining new results'),
'#description' => t('The method by which to decide which results are new. "Determine by result ID" will internally save the IDs of all results that were previously found by the user and only report results not already reported. (This might use a lot of memory for large result sets.) The other options check whether the date in the selected field is later than the date of last notification.'),
'#options' => $fields,
'#default_value' => $options['date_field'],
'#parents' => array('options', 'date_field'),
);
}
else {
$form['options'] = array(
'#type' => 'value',
'#value' => NULL,
);
}
$form['options']['misc']['description'] = array(
'#type' => 'textarea',
'#title' => t('Description'),
'#description' => t('Enter a text that will be displayed to users when creating a saved search.'),
'#default_value' => $settings->options['description'],
'#parents' => array('options', 'description'),
);
$search_ids = variable_get('search_api_saved_searches_search_ids', array());
if (empty($search_ids[$index->machine_name]) || count($search_ids[$index->machine_name]) <= 1) {
$form['options']['default_true'] = array(
'#type' => 'value',
'#value' => $options['default_true'],
);
$form['options']['ids_list'] = array(
'#type' => 'value',
'#value' => $options['ids_list'],
);
}
else {
$form['options']['misc']['default_true'] = array(
'#type' => 'select',
'#title' => t('Display for searches'),
'#options' => array(
TRUE => t('For all except the selected'),
FALSE => t('Only for the selected'),
),
'#default_value' => $options['default_true'],
'#parents' => array('options', 'default_true'),
);
$form['options']['misc']['ids_list'] = array(
'#type' => 'select',
'#title' => t('Search IDs'),
'#options' => $search_ids[$index->machine_name],
'#size' => min(4, count($search_ids[$index->machine_name])),
'#multiple' => TRUE,
'#default_value' => $options['ids_list'],
'#parents' => array('options', 'ids_list'),
);
}
$form['options']['misc']['registered_choose_mail'] = array(
'#type' => 'checkbox',
'#title' => t('Let logged-in users also enter a different mail address'),
'#default_value' => $options['registered_choose_mail'],
'#parents' => array('options', 'registered_choose_mail'),
);
$form['options']['misc']['choose_name'] = array(
'#type' => 'checkbox',
'#title' => t('Customizable search name'),
'#description' => t("Let users modify the saved search's name even when not manually creating it."),
'#default_value' => $options['choose_name'],
'#parents' => array('options', 'choose_name'),
);
$form['options']['misc']['registered_user_delete_key'] = array(
'#type' => 'checkbox',
'#title' => t('Create a delete link for registered users'),
'#description' => t('If enabled, registered users will also get the option to delete their searches via a special link, without logging in.'),
'#default_value' => $options['registered_user_delete_key'],
'#parents' => array('options', 'registered_user_delete_key'),
);
$form['options']['misc']['show_empty_list'] = array(
'#type' => 'checkbox',
'#title' => t('Show empty list of saved searches'),
'#description' => t('If enabled, the "Saved searches" tab for registered users will even be available when no saved searches were created by them yet.'),
'#default_value' => $options['show_empty_list'],
'#parents' => array('options', 'show_empty_list'),
);
// @todo Access options? Maximum number of saved searches per user, maximum
// number of results to create saved search, minimum number of filters?
$form['options']['interval'] = array(
'#type' => 'fieldset',
'#title' => t('Notification interval'),
'#collapsible' => TRUE,
'#collapsed' => $settings->enabled,
);
$form['options']['interval']['user_select_interval'] = array(
'#type' => 'checkbox',
'#title' => t('Let users select the interval'),
'#default_value' => $options['user_select_interval'],
'#parents' => array('options', 'user_select_interval'),
);
$interval_options = array();
foreach ($options['interval_options'] as $k => $v) {
$interval_options[] = "$k | $v";
}
$interval_options = implode("\n", $interval_options);
$form['options']['interval']['interval_options'] = array(
'#type' => 'textarea',
'#title' => t('Interval options'),
'#description' => t('The possible intervals the user can choose from. Enter one value per line, in the format seconds|label. Use a negative value for disabling notifications.'),
'#default_value' => $interval_options,
'#parents' => array('options', 'interval_options'),
'#states' => array(
'visible' => array(
':input[name="options[user_select_interval]"]' => array('checked' => TRUE),
),
),
);
$interval_options = array(
60 * 60 * 24 => t('Daily'),
60 * 60 * 24 * 7 => t('Weekly'),
0 => t('Custom'),
);
$form['options']['interval']['set_interval'] = array(
'#type' => 'select',
'#title' => t('Fixed notification interval'),
'#options' => $interval_options,
'#default_value' => isset($interval_options[$options['set_interval']]) ? $options['set_interval'] : 0,
'#parents' => array('options', 'set_interval'),
'#states' => array(
'visible' => array(
':input[name="options[user_select_interval]"]' => array('checked' => FALSE),
),
),
);
$form['options']['interval']['set_interval_custom'] = array(
'#type' => 'textfield',
'#description' => t('Enter the custom notification interval, in seconds. Use a negative value to disable notifications.'),
'#default_value' => isset($interval_options[$options['set_interval']]) ? $options['set_interval'] : 0,
'#parents' => array('options', 'set_interval_custom'),
'#states' => array(
'visible' => array(
':input[name="options[user_select_interval]"]' => array('checked' => FALSE),
':input[name="options[set_interval]"]' => array('value' => 0),
),
),
);
$form['options']['mail'] = array(
'#type' => 'fieldset',
'#title' => t('E-mails'),
'#collapsible' => TRUE,
'#collapsed' => $settings->enabled,
);
$form['options']['mail']['activate_send'] = array(
'#type' => 'checkbox',
'#title' => t('Use activation mail for anonymous users'),
'#description' => t("Will need saved searches created by anonymous users, or by normal users with an e-mail address that isn't their own, to be activated by clicking a link in an e-mail."),
'#default_value' => $options['mail']['activate']['send'],
'#parents' => array('options', 'mail', 'activate', 'send'),
);
$form['options']['mail']['activate'] = array(
'#type' => 'fieldset',
'#title' => t('Activation mail'),
'#collapsible' => TRUE,
'#collapsed' => $settings->enabled,
);
$form['options']['mail']['activate']['#states']['visible'][':input[name="options[mail][activate][send]"]']['checked'] = TRUE;
$form['options']['mail']['activate']['title'] = array(
'#type' => 'textfield',
'#title' => t('Subject'),
'#description' => t("Enter the mail's subject.") . ' ' . t('Available variables are: @vars.',
array('@vars' => '[site:name], [user:name], [user:mail], [search-api-saved-search:activate-url], ' .
'[search-api-saved-search:view-url]')),
'#default_value' => $options['mail']['activate']['title'],
'#required' => TRUE,
);
$form['options']['mail']['activate']['body'] = array(
'#type' => 'textarea',
'#title' => t('Body'),
'#description' => t("Enter the mail's body.") . ' ' . t('Available variables are: @vars.',
array('@vars' => '[site:name], [site:url], [user:name], [user:mail], [site:url-brief], ' .
'[search-api-saved-searches:results], [user:search-api-saved-searches-url]')) . ' ' .
t('The replacement for @var can be configured below.', array('@var' => '[search-api-saved-searches:results]')) . '<br />' .
t('Please note: For anonymous users, the [user:*] variables will be empty.'),
'#default_value' => $options['mail']['activate']['body'],
'#rows' => 12,
'#required' => TRUE,
);
$form['options']['mail']['notify'] = array(
'#type' => 'fieldset',
'#title' => t('Notification mails'),
'#collapsible' => TRUE,
'#collapsed' => $settings->enabled,
);
$form['options']['mail']['notify']['title'] = array(
'#type' => 'textfield',
'#title' => t('Subject'),
'#description' => t("Enter the mail's subject.") . ' ' . t('Available variables are: @vars.',
array('@vars' => '[site:name], [user:name], [user:mail]')),
'#default_value' => $options['mail']['notify']['title'],
'#required' => TRUE,
);
$form['options']['mail']['notify']['body'] = array(
'#type' => 'textarea',
'#title' => t('Body'),
'#description' => t("Enter the mail's body.") . ' ' . t('Available variables are: @vars.',
array('@vars' => '[site:name], [site:url], [user:name], [user:mail], [site:url-brief], ' .
'[search-api-saved-searches:results], [user:search-api-saved-searches-url]')) . ' ' .
t('The replacement for @var can be configured below.', array('@var' => '[search-api-saved-searches:results]')) . '<br />' .
t('Please note: For anonymous users, the [user:*] variables will be empty.'),
'#default_value' => $options['mail']['notify']['body'],
'#rows' => 12,
'#required' => TRUE,
);
$form['options']['mail']['notify']['results'] = array(
'#type' => 'textarea',
'#title' => t('Results replacement'),
'#description' => t('Enter the text that will replace the [search-api-saved-searches:results] variable above. If there are new results for several saved searches of a single user, this text will be inserted multiple times.') . ' ' .
t('Available variables are: @vars.',
array('@vars' => '[site:url], [search-api-saved-search:name], [search-api-saved-search:created], ' .
'[search-api-saved-search:items], [search-api-saved-search:results-capped], [search-api-saved-search:view-url], ' .
'[search-api-saved-search:edit-url], [search-api-saved-search:delete-url]')) . ' ' .
t('The replacement for @var can be configured below.', array('@var' => '[search-api-saved-search:items]')),
'#default_value' => $options['mail']['notify']['results'],
'#rows' => 5,
'#required' => TRUE,
);
$form['options']['mail']['notify']['result'] = array(
'#type' => 'textarea',
'#title' => t('Result item replacement'),
'#description' => t('Enter the text that will replace the [search-api-saved-search:items] variable above. This text will be inserted on a new line once for every new result.') . ' ' .
t('Available variables are: @vars.',
array('@vars' => '[site:url], [search-api-saved-search-result:label], [search-api-saved-search-result:url], ' .
'[search-api-saved-search:view-url], [search-api-saved-search:edit-url], [search-api-saved-search:delete-url]')),
'#default_value' => $options['mail']['notify']['result'],
'#rows' => 2,
'#required' => TRUE,
);
$tokens = token_info();
$type = $index->item_type;
if (isset($tokens['types'][$type])) {
$form['options']['mail']['notify']['result']['#description'] .= ' ' . t('You can also use the @varstyle variables.',
array('@varstyle' => "[$type:*]"));
}
$form['options']['mail']['notify']['max_results'] = array(
'#type' => 'textfield',
'#title' => t('Maximum number of results'),
'#description' => t('Maximum number of results per search that will be included in the mail. Specify an integer greater than 0 to limit the results.'),
'#default_value' => $options['mail']['notify']['max_results'],
'#element_validate' => array('element_validate_integer'),
);
$form['options']['mail']['notify']['results_capped'] = array(
'#type' => 'textarea',
'#title' => t('Show text if not all results are displayed'),
'#description' => t('Enter the text that will replace the [search-api-saved-search:results-capped] variable above. This text will only be inserted for searches in which the number of new results exceeds the set maximum.') . ' ' .
t('Available variables are: @vars.',
array('@vars' => '[site:url], [search-api-saved-search:name], [search-api-saved-search:created], ' .
'[search-api-saved-search:items], [search-api-saved-search:view-url], ' .
'[search-api-saved-search:edit-url], [search-api-saved-search:delete-url]')),
'#default_value' => $options['mail']['notify']['results_capped'],
'#rows' => 4,
'#states' => array(
'invisible' => array(
':input[name="options[mail][notify][max_results]"]' => array('value' => 0),
),
),
);
$form['options']['manual'] = array(
'#type' => 'fieldset',
'#title' => t('Manual saved search creation'),
'#description' => t('This provides a form to users where they can create a saved search manually, without first executing a search.'),
'#collapsible' => TRUE,
'#collapsed' => $settings->enabled,
);
$form['options']['manual']['allow'] = array(
'#type' => 'checkbox',
'#title' => t('Allow manual creation of saved searches'),
'#default_value' => $options['manual']['allow'],
);
$form['options']['manual']['fulltext'] = array(
'#type' => 'checkbox',
'#title' => t('Provide textfield for fulltext keywords'),
'#default_value' => $options['manual']['fulltext'],
);
if (!empty($index->options['fields'])) {
$fields = array();
foreach ($index->getFields() as $field => $info) {
$fields[$field] = $info['name'];
}
}
if (!empty($fields)) {
$form['options']['manual']['fields'] = array(
'#type' => 'checkboxes',
'#title' => t('Fields for which to provide filter options'),
'#options' => $fields,
'#attributes' => array(
'class' => array('search-api-checkboxes-list'),
),
'#default_value' => drupal_map_assoc($options['manual']['fields']),
);
}
$form['options']['manual']['page'] = array(
'#type' => 'fieldset',
'#title' => t('Search page'),
'#description' => t('Specify the page where search results can be viewed.'),
'#collapsible' => TRUE,
);
$form['options']['manual']['page']['path'] = array(
'#type' => 'textfield',
'#title' => t('Base path'),
'#description' => t('Base path for a search without any of the restrictions that can be applied. ' .
'If this is not specified, no link to a search page will be provided to users for manually created searches.'),
'#default_value' => $options['manual']['page']['path'],
);
$form['options']['manual']['page']['fulltext'] = array(
'#type' => 'textfield',
'#title' => t('Fulltext URL parameter'),
'#description' => t('Query parameter used for passing the fulltext keywords in the URL. ' .
'If left empty, the fulltext keywords (if present at all) will be appended to the path, instead of being passed as a parameter.'),
'#default_value' => $options['manual']['page']['fulltext'],
);
$form['options']['manual']['page']['direct_filter_params'] = array(
'#type' => 'select',
'#title' => t('Method for passing filter values in the URL'),
'#options' => array(
FALSE => t('In filter[*], as used by facets'),
TRUE => t('As direct URL parameters'),
),
'#default_value' => $options['manual']['page']['direct_filter_params'],
);
foreach (array('fulltext', 'fields', 'page') as $v) {
$form['options']['manual'][$v]['#states']['visible'][':input[name="options[manual][allow]"]']['checked'] = TRUE;
}
foreach (array('fulltext', 'direct_filter_params') as $v) {
$form['options']['manual']['page'][$v]['#states']['visible'][':input[name="options[manual][page][path]"]']['empty'] = FALSE;
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save settings'),
);
return $form;
}
/**
* Form validation handler for search_api_saved_searches_index_edit().
*
* @see search_api_saved_searches_index_edit()
* @see search_api_saved_searches_index_edit_submit()
*/
function search_api_saved_searches_index_edit_validate(array $form, array &$form_state) {
$values = &$form_state['values'];
$interval_options = $values['options']['interval_options'];
$values['options']['interval_options'] = array();
foreach (explode("\n", $interval_options) as $line) {
$parts = explode('|', $line, 2);
if (count($parts) == 1) {
$k = $v = trim($line);
}
else {
list($k, $v) = array_map('trim', $parts);
}
$values['options']['interval_options'][$k] = $v;
}
if ($values['options']['user_select_interval']) {
foreach ($values['options']['interval_options'] as $k => $v) {
if (!preg_match('/^-?\d+$/', $k)) {
form_error($form['options']['interval_options'], t('"@input" is not a valid integer. Only integers can be used as intervals.', array('@input' => $k)));
}
}
}
elseif ($values['options']['set_interval'] == 0) {
$v = $values['options']['set_interval_custom'];
if (!preg_match('/^-?\d+$/', $v)) {
form_error($form['options']['set_interval_custom'], t('"@input" is not a valid integer. Only integers can be used as intervals.', array('@input' => $v)));
}
}
}
/**
* Form submission handler for search_api_saved_searches_index_edit().
*
* @see search_api_saved_searches_index_edit()
* @see search_api_saved_searches_index_edit_vaidate()
*/
function search_api_saved_searches_index_edit_submit(array $form, array &$form_state) {
$values = $form_state['values'];
$settings = $form_state['settings'];
$options = $values['options'];
if ($options['set_interval'] == 0) {
$options['set_interval'] = $options['set_interval_custom'];
}
unset($options['set_interval_custom']);
$options['manual']['fields'] = array_keys(array_filter($options['manual']['fields']));
$settings->enabled = $values['enabled'];
$settings->options = $options;
$ret = $settings->save();
if ($ret === FALSE) {
drupal_set_message('An error occurred while trying to save the settings. Check the logs for details.', 'error');
$form_state['rebuild'] = TRUE;
}
else {
drupal_set_message('The settings were successfully saved.');
}
}

View File

@@ -0,0 +1,235 @@
<?php
/**
* @file
* Hooks provided by the Search API saved searches module.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Acts on saved searches being loaded from the database.
*
* This hook is invoked during saved search loading, which is handled by
* entity_load(), via the EntityCRUDController.
*
* @param array $searches
* An array of saved search entities being loaded, keyed by id.
*
* @see hook_entity_load()
*/
function hook_search_api_saved_search_load(array $searches) {
$result = db_query('SELECT pid, foo FROM {mytable} WHERE pid IN(:ids)', array(':ids' => array_keys($searches)));
foreach ($result as $record) {
$searches[$record->pid]->foo = $record->foo;
}
}
/**
* Responds when a saved search is inserted.
*
* This hook is invoked after the saved search is inserted into the database.
*
* @param SearchApiSavedSearch $search
* The saved search that is being inserted.
*
* @see hook_entity_insert()
*/
function hook_search_api_saved_search_insert(SearchApiSavedSearch $search) {
db_insert('mytable')
->fields(array(
'id' => entity_id('search_api_saved_search', $search),
'extra' => print_r($search, TRUE),
))
->execute();
}
/**
* Acts on a saved search being inserted or updated.
*
* This hook is invoked before the saved search is saved to the database.
*
* @param SearchApiSavedSearch $search
* The saved search that is being inserted or updated.
*
* @see hook_entity_presave()
*/
function hook_search_api_saved_search_presave(SearchApiSavedSearch $search) {
$search->name = 'foo';
}
/**
* Responds to a saved search being updated.
*
* This hook is invoked after the saved search has been updated in the database.
*
* @param SearchApiSavedSearch $search
* The saved search that is being updated.
*
* @see hook_entity_update()
*/
function hook_search_api_saved_search_update(SearchApiSavedSearch $search) {
db_update('mytable')
->fields(array('extra' => print_r($search, TRUE)))
->condition('id', entity_id('search_api_saved_search', $search))
->execute();
}
/**
* Responds to saved search deletion.
*
* This hook is invoked after the saved search has been removed from the database.
*
* @param SearchApiSavedSearch $search
* The saved search that is being deleted.
*
* @see hook_entity_delete()
*/
function hook_search_api_saved_search_delete(SearchApiSavedSearch $search) {
db_delete('mytable')
->condition('pid', entity_id('search_api_saved_search', $search))
->execute();
}
/**
* Acts on saved search settings being loaded from the database.
*
* This hook is invoked during settings entity loading, which is handled by
* entity_load(), via the EntityCRUDController.
*
* @param array $entities
* An array of settings entity entities being loaded, keyed by delta.
*
* @see hook_entity_load()
*/
function hook_search_api_saved_search_settings_load(array $entities) {
$result = db_query('SELECT pid, foo FROM {mytable} WHERE pid IN(:ids)', array(':ids' => array_keys($entities)));
foreach ($result as $record) {
$entities[$record->pid]->foo = $record->foo;
}
}
/**
* Responds when a settings entity is inserted.
*
* This hook is invoked after the settings entity is inserted into the database.
*
* @param SearchApiSavedSearchSettings $settings
* The settings entity that is being inserted.
*
* @see hook_entity_insert()
*/
function hook_search_api_saved_search_settings_insert(SearchApiSavedSearchSettings $settings) {
db_insert('mytable')
->fields(array(
'id' => entity_id('search_api_saved_search_settings', $settings),
'extra' => print_r($settings, TRUE),
))
->execute();
}
/**
* Acts on a settings entity being inserted or updated.
*
* This hook is invoked before the settings entity is saved to the database.
*
* @param SearchApiSavedSearchSettings $settings
* The settings entity that is being inserted or updated.
*
* @see hook_entity_presave()
*/
function hook_search_api_saved_search_settings_presave(SearchApiSavedSearchSettings $settings) {
$settings->options['foo'] = 'bar';
}
/**
* Responds to a settings entity being updated.
*
* This hook is invoked after the settings entity has been updated in the
* database.
*
* @param SearchApiSavedSearchSettings $settings
* The settings entity that is being updated.
*
* @see hook_entity_update()
*/
function hook_search_api_saved_search_settings_update(SearchApiSavedSearchSettings $settings) {
db_update('mytable')
->fields(array('extra' => print_r($settings, TRUE)))
->condition('id', entity_id('search_api_saved_search_settings', $settings))
->execute();
}
/**
* Responds to settings entity deletion.
*
* This hook is invoked after the settings entity has been removed from the
* database.
*
* @param SearchApiSavedSearchSettings $settings
* The settings entity that is being deleted.
*
* @see hook_entity_delete()
*/
function hook_search_api_saved_search_settings_delete(SearchApiSavedSearchSettings $settings) {
db_delete('mytable')
->condition('pid', entity_id('search_api_saved_search_settings', $settings))
->execute();
}
/**
* Define default settings entity configurations.
*
* @return
* An array of default saved search settings, keyed by deltas.
*
* @see hook_default_search_api_saved_search_settings_alter()
*/
function hook_default_search_api_saved_search_settings() {
$defaults['main'] = entity_create('search_api_saved_search_settings', array(
// …
));
return $defaults;
}
/**
* Alter default settings entity configurations.
*
* @param array $defaults
* An array of default saved search settings, keyed by deltas.
*
* @see hook_default_search_api_saved_search_settings()
*/
function hook_default_search_api_saved_search_settings_alter(array &$defaults) {
$defaults['main']->options['foo'] = 'bar';
}
/**
* Alter or react on new results found for a saved search.
*
* The results will then be used to send a mail to the saved search's creator.
*
* @param array $results
* An array of items representing new results for the search. The items that
* would be sent to the user are passed as loaded items, all others are passed
* only by ID.
* @param SearchApiSavedSearch $search
* The saved search that was executed.
*/
function hook_search_api_saved_searches_new_results_alter(array &$results, SearchApiSavedSearch $search) {
// Remove all results with an ID that is a multiple of 6.
foreach ($results as $id => $result) {
// Use is_scalar() to make sure we only remove loaded items that would be
// sent to the user.
if (!is_scalar($result) && $id % 6 == 0) {
unset($results[$id]);
}
}
}
/**
* @} End of "addtogroup hooks".
*/

View File

@@ -0,0 +1,18 @@
name = Search API saved searches
description = Offers users the ability to save executed searches and receive notifications about new results.
dependencies[] = search_api
core = 7.x
package = Search
files[] = search_api_saved_searches.search_entity.inc
files[] = search_api_saved_searches.settings_entity.inc
files[] = views/handler_field_saved_search_interval.inc
files[] = views/handler_field_saved_search_link.inc
files[] = views/handler_field_saved_search_name.inc
; Information added by drupal.org packaging script on 2013-07-21
version = "7.x-1.2"
core = "7.x"
project = "search_api_saved_searches"
datestamp = "1374443489"

View File

@@ -0,0 +1,174 @@
<?php
/**
* @file
* Install, update and uninstall functions for the Search API saved searches
* module.
*/
/**
* Implements hook_schema().
*/
function search_api_saved_searches_schema() {
$schema['search_api_saved_searches_settings'] = array(
'description' => 'The "saved searches" settings for a specific index.',
'fields' => array(
'id' => array(
'description' => 'The primary identifier for saved search settings.',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'delta' => array(
'description' => 'The {block}.delta used for these saved searches.',
'type' => 'varchar',
'length' => 32,
'not null' => TRUE,
'default' => '0',
),
'index_id' => array(
'description' => 'The {search_api_index}.machine_name this settings record is for.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
),
'enabled' => array(
'description' => 'A flag indicating whether saved searches for this index are enabled.',
'type' => 'int',
'size' => 'tiny',
'not null' => TRUE,
'default' => 1,
),
'options' => array(
'description' => 'The actual settings for saved searches.',
'type' => 'blob',
'serialize' => TRUE,
'not null' => TRUE,
),
'status' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0x01,
'size' => 'tiny',
'description' => 'The exportable status of the entity.',
),
'module' => array(
'description' => 'The name of the providing module if the entity has been defined in code.',
'type' => 'varchar',
'length' => 255,
'not null' => FALSE,
),
),
'indexes' => array(
'index_id' => array('index_id'),
),
'unique keys' => array(
'delta' => array('delta'),
),
'primary key' => array('id'),
);
$schema['search_api_saved_search'] = array(
'description' => 'A saved search that will be periodically executed.',
'fields' => array(
'id' => array(
'description' => 'The primary identifier for a saved search.',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
),
'uid' => array(
'description' => 'The {users}.uid that created this saved search.',
'type' => 'int',
'not null' => TRUE,
'default' => 0,
),
'settings_id' => array(
'description' => 'The {search_api_saved_searches_settings}.delta this saved search uses.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
),
'enabled' => array(
'description' => 'The state of this saved search, enabled (1) or not (0).',
'type' => 'int',
'size' => 'tiny',
'not null' => TRUE,
'default' => 0,
),
'name' => array(
'description' => 'The displayed name for this saved search.',
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
),
'mail' => array(
'description' => 'The mail address that should receive notifications.',
'type' => 'varchar',
'length' => 100,
'not null' => FALSE,
),
'created' => array(
'description' => 'The Unix timestamp when the saved search was created.',
'type' => 'int',
'not null' => TRUE,
),
'last_execute' => array(
'description' => 'The Unix timestamp when the saved search was last executed.',
'type' => 'int',
'not null' => TRUE,
),
'notify_interval' => array(
'description' => 'The interval in which this saved search will be checked for new results, in seconds.',
'type' => 'int',
'not null' => FALSE,
),
'query' => array(
'description' => 'The actual search query to be executed.',
'type' => 'blob',
'serialize' => TRUE,
'not null' => TRUE,
),
'options' => array(
'description' => 'Additional options for this saved search.',
'type' => 'blob',
'serialize' => TRUE,
'not null' => TRUE,
),
'results' => array(
'description' => 'A comma-separated list of all "old" results for this saved search.',
'type' => 'text',
'not null' => FALSE,
),
),
'indexes' => array(
'uid' => array('uid'),
'mail' => array('mail'),
),
'primary key' => array('id'),
);
return $schema;
}
/**
* Implements hook_uninstall().
*/
function search_api_saved_searches_uninstall() {
variable_del('search_api_saved_searches_search_ids');
}
/**
* Update searches to correctly use the settings' delta, not numeric ID, as the identifier.
*/
function search_api_saved_searches_update_7101() {
$settings = db_query('SELECT id, delta FROM {search_api_saved_searches_settings}')->fetchAllKeyed();
db_delete('search_api_saved_search')
->condition('settings_id', array_keys($settings), 'NOT IN')
->execute();
foreach ($settings as $id => $delta) {
db_update('search_api_saved_search')
->condition('settings_id', $id)
->fields(array('settings_id' => $delta))
->execute();
}
}

View File

@@ -0,0 +1,269 @@
<?php
/**
* @file
* User UI functions and form callbacks for saved searches.
*/
/**
* Page callback for listing all saved searches of a user.
*
* @param $account
* The user of which to list saved searches.
*/
function search_api_saved_searches_user_listing($account) {
$base_path = 'search-api/saved-search/';
$header = array(
t('Name'),
t('Created'),
t('Last executed'),
t('Interval'),
t('Operations'),
);
$searches = search_api_saved_search_load_multiple(FALSE, array('uid' => $account->uid));
$rows = array();
foreach ($searches as $search) {
$settings = $search->settings();
if (empty($search->options['page'])) {
$name = check_plain($search->name);
}
else {
$name = $search->l($search->name);
}
$created = format_date($search->created, 'short');
$last_execute = t('@time ago', array('@time' => format_interval(REQUEST_TIME - $search->last_execute)));
// Get the translated label for the interval.
$available_intervals = $settings->getTranslatedOption('interval_options');
if (isset($available_intervals[$search->notify_interval])) {
$interval = $available_intervals[$search->notify_interval];
}
elseif ($search->notify_interval < 0) {
$interval = t('Never');
}
else {
$interval = format_interval($search->notify_interval, 1);
}
$path = $base_path . $search->id;
$rows[] = array(
$name,
$created,
$last_execute,
$interval,
l(t('edit'), $path . '/edit') . ' | ' . l(t('delete'), $path . '/delete'),
);
}
$render = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => t('No searches were saved yet.'),
'#sticky' => TRUE,
);
return $render;
}
/**
* Page callback for manually creating a new saved search.
*
* @param SearchApiSavedSearchesSettings $settings
* (optional) The settings to use. If not present, either the only available
* settings will be used, or a form for selecting one will be displayed.
*/
function search_api_saved_searches_create_manual(SearchApiSavedSearchesSettings $settings = NULL) {
if (!isset($settings)) {
foreach (search_api_saved_searches_settings_load_multiple(FALSE, array('enabled' => TRUE)) as $settings) {
if (!empty($settings->options['manual']['allow'])) {
$available_settings[$settings->delta] = $settings;
}
}
if (empty($available_settings)) {
return t('There are no searches for which saved searches can be created manually.');
}
if (count($available_settings) == 1) {
$settings = reset($available_settings);
}
else {
$render = array();
$render['question']['#markup'] = t('For which search do you want to create a saved search?');
$render['list']['#theme'] = 'list';
$render['list']['#items'] = array();
$base = 'search-api/saved-searches/add/';
foreach ($available_settings as $id => $settings) {
$name = $settings->index()->name;
if (!empty($settings->options['manual']['page']['path'])) {
$item = menu_get_item($settings->options['manual']['page']['path']);
if (!empty($item['title'])) {
$name = $item['title'];
}
}
$render['list']['#items'][]['#markup'] = l($name, $base . $id);
}
return $render;
}
}
return drupal_get_form('search_api_saved_searches_save_form', $settings);
}
/**
* Page callback that activates a saved search.
*
* This is mostly necessary for anonymous users, but also when a user enters a
* different mail address than the one he registered with.
*
* @param SearchApiSavedSearch $search
* The search to activate.
* @param string $key
* The secret access key for this search, used to authenticate the user.
*/
function search_api_saved_searches_activate_page(SearchApiSavedSearch $search, $key) {
$ret = array(
'message' => array(
'#markup' => '',
),
'link' => array(
'#markup' => '<p>' . $search->l(t('View this saved search')) . '</p>',
),
);
if ($search->enabled) {
$msg = t('This saved search has already been activated.');
}
else {
$search->enabled = TRUE;
$success = $search->save();
if (!$success) {
drupal_set_message(t('An error occurred while trying to activate the search. Please contact the site administrator.'), 'error');
return $ret;
}
$msg = t('Your saved search was successfully activated.');
}
if ($search->notify_interval >= 0) {
$msg .= ' ' . t('You will receive e-mail notifications for new results in the future.');
}
$ret['message']['#markup'] = '<p>' . $msg . '</p>';
return $ret;
}
/**
* Form builder for editing a saved search.
*
* @param SearchApiSavedSearch $search
* The search to edit.
*
* @see search_api_saved_searches_search_edit_form_submit()
* @ingroup forms
*/
function search_api_saved_searches_search_edit_form(array $form, array &$form_state, SearchApiSavedSearch $search) {
$form_state['search'] = $search;
$settings = $search->settings();
if ($search->uid) {
$form_state['destination']['path'] = 'user/' . $search->uid . '/saved-searches';
}
elseif (!empty($search->options['page'])) {
$form_state['destination'] = array($search->options['page']['path'], $search->options['page']);
}
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Name'),
'#description' => t('The name that will be displayed for this saved search.'),
'#maxlength' => 50,
'#required' => TRUE,
'#default_value' => $search->name,
);
if ($settings->options['user_select_interval'] && count($settings->options['interval_options']) > 1) {
$form['notify_interval'] = array(
'#type' => 'select',
'#title' => t('Notification interval'),
'#options' => $settings->getTranslatedOption('interval_options'),
'#required' => TRUE,
'#default_value' => $search->notify_interval,
);
}
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Save changes'),
);
if (!empty($form_state['destination'])) {
$form['actions']['cancel'] = array(
'#type' => 'link',
'#title' => t('Cancel'),
'#href' => $form_state['destination']['path'],
'#options' => $form_state['destination'],
);
}
return $form;
}
/**
* Submission handler for search_api_saved_searches_search_edit_form().
*
* @see search_api_saved_searches_search_edit_form()
*/
function search_api_saved_searches_search_edit_form_submit(array $form, array &$form_state) {
$values = $form_state['values'];
$search = $form_state['search'];
$search->name = $values['name'];
if (isset($values['notify_interval'])) {
$search->notify_interval = $values['notify_interval'];
}
if ($search->save()) {
drupal_set_message(t('Successfully saved your changes.'));
if (!empty($form_state['destination'])) {
$form_state['redirect'] = $form_state['destination'];
}
}
else {
drupal_set_message(t('An error occurred while trying to save the changes.'), 'error');
}
}
/**
* Form builder for confirming the deletion of a saved search.
*
* @param SearchApiSavedSearch $search
* The search to delete.
*
* @see search_api_saved_searches_search_delete_form_submit()
* @ingroup forms
*/
function search_api_saved_searches_search_delete_form(array $form, array &$form_state, SearchApiSavedSearch $search) {
$form_state['search'] = $search;
if ($search->uid && search_api_saved_search_edit_access(user_load($search->uid))) {
$url = 'user/' . $search->uid . '/saved-searches';
}
elseif (!empty($search->options['page'])) {
$url = $search->options['page'];
}
else {
$url = '<front>';
}
return confirm_form($form, t('Do you really want to delete this saved search?'), $url);
}
/**
* Submission handler for search_api_saved_searches_search_delete_form().
*
* @see search_api_saved_searches_search_delete_form()
*/
function search_api_saved_searches_search_delete_form_submit(array $form, array &$form_state) {
$search = $form_state['search'];
$search->delete();
if ($search->uid && search_api_saved_search_edit_access(user_load($search->uid))) {
$url = 'user/' . $search->uid . '/saved-searches';
}
elseif (!empty($search->options['page'])) {
$url = $search->options['page'];
}
else {
$url = '<front>';
}
drupal_set_message(t('The saved search was successfully deleted.'));
$form_state['redirect'] = $url;
}

View File

@@ -0,0 +1,221 @@
<?php
/**
* @file
* Contains the entity class for saved searches.
*/
/**
* Class representing "Saved searches" settings.
*/
class SearchApiSavedSearch extends Entity {
/**
* The user that owns this saved search.
*
* @var stdClass
*/
protected $user;
/**
* The settings this saved search uses.
*
* @var SearchApiSavedSearchesSettings
*/
protected $settings;
/**
* The search index this saved search uses.
*
* @var SearchApiIndex
*/
protected $index;
// Database values that will be set when object is loaded
/**
* @var integer
*/
public $id;
/**
* @var integer
*/
public $uid;
/**
* @var string
*/
public $settings_id;
/**
* @var boolean
*/
public $enabled;
/**
* @var string
*/
public $name;
/**
* @var string
*/
public $mail;
/**
* @var integer
*/
public $created;
/**
* @var integer
*/
public $last_execute;
/**
* @var integer
*/
public $notify_interval;
/**
* Array representing the search query to execute, containing:
* keys: The parsed fulltext keys.
* fields: The fields that will be fulltext-searched.
* filters: An array of filters, as used in SearchApiQueryFilterInterface.
* options: The query options.
*
* @var array
*/
public $query;
/**
* @var array
*/
public $options;
/**
* @var string
*/
public $results;
/**
* Constructor as a helper to the parent constructor.
*/
public function __construct(array $values = array()) {
parent::__construct($values, 'search_api_saved_search');
}
/**
* Permanently saves the entity.
*
* @see entity_save()
*/
public function save() {
$settings = $this->settings();
if ((!$this->enabled && empty($this->options['key'])) || !empty($settings->options['registered_user_delete_key'])) {
$this->options['key'] = drupal_hash_base64(drupal_random_bytes(12));
}
$date_field = isset($settings->options['date_field']) ? $settings->options['date_field'] : NULL;
if ($this->enabled && !isset($this->results) && !$date_field) {
$results = array();
$response = $this->query()->execute();
$this->results = implode(',', array_keys($response['results']));
}
$ret = parent::save();
if ($ret == SAVED_NEW && !$this->enabled) {
$params = array(
'user' => user_load($this->uid),
'search' => $this,
);
drupal_mail('search_api_saved_searches', 'activate', $this->mail, user_preferred_language($params['user']), $params);
}
return $ret;
}
/**
* @return
* The user that owns this saved search.
*/
public function user() {
if (!isset($this->user)) {
$this->user = user_load($this->uid);
}
return $this->user;
}
/**
* @return SearchApiIndex
* The settings this saved search uses.
*
* @throws SearchApiException
* If the settings don't exist.
*/
public function settings() {
if (!isset($this->settings)) {
$this->settings = search_api_saved_searches_settings_load($this->settings_id);
}
if (!$this->settings) {
throw new SearchApiException(t("The saved search settings with the ID %id don't exist, but are used by an existing saved search.", array('%id' => $this->settings_id)));
}
return $this->settings;
}
/**
* @return SearchApiIndex
* The index this saved search uses.
*
* @throws SearchApiException
* If the index doesn't exist.
*/
public function index() {
if (!isset($this->index)) {
$this->index = search_api_index_load($this->settings()->index_id);
}
if (!$this->index) {
throw new SearchApiException(t("The index with the ID %id doesn't exist, but has saved search settings attached.", array('%id' => $this->settings()->index_id)));
}
return $this->index;
}
/**
* @return SearchApiQueryInterface
* A query for getting all new results for this saved search.
*
* @throws SearchApiException
* If the saved search's index is disabled.
*/
public function query() {
$query = $this->index()->query($this->query['options']);
if ($this->query['keys']){
$query->keys($this->query['keys']);
}
if ($this->query['fields']){
$query->fields($this->query['fields']);
}
if ($this->query['filters']){
$filters = &$query->getFilter()->getFilters();
$filters = $this->query['filters'];
}
return $query;
}
/**
* Return the URL where this search can be viewed, if any.
*/
public function url() {
if (isset($this->options['page']['path'])) {
return url($this->options['page']['path'], $this->options['page']);
}
}
/**
* Return a link to the URL where this search can be viewed, if any.
*/
public function l($text) {
if (isset($this->options['page']['path'])) {
return l($text, $this->options['page']['path'], $this->options['page']);
}
}
}

View File

@@ -0,0 +1,106 @@
<?php
/**
* @file
* Contains the entity class for stored "Saved searches" settings of search
* indexes.
*/
/**
* Class representing "Saved searches" settings.
*/
class SearchApiSavedSearchesSettings extends Entity {
/**
* The search index these settings are for.
*
* @var SearchApiIndex
*/
protected $index;
// Database values that will be set when object is loaded
/**
* @var integer
*/
public $id;
/**
* @var string
*/
public $delta;
/**
* @var string
*/
public $index_id;
/**
* @var boolean
*/
public $enabled;
/**
* @var array
*/
public $options;
/**
* Constructor as a helper to the parent constructor.
*/
public function __construct(array $values = array()) {
parent::__construct($values, 'search_api_saved_searches_settings');
}
/**
* @return SearchApiIndex
* The index these saved search settings are for.
*
* @throws SearchApiException
* If the index doesn't exist.
*/
public function index() {
if (!isset($this->index)) {
$this->index = search_api_index_load($this->index_id);
}
if (!$this->index) {
throw new SearchApiException(t("The index with the ID %id doesn't exist, but has saved search settings attached.", array('%id' => $this->index_id)));
}
return $this->index;
}
/**
* Gets the translated value of an option via i18n string translations.
*
* @param $property
* The name of the property stored in the options, as declared for i18n;
* e.g. "mail.notify.title".
* @param $langcode
* (optional) The language code of the language to which the value should
* be translated. If set to NULL, the default display language is being
* used.
*
* @return
* The raw, translated property value; or the raw, un-translated value if no
* translation is available.
*
* @see SearchApiSavedSearchesSettingsI18nController
*/
public function getTranslatedOption($property, $langcode = NULL) {
$value = drupal_array_get_nested_value($this->options, explode('.', $property));
if (isset($value) && module_exists('search_api_saved_searches_i18n') && function_exists('i18n_string')) {
$name = 'search_api_saved_searches:search_api_saved_searches_settings:' . $this->identifier() . ':' . $property;
if (is_array($value)) {
// Handle arrays of values, i.e. interval_options.
foreach ($value as $key => $data) {
$value[$key] = i18n_string($name . ".$key", $data, array('langcode' => $langcode, 'sanitize' => FALSE));
}
return $value;
}
else {
return i18n_string($name, $value, array('langcode' => $langcode, 'sanitize' => FALSE));
}
}
return $value;
}
}

View File

@@ -0,0 +1,316 @@
<?php
/**
* @file
* Builds placeholder replacement tokens for user-related data.
*/
/**
* Implements hook_token_info().
*
* Provides the following tokens:
* - [user:search-api-saved-searches-url]
* - [search-api-saved-searches:quantity]
* - [search-api-saved-searches:results]
* - [search-api-saved-search:name]
* - [search-api-saved-search:created]
* - [search-api-saved-search:quantity]
* - [search-api-saved-search:items]
* - [search-api-saved-search:results-capped]
* - [search-api-saved-search:view-url]
* - [search-api-saved-search:activate-url]
* - [search-api-saved-search:edit-url]
* - [search-api-saved-search:delete-url]
* - [search-api-saved-search-result:label]
* - [search-api-saved-search-result:url]
*
* The used data types are the following:
* - search_api_saved_searches: An array with values of type
* search_api_saved_search_info.
* - search_api_saved_search_info: An associative array containing:
* - search: A SearchApiSavedSearch entity object.
* - num_results: An integer telling how many new results there are for this
* saved search.
* - results: An array of items of the type that the index associated with
* this saved search contains.
* - search_api_saved_search_result_info: An associative array containing:
* - search: A SearchApiSavedSearch entity object.
* - entity: An item of the type corresponding to the saved search.
*
* @see search_api_saved_searches_tokens()
*/
function search_api_saved_searches_token_info() {
$info['types']['search-api-saved-searches'] = array(
'name' => t('Search API saved searches'),
'description' => t('Tokens related to several saved searches at once.'),
'needs-data' => 'search_api_saved_searches',
);
$info['types']['search-api-saved-search'] = array(
'name' => t('Search API saved search'),
'description' => t('Tokens related to a saved search.'),
'needs-data' => 'search_api_saved_search_info',
);
$info['types']['search-api-saved-search-result'] = array(
'name' => t('Search API saved search result'),
'description' => t('Tokens related to a result of a saved search.'),
'needs-data' => 'search_api_saved_search_result_info',
);
$tokens = &$info['tokens'];
$tokens['user']['search-api-saved-searches-url'] = array(
'name' => t('Config URL'),
'description' => t('The URL under which a user can configure her saved searches.'),
'type' => 'url',
);
$tokens['search-api-saved-searches']['quantity'] = array(
'name' => t('Number of results'),
'description' => t('Number of results for all saved searches in this message.'),
);
$tokens['search-api-saved-searches']['results'] = array(
'name' => t('Results'),
'description' => t('Text listing new results for one or more saved searches.'),
);
$search = &$tokens['search-api-saved-search'];
$search['name'] = array(
'name' => t('Name'),
'description' => t('The name of the saved search.'),
);
$search['created'] = array(
'name' => t('Date created'),
'description' => t('The date on which the saved search was created.'),
'type' => 'date',
);
$search['quantity'] = array(
'name' => t('Number of results'),
'description' => t('Number of results for the saved search.'),
);
$search['items'] = array(
'name' => t('Results'),
'description' => t('Text listing new results for the saved search.'),
);
$search['results-capped'] = array(
'name' => t('"Displayed results truncated" text'),
'description' => t('Text explaining that not all new results were displayed, if applicable.'),
);
$search['view-url'] = array(
'name' => t('View URL'),
'description' => t('The URL of the page displaying this search, if any.'),
'type' => 'url',
);
$search['activate-url'] = array(
'name' => t('Activate URL'),
'description' => t('The URL for activating the saved search, if necessary.'),
'type' => 'url',
);
$search['edit-url'] = array(
'name' => t('Edit URL'),
'description' => t("The URL for editing the saved search's notification interval."),
'type' => 'url',
);
$search['delete-url'] = array(
'name' => t('Delete URL'),
'description' => t('The URL for deleting the saved search.'),
'type' => 'url',
);
$tokens['search-api-saved-search-result']['id'] = array(
'name' => t('ID'),
'description' => t('The item id for the result.'),
);
$tokens['search-api-saved-search-result']['label'] = array(
'name' => t('Label'),
'description' => t('The human-readable label for the result.'),
);
$tokens['search-api-saved-search-result']['url'] = array(
'name' => t('URL'),
'description' => t('The URL at which the result can be viewed.'),
'type' => 'url',
);
return $info;
}
/**
* Implements hook_tokens().
*
* @see search_api_saved_searches_token_info()
*/
function search_api_saved_searches_tokens($type, array $tokens, array $data = array(), array $options = array()) {
$url_options = array('absolute' => TRUE);
if (isset($options['language'])) {
$url_options['language'] = $options['language'];
$language_code = $options['language']->language;
}
else {
$language_code = NULL;
}
$sanitize = !empty($options['sanitize']);
$replacements = array();
switch ($type) {
case 'user':
if (!empty($data['user']->uid)) {
if (isset($tokens['search-api-saved-searches-url'])) {
$replacements[$tokens['search-api-saved-searches-url']] = url('user/' . $data['user']->uid . '/saved-searches', $url_options);
}
if ($url_tokens = token_find_with_prefix($tokens, 'search-api-saved-searches-url')) {
$replacements += token_generate('url', $url_tokens, array(
'path' => 'user/' . $data['user']->uid . '/saved-searches',
), $options);
}
}
break;
case 'search-api-saved-searches':
if (!empty($data['search_api_saved_searches'])) {
if (isset($tokens['results'])) {
$results = array();
foreach ($data['search_api_saved_searches'] as $info) {
$search = $info['search'];
$settings = $search->settings();
if (empty($settings->options['mail']['notify']['results'])) {
continue;
}
$text = $settings->getTranslatedOption('mail.notify.results', $language_code);
$params['user'] = $search->user();
$params['search_api_saved_search_info'] = $info;
$results[] = token_replace($text, $params, $options);
}
$text = implode("\n\n", $results);
$replacements[$tokens['results']] = $sanitize ? check_plain($text) : $text;
}
if (isset($tokens['quantity'])) {
$quantity = 0;
foreach ($data['search_api_saved_searches'] as $info) {
if (isset($info['num_results'])) {
$quantity += $info['num_results'];
}
}
$replacements[$tokens['quantity']] = $quantity;
}
}
break;
case 'search-api-saved-search':
if (!empty($data['search_api_saved_search_info']['search'])) {
$search = $data['search_api_saved_search_info']['search'];
foreach ($tokens as $name => $original) {
switch ($name) {
case 'name':
$replacements[$original] = $sanitize ? check_plain($search->name) : $search->name;
break;
case 'created':
$replacements[$original] = format_date($search->created, 'medium', '', NULL, $language_code);
break;
case 'quantity':
if (empty($data['search_api_saved_search_info']['num_results'])) {
$replacements[$original] = 0;
break;
}
$replacements[$original] = $data['search_api_saved_search_info']['num_results'];
break;
case 'items':
if (!empty($data['search_api_saved_search_info']['results'])) {
$results = array();
$settings = $search->settings();
$text = $settings->getTranslatedOption('mail.notify.result', $language_code);
if (empty($text)) {
break;
}
$item_type = $search->index()->item_type;
foreach ($data['search_api_saved_search_info']['results'] as $item) {
$params = array(
$item_type => $item,
'search_api_saved_search_result_info' => array(
'search' => $search,
'entity' => $item,
),
);
$results[] = token_replace($text, $params, $options);
}
$text = implode("\n", $results);
$replacements[$original] = $sanitize ? check_plain($text) : $text;
}
break;
case 'results-capped':
if ($data['search_api_saved_search_info']['num_results'] == count($data['search_api_saved_search_info']['results'])) {
$replacements[$original] = '';
break;
}
$text = $settings->getTranslatedOption('mail.notify.results_capped', $language_code);
$text = token_replace($text, $data, $options);
$replacements[$original] = $sanitize ? check_plain($text) : $text;
break;
case 'view-url':
$replacements[$original] = $search->url();
break;
case 'activate-url':
$key = isset($search->options['key']) ? '/' . $search->options['key'] : '';
$replacements[$original] = url('search-api/saved-search/' . $search->id . '/activate' . $key, $url_options);
break;
case 'edit-url':
$key = isset($search->options['key']) ? '/' . $search->options['key'] : '';
$replacements[$original] = url('search-api/saved-search/' . $search->id . '/edit' . $key, $url_options);
break;
case 'delete-url':
$key = isset($search->options['key']) ? '/' . $search->options['key'] : '';
$replacements[$original] = url('search-api/saved-search/' . $search->id . '/delete' . $key, $url_options);
break;
}
}
if ($created_tokens = token_find_with_prefix($tokens, 'created')) {
$replacements += token_generate('date', $created_tokens, array('date' => $search->created), $options);
}
if ($view_url_tokens = token_find_with_prefix($tokens, 'view-url')) {
$replacements += token_generate('url', $view_url_tokens, array(
'path' => $search->url(),
), $options);
}
if ($activate_url_tokens = token_find_with_prefix($tokens, 'activate-url')) {
$key = isset($search->options['key']) ? '/' . $search->options['key'] : '';
$replacements += token_generate('url', $activate_url_tokens, array(
'path' => 'search-api/saved-search/' . $search->id . '/activate' . $key,
), $options);
}
if ($edit_url_tokens = token_find_with_prefix($tokens, 'edit-url')) {
$key = isset($search->options['key']) ? '/' . $search->options['key'] : '';
$replacements += token_generate('url', $edit_url_tokens, array(
'path' => 'search-api/saved-search/' . $search->id . '/edit' . $key,
), $options);
}
if ($delete_url_tokens = token_find_with_prefix($tokens, 'delete-url')) {
$key = isset($search->options['key']) ? '/' . $search->options['key'] : '';
$replacements += token_generate('url', $delete_url_tokens, array(
'path' => 'search-api/saved-search/' . $search->id . '/delete' . $key,
), $options);
}
}
break;
case 'search-api-saved-search-result':
$d = $data['search_api_saved_search_result_info'];
if (!empty($d['search']) && !empty($d['entity'])) {
$search = $d['search'];
$index = $search->index();
$item = $d['entity'];
foreach ($tokens as $name => $original) {
if ($name == 'id' && ($id = $index->datasource()->getItemId($item))) {
$replacements[$original] = $id;
}
elseif ($name == 'label' && ($label = $index->datasource()->getItemLabel($item))) {
$replacements[$original] = $label;
}
elseif ($name == 'url' && ($url = $index->datasource()->getItemUrl($item))) {
$url['options'] += $url_options;
$replacements[$original] = url($url['path'], $url['options']);
}
}
if (($url_tokens = token_find_with_prefix($tokens, 'url')) && ($url = $index->datasource()->getItemUrl($item))) {
$replacements += token_generate('url', $url_tokens, $url, $options);
}
}
break;
}
return $replacements;
}

View File

@@ -0,0 +1,38 @@
<?php
/**
* @file
* Contains the SearchApiSavedSearchesSettingsI18nStringObjectWrapper class.
*/
/**
* Customized i18n string integration controller.
*/
class SearchApiSavedSearchesSettingsI18nController extends EntityDefaultI18nStringController {
/**
* Overriddes EntityDefaultI18nStringController::hook_object_info() to include a custom object wrapper.
*/
public function hook_object_info() {
$info = parent::hook_object_info();
$info['search_api_saved_searches_settings']['class'] = 'SearchApiSavedSearchesSettingsI18nStringObjectWrapper';
return $info;
}
/**
* Overrides EntityDefaultI18nStringController::translatableProperties() to define our custom ones.
*/
protected function translatableProperties() {
$properties = array();
$properties['description'] = t('Description');
$properties['mail.activate.title'] = t('Activation mail, subject');
$properties['mail.activate.body'] = t('Activation mail, body');
$properties['mail.notify.title'] = t('Notification mail, subject');
$properties['mail.notify.body'] = t('Notification mail, body');
$properties['mail.notify.results'] = t('Notification mail, results replacement');
$properties['mail.notify.result'] = t('Notification mail, result item replacement');
$properties['mail.notify.results_capped'] = t('Notification mail, "Not all results" message');
return $properties;
}
}

View File

@@ -0,0 +1,16 @@
name = Search API saved searches translation
description = Translate Search API saved searches settings.
dependencies[] = search_api_saved_searches
dependencies[] = i18n_string
core = 7.x
package = Multilingual - Internationalization
files[] = search_api_saved_searches_i18n.controller.inc
files[] = search_api_saved_searches_i18n.string_wrapper.inc
; Information added by drupal.org packaging script on 2013-07-21
version = "7.x-1.2"
core = "7.x"
project = "search_api_saved_searches"
datestamp = "1374443489"

View File

@@ -0,0 +1,46 @@
<?php
/**
* @file
* Search API Saved Searches i18n integration module via entity API i18n support.
*
* @see EntityDefaultI18nController
*/
/**
* Implements hook_entity_info_alter().
*/
function search_api_saved_searches_i18n_entity_info_alter(&$info) {
// Enable i18n support via the entity API.
$info['search_api_saved_searches_settings']['i18n controller class'] = 'SearchApiSavedSearchesSettingsI18nController';
}
/**
* Implements hook_search_api_saved_searches_settings_insert().
*/
function search_api_saved_searches_i18n_search_api_saved_searches_settings_insert(SearchApiSavedSearchesSettings $settings) {
i18n_string_object_update('search_api_saved_searches_settings', $settings);
}
/**
* Implements hook_search_api_saved_searches_update().
*/
function search_api_saved_searches_i18n_search_api_saved_searches_settings_update(SearchApiSavedSearchesSettings $settings) {
// Account for name changes.
if ($settings->original->delta != $settings->delta) {
i18n_string_update_context("search_api_saved_searches:search_api_saved_searches_settings:{$settings->original->delta}:*", "search_api_saved_searches:search_api_saved_searches_settings:{$settings->delta}:*");
}
i18n_string_object_update('search_api_saved_searches_settings', $settings);
}
/**
* Implements hook_search_api_saved_searches_delete().
*/
function search_api_saved_searches_i18n_search_api_saved_searches_settings_delete(SearchApiSavedSearchesSettings $settings) {
if ($settings->hasStatus(ENTITY_IN_CODE)) {
i18n_string_object_update('search_api_saved_searches_settings', $settings);
}
else {
i18n_string_object_remove('search_api_saved_searches_settings', $settings);
}
}

View File

@@ -0,0 +1,50 @@
<?php
/**
* @file
* Contains the SearchApiSavedSearchesSettingsI18nStringObjectWrapper class.
*/
/**
* Custom i18n object wrapper.
*/
class SearchApiSavedSearchesSettingsI18nStringObjectWrapper extends i18n_string_object_wrapper {
/**
* Overrides i18n_string_object_wrapper::get_field() to read properties from the options array.
*/
public function get_field($field, $default = NULL) {
if (strpos($field, '.') !== FALSE) {
$value = drupal_array_get_nested_value($this->object->options, explode('.', $field));
if (isset($value)) {
return $value;
}
}
if (isset($this->object->options[$field])) {
return $this->object->options[$field];
}
// Fallback to the usual behaviour.
return parent::get_field($field, $default);
}
/**
* Get translatable properties
*/
protected function build_properties() {
$strings = parent::build_properties();
$properties = array();
// Dynamically add interval options.
foreach ($this->object->options['interval_options'] as $key => $value) {
$properties['interval_options.' . $key] = array(
'title' => t('Interval option, @key', array('@key' => $key)),
'string' => $value,
);
}
$strings[$this->get_textgroup()]['search_api_saved_searches_settings'][$this->object->delta] += $properties;
return $strings;
}
}

View File

@@ -0,0 +1,78 @@
<?php
/**
* @file
* Contains the SearchApiSavedSearchesViewsHandlerFieldInterval class.
*/
/**
* Views field handler for displaying a saved search's notification interval.
*/
class SearchApiSavedSearchesViewsHandlerFieldInterval extends views_handler_field_time_interval {
/**
* Overrides views_handler_field_time_interval::option_definition().
*
* Adds the custom_labels option.
*/
public function option_definition() {
$options = parent::option_definition();
$options['custom_labels'] = array('default' => FALSE);
return $options;
}
/**
* Overrides views_handler_field_time_interval::options_form().
*
* Adds the custom_labels option.
*/
public function options_form(&$form, &$form_state) {
$form['custom_labels'] = array(
'#type' => 'checkbox',
'#title' => t('Use custom labels defined in the saved search settings'),
'#default_value' => $this->options['custom_labels'],
);
parent::options_form($form, $form_state);
$form['granularity']['#dependency'] = array(
'edit-options-custom-labels' => array(0),
);
}
/**
* Overrides views_handler_field::query().
*
* Adds the settings_id field if custom labels should be used.
*/
public function query() {
parent::query();
if ($this->options['custom_labels']) {
$this->add_additional_fields(array('settings_id'));
}
}
/**
* Overrides views_handler_field_time_interval::render().
*
* Takes custom labels from the associated settings, if the corresponding
* handler option is enabled.
*/
public function render($values) {
if ($this->options['custom_labels']) {
$field = $this->aliases['settings_id'];
if ($values->$field && ($settings = search_api_saved_searches_settings_load($values->$field))) {
$intervals = $settings->getTranslatedOption('interval_options');
if (isset($intervals[$values->{$this->field_alias}])) {
return $intervals[$values->{$this->field_alias}];
}
}
}
if ($values->{$this->field_alias} < 0) {
return t('Never');
}
return parent::render($values);
}
}

View File

@@ -0,0 +1,63 @@
<?php
/**
* @file
* Contains the SearchApiSavedSearchesViewsHandlerFieldName class.
*/
/**
* Views field handler for displaying a saved search's name, optionally linked to the search page.
*/
class SearchApiSavedSearchesViewsHandlerFieldLink extends views_handler_field {
public function option_definition() {
$options = parent::option_definition();
$options['text'] = array('default' => '');
return $options;
}
public function options_form(&$form, &$form_state) {
$form['text'] = array(
'#type' => 'textfield',
'#title' => t('Link label'),
'#default_value' => $this->options['text'],
);
parent::options_form($form, $form_state);
// The path is set by render() so don't allow to set it.
$form['alter']['path'] = array('#access' => FALSE);
$form['alter']['external'] = array('#access' => FALSE);
}
public function query() {
$this->ensure_my_table();
$this->add_additional_fields();
}
public function render($values) {
$search = !empty($values->id) ? search_api_saved_search_load($values->id) : NULL;
if (search_api_saved_search_edit_access(NULL, $search)) {
$url = $url = 'search-api/saved-search/' . $search->id;
switch ($this->real_field) {
case 'edit_link':
$default_label = t('edit');
$url .= '/edit';
break;
case 'delete_link':
$default_label = t('delete');
$url .= '/delete';
break;
default:
return;
}
$this->options['alter']['make_link'] = TRUE;
$this->options['alter']['path'] = $url;
return $this->options['text'] ? $this->options['text'] : $default_label;
}
}
}

View File

@@ -0,0 +1,52 @@
<?php
/**
* @file
* Contains the SearchApiSavedSearchesViewsHandlerFieldName class.
*/
/**
* Views field handler for displaying a saved search's name, optionally linked to the search page.
*/
class SearchApiSavedSearchesViewsHandlerFieldName extends views_handler_field {
public function option_definition() {
$options = parent::option_definition();
$options['link_to_page'] = array('default' => TRUE);
return $options;
}
public function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
$form['link_to_page'] = array(
'#type' => 'checkbox',
'#title' => t('Link to search page'),
'#default_value' => $this->options['link_to_page'],
);
}
public function render($values) {
$value = parent::render($values);
if ($value && $this->options['link_to_page']) {
$this->render_link($values);
}
return $value;
}
public function render_link($values) {
$search = !empty($values->id) ? search_api_saved_search_load($values->id) : NULL;
if (search_api_saved_search_edit_access(NULL, $search) && !empty($search->options['page'])) {
$this->options['alter']['make_link'] = TRUE;
$page = $search->options['page'] + array(
'path' => NULL,
'query' => array(),
'absolute' => TRUE,
);
$this->options['alter']['path'] = url($page['path'], $page);
}
}
}

View File

@@ -0,0 +1,65 @@
<?php
/**
* @file
* Defines Views hook implementations.
*/
/**
* Implements hook_views_data_alter().
*
* Adds relationships to the creator of a saved search, its settings and the
* search index, as well as edit and delete links, and changes some field
* handlers.
*/
function search_api_saved_searches_views_data_alter(array &$data) {
// Relationship: settings => index.
$data['search_api_saved_searches_settings']['index_id']['relationship'] = array(
'base' => 'search_api_index',
'base field' => 'machine_name',
'title' => t('Search index'),
'label' => t('search index'),
);
// Relationship: search => user.
$data['search_api_saved_search']['uid']['relationship'] = array(
'base' => 'users',
'base field' => 'uid',
'title' => t('User'),
'label' => t('user'),
);
// Relationship: search => settings.
$data['search_api_saved_search']['settings_id']['relationship'] = array(
'base' => 'search_api_saved_searches_settings',
'base field' => 'delta',
'title' => t('Settings'),
'label' => t('settings'),
);
// Proper field type for notify_interval.
$data['search_api_saved_search']['notify_interval']['field']['handler'] = 'SearchApiSavedSearchesViewsHandlerFieldInterval';
$data['search_api_saved_search']['notify_interval']['field']['additional fields'] = array('id');
// Use our own handler so we can link the name to the search results.
$data['search_api_saved_search']['name']['field']['handler'] = 'SearchApiSavedSearchesViewsHandlerFieldName';
$data['search_api_saved_search']['name']['field']['additional fields'] = array('id');
// We have to do this here, not in hook_views_data(), since the table itself
// comes from another module and one definition would overwrite the other.
$data['search_api_saved_search']['edit_link']['field'] = array(
'title' => t('Edit link'),
'help' => t('Display a link that allows the user to edit the saved search, if they have the necessary permissions.'),
'handler' => 'SearchApiSavedSearchesViewsHandlerFieldLink',
'additional fields' => array('id'),
);
$data['search_api_saved_search']['delete_link']['field'] = array(
'title' => t('Delete link'),
'help' => t('Display a link that allows the user to delete the saved search, if they have the necessary permissions.'),
'handler' => 'SearchApiSavedSearchesViewsHandlerFieldLink',
'additional fields' => array('id'),
);
$data['search_api_saved_search']['results']['field'] = array(
'title' => t('Results'),
'help' => t('The saved search results of this search.'),
'handler' => 'entity_views_handler_field_text',
'additional fields' => array('id'),
'type' => 'list<token>',
);
}

View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1 @@
See major version branches.

View File

@@ -0,0 +1,11 @@
name = Search API Solr Overrides
description = Provides site specific overrides for search_api_solr configuration.
core = 7.x
dependencies[] = search_api_solr
; Information added by drupal.org packaging script on 2013-10-01
version = "7.x-1.0-rc1+1-dev"
core = "7.x"
project = "search_api_solr_overrides"
datestamp = "1380626863"

View File

@@ -0,0 +1,60 @@
<?php
/**
* @file
* Core hook implementations for Search API Solr Overrides.
*/
/**
* Implements hook_search_api_server_load().
*
* Provide a configuration as the same structure as the
* search api server entity in array form (keyed by the
* machine name of the solr service).
*
* Example:
* $conf['search_api_solr_overrides'] = array(
* 'solr-server-id' => array(
* 'name' => t('Solr Server (Overridden)'),
* 'options' => array(
* 'host' => '127.0.0.1',
* 'port' => 8983,
* 'path' => '/solr',
* ),
* ),
* ),
* );
*
* Note: This is an example as solr configurations vary.
*/
function search_api_solr_overrides_search_api_server_load($servers) {
// Get the solr host overrides.
$overrides = variable_get('search_api_solr_overrides', FALSE);
// Ensure the is information provided.
if (empty($overrides)) {
return;
}
// Loop over an make the required updates.
foreach ($overrides as $id => $override) {
// Check to see if the server config exists.
if (!empty($servers[$id])) {
foreach ($servers[$id] as $key => $field) {
// Ensure we need to override.
if (empty($override[$key])) {
continue;
}
// Check for if the field is an array.
if (is_array($field)) {
$servers[$id]->$key = array_merge($servers[$id]->$key, $override[$key]);
}
// Else its a value.
else {
$servers[$id]->$key = $override[$key];
}
}
}
}
}

View File

@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -0,0 +1,15 @@
name = Search API stats term blocks
description = "Display Drupal blocks for top search terms."
dependencies[] = search_api_stats
core = 7.x
package = Search
; Classes
; Views Handlers
; Information added by drupal.org packaging script on 2012-08-15
version = "7.x-1.1"
core = "7.x"
project = "search_api_stats"
datestamp = "1345066383"

View File

@@ -0,0 +1,134 @@
<?php
/**
* @file
* search_api_stats_block.module
*/
/**
* Implements hook_block_info().
*/
function search_api_stats_block_block_info() {
$blocks = array();
foreach (search_api_index_load_multiple(FALSE) as $index) {
$blocks[$index->server . '__' . $index->machine_name] = array(
'info' => t('Search API stats block: @identifier', array('@identifier' => $index->server . ' - ' . $index->machine_name)),
'cache' => DRUPAL_CACHE_GLOBAL,
);
}
return $blocks;
}
/**
* Implements hook_block_view().
*/
function search_api_stats_block_block_view($delta = '') {
$block = array();
list($s_name, $i_name) = explode('__', $delta);
if (!empty($s_name) && !empty($i_name)) {
$block = array(
'subject' => t('Top search phrases'),
'content' => _search_api_stats_block_show_keywords($s_name, $i_name),
);
}
return $block;
}
/**
* Implements hook_block_configure().
*/
function search_api_stats_block_block_configure($delta = '') {
$form = array();
$config = variable_get('search_api_stats_block_config', array());
list($s_name, $i_name) = explode('__', $delta);
if (!empty($s_name) && !empty($i_name)) {
// Number of top search phrases to display
$form['search_api_stats_block_num_phrases'] = array(
'#type' => 'select',
'#title' => t('Number of top search phrases to display'),
'#default_value' => empty($config[$s_name][$i_name]['num_phrases']) ? 8 : $config[$s_name][$i_name]['num_phrases'],
'#options' => drupal_map_assoc(array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30)),
);
// Path of search page
$form['search_api_stats_block_path'] = array(
'#type' => 'textfield',
'#title' => t('Path of search page'),
'#default_value' => empty($config[$s_name][$i_name]['path']) ? '' : $config[$s_name][$i_name]['path'],
'#required' => TRUE,
);
// Parameter name for the search phrase
$form['search_api_stats_block_param_name'] = array(
'#type' => 'textfield',
'#title' => t('Parameter name for the search phrase'),
'#default_value' => empty($config[$s_name][$i_name]['param_name']) ? 'keywords' : $config[$s_name][$i_name]['param_name'],
'#required' => TRUE,
);
}
return $form;
}
/**
* Implements hook_block_save().
*/
function search_api_stats_block_block_save($delta = '', $edit = array()) {
$config = variable_get('search_api_stats_block_config', array());
list($s_name, $i_name) = explode('__', $delta);
if (!empty($s_name) && !empty($i_name)) {
// Number of top search phrases to display
$config[$s_name][$i_name]['num_phrases'] = (int)$edit['search_api_stats_block_num_phrases'];
// Path of search page
$config[$s_name][$i_name]['path'] = $edit['search_api_stats_block_path'];
// Parameter name for the search phrase
$config[$s_name][$i_name]['param_name'] = $edit['search_api_stats_block_param_name'];
}
variable_set('search_api_stats_block_config', $config);
}
/**
* Implements hook_theme().
*/
function search_api_stats_block_theme($existing, $type, $theme, $path) {
return array(
'search_api_stats_block' => array(
'variables' => array('phrases' => NULL, 'path' => NULL, 'param_name' => NULL),
'file' => 'search_api_stats_block.theme.inc',
),
);
}
/**
* Responsible for querying the database and generating the list of phrases.
* @param string $s_name The machine name of the Search API server
* @param string $i_name The machine name of the Search API index
* @return markup Complete markup for the block content
*/
function _search_api_stats_block_show_keywords($s_name, $i_name) {
$config = variable_get('search_api_stats_block_config', array());
// Default variables passed to theming function.
$phrases = array();
$path = empty($config[$s_name][$i_name]['path']) ? '' : $config[$s_name][$i_name]['path'];
$param_name = empty($config[$s_name][$i_name]['param_name']) ? 'keywords' : $config[$s_name][$i_name]['param_name'];
$result = db_query_range("SELECT *, count(*) as num FROM {search_api_stats} WHERE s_name=:s_name AND i_name=:i_name GROUP BY keywords ORDER BY num DESC", 0, 8, array(':s_name' => $s_name, ':i_name' => $i_name));
foreach ($result as $phrase) {
$phrases[$phrase->keywords] = (array)$result;
}
return theme('search_api_stats_block', array('phrases' => $phrases, 'path' => $path, 'param_name' => $param_name));
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* @file
* search_api_stats_block.theme.inc
*/
function theme_search_api_stats_block($vars) {
$links = array();
$attributes = array(
'class' => array('search-api-stats-top-phrases'),
);
foreach ($vars['phrases'] as $key => $phrase) {
$links[$key] = array(
'title' => $key,
'href' => $vars['path'],
'query' => array(
$vars['param_name'] => $key,
),
);
}
return theme('links', array('links' => $links, 'attributes' => $attributes));
}

View File

@@ -0,0 +1,15 @@
name = Search API stats reporting tool
description = "Generate reports for viewing statistics from Search API queries."
dependencies[] = search_api_stats
core = 7.x
package = Search
; Classes
; Views Handlers
; Information added by drupal.org packaging script on 2012-08-15
version = "7.x-1.1"
core = "7.x"
project = "search_api_stats"
datestamp = "1345066383"

View File

@@ -0,0 +1,15 @@
name = Search API stats
description = "Enabling the recording and presentation of statistics for the Search API module."
dependencies[] = search_api
core = 7.x
package = Search
; Classes
; Views Handlers
; Information added by drupal.org packaging script on 2012-08-15
version = "7.x-1.1"
core = "7.x"
project = "search_api_stats"
datestamp = "1345066383"

View File

@@ -0,0 +1,133 @@
<?php
/**
* @file
* Install, update and uninstall functions for the search_api_stats module.
*
*/
/**
* Implements hook_install().
*/
function search_api_stats_install() {
}
/**
* Implements hook_uninstall().
*/
function search_api_stats_uninstall() {
}
/**
* Implements hook_enable().
*/
function search_api_stats_enable() {
}
/**
* Implements hook_schema().
*/
function search_api_stats_schema() {
$schema['search_api_stats'] = array(
'description' => 'Table that contains a log of Search API queries and performance.',
'fields' => array(
'qid' => array(
'type' => 'serial',
'not null' => TRUE,
'description' => 'Primary Key: Unique log ID.',
),
's_name' => array(
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
'description' => 'Search API server machine_name',
),
'i_name' => array(
'type' => 'varchar',
'length' => 50,
'not null' => TRUE,
'description' => 'Search API index machine_name',
),
'timestamp' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'Unix timestamp of when query occurred.',
),
'numfound' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'Number of results.',
),
'total_time' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'Total query time (miliseconds).',
),
'prepare_time' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'Time taken by Search API prepare phase for this query (miliseconds).',
),
'process_time' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'Time taken by Search API process phase for this query (miliseconds).',
),
'uid' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'The {users}.uid of the user who triggered the query.',
),
'sid' => array(
'type' => 'varchar',
'length' => 64,
'not null' => TRUE,
'default' => '',
'description' => 'Session ID of user who triggered the query.',
),
'showed_suggestions' => array(
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'Indicates whether a spelling suggestion was shown.',
),
'page' => array(
'type' => 'varchar',
'length' => 10,
'not null' => TRUE,
'default' => '',
'description' => 'Current results page.',
),
'keywords' => array(
'type' => 'varchar',
'length' => 128,
'not null' => FALSE,
'default' => '',
'description' => 'Query keywords arguments.',
),
'filters' => array(
'type' => 'text',
'size' => 'normal',
'not null' => TRUE,
'description' => 'Query filter arguments.',
),
'sort' => array(
'type' => 'varchar',
'length' => 128,
'not null' => TRUE,
'description' => 'Query sort arguments.',
),
),
'primary key' => array('qid'),
);
return $schema;
}

View File

@@ -0,0 +1,40 @@
<?php
/**
* @file
* search_api_stats.module
*/
/**
* Implements hook_search_api_query_alter($query).
*
* @param SearchApiQueryInterface $query
* The SearchApiQueryInterface object representing the search query.
*/
function search_api_stats_search_api_query_alter(SearchApiQueryInterface $query) {
global $user;
// Assign some object variables to avoid chained member access.
$index = $query->getIndex();
if (!empty($index)) {
$server = $index->server();
}
// Fail out if there's no valid index or server objects to work from.
if (empty($index) || empty($server)) {
return;
}
$log = array(
's_name' => $server->machine_name,
'i_name' => $index->machine_name,
'timestamp' => REQUEST_TIME,
'uid' => $user->uid,
'sid' => session_id(),
'keywords' => trim(drupal_strtolower($query->getOriginalKeys())),
'filters' => '',
'sort' => '',
);
drupal_write_record('search_api_stats', $log);
}