Compare commits

...
56 Commits
Author SHA1 Message Date
Bachir Soussi Chiadmi e36279d8b1 changed materio_serach_api, query configuration by query 2016-03-16 12:35:55 +01:00
Bachir Soussi Chiadmi 0b6e0c10cb updated search feature 2016-03-02 10:15:50 +01:00
Bachir Soussi Chiadmi ba1ec7113e updated search_api and search_api_solr 2016-03-01 16:23:45 +01:00
Bachir Soussi Chiadmi deb2bff572 print fine tuning 2016-01-21 12:02:55 +01:00
Bachir Soussi Chiadmi 538c791bae fine tunning print fiche 2016-01-20 18:15:38 +01:00
Bachir Soussi Chiadmi df107a0443 fixed printed material
WARNING : we are nox using gulp instead of grunt, watch for bugs
2016-01-19 19:23:16 +01:00
Bachir Soussi Chiadmi c9b16289ef added remove duplicates modules 2016-01-19 15:10:33 +01:00
Bachir Soussi Chiadmi b4acd7d8bb updated video filter module to handle https on embeded videos 2015-12-20 10:56:50 +01:00
Bachir Soussi Chiadmi 3af02617b4 added html5 boiler plate mime headers to htaccess 2015-12-19 21:36:40 +01:00
Bachir Soussi Chiadmi 0fdb4abd71 ajax autocomplete fixe 2015-12-03 12:23:53 +01:00
Bachir Soussi Chiadmi 90be34eef1 updated htaccess 2015-12-02 17:17:06 +01:00
Bachir Soussi Chiadmi 3e984dc6c5 updated htaccess 2015-12-02 17:13:13 +01:00
Bachir Soussi Chiadmi a0cb0b2171 updated htaccess 2015-12-02 16:57:17 +01:00
Bachir Soussi Chiadmi f6346b0195 updated htaccess 2015-12-02 16:52:56 +01:00
Bachir Soussi Chiadmi 300f698989 updated htaccess 2015-12-02 16:46:36 +01:00
Bachir Soussi Chiadmi 8cbb5f8c4c updated htaccess 2015-12-02 16:45:51 +01:00
Bachir Soussi Chiadmi a106b98209 updated htaccess 2015-12-02 16:30:59 +01:00
Bachir Soussi Chiadmi 8fe92dbcc7 updated htaccess 2015-12-02 16:29:02 +01:00
Bachir Soussi Chiadmi 60f2c5c7fa updated htaccess 2015-12-02 15:20:02 +01:00
Bachir Soussi Chiadmi d96c17454b updated htaccess 2015-12-02 11:40:34 +01:00
Bachir Soussi Chiadmi ed6ae84181 added ubercart ssl module 2015-12-02 11:36:55 +01:00
Bachir Soussi Chiadmi 35e914df58 created admon taxo view 2015-11-25 11:34:49 +01:00
Bachir Soussi Chiadmi 6b46869a16 htaccess : all redirects are handle by claranet 2015-11-25 09:47:27 +01:00
Bachir Soussi Chiadmi 892dba801f added entity_translation_export_import module 2015-11-25 00:53:33 +01:00
Bachir Soussi Chiadmi 50dfd2d89b removed i18n_taxonomy module from features dependencies
fixed some bugs
2015-11-24 23:50:19 +01:00
Bachir Soussi Chiadmi 9a18821b7e fixed search api materio settings 2015-11-24 18:17:34 +01:00
Bachir Soussi Chiadmi 82bf36a5eb recreated features 2015-11-24 18:05:48 +01:00
Bachir Soussi Chiadmi 3eb20676ca search api autocomplet t() for transmlate term name 2015-11-24 16:51:48 +01:00
Bachir Soussi Chiadmi 2155a66eb1 added special menu items module 2015-11-24 15:29:54 +01:00
Bachir Soussi Chiadmi 62fef652fc removed redirects from htaccess, claranet will handle this on vhosts 2015-11-24 15:15:10 +01:00
Bachir Soussi Chiadmi 951c9114a2 added code for remove all http on file address 2015-11-24 13:42:37 +01:00
Bachir Soussi Chiadmi edba04f103 htaccess fixe 2015-11-24 13:23:18 +01:00
Bachir Soussi Chiadmi 26ab9aa56b htaccess fixe 2015-11-24 13:22:11 +01:00
Bachir Soussi Chiadmi 5716acf5bb htaccess fixe 2015-11-24 13:20:51 +01:00
Bachir Soussi Chiadmi 12fe570fbd htaccess fixe 2015-11-24 13:20:11 +01:00
Bachir Soussi Chiadmi 66ee9c6657 htaccess fixe 2015-11-24 13:19:01 +01:00
Bachir Soussi Chiadmi ca5231f1fe htaccess fixe 2015-11-24 13:09:04 +01:00
Bachir Soussi Chiadmi b9a8db8140 htaccess fixe 2015-11-24 13:08:22 +01:00
Bachir Soussi Chiadmi d25e7428bc htaccess fixe 2015-11-24 12:55:37 +01:00
Bachir Soussi Chiadmi 3027b3985b htaccess fixe 2015-11-24 12:55:09 +01:00
Bachir Soussi Chiadmi d214a44291 htaccess fixe 2015-11-24 12:49:06 +01:00
Bachir Soussi Chiadmi fc7753f7a0 htaccess fixe 2015-11-24 12:48:26 +01:00
Bachir Soussi Chiadmi 7c51b255fb htaccess fixe 2015-11-24 12:47:26 +01:00
Bachir Soussi Chiadmi 5e099d48de htaccess fixe 2015-11-24 12:35:16 +01:00
Bachir Soussi Chiadmi bf84ac06cd htaccess fixe 2015-11-24 12:34:56 +01:00
Bachir Soussi Chiadmi 87beabee92 htaccess fixe 2015-11-24 12:29:51 +01:00
Bachir Soussi Chiadmi f6ee366a71 htaccess fixe 2015-11-24 12:29:32 +01:00
Bachir Soussi Chiadmi b216e30f28 htaccess fixe 2015-11-24 12:28:04 +01:00
Bachir Soussi Chiadmi 0a863fc1bb htaccess ssl 2015-11-24 12:26:56 +01:00
Bachir Soussi Chiadmi a5edc41323 htaccess fixe 2015-11-24 12:12:57 +01:00
Bachir Soussi Chiadmi 1cc2c9af75 updated term csv files 2015-11-24 11:17:12 +01:00
Bachir Soussi Chiadmi cc653b73be bug fixe 2015-11-24 11:02:29 +01:00
Bachir Soussi Chiadmi 73993a539b added fr2en batch function 2015-11-24 10:59:13 +01:00
Bachir Soussi Chiadmi d7e7410950 added term_merge module 2015-11-24 10:56:30 +01:00
Bachir Soussi Chiadmi 7298235d4f added taxonomy wrangler module 2015-11-23 14:47:44 +01:00
Bachir Soussi Chiadmi fc0a779214 fixed bookmarks for students 2015-10-21 20:22:58 +02:00
174 changed files with 27187 additions and 16367 deletions
+149 -106
View File
@@ -3,7 +3,7 @@
#
# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig\.save)$">
Order allow,deny
</FilesMatch>
@@ -20,7 +20,7 @@ ErrorDocument 404 /index.php
DirectoryIndex index.php index.html index.htm
# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_initialize_variables() in
# sites/default/default.settings.php and drupal_environment_initialize() in
# includes/bootstrap.inc for settings that can be changed at runtime.
# PHP 5, Apache 1 and 2.
@@ -56,6 +56,17 @@ DirectoryIndex index.php index.html index.htm
<IfModule mod_rewrite.c>
RewriteEngine on
# Set "protossl" to "s" if we were accessed via https://. This is used later
# if you enable "www." stripping or enforcement, in order to ensure that
# you don't bounce between http and https.
RewriteRule ^ - [E=protossl]
RewriteCond %{HTTPS} on
RewriteRule ^ - [E=protossl:s]
# Make sure Authorization HTTP header is available to PHP
# even when running as CGI or FastCGI.
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Block access to "hidden" directories whose names begin with a period. This
# includes directories used by version control systems such as Subversion or
# Git to store control files. Files whose names begin with a period, as well
@@ -71,18 +82,6 @@ DirectoryIndex index.php index.html index.htm
# downloaded.
RewriteRule "(^|/)\." - [F]
# custom
RewriteCond %{HTTP_HOST} ^basebeta\.materio\.com [OR]
RewriteCond %{HTTP_HOST} ^materio\.com [OR]
RewriteCond %{HTTP_HOST} ^www\.materio\.fr [OR]
RewriteCond %{HTTP_HOST} ^materio\.fr [OR]
RewriteCond %{HTTP_HOST} ^www\.materio\.net [OR]
RewriteCond %{HTTP_HOST} ^materio\.net [OR]
RewriteCond %{HTTP_HOST} ^www\.materio\.eu [OR]
RewriteCond %{HTTP_HOST} ^materio\.eu [NC]
RewriteRule ^ http://www.materio.com%{REQUEST_URI} [L,R=301]
# If your site can be accessed both with and without the 'www.' prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
@@ -90,14 +89,32 @@ DirectoryIndex index.php index.html index.htm
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} .
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]
# RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]
# redirect all materiau domains to materio.com
RewriteCond %{HTTP_HOST} ^basebeta\.materio\.com [OR]
RewriteCond %{HTTP_HOST} ^www\.materio\.fr [OR]
RewriteCond %{HTTP_HOST} ^materio\.fr [OR]
RewriteCond %{HTTP_HOST} ^www\.materio\.net [OR]
RewriteCond %{HTTP_HOST} ^materio\.net [OR]
RewriteCond %{HTTP_HOST} ^www\.materio\.eu [OR]
RewriteCond %{HTTP_HOST} ^materio\.eu [OR]
RewriteCond %{HTTP_HOST} ^www\.materio\.com
# RewriteRule ^ http%{ENV:protossl}://materio.com%{REQUEST_URI} [L,R=301]
RewriteRule ^ https://materio.com%{REQUEST_URI} [L,R=301]
# Redirect to HTTPS
# RewriteCond %{HTTPS} off
# RewriteCond %{HTTP:X-Forwarded-Proto} !https
# RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
@@ -116,24 +133,6 @@ DirectoryIndex index.php index.html index.htm
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]
## local
# RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1
## maison quentin
# RewriteCond %{REMOTE_ADDR} !^86\.68\.188\.175
## materio
# RewriteCond %{REMOTE_ADDR} !^212\.198\.136\.215
## maison bach
# RewriteCond %{REMOTE_ADDR} !^82\.230\.62\.145
# RewriteRule !maintenance http://www.materio.com/maintenance [L,R=302,E=nocache:1]
## http://mark.koli.ch/2010/12/set-cache-control-and-expires-headers-on-a-redirect-with-mod-rewrite.html
## Set the response header if the "nocache" environment variable is set
## in the RewriteRule above.
# Header always set Cache-Control "no-store, no-cache, must-revalidate" env=nocache
## Set Expires too ...
# Header always set Expires "Thu, 01 Jan 1970 00:00:00 GMT" env=nocache
# Rules to correctly serve gzip compressed CSS and JS files.
# Requires both mod_rewrite and mod_headers to be enabled.
<IfModule mod_headers.c>
@@ -160,94 +159,138 @@ DirectoryIndex index.php index.html index.htm
</IfModule>
</IfModule>
# Add headers to all responses.
<IfModule mod_headers.c>
# Disable content sniffing, since it's an attack vector.
Header always set X-Content-Type-Options nosniff
</IfModule>
# from boiler plate V5.02
# FROM Html5 BoilerPlate 4.0
# ######################################################################
# # MEDIA TYPES AND CHARACTER ENCODINGS #
# ######################################################################
# ----------------------------------------------------------------------
# Proper MIME type for all files
# | Media types |
# ----------------------------------------------------------------------
# JavaScript
# Normalize to standard type (it's sniffed in IE anyways)
# tools.ietf.org/html/rfc4329#section-7.2
AddType application/javascript js jsonp
AddType application/json json
# Serve resources with the proper media types (f.k.a. MIME types).
#
# https://www.iana.org/assignments/media-types/media-types.xhtml
# https://httpd.apache.org/docs/current/mod/mod_mime.html#addtype
# Audio
AddType audio/ogg oga ogg
AddType audio/mp4 m4a f4a f4b
<IfModule mod_mime.c>
# Video
AddType video/ogg ogv
AddType video/mp4 mp4 m4v f4v f4p
AddType video/webm webm
AddType video/x-flv flv
# Data interchange
# SVG
# Required for svg webfonts on iPad
# twitter.com/FontSquirrel/status/14855840545
AddType image/svg+xml svg svgz
AddEncoding gzip svgz
# Webfonts
AddType application/vnd.ms-fontobject eot
AddType application/x-font-ttf ttf ttc
AddType font/opentype otf
AddType application/x-font-woff woff
# Assorted types
AddType image/x-icon ico
AddType image/webp webp
AddType text/cache-manifest appcache manifest
AddType text/x-component htc
AddType application/xml rss atom xml rdf
AddType application/x-chrome-extension crx
AddType application/x-opera-extension oex
AddType application/x-xpinstall xpi
AddType application/octet-stream safariextz
AddType application/x-web-app-manifest+json webapp
AddType text/x-vcard vcf
AddType application/x-shockwave-flash swf
AddType text/vtt vtt
AddType application/atom+xml atom
AddType application/json json map topojson
AddType application/ld+json jsonld
AddType application/rss+xml rss
AddType application/vnd.geo+json geojson
AddType application/xml rdf xml
# JavaScript
# Normalize to standard type.
# https://tools.ietf.org/html/rfc4329#section-7.2
AddType application/javascript js
# Manifest files
AddType application/manifest+json webmanifest
AddType application/x-web-app-manifest+json webapp
AddType text/cache-manifest appcache
# Media files
AddType audio/mp4 f4a f4b m4a
AddType audio/ogg oga ogg opus
AddType image/bmp bmp
AddType image/svg+xml svg svgz
AddType image/webp webp
AddType video/mp4 f4v f4p m4v mp4
AddType video/ogg ogv
AddType video/webm webm
AddType video/x-flv flv
# Serving `.ico` image files with a different media type
# prevents Internet Explorer from displaying then as images:
# https://github.com/h5bp/html5-boilerplate/commit/37b5fec090d00f38de64b591bcddcb205aadf8ee
AddType image/x-icon cur ico
# Web fonts
AddType application/font-woff woff
AddType application/font-woff2 woff2
AddType application/vnd.ms-fontobject eot
# Browsers usually ignore the font media types and simply sniff
# the bytes to figure out the font type.
# https://mimesniff.spec.whatwg.org/#matching-a-font-type-pattern
#
# However, Blink and WebKit based browsers will show a warning
# in the console if the following font types are served with any
# other media types.
AddType application/x-font-ttf ttc ttf
AddType font/opentype otf
# Other
AddType application/octet-stream safariextz
AddType application/x-bb-appworld bbaw
AddType application/x-chrome-extension crx
AddType application/x-opera-extension oex
AddType application/x-xpinstall xpi
AddType text/vcard vcard vcf
AddType text/vnd.rim.location.xloc xloc
AddType text/vtt vtt
AddType text/x-component htc
</IfModule>
# ----------------------------------------------------------------------
# UTF-8 encoding
# | Character encodings |
# ----------------------------------------------------------------------
# Use UTF-8 encoding for anything served text/plain or text/html
# Serve all resources labeled as `text/html` or `text/plain`
# with the media type `charset` parameter set to `UTF-8`.
#
# https://httpd.apache.org/docs/current/mod/core.html#adddefaultcharset
AddDefaultCharset utf-8
# Force UTF-8 for a number of file formats
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Serve the following file types with the media type `charset`
# parameter set to `UTF-8`.
#
# https://httpd.apache.org/docs/current/mod/mod_mime.html#addcharset
# ----------------------------------------------------------------------
# A little more security
# ----------------------------------------------------------------------
# Block access to "hidden" directories or files whose names begin with a
# period. This includes directories used by version control systems such as
# Subversion or Git.
<IfModule mod_rewrite.c>
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]
</IfModule>
# Block access to backup and source files. These files may be left by some
# text/html editors and pose a great security danger, when anyone can access
# them.
<FilesMatch "(\.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)|~)$">
Order allow,deny
Deny from all
Satisfy All
</FilesMatch>
# Increase cookie security
<IfModule php5_module>
php_value session.cookie_httponly true
<IfModule mod_mime.c>
AddCharset utf-8 .atom \
.bbaw \
.css \
.geojson \
.js \
.json \
.jsonld \
.manifest \
.rdf \
.rss \
.topojson \
.vtt \
.webapp \
.webmanifest \
.xloc \
.xml
</IfModule>
+2 -3
View File
@@ -17,9 +17,9 @@ feedback
filter_path_alias
flag_lists
//nodeformcols
search_api
//search_api
search_api_page
search_api_solr
//search_api_solr
termreferencetree
views
wysiwyg
@@ -27,4 +27,3 @@ views_rss_media
node_export :
- https://www.drupal.org/node/1869918
- https://www.drupal.org/node/1911638
@@ -0,0 +1 @@
.DS_Store
@@ -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.
@@ -0,0 +1,539 @@
<?php
/**
* Menu Callback. Handles the export of the translatable entities.
*/
function entity_translation_export_import_admin_export_form($form, $form_state){
$form = array('#tree' => TRUE);
// Get translatable entity types.
$enabled = variable_get('entity_translation_entity_types', array());
$info = entity_get_info();
$entities_options = array();
$bundles_options = array();
$fields_options = array();
// Get the translatable fields foreach translatable entity_type.
foreach ($enabled as $entity_type) {
if (entity_translation_enabled($entity_type)) {
$bundles = !empty($info[$entity_type]['bundles']) ? array_keys($info[$entity_type]['bundles']) : array($entity_type);
foreach ($bundles as $bundle) {
$settings = entity_translation_settings($entity_type, $bundle);
if (entity_translation_enabled_bundle($entity_type, $bundle) && ($handler = entity_translation_get_handler($entity_type, $bundle))) {
$fields_info = field_info_instances($entity_type, $bundle);
foreach ($fields_info as $field_name => $value) {
$field = field_info_field($field_name);
if(field_is_translatable($entity_type, $field) and in_array($field['type'], array('text', 'text_long', 'text_with_summary')) and $field['cardinality'] == 1){
if(!array_key_exists($entity_type, $entities_options)){
$entities_options[$entity_type] = $info[$entity_type]['label'];
}
if(!isset($bundles_options[$entity_type][$bundle])){
$bundles_options[$entity_type][$bundle] = $info[$entity_type]['bundles'][$bundle]['label'];
}
$field_value = $entity_type . ':' . $bundle . ':' . $field_name;
if(!isset($fields_options[$entity_type][$bundle][$field_value])){
$fields_options[$entity_type][$bundle][$field_value] = $value['label'];
}
}
}
}
}
}
}
// If there is no translatable field yet.
if(empty($fields_options)){
$form['no_result'] = array('#markup' => '<p>' . t('You need to enable entity translation for at least one field.') . '</p>');
}
else{
drupal_set_title(t('Export entity translations'));
$form['export'] = array(
'#type' => 'fieldset',
'#title' => t('Export Settings'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
);
$form['export']['entity_type'] = array(
'#type' => 'checkboxes',
'#options' => $entities_options,
'#ajax' => array(
'callback' => 'entity_translation_export_import_admin_export_bundle_callback',
'wrapper' => 'entity-type-wrapper',
),
);
$form['export']['entity_type_wrapper'] = array(
'#type' => 'container',
'#id' => 'entity-type-wrapper',
);
if(isset($form_state['values']['export']['entity_type'])){
foreach($form_state['values']['export']['entity_type'] as $entity_type => $entity_type_value){
if($entity_type_value){
$form['export']['entity_type_wrapper'][$entity_type] = array(
'#type' => 'fieldset',
'#title' => $entities_options[$entity_type],
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
foreach($bundles_options[$entity_type] as $bundle_option){
$form['export']['entity_type_wrapper'][$entity_type]['bundle'] = array(
'#type' => 'checkboxes',
'#options' => $bundles_options[$entity_type],
'#ajax' => array(
'callback' => 'entity_translation_export_import_admin_export_fields_callback',
'wrapper' => drupal_html_class($entity_type . '-bundle-wrapper'),
),
);
$form['export']['entity_type_wrapper'][$entity_type]['bundle_wrapper'] = array(
'#type' => 'container',
'#id' => drupal_html_class($entity_type . '-bundle-wrapper'),
);
if(isset($form_state['values']['export']['entity_type_wrapper'][$entity_type]['bundle'])){
foreach($form_state['values']['export']['entity_type_wrapper'][$entity_type]['bundle'] as $bundle => $bundle_value){
if($bundle_value){
$form['export']['entity_type_wrapper'][$entity_type]['bundle_wrapper'][$bundle] = array(
'#type' => 'fieldset',
'#title' => $bundles_options[$entity_type][$bundle],
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
foreach($bundles_options[$entity_type] as $bundle_option){
$form['export']['entity_type_wrapper'][$entity_type]['bundle_wrapper'][$bundle]['field'] = array(
'#type' => 'checkboxes',
'#options' => $fields_options[$entity_type][$bundle],
);
}
}
}
}
}
}
}
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Export Translations'),
);
}
return $form;
}
/**
* Ajax callback.
*/
function entity_translation_export_import_admin_export_bundle_callback($form, $form_state){
$parents = array_slice($form_state['triggering_element']['#array_parents'], 0, -2);
$element = drupal_array_get_nested_value($form, $parents);
return $element['entity_type_wrapper'];
}
/**
* Ajax callback.
*/
function entity_translation_export_import_admin_export_fields_callback($form, $form_state){
$parents = array_slice($form_state['triggering_element']['#array_parents'], 0, -2);
$element = drupal_array_get_nested_value($form, $parents);
return $element['bundle_wrapper'];
}
/**
* Submit callback.
*/
function entity_translation_export_import_admin_export_form_validate($form, $form_state){
// Get all entities to export.
$at_least_one_field = FALSE;
if(isset($form_state['values']['export']['entity_type_wrapper'])){
foreach($form_state['values']['export']['entity_type_wrapper'] as $entity_type => $entity_type_value) {
if($entity_type_value and isset($entity_type_value['bundle_wrapper'])){
foreach($entity_type_value['bundle_wrapper'] as $bundle => $bundle_value) {
if($bundle_value){
foreach($bundle_value['field'] as $field_value){
if($field_value){
$at_least_one_field = TRUE;
}
}
}
}
}
}
}
if(!$at_least_one_field){
form_set_error('', t('You need to select at least one field.'));
}
}
/**
* Submit callback.
*/
function entity_translation_export_import_admin_export_form_submit($form, $form_state){
// Get all entities to export.
$entities = array();
foreach($form_state['values']['export']['entity_type_wrapper'] as $entity_type => $entity_type_value) {
if($entity_type_value){
foreach($entity_type_value['bundle_wrapper'] as $bundle => $bundle_value) {
if($bundle_value){
foreach($bundle_value['field'] as $field_value){
if($field_value){
$parts = explode(':', $field_value);
$entities[$parts[0]][$parts[1]][] = $parts[2];
}
}
}
}
}
}
$limit = 500;
$filename = 'public://entity_translation_export.csv';
variable_set('entity_translation_export_import_file', '');
$batch = array(
'operations' => array(
array('entity_translation_export_import_export_process', array($entities, $limit, $filename)),
),
'finished' => 'entity_translation_export_import_export_finished',
'title' => t('Export Translations'),
'init_message' => t('Retrieving Entities...'),
'progress_message' => t('Processed @current out of @total.'),
'error_message' => t('Exporting has encountered an error.'),
'file' => drupal_get_path('module', 'entity_translation_export_import') . '/entity_translation_export_import.admin.inc',
);
batch_set($batch);
batch_process('admin/config/regional/entity_translation/export');
}
/**
* Batch process callback.
*/
function entity_translation_export_import_export_process($entities, $limit, $filename, &$context){
// Set the default progress data.
if (!isset($context['sandbox']['progress'])) {
$context['results']['file'] = file_save_data('', $filename);
$context['sandbox']['progress'] = array();
$context['sandbox']['progress_total']['max'] = 0;
$context['sandbox']['progress_total']['current'] = 0;
foreach($entities as $entity_type => $bundles){
foreach($bundles as $bundle => $fields){
$query = new EntityFieldQuery();
$context['sandbox']['progress'][$entity_type][$bundle]['max'] = $query->entityCondition('entity_type', $entity_type)->entityCondition('bundle', $bundle)->count()->execute();
$context['sandbox']['progress'][$entity_type][$bundle]['current'] = 0;
$context['sandbox']['progress_total']['max'] += $context['sandbox']['progress'][$entity_type][$bundle]['max'];
}
}
}
if(!empty($context['sandbox']['progress'])){
$entity_type = key($context['sandbox']['progress']);
$bundle = key(current($context['sandbox']['progress']));
$progress = current(current($context['sandbox']['progress']));
// Receive items.
$items = _entity_translation_export_import_export_entity($entity_type, $bundle, $progress['current'], $limit, $entities[$entity_type][$bundle]);
$is_header = ($context['sandbox']['progress_total']['current'] === 0);
$data = _entity_translation_export_import_csv($items, $is_header);
file_put_contents($context['results']['file']->uri, $data, FILE_APPEND);
$progress['current'] += $limit;
$context['sandbox']['progress_total']['current'] += ($progress['current'] > $progress['max'] ? ($progress['max'] - ($progress['current']-$limit)) : $limit);
$context['sandbox']['progress'][$entity_type][$bundle]['current'] = $progress['current'];
if($progress['current'] >= $progress['max']){
unset($context['sandbox']['progress'][$entity_type][$bundle]);
if(empty($context['sandbox']['progress'][$entity_type])){
unset($context['sandbox']['progress'][$entity_type]);
}
}
if(!empty($context['sandbox']['progress'])){
reset($context['sandbox']['progress']);
$entity_type = key($context['sandbox']['progress']);
$bundle = key(current($context['sandbox']['progress']));
$progress = current(current($context['sandbox']['progress']));
$percentage = '';
if(isset($progress['current']) and $progress['current'] > 0){
$percentage = ' (' . $progress['current'] . '/' . $progress['max'] . ')';
}
$info = entity_get_info();
$context['message'] = t('Exporting ' . $info[$entity_type]['label'] . ' - ' . $info[$entity_type]['bundles'][$bundle]['label'] . $percentage);
}
}
$context['finished'] = ($context['sandbox']['progress_total']['current']/$context['sandbox']['progress_total']['max']);
}
/**
* batch process finish callback.
*/
function entity_translation_export_import_export_finished($success, $results){
$link = file_create_url($results['file']->uri);
drupal_set_message(t('Export has been created! Download the <a href="@link">file</a>.', array('@link' => $link)));
}
/**
* Get the field values of an entity.
*/
function _entity_translation_export_import_export_entity($entity_type, $bundle, $limitstart, $limit, $fields){
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', $entity_type)
->entityCondition('bundle', $bundle)
->entityOrderBy('entity_id')
->range($limitstart, $limit)
->execute();
// Force Default Language to be first.
$languages = language_list();
$language_default = language_default();
unset($languages[$language_default->language]);
$languages = array_merge(array($language_default->language => $language_default), $languages);
$export = array();
foreach($result as $entity_type => $items){
foreach($items as $entity_id => $item){
foreach($languages as $language){
$entity = current(entity_load($entity_type, array($entity_id)));
$export[$entity_id]['Entity Type (Not Editable)'] = $entity_type;
$export[$entity_id]['Bundle (Not Editable)'] = $bundle;
$export[$entity_id]['Entity ID (Not Editable)'] = $entity_id;
$handler = entity_translation_get_handler($entity_type, $entity, TRUE);
$translations = $handler->getTranslations();
foreach($fields as $field){
$value = '';
if(isset($translations->data[$language->language])){
$value = $entity->{$field}[$language->language][0]['value'];
}
$export[$entity_id][$field][$language->language] = $value;
}
}
}
}
return $export;
}
/**
* Format entity values as csv.
*/
function _entity_translation_export_import_csv($items, $is_header = FALSE){
$data = '';
// Render Header.
if($is_header){
$titles = array();
foreach(reset($items) as $field_name => $value){
if(is_array($value)){
foreach($value as $lang_code => $language_value){
$titles[] = $field_name . '_' . $lang_code;
}
}
else{
$titles[] = $field_name;
}
}
$data .= implode(",", $titles) . "\n";
}
foreach($items as $item){
$row = array();
foreach($item as $field_name => $value){
if(is_array($value)){
foreach($value as $language_value){
$row[] = '"' . str_replace('"', '""', $language_value) . '"';
}
}
else{
$row[] = '"' . str_replace('"', '""', $value) . '"';
}
}
$data .= implode(",", $row) . "\n";
}
return $data;
}
/**
* Import form callback.
*/
function entity_translation_export_import_admin_import_form($form, $form_state){
$form = array('#attributes' => array('enctype' => "multipart/form-data"));
$form['fid'] = array(
'#type' => 'managed_file',
'#title' => 'Translation File for Import',
'#upload_validators' => array('file_validate_extensions' => array('csv')),
'#description' => t('WARNING! Do not upload any file that is not formated as needed. Please try to export the translations first.'),
);
$fid = variable_get('entity_translation_export_import_file', '');
if(file_load($fid)){
$form['fid']['#default_value'] = $fid;
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Import Translations'
);
return $form;
}
/**
* Import form submit callback.
*/
function entity_translation_export_import_admin_import_form_submit($form, $form_state){
$file = file_load($form_state['values']['fid']);
variable_set('entity_translation_export_import_file', $file->fid);
$batch = array(
'operations' => array(
array('entity_translation_export_import_import_process', array($file)),
),
'finished' => 'entity_translation_export_import_import_finished',
'title' => t('Import Translations'),
'init_message' => t('Retrieving Entities...'),
'progress_message' => t('Processed @current out of @total.'),
'error_message' => t('Importing has encountered an error.'),
'file' => drupal_get_path('module', 'entity_translation_export_import') . '/entity_translation_export_import.admin.inc',
);
batch_set($batch);
batch_process('admin/config/regional/entity_translation/import');
}
/**
* Batch process callback.
*/
function entity_translation_export_import_import_process($file, &$context){
// Initialize Sandbox Data.
if (!isset($context['sandbox']['current'])) {
$context['sandbox']['total'] = filesize($file->uri);
$context['sandbox']['current'] = 0;
}
if($context['sandbox']['current'] < $context['sandbox']['total']){
$fp = @fopen($file->uri, "r");
// Set the current csv pointer.
@fseek($fp, $context['sandbox']['current']);
if($data = fgetcsv($fp)){
if(!isset($context['sandbox']['header'])){
$context['sandbox']['header'] = $data;
}
else{
entity_translation_export_import_import_translation(array_combine($context['sandbox']['header'], $data));
}
}
// Get the current csv pointer.
$context['sandbox']['current'] = @ftell($fp);
}
$context['finished'] = ($context['sandbox']['current']/$context['sandbox']['total']);
}
/**
* Batch process finish callback.
*/
function entity_translation_export_import_import_finished($success, $results){
drupal_set_message(t('Entity Translations have been imported successfully!'));
}
/**
* Imports entity translations.
*/
function entity_translation_export_import_import_translation($data){
$entity_type = $data['Entity Type (Not Editable)'];
$bundle = $data['Bundle (Not Editable)'];
$entity_id = $data['Entity ID (Not Editable)'];
$entities = entity_load($entity_type, array($entity_id));
// If cannot load entity.
if(empty($entities)){
drupal_set_message(t('Entity with id @id could not be found in database.', array('@id' => $entity_id)));
return FALSE;
}
// Get the entity.
$entity = current($entities);
// Get the default entity's language.
$source_language = entity_language($entity_type, $entity);
// Get the current entity's field info.
$fields_info = field_info_instances($entity_type, $bundle);
$values = array();
$languages = array();
foreach($data as $key => $value){
if(strstr($key, '_') and !empty($value)){
$parts = explode('_', $key);
$field_language = array_pop($parts);
$field_name = implode('_', $parts);
// If field is translatable.
if(array_key_exists($field_name, $fields_info)){
$field = field_info_field($field_name);
if(field_is_translatable($entity_type, $field) and in_array($field['type'], array('text', 'text_long', 'text_with_summary')) and $field['cardinality'] == 1){
if(!in_array($field_language, $languages)){
$languages[] = $field_language;
}
if(!isset($entity->{$field_name}[$field_language])){
$entity->{$field_name}[$field_language] = $entity->{$field_name}[$source_language];
}
$entity->{$field_name}[$field_language][0]['value'] = $value;
}
}
}
}
$handler = entity_translation_get_handler($entity_type, $entity, TRUE);
if($handler){
foreach($languages as $langcode){
$translation = array(
'translate' => 0,
'status' => 1,
'source' => ($source_language != $langcode) ? $source_language : '',
'language' => $langcode,
);
$handler->setTranslation($translation);
// If original entity and module title exists then do the replacements.
if($source_language == $langcode and module_exists('title')){
$fr_info = title_field_replacement_info($entity_type);
foreach($fr_info as $legacy_field => $info) {
if(isset($entity->{$info['field']['field_name']})){
drupal_static_reset('field_language');
title_field_sync_get($entity_type, $entity, $legacy_field, $info, $langcode);
}
}
}
}
}
entity_save($entity_type, $entity);
}
@@ -0,0 +1,13 @@
name = Entity Translation Export/Import
description = Exports/Imports entity translation fields. Very useful for fast updating of taxonomy terms, nodes etc.
core = 7.x
package = Multilingual - Entity Translation
dependencies[] = entity
dependencies[] = entity_translation
; Information added by drupal.org packaging script on 2013-09-30
version = "7.x-1.0-beta3+0-dev"
core = "7.x"
project = "entity_translation_export_import"
datestamp = "1380577025"
@@ -0,0 +1,37 @@
<?php
/**
* Implements hook_menu().
*/
function entity_translation_export_import_menu() {
$items['admin/config/regional/entity_translation/export'] = array(
'title' => 'Export',
'page callback' => 'drupal_get_form',
'page arguments' => array('entity_translation_export_import_admin_export_form'),
'access arguments' => array('administer entity translation'),
'type' => MENU_LOCAL_TASK,
'file' => 'entity_translation_export_import.admin.inc',
'file path' => drupal_get_path('module', 'entity_translation_export_import'),
);
$items['admin/config/regional/entity_translation/import'] = array(
'title' => 'Import',
'page callback' => 'drupal_get_form',
'page arguments' => array('entity_translation_export_import_admin_import_form'),
'access arguments' => array('administer entity translation'),
'type' => MENU_LOCAL_TASK,
'file' => 'entity_translation_export_import.admin.inc',
'file path' => drupal_get_path('module', 'entity_translation_export_import'),
);
return $items;
}
/**
* Implements hook_menu_alter().
*/
function entity_translation_export_import_menu_alter(&$items) {
$items['admin/config/regional/entity_translation/settings'] = $items['admin/config/regional/entity_translation'];
$items['admin/config/regional/entity_translation/settings']['type'] = MENU_DEFAULT_LOCAL_TASK;
}
@@ -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.
@@ -0,0 +1,95 @@
CONTENTS OF THIS FILE
---------------------
* Introduction
* Installing
* Uninstalling
* Frequently Asked Questions (FAQ)
* Known Issues
* More Information
* How Can You Contribute?
INTRODUCTION
------------
Current Maintainer: Sami Radi a.k.a VirtuoWorks <http://drupal.org/user/656630>
Remove Duplicates removes duplicate nodes
according to any selected content field.
This can be very useful with Drupal feeds module :
- http://drupal.org/project/feeds
This module was inspired by these threads :
- http://drupal.org/node/720190 : Remove Duplicate Nodes based on title
- http://drupal.org/node/1211922 : remove duplicated node base on title problem
THANKS
------
Thanks to dman <https://drupal.org/user/33240> for endorsing this project.
He wrote a sandbox module "Deduplicate Nodes" for D6 intended to deduplicate
nodes according to titles only : https://drupal.org/sandbox/dman/1422586
INSTALLING
----------
See http://drupal.org/getting-started/install-contrib
for instructions on how to install or update Drupal modules.
Once Remove Duplicates is installed and enabled,
you can use it at admin/config/content/remove_duplicates.
It is highly recommended that you backup your database before using this module.
UNINSTALLING
------------
Because Drupal does not uninstall modules in reverse
order of their dependencies, if you want to uninstall
all the Remove Duplicates modules, be sure to disable
and uninstall all the sub-modules before the base Remove
Duplicates module.
To help fix this bug in Drupal core, visit http://drupal.org/node/151452.
FREQUENTLY ASKED QUESTIONS (FAQ)
--------------------------------
- There are no frequently asked questions at this time.
KNOWN ISSUES
------------
- See http://drupal.org/project/issues/2005296
for a list of the current known issues.
MORE INFORMATION
----------------
- To issue any bug reports, feature or support requests
see the module issue queue at
http://drupal.org/project/issues/2005296
- For additional documentation, see the online module handbook at
https://drupal.org/project/remove_duplicates
HOW CAN YOU CONTRIBUTE?
-----------------------
- Report any bugs, feature requests, etc. in the issue tracker.
http://drupal.org/node/add/project-issue/2005296
- Help translate this module.
- Write a review for this module at drupalmodules.com.
http://drupalmodules.com/
- Help keep development active by donating to the developers.
http://www.virtuoworks.com/
@@ -0,0 +1,12 @@
name = Remove Duplicates
description = "Remove duplicate nodes according to node fields or CCK fields."
core = 7.x
package = Content management
configure = admin/config/content/remove_duplicates
; Information added by Drupal.org packaging script on 2015-04-13
version = "7.x-1.4"
core = "7.x"
project = "remove_duplicates"
datestamp = "1428944507"
File diff suppressed because it is too large Load Diff
@@ -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.
@@ -0,0 +1,41 @@
Special Menu Items Module
------------------------
Written by Tamir Al Zoubi and Karim Djelid - Servit Open Source Solutions - www.servit.ch
Description
-----------
Special Menu Items is module that enables placeholder and separator menu items.Placeholder is a menu item which is
actually not a link. Something like this is useful with drop down menus where we want to have a parent link which
is actually not linking to a page but which is just acting as a parent grouping some children below it.
A separator menu item is something like "-------" which is also not linking anywhere but merely a mean to structure menus.
This module depends on the Menu module. It is recommended that the SimpleMenu module or another drop down menu module
is used, or you will not be able to acess children of nolink menu items.
Features
--------
- User can create a new menu item and place either "<nolink>" or "<separator>" in the Path field, without quotes.
- When the menu is rendered the "nolink" item will be rendered similar to a normal menu link item, but there will
be no link, just the title. Since version 1.3 you can change HTML tag used for menu item.
- When the menu is rendered the "separator" item will be rendered as an item which has no link,
and the default title will be "-------". Since version 1.3 it is possible to change both the HTML tag and title.
- Breadcrumb of "<nolink>" will be rendered same as "<nolink>" menu item.
- CSS class "nolink" is added to "<nolink>" menu item.
- CSS class "seperator" is added to "<seperator>" menu item.
- Compatible with the Sitemap module.
Installation
------------
1. Copy the special_menu_items folder to your sites/all/modules directory.
2. At Administer -> Site building -> Modules (admin/modules) enable the module.
3. Configure the module settings at Administer -> Site configuration -> Special Menu Items (admin/config/system/special_menu_items).
Upgrading
---------
Just overwrite (or replace) the older special_menu_items folder with the newer version.
Contact
-------
This module is developed by Servit Open Source Solutions - http://servit.ch
and maintained by Khaled Zaidan - zaidan@servit.ch
@@ -0,0 +1,13 @@
name = Special menu items
description = "Allow users to add placeholder and/or separator menu items."
core = 7.x
dependencies[] = menu
configure = admin/config/system/special_menu_items
; Information added by drupal.org packaging script on 2012-09-04
version = "7.x-2.0"
core = "7.x"
project = "special_menu_items"
datestamp = "1346788411"
@@ -0,0 +1,38 @@
<?php
/**
* Implementation of hook_uninstall().
*/
function special_menu_items_uninstall() {
variable_del('special_menu_items_nolink_tag');
variable_del('special_menu_items_seperator_tag');
variable_del('special_menu_items_seperator_value');
variable_del('special_menu_items_menu_item_link');
}
/**
* "nolink" to <nolink> and "separator" to <separator>
*/
function special_menu_items_update_7000(&$sandbox){
//change "nolink" to <nolink>
db_update('menu_links')
->fields(array(
'link_path' => '<nolink>',
'router_path' => '<nolink>',
))
->condition('router_path', 'nolink', '=')
->execute();
//change "separator" to <separator>
db_update('menu_links')
->fields(array(
'link_path' => '<separator>',
'router_path' => '<separator>',
))
->condition('router_path', 'separator', '=')
->execute();
//we don't need this variable anymore
variable_del('special_menu_items_menu_item_link');
}
@@ -0,0 +1,199 @@
<?php
/**
* @file
* Module to enable placeholder or separator menu items.Placeholder is a menu item which is
* actually not a link. Something like this is useful with drop down menus where we want to
* have a parent link which is actually not linking to a page but which is just acting as a
* parent and grouping some children below it.
* A separator menu item is something like "-------" which is also not linking anywhere but
* merely a mean to structure menus.
*
* Written by Tamir Al Zoubi and Karim Djelid - Servit Open Source Solutions - www.servit.ch
*/
/**
*Implementation of hook_menu()
*/
function special_menu_items_menu() {
$items['<nolink>'] = array(
'page callback' => 'drupal_not_found',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['<separator>'] = array(
'page callback' => 'drupal_not_found',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
$items['admin/config/system/special_menu_items'] = array(
'title' => 'Special Menu Items',
'description' => 'Configure Special Menu Items.',
'page callback' => 'drupal_get_form',
'page arguments' => array('special_menu_items_admin_settings_form'),
'access arguments' => array('administer site configuration'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
/**
* Override of theme_link()
* This function will render link if it is "nolink" or "separator". Otherwise it will call originally
* overwritten menu_item_link function.
*/
function special_menu_items_link(array $variables) {
if (in_array($variables['path'], array('<nolink>', '<separator>'))) {
switch ($variables['path']) {
case '<nolink>':
$tag = variable_get('special_menu_items_nolink_tag', '<span>');
$title = $variables['options']['html'] ? $variables['text'] : check_plain($variables['text']);
$variables['options']['attributes']['class'][] = 'nolink';
break;
case '<separator>':
$tag = variable_get('special_menu_items_separator_tag', '<span>');
$title = variable_get('special_menu_items_separator_value', '<hr>');
$variables['options']['attributes']['class'][] = 'separator';
break;
}
$attributes = drupal_attributes($variables['options']['attributes']);
if ($tag != '<a>') {
// <a> tags can have these but a <span> cannot, so we remove them.
foreach (array('accesskey', 'target', 'rel', 'name') as $attribute) {
$attributes = preg_replace("/ $attribute=\".*\"/i", "", $attributes);
}
}
return special_menu_items_render_menu_item($tag, $title, $attributes);
}
// Call the original theme function for normal menu link.
return theme('special_menu_items_link_default', $variables);
}
/**
* Returns menu item rendered.
*/
function special_menu_items_render_menu_item($tag, $value, $attrs = array()) {
// $attrs may be a string already or an array
if (is_array($attrs)) {
$attrs = drupal_attributes($attrs);
}
$length = strlen($tag);
if ($tag[0] == '<' && $tag[$length - 1] == '>') {
$tag = substr($tag, 1, $length-2);
}
$closingtag = explode(' ', $tag,2);
$closingtag = '</' . $closingtag[0] . '>';
$tag = '<' . $tag . $attrs . '>';
return $tag . $value . $closingtag;
}
/**
* Implementation of hook_theme_registry_alter()
* We replace theme_menu_item_link with our own function.
*/
function special_menu_items_theme_registry_alter(&$registry) {
// Save previous value from registry in case another theme overwrites menu_item_link
$registry['special_menu_items_link_default'] = $registry['link'];
$registry['link']['function'] = 'special_menu_items_link';
}
/**
* Implementation of hook_form_FROM_ID_alter()
* Description changed, added nolink and separator as path types.
*/
function special_menu_items_form_menu_edit_item_alter(&$form, &$form_state) {
// Some menu items have a pre-defined path which cannot be modified hence no default_value
if (isset($form['link_path']['#default_value'])) {
$default_value = $form['link_path']['#default_value'];
if (preg_match('/^<nolink>\/[0-9]+$/', $default_value)) {
$default_value = '<nolink>';
}
elseif (preg_match('/^<separator>\/[0-9]+$/', $default_value)) {
$default_value = '<separator>';
}
$form['link_path']['#default_value'] = $default_value;
$form['link_path']['#description'] .= ' ' . t('Enter "%nolink" to generate non-linkable item, enter "%separator" to generate separator item.', array('%nolink' => '<nolink>', '%separator' => '<separator>'));
}
}
/**
* Implementation of hook_init().
*/
function special_menu_items_init() {
// Make breadcrumb of nolink menu item nonlinkable.
$breadcrumb = drupal_get_breadcrumb();
foreach($breadcrumb as $key => $crumb){
if (strlen(strstr($crumb,'<nolink>')) > 0) {
$crumb = strip_tags($crumb);
$tag = variable_get('special_menu_items_nolink_tag', '<span>');
$breadcrumb[$key] = special_menu_items_render_menu_item($tag, $crumb);
}
}
drupal_set_breadcrumb($breadcrumb);
}
/**
* Special Menu Items admin settings form.
*
* @return
* The settings form used by Special Menu Items.
*/
function special_menu_items_admin_settings_form() {
$form['special_menu_items_nolink_tag'] = array(
'#type' => 'textfield',
'#title' => t('HTML tag for "nolink"'),
'#description' => t('By default, Special Menu Items will use a span tag for the nolink menu item. Here you can specify your own tag.'),
'#default_value' => variable_get('special_menu_items_nolink_tag', '<span>'),
);
$form['special_menu_items_separator_tag'] = array(
'#type' => 'textfield',
'#title' => t('HTML tag for "separator"'),
'#description' => t('By default, Special Menu Items will use a span tag for the separator menu item. Here you can specify your own tag.'),
'#default_value' => variable_get('special_menu_items_separator_tag', '<span>'),
);
$form['special_menu_items_separator_value'] = array(
'#type' => 'textfield',
'#title' => t('Value to be displayed for the "separator"'),
'#description' => t('By default, Special Menu Items will use a "&lt;hr&gt;" value for the separator. You can specify your own value for the separator.'),
'#default_value' => variable_get('special_menu_items_separator_value', '<hr>'),
);
return system_settings_form($form);
}
/**
* Implements hook_menu_link_update()
*
*/
/*
function special_menu_items_menu_link_update($link) {
//do all links in db
global $db_type;
if ($db_type == 'pgsql') {
db_query("UPDATE {menu_links} SET link_path=link_path||'/'||mlid WHERE (link_path='<nolink>' OR link_path='<separator>') AND hidden != -1");
}
else {
db_query("UPDATE {menu_links} SET link_path=CONCAT(CONCAT(link_path,'/'),mlid) WHERE (link_path='<nolink>' OR link_path='<separator>') AND hidden!=-1");
}
}
*
*/
@@ -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.
@@ -0,0 +1,21 @@
/**
* @file
* Styles for taxonomy wrangler
*/
.taxonomy-wrangler-accordion-item {
float: left;
font-size: 1.35em;
min-width: 15px;
padding-right: 5px;
padding-left: 5px;
color: #656565;
}
.taxonomy-wrangler-accordion-item:hover {
text-decoration: none;
}
.taxonomy-wrangler-accordion-item--parent span:after {
content: "\25be"; /*right pointing small triangle*/
}
.taxonomy-wrangler-accordion-item--parent.is-collapsed span:after {
content: "\25b8"; /*down pointing small triangle*/
}
@@ -0,0 +1,591 @@
/**
* @file
* js for taxonomy ui tweaks
*/
(function ($, Drupal, window, document, undefined) {
function TaxonomyWranglerUID() {
var prefix = 'taxonomy-wrangler-';
var randomId = prefix + this.count;
while($('#' + randomId).length) {
this.count++;
randomId = prefix + this.count;
}
return randomId;
}
TaxonomyWranglerUID.count = 0;
function TaxonomyWranglerAccordion(table) {
this.table = table;
this.rows = $('tbody tr', table);
this.init();
}
TaxonomyWranglerAccordion.instances = {};
var ctrlDown = false;
$(window).keydown(function(e) {
if (e.keyCode == 17) {
ctrlDown = true;
}
}).keyup(function(e) {
if (e.keyCode == 17) {
ctrlDown = false;
}
});
TaxonomyWranglerAccordion.prototype.init = function() {
var accordion = this;
$('tbody tr').not(':eq(0)').each(function(){
var $row = $(this);
accordion.collapseTree($row);
accordion.attachAccordionEvents($row);
});
};
TaxonomyWranglerAccordion.prototype.attachAccordionEvents = function($row) {
var accordion = this;
$row.find('.taxonomy-wrangler-accordion-item').bind('click.tweaksAccordion', function(e){
e.preventDefault();
if (ctrlDown) {
accordion.toggleTree($row);
}
else {
accordion.toggleRow($row);
}
return false;
});
}
TaxonomyWranglerAccordion.prototype.refreshRows = function(){
var accordion = this;
this.rows.not(':eq(0)').each(function(){
var $this = $(this);
var hasChildren = accordion.rows.filter('[data-parent="'+ $this.data('tid') +'"]').length > 0 ? true : false;
var $collapseLink = $this.find('.taxonomy-wrangler-accordion-item--parent');
//create a new parent
if (hasChildren && !$collapseLink.length) {
$this.find('.tabledrag-handle').after('<a href="#" class="taxonomy-wrangler-accordion-item taxonomy-wrangler-accordion-item--parent"><span></span></a>');
accordion.attachAccordionEvents($this);
}
else if (!hasChildren && $collapseLink.length) {
$collapseLink.remove();
}
});
};
/**
* This is a bit different than a typical accordion in that the
* data structure is hierarchical, but its representation in the DOM is flat
*/
TaxonomyWranglerAccordion.prototype.showRow = function($row) {
$row.css('display', 'table-row').removeClass('tabledrag-hidden');
}
TaxonomyWranglerAccordion.prototype.hideRow = function($row) {
$row.css('display', 'none').addClass('tabledrag-hidden');
}
TaxonomyWranglerAccordion.prototype.setCollapsed = function($row, collapsed, recurse) {
var accordion = this;
var $children = this.rows.filter('[data-parent=' + $row.data('tid') + ']');
if (collapsed && $children.length) {
$row.data('is-collapsed', true);
$row.find('.taxonomy-wrangler-accordion-item').addClass('is-collapsed');
if ($children.length) {
$row.addClass('tabledrag-leaf');
}
}
else {
$row.data('is-collapsed', false).removeClass('tabledrag-leaf');
$row.find('.taxonomy-wrangler-accordion-item').removeClass('is-collapsed');
}
if (recurse) {
accordion.rows.filter('[data-parent=' + $row.data('tid') + ']').each(function(){
accordion.setCollapsed($(this), collapsed, true);
});
}
}
/*
* Hide all children
*/
TaxonomyWranglerAccordion.prototype.hideChildren = function($row) {
var $item = $row.find('.taxonomy-wrangler-accordion-item');
var accordion = this;
this.rows.filter('[data-parent=' + $row.data('tid') + ']').each(function(){
accordion.hideRow($(this));
accordion.hideChildren($(this));
});
};
/**
* Show children if they are not collapsed
*/
TaxonomyWranglerAccordion.prototype.showChildren = function($row) {
var accordion = this;
accordion.rows.filter('[data-parent=' + $row.data('tid') + ']').each(function(){
accordion.showRow($(this));
if (!$(this).data('is-collapsed')) {
accordion.showChildren($(this));
}
});
};
TaxonomyWranglerAccordion.prototype.toggleRow = function($row) {
if ($row.data('is-collapsed')) {
this.setCollapsed($row, false);
this.showChildren($row);
}
else {
this.setCollapsed($row, true);
this.hideChildren($row);
}
};
TaxonomyWranglerAccordion.prototype.expandTree = function($row) {
this.setCollapsed($row, false, true);
this.showChildren($row);
};
TaxonomyWranglerAccordion.prototype.collapseTree = function($row) {
this.setCollapsed($row, true, true);
this.hideChildren($row);
};
TaxonomyWranglerAccordion.prototype.toggleTree = function($row) {
if ($row.data('is-collapsed')) {
this.expandTree($row);
}
else {
this.collapseTree($row);
}
}
Drupal.behaviors.taxonomyWranglerAccordion = {
attach: function(context, settings) {
idCount = 0;
$('.taxonomy-wrangler-accordion', context)
.not('.taxonomy-wrangler-accordion-processed')
.addClass('taxonomy-wrangler-accordion-processed')
.each(function(){
var id = $(this).attr('id')
if (!!!id || id == '') {
$(this).attr('id', TaxonomyWranglerUID());
}
TaxonomyWranglerAccordion.instances[id] = new TaxonomyWranglerAccordion(this);
});
}
};
function TaxonomyWranglerCollection() {
this.updatedTerms = {};
};
TaxonomyWranglerCollection.prototype.updateTerm = function(row) {
var $row = $(row);
var tid = $row.data('tid');
var now = Date.now();
this.updatedTerms[tid] = {
"tid": $row.data('tid'),
"parent": $row.data('parent'),
"depth": $row.data('depth'),
"weight": $row.data('weight'),
"updated": now
}
//el.attr('data-{key}') & el.data('key') are not the same!
$row.attr('data-parent', $row.data('parent'))
.attr('data-depth', $row.data('depth'))
.attr('data-weight', $row.data('weight'))
.data('updated', now);
};
/**
* New TableDrag "class" that inherits Drupal.tableDrag
*/
function TaxonomyWranglerDrag(table, tableSettings) {
Drupal.tableDrag.call(this, table, tableSettings);
}
TaxonomyWranglerDrag.prototype = new Drupal.tableDrag();
TaxonomyWranglerDrag.instances = {};
/**
* Find the target used within a particular row and group.
* This isn't strictly necessary in this case because the data
* is stored on the row element itself.
* Copied and modified from misc/tabledrag.js
*/
TaxonomyWranglerDrag.prototype.rowSettings = function (group, row) {
for (var delta in this.tableSettings[group]) {
// Return a copy of the row settings.
var rowSettings = {};
for (var n in this.tableSettings[group][delta]) {
rowSettings[n] = this.tableSettings[group][delta][n];
}
return rowSettings;
}
};
/**
* After the row is dropped, update the table fields according to the settings
* set for this table.
*
* @param changedRow
* DOM object for the row that was just dropped.
*/
TaxonomyWranglerDrag.prototype.updateFields = function (changedRow) {
var $c = $(changedRow);
for (var group in this.tableSettings) {
// Each group may have a different setting for relationship, so we find
// the source rows for each separately.
this.updateField(changedRow, group);
}
};
/**
* After the row is dropped, update a single table field according to specific
* settings. This code is cribbed from tabledrag.js and modified to
* use the data properties on the row object rather than input fields in the row.
*
* @param changedRow
* DOM object for the row that was just dropped.
* @param group
* The settings group on which field updates will occur.
*/
TaxonomyWranglerDrag.prototype.updateField = function (changedRow, group) {
var rowSettings = this.rowSettings(group, changedRow);
// Set the row as its own target.
if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') {
var sourceRow = changedRow;
}
// Siblings are easy, check previous and next rows.
else if (rowSettings.relationship == 'sibling') {
var previousRow = $(changedRow).prev('tr').get(0);
var nextRow = $(changedRow).next('tr').get(0);
var sourceRow = changedRow;
if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) {
if (this.indentEnabled) {
if ($('.indentations', previousRow).length == $('.indentations', changedRow)) {
sourceRow = previousRow;
}
}
else {
sourceRow = previousRow;
}
}
else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) {
if (this.indentEnabled) {
if ($('.indentations', nextRow).length == $('.indentations', changedRow)) {
sourceRow = nextRow;
}
}
else {
sourceRow = nextRow;
}
}
}
// Parents, look up the tree until we find a field not in this group.
// Go up as many parents as indentations in the changed row.
else if (rowSettings.relationship == 'parent') {
var previousRow = $(changedRow).prev('tr');
while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) {
previousRow = previousRow.prev('tr');
}
// If we found a row.
if (previousRow.length) {
sourceRow = previousRow[0];
}
// Otherwise we went all the way to the left of the table without finding
// a parent, meaning this item has been placed at the root level.
else {
// Use the first row in the table as source, because it's guaranteed to
// be at the root level. Find the first item, then compare this row
// against it as a sibling.
sourceRow = $(this.table).find('tr.draggable:first').get(0);
if (sourceRow == this.rowObject.element) {
sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0);
}
var useSibling = true;
}
}
// Because we may have moved the row from one category to another,
// take a look at our sibling and borrow its sources and targets.
this.copyDragClasses(sourceRow, changedRow, group);
rowSettings = this.rowSettings(group, changedRow);
// In the case that we're looking for a parent, but the row is at the top
// of the tree, copy our sibling's values.
if (useSibling) {
rowSettings.relationship = 'sibling';
rowSettings.source = rowSettings.target;
}
var $changedRow = $(changedRow);
// Check if data exists in this row.
if (typeof $(sourceRow).data(rowSettings.target) !== 'undefined') {
switch (rowSettings.action) {
case 'depth':
// Get the depth of the target row.
$changedRow.data(rowSettings.target, $('.indentation', $(sourceRow)).length);
break;
case 'match':
// Update the value.
$changedRow.data(rowSettings.target, $(sourceRow).data(rowSettings.source));
break;
case 'order':
var siblings = this.rowObject.findSiblings(rowSettings);
// We're not using fields for this so we just assume
// weight starting from 0
var weight = 0;
$(siblings).each(function () {
$(this).data('weight', weight);
weight++;
$(this).trigger('taxonomyWranglerTermDrag.rowDataChange', [this]);
});
break;
}
}
$changedRow.trigger('taxonomyWranglerTermDrag.rowDataChange', [changedRow]);
};
TaxonomyWranglerDrag.prototype.dropRow = function (event, self) {
// Drop row functionality shared between mouseup and blur events.
if (self.rowObject != null) {
var droppedRow = self.rowObject.element;
// The row is already in the right place so we just release it.
if (self.rowObject.changed == true) {
// Update the fields in the dropped row.
self.updateFields(droppedRow);
// If a setting exists for affecting the entire group, update all the
// fields in the entire dragged group.
for (var group in self.tableSettings) {
var rowSettings = self.rowSettings(group, droppedRow);
if (rowSettings.relationship == 'group') {
for (var n in self.rowObject.children) {
self.updateField(self.rowObject.children[n], group);
}
}
}
self.rowObject.markChanged();
if (self.changed == false) {
self.changed = true;
}
}
if (self.indentEnabled) {
self.rowObject.removeIndentClasses();
}
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
$(droppedRow).removeClass('drag').addClass('drag-previous');
self.oldRowElement = droppedRow;
self.onDrop();
self.rowObject = null;
}
// Functionality specific only to mouseup event.
if (self.dragObject != null) {
$('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover');
self.dragObject = null;
$('body').removeClass('drag');
clearInterval(self.scrollInterval);
// Hack for IE6 that flickers uncontrollably if select lists are moved.
if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
$('select', this.table).css('display', 'block');
}
}
};
/**
* Indent a row within the legal bounds of the table.
*
* @param indentDiff
* The number of additional indentations proposed for the row (can be
* positive or negative). This number will be adjusted to nearest valid
* indentation level for the row.
*/
TaxonomyWranglerDrag.prototype.row.prototype.indent = function (indentDiff) {
// Determine the valid indentations interval if not available yet.
if (!this.interval) {
var prevRow = $(this.element).prevAll('tr:not(.tabledrag-hidden)').get(0);
var nextRow = $(this.group).filter(':last').nextAll('tr:not(.tabledrag-hidden)').get(0);
this.interval = this.validIndentInterval(prevRow, nextRow);
}
// Adjust to the nearest valid indentation.
var indent = this.indents + indentDiff;
indent = Math.max(indent, this.interval.min);
indent = Math.min(indent, this.interval.max);
indentDiff = indent - this.indents;
for (var n = 1; n <= Math.abs(indentDiff); n++) {
// Add or remove indentations.
if (indentDiff < 0) {
$('.indentation:first', this.group).remove();
this.indents--;
}
else {
$('td:first', this.group).prepend(Drupal.theme('tableDragIndentation'));
this.indents++;
}
}
if (indentDiff) {
// Update indentation for this row.
this.changed = true;
this.groupDepth += indentDiff;
this.onIndent();
}
return indentDiff;
};
/**
* Perform the swap between two rows. Take into account the collapsed
* accordion rows when swapping after.
*
* @param position
* Whether the swap will occur 'before' or 'after' the given row.
* @param row
* DOM element what will be swapped with the row group.
*/
TaxonomyWranglerDrag.prototype.row.prototype.swap = function (position, row) {
var swapRow = row;
if (position == 'after') {
var $row = $(row);
if ($row.data('is-collapsed')) {
var $target = $row.nextUntil(":visible");
if ($target.length) {
swapRow = $target.get($target.length - 1);
}
else {
// If there are no other rows visible, we must be at the bottom
// of the table, get the last row.
swapRow = $row.nextAll(":last").get(0);
}
}
}
Drupal.detachBehaviors(this.group, Drupal.settings, 'move');
$(swapRow)[position](this.group);
Drupal.attachBehaviors(this.group, Drupal.settings);
this.changed = true;
this.onSwap(row);
};
/**
* Ensure that two rows are allowed to be swapped.
*
* @param row
* DOM object for the row being considered for swapping.
*/
TaxonomyWranglerDrag.prototype.row.prototype.isValidSwap = function (row) {
if (this.indentEnabled) {
var prevRow, nextRow;
if (this.direction == 'down') {
prevRow = row;
nextRow = $(row).nextAll('tr:not(:hidden)').get(0);
}
else {
prevRow = $(row).prevAll('tr:not(:hidden)').get(0);
nextRow = row;
}
this.interval = this.validIndentInterval(prevRow, nextRow);
// We have an invalid swap if the valid indentations interval is empty.
if (this.interval.min > this.interval.max) {
return false;
}
}
// Do not let an un-draggable first row have anything put before it.
if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) {
return false;
}
return true;
};
/**
* Move a block in the blocks table from one region to another via select list.
*
* This behavior is dependent on the tableDrag behavior, since it uses the
* objects initialized in that behavior to update the row.
*/
Drupal.behaviors.taxonomyWranglerTermDrag = {
attach: function (context, settings) {
for (var base in settings.taxonomyWrangler.tables) {
if (typeof TaxonomyWranglerDrag.instances[base] == 'undefined') {
$('#' + base, context).once('tabledrag', function () {
// Create the new tableDrag instance. Save in the Drupal variable
// to allow other scripts access to the object.
TaxonomyWranglerDrag.instances[base] = new TaxonomyWranglerDrag(this, settings.taxonomyWrangler.tables[base]);
});
}
}
var table = $('#taxonomy-wrangler', context);
var tableDrag = TaxonomyWranglerDrag.instances['taxonomy-wrangler']; // Get the blocks tableDrag object.
var $messages = $('#taxonomy-wrangler-messages-js', context);
// Compare server timestamp with javascript changed stamp and remove changed classes.
if (settings.taxonomyWrangler && settings.taxonomyWrangler.updatedTimestamps) {
$.each(settings.taxonomyWrangler.updatedTimestamps, function (tid, stamp) {
var $row = table.find('tr[data-tid="'+ tid +'"]');
if ($row.data('updated') == stamp) {
$row.removeClass('drag-previous').find('span.tabledrag-changed').remove();
}
});
}
if (tableDrag.tm === null) {
$messages.removeClass('is-busy').empty();
}
if (!table.hasClass('taxonomy-wrangler-processed')) {
table.addClass('taxonomy-wrangler-processed');
var rows = $('tr', table).length;
var $termData = $('input[name="term_data"]', context);
var $submit = $('input[name="op"][value="Save"]', context)
var $rows = $('tr', table);
tableDrag.collection = new TaxonomyWranglerCollection();
var updatedTerms = {};
$submit.attr('disabled', 'disabled');
var accordion = !!TaxonomyWranglerAccordion.instances[table.attr('id')] ? TaxonomyWranglerAccordion.instances[table.attr('id')] : null;
$rows.bind('taxonomyWranglerTermDrag.rowDataChange', function(e, row){
tableDrag.collection.updateTerm(row);
var termsArray = [];
var tids = [];
accordion.refreshRows();
$.each(tableDrag.collection.updatedTerms, function(i, val) {
termsArray.push(val);
tids.push(val.tid + ':' + val.weight);
});
$termData.val(JSON.stringify({ "termData": termsArray }));
if (tableDrag.tm) {
clearTimeout(tableDrag.tm);
tableDrag.tm = null;
}
tableDrag.tm = setTimeout(function(){
$submit.removeAttr('disabled').trigger('mousedown').attr('disabled', 'disabled');
tableDrag.tm = null;
}, 1000);
if (!$messages.hasClass('is-busy')) {
$messages.addClass('is-busy').append('<div class="ajax-progress ajax-progress-throbber ajax-progress-throbber--taxonomy-wrangler"><div class="throbber">&nbsp;</div> Updating terms</div>');
}
});
}
}
};
})(jQuery, Drupal, this, this.document);
@@ -0,0 +1,291 @@
<?php
/**
* @file
* Administrative page callbacks for the taxonomy ui tweaks module.
*/
/**
* Form builder for the taxonomy tweaks terms overview.
*
* Display a tree of all the terms in a vocabulary, with options to edit
* each one. The form is made drag and drop by the theme function.
*
* @ingroup forms
* @see taxonomy_overview_terms_submit()
* @see theme_taxonomy_overview_terms()
*/
function taxonomy_wrangler_overview_terms($form, &$form_state, $vocabulary) {
global $pager_page_array, $pager_total, $pager_total_items;
// Check for confirmation forms.
if (isset($form_state['confirm_reset_alphabetical'])) {
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
return taxonomy_vocabulary_confirm_reset_alphabetical($form, $form_state, $vocabulary->vid);
}
$form['#vocabulary'] = $vocabulary;
$form['#tree'] = TRUE;
$form['#parent_fields'] = FALSE;
$form['header']['info'] = array(
'#markup' => '<p>' . t('Drag and drop taxonomy terms below. Ctrl + click on an arrow will expand the term and all its children') . '</p>',
);
$form['header']['messages'] = array(
'#markup' => '<div id="taxonomy-wrangler-messages"><div id="taxonomy-wrangler-messages-server"></div><div id="taxonomy-wrangler-messages-js"></div></div>',
);
$root_entries = 0; // Elements at the root level on this page.
$delta = 0;
$term_deltas = array();
$tree = taxonomy_get_tree($vocabulary->vid);
$form_state['storage']['tree'] = $tree;
$term = current($tree);
$form['taxonomy_wrangler_messages'] = array(
'#type' => 'markup',
'#markup' => '',
);
// The original form handled setting the order after a validation error.
// Since we aren't supporting the non-ajax form, it has been removed.
// Build the actual form.
foreach ($tree as $orig_key => $term) {
$term_deltas[$term->tid] = isset($term_deltas[$term->tid]) ? $term_deltas[$term->tid] + 1 : 0;
$key = 'tid:' . $term->tid . ':' . $term_deltas[$term->tid];
// Save the term for the current page so we don't have to load it a second time.
$form[$key]['#term'] = (array) $term;
if (isset($term->parents)) {
$form[$key]['#term']['parent'] = $term->parent = $term->parents[0];
unset($form[$key]['#term']['parents'], $term->parents);
}
$form[$key]['view'] = array('#type' => 'link', '#title' => $term->name, '#href' => "taxonomy/term/$term->tid");
if ($vocabulary->hierarchy < 2 && count($tree) > 1) {
$form['#parent_fields'] = TRUE;
$form[$key]['view']['#options']['attributes']['data-tid'] = $term->tid;
$form[$key]['view']['#options']['attributes']['data-parent'] = $term->tid;
$form[$key]['view']['#options']['attributes']['data-depth'] = $term->depth;
$form[$key]['view']['#options']['attributes']['data-weight'] = $term->weight;
}
$form[$key]['edit'] = array('#type' => 'link', '#title' => t('edit'), '#href' => 'taxonomy/term/' . $term->tid . '/edit', '#options' => array('query' => drupal_get_destination()));
}
$form['#empty_text'] = t('No terms available. <a href="@link">Add term</a>.', array('@link' => url('admin/structure/taxonomy/' . $vocabulary->machine_name . '/add')));
// Hidden input field for ajax.
$form['term_data'] = array(
'#type' => 'hidden',
'#default_value' => '{}',
);
if ($vocabulary->hierarchy < 2 && count($tree) > 1) {
$form['actions'] = array('#type' => 'actions', '#tree' => FALSE);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#ajax' => array(
'callback' => 'taxonomy_wrangler_terms_overview_ajax_handler',
),
);
$form['actions']['reset_alphabetical'] = array(
'#type' => 'submit',
'#value' => t('Reset to alphabetical'),
);
}
$module_path = drupal_get_path('module', 'taxonomy_wrangler');
$form['#attached']['css'][] = $module_path . '/css/taxonomy_wrangler.css';
$form['#attached']['js'][] = $module_path . '/js/taxonomy_wrangler.js';
return $form;
}
/**
* Validate callback for taxonomy_wrangler_overview_terms.
*/
function taxonomy_wrangler_overview_terms_validate($form, &$form_state) {
if ($form_state['triggering_element']['#value'] != t('Reset to alphabetical')) {
if (isset($form_state['values']['term_data'])) {
$updated_terms_json = json_decode($form_state['values']['term_data']);
if ($updated_terms_json == NULL) {
drupal_set_message(t('an error occurred parsing submitted values.'), 'error');
}
else {
$form_state['storage']['updated_terms'] = array();
$values_to_update = array('parent', 'weight');
if (!empty($updated_terms_json->termData)) {
$form_state['storage']['raw_term_data'] = $updated_terms_json->termData;
foreach ($updated_terms_json->termData as $updated_term) {
$term = taxonomy_term_load($updated_term->tid);
foreach ($values_to_update as $prop) {
if (isset($updated_term->{$prop})) {
$term->{$prop} = (int) $updated_term->{$prop};
}
}
$form_state['storage']['updated_terms'][$term->tid] = $term;
}
}
}
}
}
}
/**
* Submit callback for taxonomy_wrangler_overview_terms.
*/
function taxonomy_wrangler_overview_terms_submit($form, &$form_state) {
if ($form_state['triggering_element']['#value'] == t('Reset to alphabetical')) {
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
// Execute the reset action.
if ($form_state['values']['reset_alphabetical'] === TRUE) {
return taxonomy_vocabulary_confirm_reset_alphabetical_submit($form, $form_state);
}
// Rebuild the form to confirm the reset action.
$form_state['rebuild'] = TRUE;
$form_state['confirm_reset_alphabetical'] = TRUE;
return;
}
else {
if (!empty($form_state['storage']['updated_terms'])) {
foreach ($form_state['storage']['updated_terms'] as $term) {
taxonomy_term_save($term);
}
}
}
}
/**
* Ajax handler for taxonomy_wrangler_overview_terms.
*/
function taxonomy_wrangler_terms_overview_ajax_handler($form, &$form_state) {
$commands = array();
$messages = '<div id="taxonomy-wrangler-messages-server">';
$messages .= theme('status_messages');
$messages .= '</div>';
$commands[] = ajax_command_replace('#taxonomy-wrangler-messages-server', $messages);
// Send timestamps back to browser so it can update the row status.
$timestamps = array();
if (!empty($form_state['storage']['raw_term_data'])) {
foreach($form_state['storage']['raw_term_data'] as $term) {
if (isset($term->updated)) {
$timestamps[$term->tid] = (float) $term->updated;
}
}
}
$commands[] = ajax_command_settings(array(
'taxonomyWrangler' => array('updatedTimestamps' => $timestamps),
));
return array('#type' => 'ajax', '#commands' => $commands);
}
/**
* Returns HTML for a terms overview form as a sortable list of terms.
*
* @param $variables
* An associative array containing:
* - form: A render element representing the form.
*
* @see taxonomy_overview_terms()
* @ingroup themeable
*/
function theme_taxonomy_wrangler_overview_terms($variables) {
$form = $variables['form'];
// Add drag and drop if parent fields are present in the form.
if ($form['#parent_fields']) {
taxonomy_wrangler_add_tabledrag('taxonomy-wrangler', 'match', 'parent', 'parent', 'parent', 'tid', FALSE);
taxonomy_wrangler_add_tabledrag('taxonomy-wrangler', 'depth', 'group', 'depth', NULL, NULL, FALSE);
drupal_add_css(drupal_get_path('module', 'taxonomy') . '/taxonomy.css');
}
taxonomy_wrangler_add_tabledrag('taxonomy-wrangler', 'order', 'sibling', 'weight');
$errors = form_get_errors() != FALSE ? form_get_errors() : array();
$rows = array();
$element_children = element_children($form);
$is_root = TRUE;
foreach ($element_children as $i => $key) {
if (isset($form[$key]['#term'])) {
$term = &$form[$key];
$next_key = isset($element_children[$i + 1]) ? $element_children[$i + 1] : FALSE;
$is_parent = FALSE;
if (isset($form[$next_key]['#term']) && $form[$next_key]['#term']['depth'] > $term['#term']['depth'] && !$is_root) {
$is_parent = TRUE;
}
$row = array();
$row[] = (isset($term['#term']['depth']) && $term['#term']['depth'] > 0 ? theme('indentation', array('size' => $term['#term']['depth'])) : '');
$accordion_classes = array('taxonomy-wrangler-accordion-item');
if ($is_root) {
$accordion_classes[] = 'taxonomy-wrangler-accordion-item--root';
$is_root = FALSE;
}
elseif ($is_parent) {
$accordion_classes[] = 'taxonomy-wrangler-accordion-item--parent';
}
else {
$accordion_classes[] = 'taxonomy-wrangler-accordion-item--child';
}
$row[0] .= '<a href="#" class="' . implode(' ', $accordion_classes) . '"><span></span></a>';
$row[0] .= drupal_render($term['view']);
if ($form['#parent_fields']) {
$term['tid']['#attributes']['class'] = array('term-id');
$term['parent']['#attributes']['class'] = array('term-parent');
$term['depth']['#attributes']['class'] = array('term-depth');
$row[0] .= drupal_render($term['parent']) . drupal_render($term['tid']) . drupal_render($term['depth']);
}
$term['weight']['#attributes']['class'] = array('term-weight');
$row[] = drupal_render($term['weight']);
$row[] = drupal_render($term['edit']);
$row = array(
'data' => $row,
'data-tid' => $term['#term']['tid'],
'data-parent' => $term['#term']['parent'],
'data-depth' => $term['#term']['depth'],
'data-weight' => $term['#term']['weight'],
'data-haschildren' => $is_parent,
);
$rows[$key] = $row;
}
}
// Add necessary classes to rows.
$row_position = 0;
foreach ($rows as $key => $row) {
$rows[$key]['class'] = array();
if (isset($form['#parent_fields'])) {
$rows[$key]['class'][] = 'draggable';
}
// Add an error class if this row contains a form error.
foreach ($errors as $error_key => $error) {
if (strpos($error_key, $key) === 0) {
$rows[$key]['class'][] = 'error';
}
}
$rows[$key]['class'][] = 'taxonomy-wrangler-term-row';
$rows[$key]['class'][] = 'term-weight-row';
$row_position++;
}
if (empty($rows)) {
$rows[] = array(array('data' => $form['#empty_text'], 'colspan' => '3'));
}
$output = drupal_render($form['header']);
//unset($form['header']);
$header = array(t('Name'), t('Weight'), t('Operations'));
$output .= theme('table', array(
'header' => $header,
'rows' => $rows,
'attributes' => array(
'id' => 'taxonomy-wrangler',
'class' => array('taxonomy-wrangler', 'taxonomy-wrangler-accordion'),
),
));
$output .= drupal_render_children($form);
return $output;
}
@@ -0,0 +1,12 @@
name = Taxonomy Wrangler
description = Provides a better UI for the taxonomy overview page
core = 7.x
dependencies[] = taxonomy
package = Taxonomy
; Information added by Drupal.org packaging script on 2015-02-17
version = "7.x-1.x-dev"
core = "7.x"
project = "taxonomy_wrangler"
datestamp = "1424205783"
@@ -0,0 +1,59 @@
<?php
/**
* @file
* Taxonomy wrangler main module file
*/
/**
* Implements hook_menu_alter().
*
* Override the main taxonomy overview page.
*/
function taxonomy_wrangler_menu_alter(&$items) {
$items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name']['page arguments'] = array('taxonomy_wrangler_overview_terms', 3);
$items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name']['file'] = 'taxonomy_wrangler.admin.inc';
$items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name']['file path'] = drupal_get_path('module', 'taxonomy_wrangler');
}
/**
* Implements hook_theme().
*/
function taxonomy_wrangler_theme() {
return array(
'taxonomy_wrangler_overview_terms' => array(
'render element' => 'form',
),
);
}
/**
* Copy of drupal_add_tabledrag().
*
* This is a copy of drupal_add_tabledrag used just to instantiate
* our own tabledrag class vs Drupal's.
* @see drupal_add_tabledrag
*/
function taxonomy_wrangler_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
$js_added = &drupal_static(__FUNCTION__, FALSE);
if (!$js_added) {
// Add the table drag JavaScript to the page before the module JavaScript
// to ensure that table drag behaviors are registered before any module
// uses it.
drupal_add_library('system', 'jquery.cookie');
drupal_add_js('misc/tabledrag.js', array('weight' => -1));
$js_added = TRUE;
}
// If a subgroup or source isn't set, assume it is the same as the group.
$target = isset($subgroup) ? $subgroup : $group;
$source = isset($source) ? $source : $target;
$settings['taxonomyWrangler']['tables'][$table_id][$group][] = array(
'target' => $target,
'source' => $source,
'relationship' => $relationship,
'action' => $action,
'hidden' => $hidden,
'limit' => $limit,
);
drupal_add_js($settings, 'setting');
}
@@ -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.
@@ -0,0 +1,78 @@
<?php
function uc_ssl_admin()
{
$form = array();
$form['uc_ssl_ssl_domain'] = array(
'#type' => 'textfield',
'#title' => t('Secure Domain Name'),
'#default_value' => variable_get('uc_ssl_ssl_domain', ''),
//'#size' => 2,
//'#maxlength' => 2,
'#description' => t("This field accepts domain names in the following format: https://something.com OR https://something.com:5938. <br><br><b>IPMORTANT DRUPAL 7 NOTICE ABOUT DOMAIN NAMES:</b> This module DOES support using port numbers and different domains for SSL and normal HTTP like it's Drupal 6 predecessor HOWEVER, this is NOT meant for a production environment!!!! RFC restrictions PROHIBIT passing cookie data between sites with different port numbers (80 to 5933 for example. The ONLY exception is for the default ports of 80 and 443 which are never specified to begin with and thus pass RFC requirements for sharing data!!) and it treats them as separate sites. So if you use a port number drupal WILL require you to login BEFORE that url will work (drupal 6 has the same limitation btw, I just never documented it). In Drupal 7 this results in the 'Store' configuration panel NOT showing up. You must login to the store config panel by going to the https://yoursite.com:PORTNUMBER/admin/store url FIRST and login. Once you have done that, you can access store/admin. The administration panel overlay code for drupal 7 is NOT compatible with this module because it is NOT a secure method to access data!!!! ALWAYS go DIRECTLY to the /store/admin link DIRECTLY. The same goes for /cart. /cart WILL ask you to login. Once your site is ready for production you must absolutely use the SAME url for both secure AND non-secure pages. So your site should always be accessed from http://yoursite.com and https://yoursite.com OR http://www.yoursite.com and https://www.yoursite.com. It should NEVER be accessed like this: http://yoursite.com http://ssl.yoursite.com. Or any other sub domain for that matter. It will result in drupal asking you to login!"),
'#required' => TRUE,
);
$form['uc_ssl_non_ssl_domain'] = array(
'#type' => 'textfield',
'#title' => t('NON-Secure Domain Name'),
'#default_value' => variable_get('uc_ssl_non_ssl_domain', ''),
//'#size' => 2,
//'#maxlength' => 2,
'#description' => t("This field accepts domain names in the following format: http://something.com OR http://something.com:8080"),
'#required' => TRUE,
);
$form['uc_ssl_status'] = array(
'#type' => 'radios',
'#title' => t('Ubercart SSL Status'),
'#default_value' => variable_get('uc_ssl_status', ''),
'#options' => array( TRUE => t('Enabled'), FALSE => t('Disabled')),
'#required' => TRUE,
);
$form['uc_ssl_switch_to_non_ssl'] = array(
'#type' => 'radios',
'#title' => t('Ubercart Non-SSL Switch'),
'#default_value' => variable_get('uc_ssl_switch_to_non_ssl', ''),
'#options' => array( TRUE => t('Enabled'), FALSE => t('Disabled')),
'#required' => TRUE,
'#description' => t("Since this module switches to SSL mode during checkout, all links will link back to a secured version of the website. If you want to switch back to non-secured mode after a transaction is complete or they click on a keep shopping link, etc. This isnt really necessary but some people may want to save on the small resources savings you can get from doing this. So if you want to keep http for any non-cart related things, you should check this as enabled. If you dont care, then set it to disabled.<br><br>DRUPAL 7 NOTICE: Enabling this will DISABLE the Overlay module because it cannot work securely in a mixed SSL environment!! Setting this back to Disabled WILL NOT re-enable the Overlay module. You must re-enable the Overlay module yourself."),
);
$form['uc_ssl_case_insensitive'] = array(
'#type' => 'radios',
'#title' => t('Ubercart SSL Case Sensitivity'),
'#default_value' => variable_get('uc_ssl_case_insensitive', TRUE),
'#options' => array( TRUE => t('Enabled'), FALSE => t('Disabled')),
'#required' => TRUE,
'#description' => t('By default drupal allows paths to be accessed in a case insensitive manor. This is fine but not very secure. SSL Standards dictate that paths should always be case sensitive. So in order to be compatible with SSL standards, we allow the administrator to change SSL path recognition to case sensitive by simply setting this setting to disabled. In order to stick close to drupal standards, this module defaults this value to Enabled which means /Cart AND /cart would match and be secured where as in case sensitive mode /Cart would NOT be secured, alerting the user to an insecure page but /cart would be secured.'),
);
return system_settings_form($form);
}
function uc_ssl_admin_validate($form, &$form_state)
{
$ssl_domain = $form_state['values']['uc_ssl_ssl_domain'];
$non_ssl_domain = $form_state['values']['uc_ssl_non_ssl_domain'];
if (!valid_url($ssl_domain) || !stristr($ssl_domain, 'https://'))
{
form_set_error('uc_ssl_ssl_domain', t('You must enter a valid SSL Domain name.'));
}
if (!valid_url($non_ssl_domain) || !stristr($non_ssl_domain, 'http://'))
{
form_set_error('uc_ssl_non_ssl_domain', t('You must enter a valid Non-SSL Domain name.'));
}
if (!uc_ssl_check($ssl_domain.base_path()))
{
form_set_error('uc_ssl_ssl_domain', t('CRITICAL ERROR! The domain you entered for the secured domain came back as non-secure or it does not point back to this installation of drupal. Your secure domain name MUST be setup and MUST be pointing at this install of drupal.'));
variable_set('uc_ssl_status', '0');
$form_state['values']['uc_ssl_status'] = '0';
$form['values']['uc_ssl_status'] = '0';
}
}
@@ -0,0 +1,14 @@
name = Ubercart SSL
description = (D7) Secure Ubercart /cart links with an SSL Cert. Do NOT enable this unless your site works with SSL as it WILL break your cart. If it does, just disable this and get your site working with SSL first and then re-enable this module. This module does not require Ubercart so it can be used for anything else as well, its just that its most common use is to be used with Ubercart so that is why I named it so. Feel free to use it with anything you like.
package = Ubercart - extra
core = 7.x
project = "uc_ssl"
configure = admin/config/system/uc_ssl
; Information added by drupal.org packaging script on 2012-12-03
version = "7.x-1.11"
core = "7.x"
project = "uc_ssl"
datestamp = "1354572030"
@@ -0,0 +1,12 @@
<?php
/**
* Implementation of hook_uninstall().
*/
function uc_ssl_uninstall()
{
variable_del('uc_ssl_ssl_domain');
variable_del('uc_ssl_non_ssl_domain');
variable_del('uc_ssl_status');
variable_del('uc_ssl_switch_to_non_ssl');
}
@@ -0,0 +1,416 @@
<?php
//
//Note about the include/exclude hooks. As an example, this module includes /cart* which essentially secures ALL cart pages with SSL. But it also implements an exclude which is called /cart Which you would think would negate the include but it DOES NOT. Even though Excludes take presedence over includes, it still allows /cart/1 for example, to be secured. Why? Because the exclude is not a wildcard match! Thus the exclude would NOT match /cart/1 because it's defined as /cart. Thus while /cart IS excluded (not secured with SSL),/cart/1 is STILL secured.
//Implementation of hook_include_ssl_paths()
//NOTE: Exclude takes presedence over Includes!!! So if the same path is in both hooks, then the path will be EXCLUDED from secured pages.
//Since base_url has a design flaw in D4/D5/D6/D7 that seemingly will never be fixed, we fix it here.
function uc_ssl_boot()
{
global $conf;
//the $conf['https'] option MUST be enabled if mixed ssl mode is enabled. We make sure its enabled here. If it's not enabled then user
//sessions will not persist across the secure and non-secure domain names resulting in the user being prompted to log in whenever they are
//sent to a secure page.
if (uc_ssl_switch_to_non_ssl() && !isset($conf['https']) || (isset($conf['https']) && !$conf['https']))
{
$conf['https'] = TRUE;
}
if ($GLOBALS['base_url'])
{
//If base_url exists and is set to a non-secure protocol while the page being called is secure, allow base_url to be changed to
//the secure version of the website. Drupal for some reason doesnt have this logic anywhere for $base_url.
if (uc_ssl_page_is_in_https_mode() && stristr($GLOBALS['base_url'], 'http://'))
{
$GLOBALS['base_url'] = str_ireplace('http://', 'https://', $GLOBALS['base_url']);
}
}
}
function uc_ssl_permission()
{
$perms = array(
'administer uc_ssl' => array(
'title' => t('Administer Ubercart SSL settings'),
),
);
return $perms;
}
function uc_ssl_page_is_in_https_mode()
{
if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']))
{
return TRUE;
}
return FALSE;
}
function uc_ssl_disable_overlay_module()
{
$modules = module_list();
$base_path = base_path();
if (variable_get('uc_ssl_switch_to_non_ssl', '') && in_array('overlay', $modules))
{
//Overlay is on, lets disable it.
module_disable(array(0 => 'overlay'));
}
}
function uc_ssl_init()
{
//Drupals Overlay panel is not secure! Fix that here by disable it all together. We cannot allow this. Drupal 7 is insecure by default, such a sad thing :/
uc_ssl_disable_overlay_module();
//menu_rebuild();
//First and foremost, make sure Clean URLs are on.
if (uc_ssl_clean_urls_enabled() && !drupal_is_cli())
{
//Setup a hook for ssl checking
uc_ssl_check();
//Run ssl check on every page load.
uc_ssl_run();
}
}
function uc_ssl_include_ssl_paths()
{
global $user;
$paths = array(
'All Ubercart Cart pages' => '/cart*', //Secure ALL cart pages.
//NOTE: If you remove the /user definition here, you CAN NOT use Mixed SSL Mode with D7. It HAS to exist because D7 http sessions are missing
//data that https sessions require. But http sessions work with the https session variables. Thus, you MUST login with https or your sessions
//will not carry between the http and https versions of your wesite. This is a D7 bug only, I believe its more of a feature than a bug.
'All User pages' => '/user*', //Secure ALL user pages.
//Added support for Drupal commerce which is based upon Ubercart.
'All Drupal Commerce Checkout pages' => '/checkout*', //Secure ALL cart pages. NOTE: SEE EXCLUDES to see why the cart listing itself isnt secured!
//This supports both UC and Commerce admins
'All Ubercart Cart Admin pages' => '/admin/store*', //Secure ALL UC admin pages.
#'example 1' => '/cart', //Only secure the /cart and /cart/ page.
#'example 2' => 'cart', //Only secure the /cart and /cart/ page.
#'example 3' => 'cart/', //Only secure the /cart and /cart/ page.
#'example 4' => '/cart*/something', //matches /cartThis/something and /cart/something but NOT thiscart/something etc.
#'example 5' => '/cart/*/something', //Matches /cart/123/something and cart/this/something, but NOT /cart/something
#'example 6' => '/cart/something', //Only secure the /cart/something and /cart/something/ page.
);
return $paths;
}
//Implementation of hook_exclude_ssl_paths()
function uc_ssl_exclude_ssl_paths()
{
$paths = array(
//These excludes no longer seem to be required for the D7 version and thus they have been removed until issues come up again.
//'Exclude the cart page itself' => '/cart', //We dont need to secure the cart contents so we exclude that here
//'Exclude Autocomplete' => '*autocomplete*',
//'Exclude Ajax' => '*ajax*',
#'example 1' => '/cart', //Only exclude the /cart and /cart/ page.
#'example 2' => 'cart', //Only exclude the /cart and /cart/ page.
#'example 3' => 'cart/', //Only secure the /cart and /cart/ page.
#'example 4' => '/cart*/something', //matches /cartThis/something and /cart/something but NOT thiscart/something etc.
#'example 5' => '/cart/*/something', //Matches /cart/123/something and cart/this/something, but NOT /cart/something
#'example 6' => '/cart/something', //Only exclude the /cart/something and /cart/something/ page.
);
return $paths;
}
//Implementation of hook_exclude_ssl_paths()
//This function is so you can completely ignore ANY switching at all no matter what.
function uc_ssl_exclude_ssl_switch_paths()
{
$paths = array(
#'example 1' => '/*ajax*', //Dont touch ajax paths whatsoever, this is just an example.
);
return $paths;
}
function uc_ssl_menu()
{
$items = array();
$items['admin/config/system/uc_ssl'] = array(
'title' => 'Ubercart SSL',
// 'title' => 'Ubercart SSL module settings',
'description' => 'Ubercart SSL module settings',
'page callback' => 'drupal_get_form',
'page arguments' => array('uc_ssl_admin'),
'access arguments' => array('administer uc_ssl'),
'type' => MENU_NORMAL_ITEM,
'file' => 'uc_ssl.admin.inc',
);
return $items;
}
function uc_ssl_enabled()
{
return variable_get('uc_ssl_status', '');
}
function uc_ssl_is_configured()
{
$query = "SELECT count(name) AS count from {variable} WHERE name = 'uc_ssl_status'";
$results = db_query($query);
$rows = $results->fetchAll();
$rows = $rows[0];
//If uc_ssl is not configured, warn the user and show a link to config it.
if (!$rows->count)
{
$admin_link = 'http://'.$_SERVER['HTTP_HOST'].url().'admin/config/system/uc_ssl';
drupal_set_message("Please configure Ubercart SSL for SSL enabled cart checkouts to work: <a href = '$admin_link'>$admin_link</a>", 'warning');
}
return $rows->count;
}
function uc_ssl_switch_to_non_ssl()
{
return variable_get('uc_ssl_switch_to_non_ssl', '');
}
function uc_ssl_path_match($path, $pages)
{
$result = FALSE; //This is here just to get rid of retarded php 'notice' messages. I hate php notices.
if (!empty($pages))
{
//Trim off trailing / and then re-add it to avoid double /'s. This allows cart and cart/ to match as the same thing or cart/1 and cart/1/ to be the same.
$path = trim($path, '/').'/';
$regexp = '/^(';
foreach ($pages AS $key => $regexp_path)
{
if ($regexp_path)
{
$regexp_path = trim($regexp_path, '/').'/';
$regexp_path1 = str_replace('/', '\/', $regexp_path); //replace / with a \/
$regexp_path2 = str_replace('*', '.*', $regexp_path1);//replace * with a .*
$regexp .= $regexp_path2.'|'; //Append a | to signify end of this expression
}
}
$regexp = trim($regexp, '|');
$regexp .= ')$/';
if (variable_get('uc_ssl_case_insensitive', 1))
{
$regexp .= 'i';
}
$result = preg_match($regexp, $path);
}
return $result;
}
function is_clean_url($path)
{
//Skip ANY ?q= urls since these do NOT come from a web browser when clean URLs is on. Doing this allows us to skip
//ajax and autocomplete type URLs that come from within drupal itself. This is a major problem with Secure_Pages module
//and we dont want the same problems so we restrict people to using ONLY clean URLs.
if (!stristr($path, '?q='))
{
return TRUE;
}
return FALSE;
}
function uc_ssl_http_request($url)
{
//Handle JS type urls in the background as they are likely to be ajax type posts.
if (arg(0) == 'js')
{
$js_response = drupal_http_request($url);
return;
}
//Handle post type URLs. This should handle ajax POST urls such as the tax calculation/progress bars.
if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST['uc_ssl_post']))
{
$_POST['uc_ssl_post'] = 1;
$options['headers'] = array('Content-Type' => 'application/x-www-form-urlencoded');
$options['method'] = 'POST';
$options['data'] = http_build_query($_POST, '', '&');
//Drupal 7 decided to completely recode drupal_http_request so I dont know if this will cause issues or not. Report any bugs please.
//$response = drupal_http_request($url, $headers, 'POST', http_build_query($_POST, '', '&'));
$response = drupal_http_request($url, $options);
return;
}
//All other types of urls are handled normally.
// Reset destination variables or we'll get sent there instead of to $url
unset($_REQUEST['destination'], $_GET['destination']);
drupal_goto($url);
return;
}
function uc_ssl_run()
{
//Set the current path without url() since it will mess up regex checks. Using url() also supports languages, base_path does not.
//$current_path = trim($_SERVER['REQUEST_URI'], url());
$root = url();
$current_path = substr(trim($_SERVER['REQUEST_URI']),strlen($root));
$ssl_domain = variable_get('uc_ssl_ssl_domain', '');
$nonssl_domain = variable_get('uc_ssl_non_ssl_domain', '');
//If uc_ssl is configured, run it.
if (uc_ssl_is_configured() && is_clean_url($current_path))
{
if (uc_ssl_enabled())
{
//Get a list of all the URL links that should be included and excluded from SSL pages from other modules.
$items = array();
$exclude_secured_urls = array();
$exclude_secured_urls = module_invoke('uc_ssl', 'exclude_ssl_paths', $exclude_secured_urls);
foreach (module_implements('exclude_ssl_paths') as $module)
{
$new = module_invoke($module, 'exclude_ssl_paths', $exclude_secured_urls);
if ($module != 'uc_ssl') //Skip uc_ssl since we already processed it above. Allow external modules to change uc_ssl defaults.
{
if (is_array($new))
{
$exclude_secured_urls = array_merge($exclude_secured_urls, $new);
}
}
}
$include_secured_urls = array();
$include_secured_urls = module_invoke('uc_ssl', 'include_ssl_paths', $include_secured_urls);
foreach (module_implements('include_ssl_paths') as $module)
{
$new = module_invoke($module, 'include_ssl_paths', $include_secured_urls);
if ($module != 'uc_ssl') //Skip uc_ssl since we already processed it above. Allow external modules to change uc_ssl defaults.
{
if (is_array($new))
{
$include_secured_urls = array_merge($include_secured_urls, $new);
}
}
}
// Get a list of all the URL links that should not switch between HTTP/HTTPS at all.
$exclude_switch_urls = array();
$exclude_switch_urls = module_invoke('uc_ssl', 'exclude_ssl_switch_paths', $exclude_switch_urls);
foreach (module_implements('exclude_ssl_switch_paths') as $module)
{
$new = module_invoke($module, 'exclude_ssl_switch_paths', $exclude_switch_urls);
if ($module != 'uc_ssl') //Skip uc_ssl since we already processed it above. Allow external modules to change uc_ssl defaults.
{
if (is_array($new))
{
$exclude_switch_urls = array_merge($exclude_switch_urls, $new);
}
}
}
// make sure we return an array
if (! is_array($include_secured_urls)) { $include_secured_urls = array(); }
if (! is_array($exclude_secured_urls)) { $exclude_secured_urls = array(); }
if (! is_array($exclude_switch_urls)) { $exclude_switch_urls = array(); }
//If the path is in the exclude switch hook, dont do ANYTHING at all.
if (uc_ssl_path_match($current_path, $exclude_switch_urls))
{
return;
}
//Switch to SSL no matter what the link is if Switch isnt on.
if (!uc_ssl_switch_to_non_ssl())
{
if (!uc_ssl_page_is_in_https_mode() && !uc_ssl_path_match($current_path, $exclude_secured_urls))
{
uc_ssl_http_request($ssl_domain . $_SERVER['REQUEST_URI']);
}
}
else
{
//If uc_ssl_switch_to_non_ssl() is enabled then we switch back to non-ssl link for non-cart links.
if (uc_ssl_page_is_in_https_mode())
{
//The only exceptions are the links listed in the exclude list by other modules.
if (uc_ssl_path_match($current_path, $exclude_secured_urls))
{
uc_ssl_http_request($nonssl_domain . $_SERVER['REQUEST_URI']);
}
if (!uc_ssl_path_match($current_path, $include_secured_urls) && uc_ssl_switch_to_non_ssl())
{
uc_ssl_http_request($nonssl_domain . $_SERVER['REQUEST_URI']);
}
}
}
//If on a cart url, use HTTPS and re-post/re-direct to the SSL version of the url.
if (!uc_ssl_page_is_in_https_mode() && uc_ssl_path_match($current_path, $include_secured_urls) && !uc_ssl_path_match($current_path, $exclude_secured_urls))
{
uc_ssl_http_request($ssl_domain . $_SERVER['REQUEST_URI']);
}
}
}
}
function uc_ssl_clean_urls_enabled()
{
$check = variable_get('clean_url', 0);
if ($check == 1)
{
return TRUE;
}
drupal_set_message('Ubercart SSL (uc_ssl): The uc_ssl module REQUIRES that Clean URLs be enabled in order to work properly. This allows the module to distinguish between an Ajax call and a Web browser call as the two are handled differently so we need a way to distinguish them and this is the quickest easiest way to do so. This will also make your website URLs search engine friendly as well which is a good thing. Please enable clean urls here: <a href="?q=admin/settings/clean-urls">Clean URLs</a>', 'warn');
return FALSE;
}
//This is a quickie hook to see if SSL works or not. It's not fool proof but it works for me.
function uc_ssl_check($site = '')
{
error_reporting(E_ALL);
if (!$site)
{
if (isset($_GET['uc_ssl_check']) && $_GET['uc_ssl_check'])
{
if (uc_ssl_page_is_in_https_mode())
{
echo TRUE;
}
else
{
echo FALSE;
}
exit;
}
}
else
{
$check = drupal_http_request($site."?uc_ssl_check=1");
if (isset($check->data) && $check->data == '1')
{
return TRUE;
}
//IF we are here, then the request failed for some reason, so we try to use a different method.
if (ini_get('allow_url_fopen'))
{
if (file_get_contents($site."?uc_ssl_check=1") == '1')
{
return TRUE;
}
}
//If we are here, something went wrong. Give the user some ideas on what they need to fix.
drupal_set_message("Ubercart SSL (uc_ssl): The uc_ssl_check() function is returning FALSE because it was unable to contact the SSL (https) version of your website that you defined in the settings. This can be caused by 3 things. 1. Your website is not setup properly for SSL, 2. The OpenSSL extension is not enabled on in your PHP installation, 3. allow_url_fopen is not enabled in php.ini. If #2 fails, uc_ssl will try to use file_get_contents() which requires allow_url_fopen to be set to TRUE in php.ini. Hopefully these hints will help you fix this issue so that you can use uc_ssl. You can try to debug this by going to $site?uc_ssl_check=1", "error");
}
return FALSE;
}
if (!function_exists('printr'))
{
function printr($arr)
{
echo "<pre>";
print_r($arr);
echo "</pre>";
}
}
@@ -1,4 +1,3 @@
This is a highly flexible and easy extendable filter module to embed any type
of video in your site using a simple tag. Other modules can add video
sites/formats (called codecs) using an easy plug-in architecture.
@@ -22,6 +21,9 @@ processed after that filter.
To enable WYSIWYG support, go to the WYSIWYG settings for each input format and
enable the Video Filter button.
To enable CKEditor (standalone) support, please see plugin instructions in:
editors/ckeditor/README.txt
========= Usage =========
Single video: [video:url]
@@ -1,35 +1,15 @@
##############################################
## ONLY if you use ckeditor WITHOUT wysiwyg ##
##############################################
############################################################
## ONLY if with the CKEditor module, *NOT* WYSIWYG module ##
############################################################
Installation:
Do the following steps to add video_filter button to the CKEditor toolbar:
1. Open ckeditor.config.js (in the ckeditor module root)
1. Go to Configuration -> CKEditor (admin/config/content/ckeditor)
Click "Edit" on the profile you what to use with the video filter.
2. Scroll down to the end of the file, right before "};" insert:
2. Expand "Editor appearance" and go to "Toolbar". Drag the new video_filter
button from the "All Buttons" toolbar to the "Used Buttons" toolbar.
// Video_filter plugin.
config.extraPlugins += (config.extraPlugins ? ',video_filter' : 'video_filter' );
CKEDITOR.plugins.addExternal('video_filter', Drupal.settings.basePath + Drupal.settings.video_filter.modulepath + '/editors/ckeditor/');
3. Add button to the toolbar.
3.1 Go to Configuration -> CKEditor (admin/config/content/ckeditor)
Click "Edit" on the profile you what to use with Linkit.
3.2 Expand "Editor appearance" and go to "Toolbar".
The button name is: video_filter
For example if you have a toolbar with an array of buttons defined as
follows:
['Bold','Italic']
simply add the button somewhere in the array:
['Bold','Italic','video_filter']
(remember the single quotes).
3. Go to "Plugins" on the same page. Enable the video filter plugin.
@@ -7,25 +7,126 @@
requires : [],
init: function(editor) {
// Add Button
editor.ui.addButton('video_filter', {
label: 'Video filter',
command: 'video_filter',
icon: this.path + 'video_filter.png'
});
// Add Command
editor.addCommand('video_filter', {
exec : function () {
var path = (Drupal.settings.video_filter.url.wysiwyg_ckeditor) ? Drupal.settings.video_filter.url.wysiwyg_ckeditor : Drupal.settings.video_filter.url.ckeditor
var media = window.showModalDialog(path, { 'opener' : window, 'editorname' : editor.name }, "dialogWidth:580px; dialogHeight:480px; center:yes; resizable:yes; help:no;");
}
});
// Register an extra fucntion, this will be used in the popup.
editor._.video_filterFnNum = CKEDITOR.tools.addFunction(insert, editor);
if(typeof window.showModalDialog !== 'undefined') {
editor.addCommand('video_filter', {
exec : function () {
var path = (Drupal.settings.video_filter.url.wysiwyg_ckeditor) ? Drupal.settings.video_filter.url.wysiwyg_ckeditor : Drupal.settings.video_filter.url.ckeditor
var media = window.showModalDialog(path, { 'opener' : window, 'editorname' : editor.name }, "dialogWidth:580px; dialogHeight:480px; center:yes; resizable:yes; help:no;");
}
});
// Register an extra function, this will be used in the popup.
editor._.video_filterFnNum = CKEDITOR.tools.addFunction(insert, editor);
}
else {
editor.addCommand('video_filter', new CKEDITOR.dialogCommand('video_filterDialog'));
}
}
});
CKEDITOR.dialog.add('video_filterDialog', function( editor ) {
var instructions_path = Drupal.settings.video_filter.instructions_url;
return {
title : 'Add Video',
minWidth : 600,
minHeight : 180,
contents : [{
id : 'general',
label : 'Settings',
elements : [
{
type : 'text',
id : 'file_url',
label : 'URL',
validate : CKEDITOR.dialog.validate.notEmpty( 'The link must have a URL.' ),
required : true,
commit : function( data )
{
data.file_url = this.getValue();
}
},
{
type : 'text',
id : 'width',
label : 'Width',
commit : function( data )
{
data.width = this.getValue();
}
},
{
type : 'text',
id : 'height',
label : 'Height',
commit : function( data )
{
data.height = this.getValue();
}
},
{
type : 'select',
id : 'align',
label : 'Align',
'default': 'none',
items: [
['None', ''],
['Left', 'left'],
['Right', 'right'],
['Center', 'center']
],
commit : function( data )
{
data.align = this.getValue();
}
},
{
type : 'checkbox',
id : 'autoplay',
label : 'Autoplay',
'default': '',
commit : function( data )
{
data.autoplay = this.getValue() ? 1 : 0;
}
},
{
type: 'html',
html: '<iframe src="' + instructions_path + '" style="width:100%; height: 200px;"></iframe>',
},
]
}],
onOk : function()
{
var dialog = this,
data = {},
link = editor.document.createElement( 'p' );
this.commitContent( data );
var str = '[video:' + data.file_url;
if (data.width) {
str += ' width:' + data.width;
}
if (data.height) {
str += ' height:' + data.height;
}
if (data.align) {
str += ' align:' + data.align;
}
if (data.autoplay) {
str += ' autoplay:' + data.autoplay;
}
str += ']';
link.setHtml( str );
editor.insertElement( link );
}
};
});
function insert(params, editor) {
@@ -49,6 +150,9 @@
if (params.autoplay) {
str += ' autoplay:' + params.autoplay;
}
else {
str += ' autoplay:' + '0';
}
str += ']';
for (var i = 0, len = ranges.length; i < len; i++) {
@@ -43,6 +43,9 @@ function Ok() {
if ($('#edit-autoplay').is(':checked')) {
str += ' autoplay:' + $('#edit-autoplay').val();
}
else {
str += ' autoplay:' + '0';
}
str += ']';
oEditor.FCKUndo.SaveUndoStep();
@@ -34,6 +34,9 @@ video_filter_dialog = {
if ($('#edit-autoplay').is(':checked')) {
str += ' autoplay:' + $('#edit-autoplay').val();
}
else {
str += ' autoplay:' + '0';
}
str += ']';
ed.execCommand('mceInsertContent', false, str);
@@ -0,0 +1,70 @@
<?php
/**
* @file
* Hooks provided by the Video Filter module.
*/
/**
* Defines video codecs and callbacks.
*
* @return array
* A video codec described as an associative array that may contain the
* following key-value pairs:
* - name: Required. A name for the codec.
* - sample_url: Required. An example of a URL the codec can handle.
* - callback: The function to call to generate embed code for the codec.
* Either this or html5_callback must be specified.
* - html5_callback: The function to call to generate device agnostic, HTML5
* embed code for the codec. Either this or callback must be specified.
* - instructions: Instructions for using the codec, to be displayed on the
* "Compse tips" page at filter/tips.
* - regexp: Required. A regular expression describing URLs the codec can
* handle. Multiple regular expressions may be supplied as an array.
* $video['codec']['delta'] will be set to the key of the match.
* - ratio: Required. A ratio for resizing the video within the dimensions
* optionally supplied in the token, expressed as height / width.
* - control_bar_height: The pixel height of the video player control bar, if
* applicable.
*/
function hook_codec_info() {
$codecs = array();
$codecs['minimal_example'] = array(
'name' => t('Minimal Example'),
'sample_url' => 'http://minimal.example.com/uN1qUeId',
'callback' => 'MODULE_minimal_example',
'regexp' => '/minimal\.example\.com\/([a-z0-9\-_]+)/i',
'ratio' => 4 / 3,
);
$codecs['complete_example'] = array(
'name' => t('Complete Example'),
'sample_url' => 'http://complete.example.com/username/uN1qUeId',
'callback' => 'MODULE_complete_example',
'html5_callback' => 'MODULE_complete_example_html5',
'instructions' => t('Your Complete Example username can be the first URL argument or a sub-subdomain.'),
'regexp' => array(
'/complete\.example\.com\/([a-z0-9\-_]+)\/([a-z0-9\-_]+)/i',
'/([a-z0-9\-_]+)\.complete\.example\.com\/([a-z0-9\-_]+)/i',
),
'ratio' => 4 / 3,
'control_bar_height' => 25,
);
return $codecs;
}
/**
* Alters the codecs available to Video Filter.
*
* @param array $codecs
*/
function hook_video_filter_codec_info_alter(&$codecs) {}
/**
* Alters a video's attributes previous to rendering.
*
* @param array $video
*/
function hook_video_filter_video_alter(&$video) {}
@@ -34,6 +34,15 @@ function video_filter_codec_info() {
'control_bar_height' => 30,
);
$codecs['candidcareer'] = array(
'name' => t('Candid Career'),
'sample_url' => 'https://www.candidcareer.com/embed.php?vkey=ed5fdd900a274930252f&shared=CandidCareer&uid=30',
'callback' => 'video_filter_candidcareer',
'regexp' => '/candidcareer\.com\/embed\.php\?vkey=([a-zA-Z0-9\-_&;]+)shared=([a-zA-Z0-9\-_&;]+)uid=([a-zA-Z0-9\-_&;]+)/',
'ratio' => 16 / 9,
'control_bar_height' => 20,
);
$codecs['capped'] = array(
'name' => t('Capped'),
'sample_url' => 'http://capped.tv/playeralt.php?vid=some-title',
@@ -196,7 +205,7 @@ function video_filter_codec_info() {
'sample_url' => 'http://wistia.com/medias/9pj9n6ftlk',
'callback' => 'video_filter_wistia_html5',
'html5_callback' => 'video_filter_wistia_html5',
'regexp' => '@https?://(.+\.)?(wistia\.com|wi\.st)/((m|medias|projects)|embed/(iframe|playlists))/([a-zA-Z0-9]+)@',
'regexp' => '@https?://(.+\.)?(wistia\.(com|net)|wi\.st)/((m|medias|projects)|embed/(iframe|playlists))/([a-zA-Z0-9]+)@',
);
$codecs['youtube'] = array(
@@ -205,9 +214,10 @@ function video_filter_codec_info() {
'callback' => 'video_filter_youtube',
'html5_callback' => 'video_filter_youtube_html5',
'regexp' => array(
'/youtube\.com\/watch\?v=([a-z0-9\-_]+)/i',
'/youtube\.com\/watch\?.*?v=([a-z0-9\-_]+)/i',
'/youtu.be\/([a-z0-9\-_]+)/i',
'/youtube\.com\/v\/([a-z0-9\-_]+)/i',
'/youtube\.com\/embed\/([a-z0-9\-_]+)/i',
),
'ratio' => 16 / 9,
'control_bar_height' => 25,
@@ -233,7 +243,7 @@ function video_filter_codec_info() {
* @see video_filter_codec_info()
*/
function video_filter_archive($video) {
$video['source'] = 'http://www.archive.org/embed/' . $video['codec']['matches'][1];
$video['source'] = '//www.archive.org/embed/' . $video['codec']['matches'][1];
return video_filter_iframe($video);
}
@@ -290,7 +300,7 @@ function video_filter_bliptv($video) {
}
}
$video['source'] = 'http://blip.tv/play/' . $id;
$video['source'] = '//blip.tv/play/' . $id;
$params = array(
'allowscriptaccess' => 'always',
);
@@ -298,13 +308,27 @@ function video_filter_bliptv($video) {
return video_filter_flash($video, $params);
}
/**
* Callback for Candid Career codec.
*
* @see video_filter_codec_info()
*/
function video_filter_candidcareer($video) {
// Their urls contain & symbols which Drupal is encoding, so decode those.
$decoded = decode_entities($video['codec']['matches'][0]);
$video['source'] = '//' . $decoded;
$video['attributes']['marginwidth'] = 0;
$video['attributes']['marginheight'] = 0;
return video_filter_iframe($video);
}
/**
* Callback for Capped codec.
*
* @see video_filter_codec_info()
*/
function video_filter_capped($video) {
$video['source'] = 'http://capped.micksam7.com/playeralt.swf?vid=' . $video['codec']['matches'][1];
$video['source'] = '//capped.micksam7.com/playeralt.swf?vid=' . $video['codec']['matches'][1];
return video_filter_flash($video);
}
@@ -315,7 +339,7 @@ function video_filter_capped($video) {
* @see video_filter_codec_info()
*/
function video_filter_collegehumor($video) {
$video['source'] = 'http://www.collegehumor.com/moogaloop/moogaloop.swf?clip_id=' . $video['codec']['matches'][1] . '&amp;fullscreen=1';
$video['source'] = '//www.collegehumor.com/moogaloop/moogaloop.swf?clip_id=' . $video['codec']['matches'][1] . '&amp;fullscreen=1';
return video_filter_flash($video);
}
@@ -326,7 +350,7 @@ function video_filter_collegehumor($video) {
* @see video_filter_codec_info()
*/
function video_filter_dailymotion($video) {
$video['source'] = 'http://www.dailymotion.com/swf/' . $video['codec']['matches'][1];
$video['source'] = '//www.dailymotion.com/swf/' . $video['codec']['matches'][1];
return video_filter_flash($video);
}
@@ -354,7 +378,7 @@ function video_filter_flickr_slideshows($video) {
* @see video_filter_codec_info()
*/
function video_filter_flickr_video($video) {
$video['source'] = 'http://www.flickr.com/apps/video/stewart.swf?v=1.161';
$video['source'] = '//www.flickr.com/apps/video/stewart.swf?v=1.161';
$params['flashvars'] = '&amp;photo_id=' . $video['codec']['matches'][2] . '&amp;flickr_show_info_box=true';
@@ -373,7 +397,7 @@ function video_filter_gametrailers($video) {
elseif (is_numeric($video['codec']['matches'][2])) {
$match = $video['codec']['matches'][2];
}
$video['source'] = 'http://media.mtvnservices.com/embed/mgid:moses:video:gametrailers.com:' . $match;
$video['source'] = '//media.mtvnservices.com/embed/mgid:moses:video:gametrailers.com:' . $match;
return video_filter_iframe($video);
}
@@ -384,7 +408,7 @@ function video_filter_gametrailers($video) {
* @see video_filter_codec_info()
*/
function video_filter_gamevideos($video) {
$video['source'] = 'http://gamevideos.1up.com/swf/gamevideos12.swf?embedded=1&amp;fullscreen=1&amp;autoplay=0&amp;src=http://gamevideos.1up.com/do/videoListXML%3Fid%3D' . $video['codec']['matches'][1];
$video['source'] = '//gamevideos.1up.com/swf/gamevideos12.swf?embedded=1&amp;fullscreen=1&amp;autoplay=0&amp;src=http://gamevideos.1up.com/do/videoListXML%3Fid%3D' . $video['codec']['matches'][1];
return video_filter_flash($video);
}
@@ -395,7 +419,7 @@ function video_filter_gamevideos($video) {
* @see video_filter_codec_info()
*/
function video_filter_godtube($video) {
$video['source'] = 'http://www.godtube.com/embed/watch/' . $video['codec']['matches'][1];
$video['source'] = '//www.godtube.com/embed/watch/' . $video['codec']['matches'][1];
return video_filter_iframe($video);
}
@@ -406,7 +430,7 @@ function video_filter_godtube($video) {
* @see video_filter_codec_info()
*/
function video_filter_google($video) {
$video['source'] = 'http://video.google.com/googleplayer.swf?docId=' . $video['codec']['matches'][1];
$video['source'] = '//video.google.com/googleplayer.swf?docId=' . $video['codec']['matches'][1];
return video_filter_flash($video);
}
@@ -417,7 +441,7 @@ function video_filter_google($video) {
* @see video_filter_codec_info()
*/
function video_filter_metacafe($video) {
$video['source'] = 'http://metacafe.com/fplayer/' . $video['codec']['matches'][1] . '/' . $video['codec']['matches'][2] . '.swf';
$video['source'] = '//metacafe.com/fplayer/' . $video['codec']['matches'][1] . '/' . $video['codec']['matches'][2] . '.swf';
return video_filter_flash($video);
}
@@ -430,7 +454,7 @@ function video_filter_metacafe($video) {
function video_filter_myspace($video) {
// The last match is the ID we need.
$last = count($video['codec']['matches']);
$video['source'] = 'http://mediaservices.myspace.com/services/media/embed.aspx/m=' . $video['codec']['matches'][$last - 1];
$video['source'] = '//mediaservices.myspace.com/services/media/embed.aspx/m=' . $video['codec']['matches'][$last - 1];
return video_filter_flash($video, $params);
}
@@ -441,7 +465,7 @@ function video_filter_myspace($video) {
* @see video_filter_codec_info()
*/
function video_filter_picasa_slideshows($video) {
$video['source'] = 'http://picasaweb.google.com/s/c/bin/slideshow.swf';
$video['source'] = '//picasaweb.google.com/s/c/bin/slideshow.swf';
$user_name = $video['codec']['matches'][1];
$set_id = $video['codec']['matches'][2];
@@ -457,7 +481,7 @@ function video_filter_picasa_slideshows($video) {
* @see video_filter_codec_info()
*/
function video_filter_slideshare($video) {
$video['source'] = 'http://www.slideshare.net/slideshow/embed_code/' . $video['codec']['matches'][1];
$video['source'] = '//www.slideshare.net/slideshow/embed_code/' . $video['codec']['matches'][1];
return video_filter_iframe($video);
}
@@ -468,7 +492,7 @@ function video_filter_slideshare($video) {
* @see video_filter_codec_info()
*/
function video_filter_streamhoster($video) {
$video['source'] = 'http://public.streamhoster.com/Resources/Flash/JWFLVMediaPlayer/mediaplayer.swf';
$video['source'] = '//public.streamhoster.com/Resources/Flash/JWFLVMediaPlayer/mediaplayer.swf';
$params = array('allowscriptaccess' => 'always');
$protocol = $video['codec']['matches'][1];
@@ -496,7 +520,7 @@ function video_filter_streamhoster($video) {
* @see video_filter_codec_info()
*/
function video_filter_teachertube($video) {
$video['source'] = 'http://www.teachertube.com/embed/player.swf';
$video['source'] = '//www.teachertube.com/embed/player.swf';
$params['flashvars'] = 'file=http://www.teachertube.com/embedFLV.php?pg=video_' . $video['codec']['matches'][1] . '&amp;menu=false&amp;frontcolor=ffffff&amp;lightcolor=FF0000&amp;logo=http://www.teachertube.com/www3/images/greylogo.swf&amp;skin=http://www.teachertube.com/embed/overlay.swf&amp;volume=80&amp;controlbar=over&amp;displayclick=link&amp;viral.link=http://www.teachertube.com/viewVideo.php?video_id=' . $video['codec']['matches'][1] . '&amp;stretching=exactfit&amp;plugins=viral-2&amp;viral.callout=none&amp;viral.onpause=false';
@@ -509,7 +533,7 @@ function video_filter_teachertube($video) {
* @see video_filter_codec_info()
*/
function video_filter_vimeo($video) {
$video['source'] = 'http://www.vimeo.com/moogaloop.swf?clip_id=' . $video['codec']['matches'][1] . '&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;autoplay=' . $video['autoplay'];
$video['source'] = '//www.vimeo.com/moogaloop.swf?clip_id=' . $video['codec']['matches'][1] . '&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;autoplay=' . $video['autoplay'];
return video_filter_flash($video);
}
@@ -520,7 +544,7 @@ function video_filter_vimeo($video) {
* @see video_filter_codec_info()
*/
function video_filter_vimeo_html5($video) {
$video['source'] = 'http://player.vimeo.com/video/' . $video['codec']['matches'][1] . ($video['autoplay'] ? '?autoplay=1' : '');
$video['source'] = '//player.vimeo.com/video/' . $video['codec']['matches'][1] . ($video['autoplay'] ? '?autoplay=1' : '');
return video_filter_iframe($video);
}
@@ -537,7 +561,7 @@ function video_filter_youtube($video) {
'fs' => 'fs=1',
);
$video['source'] = 'http://www.youtube.com/v/' . $video['codec']['matches'][1] . '?' . implode('&amp;', $attributes);
$video['source'] = '//www.youtube.com/v/' . $video['codec']['matches'][1] . '?' . implode('&amp;', $attributes);
$params['wmode'] = 'opaque';
@@ -551,11 +575,12 @@ function video_filter_youtube($video) {
*/
function video_filter_youtube_html5($video) {
$attributes = array(
'html5' => 'html5=1',
'rel' => $video['related'] ? 'rel=1' : 'rel=0',
'autoplay' => $video['autoplay'] ? 'autoplay=1' : 'autoplay=0',
'wmode' => 'wmode=opaque',
);
$video['source'] = 'http://www.youtube.com/embed/' . $video['codec']['matches'][1] . '?' . implode('&amp;', $attributes);
$video['source'] = '//www.youtube.com/embed/' . $video['codec']['matches'][1] . '?' . implode('&amp;', $attributes);
return video_filter_iframe($video);
}
@@ -571,7 +596,7 @@ function video_filter_youtube_playlist_html5($video) {
'autoplay' => $video['autoplay'] ? 'autoplay=1' : 'autoplay=0',
'wmode' => 'wmode=opaque',
);
$video['source'] = 'http://www.youtube.com/embed/videoseries?list=' . $video['codec']['matches'][1] . '&amp;' . implode('&amp;', $attributes);
$video['source'] = '//www.youtube.com/embed/videoseries?list=' . $video['codec']['matches'][1] . '&amp;' . implode('&amp;', $attributes);
return video_filter_iframe($video);
}
@@ -584,9 +609,9 @@ function video_filter_youtube_playlist_html5($video) {
* @see video_filter_codec_info()
*/
function video_filter_wistia_html5($video) {
$video_code = $video['codec']['matches'][6];
$video_code = $video['codec']['matches'][7];
$matches = $video['codec']['matches'];
$embed_type = ($matches[3] == 'projects' || $matches[5] == 'playlists') ? 'playlists' : 'iframe';
$embed_type = ($matches[4] == 'projects' || $matches[6] == 'playlists') ? 'playlists' : 'iframe';
// Get embed code via oEmbed.
$endpoint = 'http://fast.wistia.com/oembed';
@@ -599,12 +624,12 @@ function video_filter_wistia_html5($video) {
$html = $data['html'];
// See if the video source is already an iframe src.
$pattern = '@https?://fast.wistia.com/embed/(iframe|playlists)/[a-zA-Z0-9]+\?+.+@';
$pattern = '@https?://fast.wistia.(com|net)/embed/(iframe|playlists)/[a-zA-Z0-9]+\?+.+@';
$matches = array();
if (preg_match($pattern, $video['source'], $matches)) {
// Replace the oEmbed iframe src with that provided in the token, in order
// to support embed builder URLs.
$pattern = '@https?://fast.wistia.com/embed/(iframe|playlists)/[a-zA-Z0-9]+\?[^"]+@';
$pattern = '@https?://fast.wistia.(com|net)/embed/(iframe|playlists)/[a-zA-Z0-9]+\?[^"]+@';
$replacement = $matches[0];
$html = preg_replace($pattern, $replacement, $html);
}
@@ -5,9 +5,9 @@ package = Input filters
stylesheets[all][] = video_filter.css
; Information added by drupal.org packaging script on 2012-11-14
version = "7.x-3.1"
; Information added by Drupal.org packaging script on 2015-09-24
version = "7.x-3.1+17-dev"
core = "7.x"
project = "video_filter"
datestamp = "1352915891"
datestamp = "1443119944"
@@ -284,9 +284,14 @@ function theme_video_filter_flash($variables) {
$classes = video_filter_get_classes($video);
$output .= '<object class="' . implode(' ', $classes) . '" type="application/x-shockwave-flash" ';
$attributes = '';
if (!empty($video['attributes'])) {
$attributes = drupal_attributes($video['attributes']);
}
$output .= 'width="' . $video['width'] . '" height="' . $video['height'] . '" data="' . $video['source'] . '">' . "\n";
$output .= '<div class="video-filter"><object class="' . implode(' ', $classes) . '" type="application/x-shockwave-flash" ';
$output .= 'width="' . $video['width'] . '" height="' . $video['height'] . '" data="' . $video['source'] . '" ' . $attributes . '>' . "\n";
$defaults = array(
'movie' => $video['source'],
@@ -300,7 +305,7 @@ function theme_video_filter_flash($variables) {
$output .= ' <param name="' . $name . '" value="' . $value . '" />' . "\n";
}
$output .= '</object>' . "\n";
$output .= '</object></div>' . "\n";
return $output;
}
@@ -312,10 +317,13 @@ function theme_video_filter_flash($variables) {
*/
function theme_video_filter_iframe($variables) {
$video = $variables['video'];
$classes = video_filter_get_classes($video);
$attributes = '';
if (!empty($video['attributes'])) {
$attributes = drupal_attributes($video['attributes']);
}
$output = '<iframe src="' . $video['source'] . '" width="' . $video['width'] . '" height="' . $video['height'] . '" class="' . implode(' ', $classes) . '" frameborder="0"></iframe>';
$output = '<div class="video-filter"><iframe src="' . $video['source'] . '" width="' . $video['width'] . '" height="' . $video['height'] . '" class="' . implode(' ', $classes) . '" frameborder="0"' . $attributes . '></iframe></div>';
return $output;
}
@@ -378,6 +386,15 @@ function video_filter_menu() {
'theme callback' => '_video_filter_dashboard_theme',
);
$items['video_filter/instructions'] = array(
'title' => 'Videofilter instructions',
'description' => 'instructions',
'page callback' => 'video_filter_instructions_page',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
'theme callback' => '_video_filter_dashboard_theme',
);
return $items;
}
@@ -432,7 +449,19 @@ function video_filter_dashboard_page($editor) {
break;
}
print theme('video_filter_dashboard', array('form' => render(drupal_get_form('_video_filter_form'))));
$form = drupal_get_form('_video_filter_form');
print theme('video_filter_dashboard', array('form' => render($form)));
exit();
}
/**
* Creates the instructions page.
*/
function video_filter_instructions_page() {
module_invoke('admin_menu', 'suppress');
$form = drupal_get_form('_video_filter_instructions_form');
print theme('video_filter_dashboard', array('form' => render($form)));
exit();
}
@@ -492,6 +521,25 @@ function _video_filter_form() {
'#weight' => 5,
);
$form += _video_filter_instructions_form();
$form['cancel'] = array(
'#type' => 'button',
'#value' => t('Cancel'),
'#weight' => 98,
);
$form['insert'] = array(
'#type' => 'button',
'#value' => t('Insert'),
'#weight' => 99,
);
return $form;
}
function _video_filter_instructions_form() {
$form['instructions'] = array(
'#type' => 'fieldset',
'#title' => t('Instructions'),
@@ -509,21 +557,28 @@ function _video_filter_form() {
'#markup' => $text,
);
$form['cancel'] = array(
'#type' => 'button',
'#value' => t('Cancel'),
'#weight' => 98,
);
$form['insert'] = array(
'#type' => 'button',
'#value' => t('Insert'),
'#weight' => 99,
);
return $form;
}
/**
* Implements hook_ckeditor_plugin().
*/
function video_filter_ckeditor_plugin() {
$plugins = array();
$plugins['video_filter'] = array(
'name' => 'video_filter',
'desc' => t('Plugin to directly embed videos with the video filter module.'),
'path' => drupal_get_path('module', 'video_filter') . '/editors/ckeditor/',
'buttons' => array(
'video_filter' => array(
'label' => t('Video filter'),
'icon' => 'video_filter.png',
),
),
);
return $plugins;
}
function video_filter_wysiwyg_plugin($editor, $version) {
_video_filter_add_settings('wysiwyg_' . $editor);
@@ -582,7 +637,10 @@ function _video_filter_add_settings($editor) {
// Add popup url.
$settings = array(
'video_filter' => array('url' => array($editor => url('video_filter/dashboard/' . $editor))),
'video_filter' => array(
'url' => array($editor => url('video_filter/dashboard/' . $editor)),
'instructions_url' => url('video_filter/instructions'),
),
);
drupal_add_js($settings, 'setting');
}
@@ -1,28 +0,0 @@
From 6402fc7ab8f6343defbee7111dee7dd16a5082fc Mon Sep 17 00:00:00 2001
From: Bachir Soussi Chiadmi <bachir@g-u-i.net>
Date: Fri, 7 Feb 2014 10:10:15 +0100
Subject: [PATCH 1/4] re-added own boosts
---
search_api.admin.inc | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/search_api.admin.inc b/search_api.admin.inc
index f4210f4..b2269d6 100644
--- a/search_api.admin.inc
+++ b/search_api.admin.inc
@@ -1658,8 +1658,9 @@ function search_api_admin_index_fields(array $form, array &$form_state, SearchAp
// An array of option arrays for types, keyed by nesting level.
$types = array(0 => search_api_field_types());
$entity_types = entity_get_info();
- $boosts = drupal_map_assoc(array('0.1', '0.2', '0.3', '0.5', '0.8', '1.0', '2.0', '3.0', '5.0', '8.0', '13.0', '21.0'));
-
+ //$boosts = drupal_map_assoc(array('0.1', '0.2', '0.3', '0.5', '0.8', '1.0', '2.0', '3.0', '5.0', '8.0', '13.0', '21.0'));
+ $boosts = drupal_map_assoc(array('0.1', '0.2', '0.3', '0.5', '0.8', '1.0', '2.0', '3.0', '5.0', '8.0', '13.0', '21.0', '100', '1000', '1010', '1020', '1030', '1040', '1050', '1060'));
+
$fulltext_types = array(0 => array('text'));
// Add all custom data types with fallback "text" to fulltext types as well.
foreach (search_api_get_data_type_info() as $id => $type) {
--
2.3.5
@@ -1,28 +0,0 @@
From 54ee5c7b3a05850e15067d77a182cb8fe723d8e0 Mon Sep 17 00:00:00 2001
From: Bachir Soussi Chiadmi <bachir@g-u-i.net>
Date: Fri, 7 Feb 2014 10:29:08 +0100
Subject: [PATCH 2/4] taxo term translation bug : added reference to bug fix in
comment
---
search_api.module | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/search_api.module b/search_api.module
index 000cadb..55bd54a 100644
--- a/search_api.module
+++ b/search_api.module
@@ -2221,6 +2221,10 @@ function search_api_extract_fields(EntityMetadataWrapper $wrapper, array $fields
foreach ($nested as $prefix => $nested_fields) {
if (isset($wrapper->$prefix)) {
$nested_fields = search_api_extract_fields($wrapper->$prefix, $nested_fields, $value_options);
+ # http://drupal.org/node/1873910#comment-6876200
+ // $subwrapper = $wrapper->$prefix;
+ // $subwrapper->language( $wrapper->language->value() );
+ // $nested_fields = search_api_extract_fields($subwrapper, $nested_fields, $value_options);
foreach ($nested_fields as $field => $info) {
$fields["$prefix:$field"] = $info;
}
--
2.3.5
@@ -1,25 +0,0 @@
From 85251183d6ad5fadaa65154e33e1e8ac8ca7f9b0 Mon Sep 17 00:00:00 2001
From: Bachir Soussi Chiadmi <bachir@g-u-i.net>
Date: Fri, 7 Feb 2014 10:32:26 +0100
Subject: [PATCH 3/4] NODE_PUBLISED : in previous patches i commented the next
line, why ? maybe will have to do it again
---
search_api.module | 1 +
1 file changed, 1 insertion(+)
diff --git a/search_api.module b/search_api.module
index 55bd54a..17f611a 100644
--- a/search_api.module
+++ b/search_api.module
@@ -1994,6 +1994,7 @@ function _search_api_query_add_node_access($account, SearchApiQueryInterface $qu
$query->filter($filter);
}
else {
+ // /!\ in previous patches i commented the next line, why ? maybe will have to do it again
$query->condition('status', $published);
}
--
2.3.5
@@ -1,50 +0,0 @@
From c06be9a44ed0be31859a1800cf7f0ae6e8ae492a Mon Sep 17 00:00:00 2001
From: Bachir Soussi Chiadmi <bachir@g-u-i.net>
Date: Fri, 21 Feb 2014 19:49:45 +0100
Subject: [PATCH 4/4] Icons re-added icons, why they didn't be here, i don't
know ...
---
disabled.png | Bin 0 -> 384 bytes
enabled.png | Bin 0 -> 383 bytes
2 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 disabled.png
create mode 100644 enabled.png
diff --git a/disabled.png b/disabled.png
new file mode 100644
index 0000000000000000000000000000000000000000..224776502046765ef7c083ffa3229fd206b9c975
GIT binary patch
literal 384
zcmV-`0e}99P)<h;3K|Lk000e1NJLTq000aC000aK1^@s6R&`wG0000PbVXQnQ*UN;
zcVTj606}DLVr3vnZDD6+Qe|Oed2z{QJOBUzB1uF+RCwBik-tg<K@i4gmNYiGco6Uz
z1Rp_+BwY$iC2}^tfuaNqN)E0PY=wY@f3Z~1&O-&?K=37m)3r_F_{}jFE*3iQyZL7J
zn_c#nMT9h-L*7E#2LVlo2k}xSM_RBBJcfJ*9ns%$zMRR1dkA@F3^O3`V!2Gwi`45z
zLR~;$(8^>Hxo5S~v);h!F5lHi?8tY}Y=6k>{VeZk13H0TfJ{L>zr#&187PJtE1&YF
z#chq}k)8^(h8y8iq7K@{qH60+Je8qL{fT(Z%i(p9?@Xp=Ap7MLyiFg&aBu-LbgHOE
zFV;2lcsCYG0D;xhDo4mEm@`uJI=W__B!9S*DqmuQ&OZ-#wfQCMPL+ypp>5y+{X%=Y
e>QV2H00RI@_ptZRUTXUQ0000<MNUMnLSTXuN2F!|
literal 0
HcmV?d00001
diff --git a/enabled.png b/enabled.png
new file mode 100644
index 0000000000000000000000000000000000000000..95f8730e6955f1de7d244817db5ed7678bce0f72
GIT binary patch
literal 383
zcmV-_0f7FAP)<h;3K|Lk000e1NJLTq000aC000aK1^@s6R&`wG0000PbVXQnQ*UN;
zcVTj606}DLVr3vnZDD6+Qe|Oed2z{QJOBUzAxT6*RCwBA{Qv(y0|*Fj@h<{WbwJF|
zfC@eWanoC$jeQ^vBS?eLCf`Lsb}R#au=t(d<~T-yb)Ka_P8S1lpp21kmFrs|LkN$e
zvp{SB#LPhaj_LoOKSDsv0L0&c_%)Ob!<&HE3Wy_s_%BE;(?6gD5Pt+>Hz0Nf;@42I
zO+Xy_DRSR0DE}{rX8QO0Hv<r}0WtHJ*h80rv@;M-2jWm5{}<Oh%P1gw1yl_KBl}E~
z|4_Gn2V&13X{Qgu9M3V!GyzD>fw~_IKsJ1Y+QJFM+u5cX*n=d1bS#iR2V^r;9)v$K
zvP{rM4_1&(vw%1sYp{YMj=5K3DUcIIAP$!OExr-W1Y&_0|Ns6i2I7xE%z%bLVr3vT
dAhiGi1_1Nf-q(XP%8~#8002ovPDHLkV1gxRmaYH*
literal 0
HcmV?d00001
--
2.3.5
@@ -1,4 +1,80 @@
Search API 1.14 (12/26/2014):
Search API 1.x, dev (xxxx-xx-xx):
---------------------------------
- #2667872 by Les Lim: Added "0" to field boost options.
- #2654328 by drunken monkey, donquixote: Fixed use of "<" and ">" for open
facet ranges.
- #2639200 by joachim: Added sorting to "related fields" select box.
- #2638740 by joachim, drunken monkey: Added a link to the index to the
"re-indexing necessary" message.
- #2629136 by drunken monkey, deranga: Fixed wrong facet counts in edge cases
for active OR facets.
- #2569461 by kraynuk.m, drunken monkey: Fixed existing table in update #7118.
- #2631276 by tauno: Fixed the MLT handler for multi-entity indexes.
- #2576265 by drunken monkey: Fixed view trying to search on non-fulltext field.
- #2572487 by drunken monkey: Removed operator setting for date facets.
- #2611714 by rakesh.gectcr, drunken monkey: Improved compliance with
documentation standards.
- #2613054 by temkin: Fixed the "search-api-index" Drush command to allow
setting further options when indexing on all indexes.
- #2611726 by Hubbs, rakesh.gectcr: Fixed several typos.
- #2603500 by drunken monkey, krishna savithraj: Fixed Views fulltext searches
for keyword "All".
- #2529262 by kingmackenzie, stefan.r: Added an option to Views date filters to
choose the format used by date popup.
- #2583263 by drunken monkey: Fixed Views integration in combination with
Search API ET and similar modules.
- #2592231 by drunken monkey, balintcsaba: Fixed ignored item language when
viewing translated items.
- #2570879 by thePanz, drunken monkey: Added sorting of remembered search IDs.
- #2565743 by drunken monkey: Fixed creation of comment indexes with specific
bundles.
- #2563793 by drunken monkey, smitty, ReBa: Fixed Views base table definition
for "Multiple types" indexes.
- #2567775 by joseph.olstad, drunken monkey: Fixed handling of broken HTML in
the "HTML filter" processor.
- #2565005 by drunken monkey: Properly escape labels of "checkboxes"/"radios"
options
- #2524314 by drunken monkey: Fixed bundle-setting for taxonomy term indexes.
- #2550599 by ACF, drunken monkey: Fixed error on entity rebuilds.
Search API 1.16 (2015-08-30):
-----------------------------
- #2502819: Fixed example code for hook_search_api_query_alter().
- #2491175 by ptmkenny, drunken monkey: Added a data alteration for filtering
out blocked users.
- #1197538 by thePanz, k4v, drunken monkey, ayalon, nadavoid, timodwhit, becw,
Elvar: Added support for the "Global: Random" sort in Views.
- #2520934 by drunken monkey: Added an item type for indexing several types of
entities in one index.
- #2533096 by drunken monkey: Fixed uncaught exception when deleting a server.
- #2479453 by prics, drunken monkey: Added a Drush command to
list/enable/disable servers.
- #2520684 by drunken monkey: Fixed "bundles" setting on indexes with "Index
immediately".
- #2489882 by dww: Fixed Views taxonomy filter with "is (not) empty" operator
- #2447213 by drunken monkey: Fixed issues with stale field settings for MLT
contextual filter.
Search API 1.15 (2015-06-03):
-----------------------------
- #2190627 by m1n0, drunken monkey: Fixed fatal errors for views of disabled
indexes.
- #2448849 by cgoffin: Added "year range" option for date filters.
- #2414425 by Darren Oh, drunken monkey: Fixed backend form validation when
adding or editing a server.
- #2450333 by drunken monkey: Added performance improvement when indexing
entity references.
- #2450227 by StryKaizer, drunken monkey: Fixed OR facets on taxonomy terms.
- #1184610 by drunken monkey: Added option to limit indexes to specific entity
bundles.
- #1396222 by drunken monkey: Added a "First letter" aggregation type to the
"Aggregated fields" data alteration.
- #2412895 by drunken monkey: Fixed entity load for Views entity access check.
- #2414367 by Darren Oh, drunken monkey: Fixed detection of missing fields in
Views.
- #2387161 by drunken monkey: Added a hook for altering search results.
Search API 1.14 (2014-12-26):
-----------------------------
- #2382385 by illusionuk, drunken monkey: Fixed error handling when using
invalid fulltext or sort field in Views.
@@ -25,7 +101,7 @@ Search API 1.14 (12/26/2014):
- #2278737 by drunken monkey: Fixed use of multiple Views fulltext search
filters.
Search API 1.13 (07/23/2014):
Search API 1.13 (2014-07-23):
-----------------------------
- #2281535 by areynolds, nicola85: Adapted to latest changes in Views cache
plugins.
@@ -38,7 +114,7 @@ Search API 1.13 (07/23/2014):
- #2216345 by bacardi55, fabianderijk, drunken monkey: Fixed array to string
conversion in Highlighting processor.
Search API 1.12 (05/23/2014):
Search API 1.12 (2014-05-23):
-----------------------------
- #2265349 by drunken monkey: Marked _search_api_settings_equals() as
deprecated.
@@ -65,7 +141,7 @@ Search API 1.12 (05/23/2014):
- #2150779 by hefox: Fixed "Overridden" detection for index features.
- #1227702 by drunken monkey: Improved error handling.
Search API 1.11 (12/25/2013):
Search API 1.11 (2013-12-25):
-----------------------------
- #1879196 by drunken monkey: Fixed invalid old indexes causing errors.
- #2155127 by drunken monkey: Clarified the scope of the "Node access" and
@@ -81,7 +157,7 @@ Search API 1.11 (12/25/2013):
- #2146435 by timkang: Fixed Views paging with custom pager add-ons.
- #2150347 by drunken monkey: Added access callbacks for indexes and servers.
Search API 1.10 (12/09/2013):
Search API 1.10 (2013-12-09):
-----------------------------
- #2130819 by drunken monkey, Bojhan: Added UI improvements for the "View" tabs.
- #2152327 by sirtet, miro_dietiker: Fixed typo in help text for drush sapi-c.
@@ -122,7 +198,7 @@ Search API 1.10 (12/09/2013):
- #2100191 by drunken monkey, Bojhan: Added an admin description to the Search
API landing page.
Search API 1.9 (10/23/2013):
Search API 1.9 (2013-10-23):
----------------------------
- #2113277 by moonray, drunken monkey: Fixed date facet count for active item.
- #2086783 by drunken monkey: Removed Views field handlers for "virtual" fields.
@@ -151,7 +227,7 @@ Search API 1.9 (10/23/2013):
- #2075839 by leeomara, drunken monkey: Added descriptions to field lists for
'Aggregated Fields'.
Search API 1.8 (09/01/2013):
Search API 1.8 (2013-09-01):
----------------------------
- #1414048 by drunken monkey: Fixed exception in views.inc removes all Search
API tables.
@@ -185,7 +261,7 @@ Search API 1.8 (09/01/2013):
- #2040111 by arpieb: Fixed Views URL argument handler to allow multiple values.
- #1064520 by drunken monkey: Added a processor for highlighting.
Search API 1.7 (07/01/2013):
Search API 1.7 (2013-07-01):
----------------------------
- #1612708 by drunken monkey: Fixed Views caching with facet blocks.
- #2024189 by drunken monkey: Improved serialization of the query class.
@@ -212,7 +288,7 @@ Search API 1.7 (07/01/2013):
- #1285794 by drunken monkey: Fixed "All" option in Views' exposed "Items per
page" setting.
Search API 1.6 (05/29/2013):
Search API 1.6 (2013-05-29):
----------------------------
- #1649976 by Berdir, ilari.stenroth, drunken monkey: Fixed memory error during
crons run for large indexes.
@@ -230,7 +306,7 @@ Search API 1.6 (05/29/2013):
- #1760706 by jgraham, das-peter, drunken monkey: Added a flexible way for
determining whether an index contains entities.
Search API 1.5 (05/04/2013):
Search API 1.5 (2013-05-04):
----------------------------
- #1169254 by cslavoie, drunken monkey, DYdave: Added transliteration processor.
- #1959088 by drunken monkey: Fixed titles for contextual filters.
@@ -247,7 +323,7 @@ Search API 1.5 (05/04/2013):
in the Hierarchy data alteration.
- #1702604 by JvE, slucero: Added option for maximum date facet depth.
Search API 1.4 (01/09/2013):
Search API 1.4 (2013-01-09):
----------------------------
- #1827272 by drunken monkey: Fixed regression introduced by #1777710.
- #1807622 by drunken monkey: Fixed definition of the default node index.
@@ -257,7 +333,7 @@ Search API 1.4 (01/09/2013):
filters.
- #1823916 by aschiwi: Fixed batch_sise typos.
Search API 1.3 (10/10/2012):
Search API 1.3 (2012-10-10):
----------------------------
- Patch by mr.baileys: Fixed "enable" function doesn't use security tokens.
- #1318904 by becw, das-peter, orakili, drunken monkey: Added improved handling
@@ -273,7 +349,7 @@ Search API 1.3 (10/10/2012):
- #1414138 by drunken monkey: Fixed internal static index property cache.
- #1253320 by drunken monkey, fago: Fixed improper error handling.
Search API 1.2 (07/07/2012):
Search API 1.2 (2012-07-07):
----------------------------
- #1368548 by das-peter: Do not index views results by entity id.
- #1422750 by drunken monkey, sepgil: Fixed illegal modification of entity
@@ -286,7 +362,7 @@ Search API 1.2 (07/07/2012):
changed.
- #1528436 by jsacksick, drunken monkey: Fixed handling of exportable entities.
Search API 1.1 (05/23/2012):
Search API 1.1 (2012-05-23):
----------------------------
- Fixed escaping of error messages.
- #1330506 by drunken monkey: Removed the old Facets module.
@@ -297,7 +373,7 @@ Search API 1.1 (05/23/2012):
$service->configurationFormValidate() for empty forms.
- #1400882 by mh86: Fixed "Index hierarchy" for "All parents".
Search API 1.0 (12/15/2011):
Search API 1.0 (2011-12-15):
----------------------------
- #1350322 by drunken monkey: Fixed regressions introduced with cron queue
indexing.
@@ -315,7 +391,7 @@ Search API 1.0 (12/15/2011):
dependency plugin.
- #1337292 by drunken monkey: Fixed facet dependency system.
Search API 1.0, RC 1 (11/10/2011):
Search API 1.0, RC 1 (2011-11-10):
----------------------------------
API changes:
- #1260834 by drunken monkey: Added a way to define custom data types.
@@ -386,7 +462,7 @@ Others:
- #1161532 by drunken monkey: Fixed discerning between delete and revert in
hook_*_delete().
Search API 1.0, Beta 10 (06/20/2011):
Search API 1.0, Beta 10 (2011-06-20):
-------------------------------------
API changes:
- #1068342 by drunken monkey: Added a 'fields to run on' option for processors.
@@ -400,7 +476,7 @@ Others:
- #1133864 by agentrickard, awolfey, greg.1.anderson, drunken monkey: Added
Drush integration.
Search API 1.0, Beta 9 (06/06/2011):
Search API 1.0, Beta 9 (2011-06-06):
------------------------------------
API changes:
- #1089758 by becw, drunken monkey: Updated Views field handlers to utilize new
@@ -442,7 +518,7 @@ Others:
- #1120850 by drunken monkey, fangel: Fixed type of related entities in nested
lists.
Search API 1.0, Beta 8 (04/02/2011):
Search API 1.0, Beta 8 (2011-04-02):
------------------------------------
API changes:
- #1012878 by drunken monkey: Added a way to index an entity directly.
@@ -461,12 +537,12 @@ Others:
search_api_facets_by_block_status().
- #1081666 by danielnolde: Fixed PHP notices when property labels are missing.
Search API 1.0, Beta 7 (03/08/2011):
Search API 1.0, Beta 7 (2011-03-08):
------------------------------------
- #1083828 by drunken monkey: Added documentation on indexing custom data.
- #1081244 by drunken monkey: Fixed debug line still contained in DB backend.
Search API 1.0, Beta 6 (03/04/2011):
Search API 1.0, Beta 6 (2011-03-04):
------------------------------------
API changes:
- #1075810 by drunken monkey: Added API function for marking entities as dirty.
@@ -509,7 +585,7 @@ Others:
- #1024514: Error when preprocessing muli-valued fulltext fields.
- #1020372: CSS classes for facets.
Search API 1.0, Beta 5 (01/05/2011):
Search API 1.0, Beta 5 (2011-01-05):
------------------------------------
API changes:
- #917998: Enhance data alterations by making them objects.
@@ -531,7 +607,7 @@ Others:
- #985324: Add "Current search" block.
- #984174: Bug in Index::prepareProcessors() when processors have not been set.
Search API 1.0, Beta 4 (11/29/2010):
Search API 1.0, Beta 4 (2010-11-29):
------------------------------------
API changes:
- #976876: Move Solr module into its own project.
@@ -573,7 +649,7 @@ Others:
- #938982: Not all SearchApiQuery options are passed.
- #931066 by luke_b: HTTP timeout not set correctly.
Search API 1.0, Beta 3 (09/30/2010):
Search API 1.0, Beta 3 (2010-09-30):
------------------------------------
- API mostly stable.
- Five contrib modules exist:
@@ -78,13 +78,10 @@ class SearchApiFacetapiAdapter extends FacetapiAdapter {
// displayed.
$facet_search_ids = isset($options['facet_search_ids']) ? $options['facet_search_ids'] : array();
// Remember this search ID, if necessary.
$this->rememberSearchId($index_id, $search_id);
if (array_search($search_id, $facet_search_ids) === FALSE) {
$search_ids = variable_get('search_api_facets_search_ids', array());
if (empty($search_ids[$index_id][$search_id])) {
// Remember this search ID.
$search_ids[$index_id][$search_id] = $search_id;
variable_set('search_api_facets_search_ids', $search_ids);
}
if (!$default_true) {
continue; // We are only to show facets for explicitly named search ids.
}
@@ -103,6 +100,23 @@ class SearchApiFacetapiAdapter extends FacetapiAdapter {
}
}
/**
* Adds a search ID to the list of known searches for an index.
*
* @param string $index_id
* The machine name of the search index.
* @param string $search_id
* The identifier of the executed search.
*/
protected function rememberSearchId($index_id, $search_id) {
$search_ids = variable_get('search_api_facets_search_ids', array());
if (empty($search_ids[$index_id][$search_id])) {
$search_ids[$index_id][$search_id] = $search_id;
asort($search_ids[$index_id]);
variable_set('search_api_facets_search_ids', $search_ids);
}
}
/**
* Add the given facet to the query.
*/
@@ -257,6 +271,9 @@ class SearchApiFacetapiAdapter extends FacetapiAdapter {
'#options' => $granularity_options,
'#default_value' => isset($options['date_granularity']) ? $options['date_granularity'] : FACETAPI_DATE_MINUTE,
);
// Date facets don't support the "OR" operator (for now).
$form['global']['operator']['#access'] = FALSE;
}
// Add an "Exclude" option for terms.
@@ -54,6 +54,27 @@ class SearchApiFacetapiTerm extends FacetapiQueryType implements FacetapiQueryTy
}
elseif ($operator == FACETAPI_OPERATOR_OR) {
$conjunction = 'OR';
// When the operator is OR, remove parent terms from the active ones if
// children are active. If we don't do this, sending a term and its
// parent will produce the same results as just sending the parent.
if ($settings['flatten'] == '0') {
// Check the filters in reverse order, to avoid checking parents that
// will afterwards be removed anyways.
foreach (array_reverse(array_keys($active)) as $filter) {
// Skip this filter if it was already removed, or if it is the
// "missing value" filter ("!").
if (!isset($active[$filter]) || !is_numeric($filter)) {
continue;
}
$parents = taxonomy_get_parents_all($filter);
// The return value of taxonomy_get_parents_all() includes the term
// itself at index 0. Remove that to only get the term's ancestors.
unset($parents[0]);
foreach ($parents as $parent) {
unset($active[$parent->tid]);
}
}
}
}
else {
$vars = array(
@@ -153,7 +174,7 @@ class SearchApiFacetapiTerm extends FacetapiQueryType implements FacetapiQueryTy
// Always include the active facet items.
foreach ($this->adapter->getActiveItems($this->facet) as $filter) {
$build[$filter['value']]['#count'] = $results['result count'];
$build[$filter['value']]['#count'] = 0;
}
// Then, add the facets returned by the server.
@@ -9,9 +9,9 @@ files[] = plugins/facetapi/adapter.inc
files[] = plugins/facetapi/query_type_term.inc
files[] = plugins/facetapi/query_type_date.inc
; Information added by Drupal.org packaging script on 2014-12-26
version = "7.x-1.14"
; Information added by Drupal.org packaging script on 2016-02-26
version = "7.x-1.16+29-dev"
core = "7.x"
project = "search_api"
datestamp = "1419580682"
datestamp = "1456500713"
@@ -340,13 +340,13 @@ function search_api_facetapi_facet_map_callback(array $values, array $options =
$lower = isset($map[$range['lower']]) ? $map[$range['lower']] : $range['lower'];
$upper = isset($map[$range['upper']]) ? $map[$range['upper']] : $range['upper'];
if ($lower == '*' && $upper == '*') {
$map[$value] = t('any');
$map[$value] = t('any');
}
elseif ($lower == '*') {
$map[$value] = "< $upper";
$map[$value] = " $upper";
}
elseif ($upper == '*') {
$map[$value] = "> $lower";
$map[$value] = " $lower";
}
else {
$map[$value] = "$lower $upper";
@@ -24,6 +24,22 @@ When these are present, the normal keywords should be ignored and the related
items be returned as results instead. Sorting, filtering and range restriction
should all work normally.
"Random sort" feature
---------------------
This module defines the "Random sort" feature (feature key:
"search_api_random_sort") that allows to randomly sort the results returned by a
search. With a server supporting this, you can use the "Global: Random" sort to
sort the view's results randomly. Every time the query is run a different
sorting will be provided.
For developers:
A service class that wants to support this feature has to check for a
"search_api_random" field in the search query's sorts and insert a random sort
in that position. If the query is sorted in this way, then the
"search_api_random_sort" query option can contain additional options for the
random sort, as an associative array with any of the following keys:
- seed: A numeric seed value to use for the random sort.
"Facets block" display
----------------------
Most features should be clear to users of Views. However, the module also
@@ -18,6 +18,7 @@ class SearchApiViewsHandlerArgumentMoreLikeThis extends SearchApiViewsHandlerArg
$options = parent::option_definition();
unset($options['break_phrase']);
unset($options['not']);
$options['entity_type'] = array('default' => FALSE);
$options['fields'] = array('default' => array());
return $options;
}
@@ -31,6 +32,20 @@ class SearchApiViewsHandlerArgumentMoreLikeThis extends SearchApiViewsHandlerArg
unset($form['not']);
$index = search_api_index_load(substr($this->table, 17));
if ($index->datasource() instanceof SearchApiCombinedEntityDataSourceController) {
$types = array_intersect_key(search_api_entity_type_options_list(), array_flip($index->options['datasource']['types']));
$form['entity_type'] = array(
'#type' => 'select',
'#title' => t('Entity type'),
'#description' => t('Select the entity type of the argument.'),
'#options' => $types,
'#default_value' => $this->options['entity_type'],
'#required' => TRUE,
);
}
if (!empty($index->options['fields'])) {
$fields = array();
foreach ($index->getFields() as $key => $field) {
@@ -71,14 +86,22 @@ class SearchApiViewsHandlerArgumentMoreLikeThis extends SearchApiViewsHandlerArg
$this->query->abort();
return;
}
$fields = $this->options['fields'] ? $this->options['fields'] : array();
if (empty($fields)) {
foreach ($this->query->getIndex()->options['fields'] as $key => $field) {
$fields[] = $key;
}
$index_fields = array_keys($this->query->getIndex()->options['fields']);
if (empty($this->options['fields'])) {
$fields = $index_fields;
}
else {
$fields = array_intersect($this->options['fields'], $index_fields);
}
if ($this->query->getIndex()->datasource() instanceof SearchApiCombinedEntityDataSourceController) {
$id = $this->options['entity_type'] . '/' . $this->argument;
}
else {
$id = $this->argument;
}
$mlt = array(
'id' => $this->argument,
'id' => $id,
'fields' => $fields,
);
$this->query->getSearchApiQuery()->setOption('search_api_mlt', $mlt);
@@ -16,6 +16,8 @@ class SearchApiViewsHandlerFilterDate extends SearchApiViewsHandlerFilter {
public function option_definition() {
return parent::option_definition() + array(
'widget_type' => array('default' => 'default'),
'date_popup_format' => array('default' => 'm/d/Y'),
'year_range' => array('default' => '-3:+3'),
);
}
@@ -34,14 +36,49 @@ class SearchApiViewsHandlerFilterDate extends SearchApiViewsHandlerFilter {
*/
public function extra_options_form(&$form, &$form_state) {
parent::extra_options_form($form, $form_state);
if (module_exists('date_popup')) {
$widget_options = array('default' => 'Default', 'date_popup' => 'Date popup');
$widget_options = array(
'default' => 'Default',
'date_popup' => 'Date popup',
);
$form['widget_type'] = array(
'#type' => 'radios',
'#title' => t('Date selection form element'),
'#default_value' => $this->options['widget_type'],
'#options' => $widget_options,
);
$form['date_popup_format'] = array(
'#type' => 'textfield',
'#title' => t('Date format'),
'#default_value' => $this->options['date_popup_format'],
'#description' => t('A date in any format understood by <a href="@doc-link">PHP</a>. For example, "Y-m-d" or "m/d/Y".', array(
'@doc-link' => 'http://php.net/manual/en/function.date.php'
)),
'#states' => array(
'visible' => array(
':input[name="options[widget_type]"]' => array('value' => 'date_popup'),
),
),
);
}
if (module_exists('date_api')) {
$form['year_range'] = array(
'#type' => 'date_year_range',
'#default_value' => $this->options['year_range'],
);
}
}
/**
* Validate extra options.
*/
public function extra_options_validate($form, &$form_state) {
if (isset($form_state['values']['options']['year_range'])) {
if (!preg_match('/^(?:\-[0-9]{1,4}|[0-9]{4}):(?:[\+|\-][0-9]{1,4}|[0-9]{4})$/', $form_state['values']['options']['year_range'])) {
form_error($form['year_range'], t('Date year range must be in the format -9:+9, 2005:2010, -9:2010, or 2005:+9'));
}
}
}
@@ -55,7 +92,8 @@ class SearchApiViewsHandlerFilterDate extends SearchApiViewsHandlerFilter {
// according to what date_popup expects.
if ($this->options['widget_type'] == 'date_popup' && module_exists('date_popup')) {
$form['value']['#type'] = 'date_popup';
$form['value']['#date_format'] = 'm/d/Y';
$form['value']['#date_format'] = $this->options['date_popup_format'];
$form['value']['#date_year_range'] = $this->options['year_range'];
unset($form['value']['#description']);
}
elseif (empty($form_state['exposed'])) {
@@ -144,7 +144,8 @@ class SearchApiViewsHandlerFilterFulltext extends SearchApiViewsHandlerFilterTex
return;
}
$fields = $this->options['fields'];
$fields = $fields ? $fields : array_keys($this->getFulltextFields());
$available_fields = array_keys($this->getFulltextFields());
$fields = $fields ? array_intersect($fields, $available_fields) : $available_fields;
// If something already specifically set different fields, we silently fall
// back to mere filtering.
@@ -178,12 +178,25 @@ class SearchApiViewsHandlerFilterTaxonomyTerm extends SearchApiViewsHandlerFilte
return TRUE;
}
// We need to know the operator, which is normally set in
// views_handler_filter::accept_exposed_input(), before we actually call
// the parent version of ourselves.
if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id']) && isset($input[$this->options['expose']['operator_id']])) {
$this->operator = $input[$this->options['expose']['operator_id']];
}
// If view is an attachment and is inheriting exposed filters, then assume
// exposed input has already been validated.
if (!empty($this->view->is_attachment) && $this->view->display_handler->uses_exposed()) {
$this->validated_exposed_input = (array) $this->view->exposed_raw_input[$this->options['expose']['identifier']];
}
// If we're checking for EMPTY or NOT, we don't need any input, and we can
// say that our input conditions are met by just having the right operator.
if ($this->operator == 'empty' || $this->operator == 'not empty') {
return TRUE;
}
// If it's non-required and there's no value don't bother filtering.
if (!$this->options['expose']['required'] && empty($this->validated_exposed_input)) {
return FALSE;
@@ -17,4 +17,52 @@ class SearchApiViewsHandlerFilterText extends SearchApiViewsHandlerFilter {
return array('=' => t('contains'), '<>' => t("doesn't contain"));
}
/**
* Determines whether input from the exposed filters affects this filter.
*
* Overridden to not treat "All" differently.
*
* @param array $input
* The user input from the exposed filters.
*
* @return bool
* TRUE if the input should change the behavior of this filter.
*/
public function accept_exposed_input($input) {
if (empty($this->options['exposed'])) {
return TRUE;
}
if (!empty($this->options['expose']['use_operator']) && !empty($this->options['expose']['operator_id']) && isset($input[$this->options['expose']['operator_id']])) {
$this->operator = $input[$this->options['expose']['operator_id']];
}
if (!empty($this->options['expose']['identifier'])) {
$value = $input[$this->options['expose']['identifier']];
// Various ways to check for the absence of non-required input.
if (empty($this->options['expose']['required'])) {
if (($this->operator == 'empty' || $this->operator == 'not empty') && $value === '') {
$value = ' ';
}
if (!empty($this->always_multiple) && $value === '') {
return FALSE;
}
}
if (isset($value)) {
$this->value = $value;
if (empty($this->always_multiple) && empty($this->options['expose']['multiple'])) {
$this->value = array($value);
}
}
else {
return FALSE;
}
}
return TRUE;
}
}
@@ -122,19 +122,63 @@ class SearchApiViewsQuery extends views_plugin_query {
}
/**
* Add a sort to the query.
* Adds a sort to the query.
*
* @param $selector
* @param string $selector
* The field to sort on. All indexed fields of the index are valid values.
* In addition, the special fields 'search_api_relevance' (sort by
* relevance) and 'search_api_id' (sort by item id) may be used.
* @param $order
* In addition, these special fields may be used:
* - search_api_relevance: sort by relevance;
* - search_api_id: sort by item id;
* - search_api_random: random sort (available only if the server supports
* the "search_api_random_sort" feature).
* @param string $order
* The order to sort items in - either 'ASC' or 'DESC'. Defaults to 'ASC'.
*/
public function add_selector_orderby($selector, $order = 'ASC') {
$this->query->sort($selector, $order);
}
/**
* Provides a sorting method as present in the Views default query plugin.
*
* This is provided so that the "Global: Random" sort included in Views will
* work properly with Search API Views. Random sorting is only supported if
* the active search server supports the "search_api_random_sort" feature,
* though, otherwise the call will be ignored.
*
* This method can only be used to sort randomly, as would be done with the
* default query plugin. All other calls are ignored.
*
* @param string|null $table
* Only "rand" is recognized here, all other calls are ignored.
* @param string|null $field
* Is ignored and only present for compatibility reasons.
* @param string $order
* Either "ASC" or "DESC".
* @param string|null $alias
* Is ignored and only present for compatibility reasons.
* @param array $params
* The following optional parameters are recognized:
* - seed: a predefined seed for the random generator.
*
* @see views_plugin_query_default::add_orderby()
*/
public function add_orderby($table, $field = NULL, $order = 'ASC', $alias = '', $params = array()) {
$server = $this->getIndex()->server();
if ($table == 'rand') {
if ($server->supportsFeature('search_api_random_sort')) {
$this->add_selector_orderby('search_api_random', $order);
if ($params) {
$this->setOption('search_api_random_sort', $params);
}
}
else {
$variables['%server'] = $server->label();
watchdog('search_api_views', 'Tried to sort results randomly on server %server which does not support random sorting.', $variables, WATCHDOG_WARNING);
}
}
}
/**
* Defines the options used by this query plugin.
*
@@ -203,6 +247,10 @@ class SearchApiViewsQuery extends views_plugin_query {
* Builds the necessary info to execute the query.
*/
public function build(&$view) {
if (!empty($this->errors)) {
return;
}
$this->view = $view;
// Setup the nested filter structure for this query.
@@ -375,8 +423,8 @@ class SearchApiViewsQuery extends views_plugin_query {
// loading any items.
foreach ($results as $id => $result) {
if (!empty($this->options['entity_access']) && ($entity_type = $this->index->getEntityType())) {
$entity = entity_load($entity_type, array($id));
if (!entity_access('view', $entity_type, $entity[$id])) {
$entity = $this->index->loadItems(array($id));
if (!$entity || !entity_access('view', $entity_type, reset($entity))) {
continue;
}
}
@@ -400,7 +448,7 @@ class SearchApiViewsQuery extends views_plugin_query {
}
// Check whether we need to extract any properties from the result item.
$missing_fields = array_diff_key($this->fields, $row);
$missing_fields = array_diff_key($this->fields, $row['_entity_properties']);
if ($missing_fields) {
$missing[$id] = $missing_fields;
if (is_object($row['entity'])) {
@@ -418,14 +466,14 @@ class SearchApiViewsQuery extends views_plugin_query {
// Load items of those rows which haven't got all field values, yet.
if (!empty($ids)) {
$items += $this->index->loadItems($ids);
// $items now includes loaded items, and those already passed in the
// search results.
foreach ($items as $id => $item) {
// Extract item properties.
$wrapper = $this->index->entityWrapper($item, FALSE);
$rows[$id]->_entity_properties += $this->extractFields($wrapper, $missing[$id]);
$rows[$id]->entity = $item;
}
}
// $items now includes all loaded items from which fields still need to be
// extracted.
foreach ($items as $id => $item) {
// Extract item properties.
$wrapper = $this->index->entityWrapper($item, FALSE);
$rows[$id]->_entity_properties += $this->extractFields($wrapper, $missing[$id]);
$rows[$id]->entity = $item;
}
// Finally, add all rows to the Views result set.
@@ -490,31 +538,31 @@ class SearchApiViewsQuery extends views_plugin_query {
* query backend.
*/
public function get_result_wrappers($results, $relationship = NULL, $field = NULL) {
$entity_type = $this->index->getEntityType();
$type = $this->index->getEntityType() ? $this->index->getEntityType() : $this->index->item_type;
$wrappers = array();
$load_entities = array();
$load_items = array();
foreach ($results as $row_index => $row) {
if ($entity_type && isset($row->entity)) {
if (isset($row->entity)) {
// If this entity isn't load, register it for pre-loading.
if (!is_object($row->entity)) {
$load_entities[$row->entity] = $row_index;
$load_items[$row->entity] = $row_index;
}
else {
$wrappers[$row_index] = $this->index->entityWrapper($row->entity);
}
$wrappers[$row_index] = $this->index->entityWrapper($row->entity);
}
}
// If the results are entities, we pre-load them to make use of a multiple
// load. (Otherwise, each result would be loaded individually.)
if (!empty($load_entities)) {
$entities = entity_load($entity_type, array_keys($load_entities));
foreach ($entities as $entity_id => $entity) {
$wrappers[$load_entities[$entity_id]] = $this->index->entityWrapper($entity);
if (!empty($load_items)) {
$items = $this->index->loadItems(array_keys($load_items));
foreach ($items as $id => $item) {
$wrappers[$load_items[$id]] = $this->index->entityWrapper($item);
}
}
// Apply the relationship, if necessary.
$type = $entity_type ? $entity_type : $this->index->item_type;
$selector_suffix = '';
if ($field && ($pos = strrpos($field, ':'))) {
$selector_suffix = substr($field, 0, $pos);
@@ -27,9 +27,9 @@ files[] = includes/handler_sort.inc
files[] = includes/plugin_cache.inc
files[] = includes/query.inc
; Information added by Drupal.org packaging script on 2014-12-26
version = "7.x-1.14"
; Information added by Drupal.org packaging script on 2016-02-26
version = "7.x-1.16+29-dev"
core = "7.x"
project = "search_api"
datestamp = "1419580682"
datestamp = "1456500713"
@@ -11,7 +11,6 @@
function search_api_views_views_data() {
try {
$data = array();
$entity_types = entity_get_info();
foreach (search_api_index_load_multiple(FALSE) as $index) {
// Fill in base data.
$key = 'search_api_index_' . $index->machine_name;
@@ -25,12 +24,8 @@ function search_api_views_views_data() {
'help' => t('Use the %name search index for filtering and retrieving data.', array('%name' => $index->name)),
'query class' => 'search_api_views_query',
);
if (isset($entity_types[$index->getEntityType()])) {
$table['table'] += array(
'entity type' => $index->getEntityType(),
'skip entity load' => TRUE,
);
}
$table['table']['entity type'] = $index->getEntityType();
$table['table']['skip entity load'] = TRUE;
try {
$wrapper = $index->entityWrapper(NULL, FALSE);
@@ -10,6 +10,16 @@
*/
class SearchApiAlterAddAggregation extends SearchApiAbstractAlterCallback {
/**
* The type of aggregation currently performed.
*
* Used to temporarily store the current aggregation type for use of
* SearchApiAlterAddAggregation::reduce() with array_reduce().
*
* @var string
*/
protected $reductionType;
public function configurationForm() {
$form['#attached']['css'][] = drupal_get_path('module', 'search_api') . '/search_api.admin.css';
@@ -193,6 +203,12 @@ class SearchApiAlterAddAggregation extends SearchApiAbstractAlterCallback {
return isset($a) ? min($a, $b) : $b;
case 'first':
return isset($a) ? $a : $b;
case 'first_char':
$b = "$b";
if (isset($a) || $b === '') {
return $a;
}
return drupal_substr($b, 0, 1);
case 'list':
if (!isset($a)) {
$a = array();
@@ -200,6 +216,7 @@ class SearchApiAlterAddAggregation extends SearchApiAbstractAlterCallback {
$a[] = $b;
return $a;
}
return NULL;
}
/**
@@ -252,10 +269,13 @@ class SearchApiAlterAddAggregation extends SearchApiAbstractAlterCallback {
/**
* Helper method for getting all available aggregation types.
*
* @param $info (optional)
* One of "name", "type" or "description", to indicate what values should be
* returned for the types. Defaults to "name".
* @param string $info
* (optional) One of "name", "type" or "description", to indicate what
* information should be returned for the types.
*
* @return string[]
* An associative array of aggregation type identifiers mapped to their
* names, data types or descriptions, as requested.
*/
protected function getTypes($info = 'name') {
switch ($info) {
@@ -267,6 +287,7 @@ class SearchApiAlterAddAggregation extends SearchApiAbstractAlterCallback {
'max' => t('Maximum'),
'min' => t('Minimum'),
'first' => t('First'),
'first_char' => t('First letter'),
'list' => t('List'),
);
case 'type':
@@ -277,6 +298,7 @@ class SearchApiAlterAddAggregation extends SearchApiAbstractAlterCallback {
'max' => 'integer',
'min' => 'integer',
'first' => 'string',
'first_char' => 'string',
'list' => 'list<string>',
);
case 'description':
@@ -287,9 +309,11 @@ class SearchApiAlterAddAggregation extends SearchApiAbstractAlterCallback {
'max' => t('The Maximum aggregation computes the numerically largest contained field value.'),
'min' => t('The Minimum aggregation computes the numerically smallest contained field value.'),
'first' => t('The First aggregation will simply keep the first encountered field value. This is helpful foremost when you know that a list field will only have a single value.'),
'first_char' => t('The "First letter" aggregation uses just the first letter of the first encountered field value as the aggregated value. This can, for example, be used to build a Glossary view.'),
'list' => t('The List aggregation collects all field values into a multi-valued field containing all values.'),
);
}
return array();
}
/**
@@ -74,7 +74,7 @@ class SearchApiAlterAddViewedEntity extends SearchApiAbstractAlterCallback {
// we use try/catch. This will at least prevent some errors, even though
// it's no protection against fatal errors and the like.
try {
$render = entity_view($type, array(entity_id($type, $item) => $item), $mode);
$render = entity_view($type, array(entity_id($type, $item) => $item), $mode, $item->search_api_language);
$text = render($render);
if (!$text) {
$item->search_api_viewed = NULL;
@@ -14,6 +14,15 @@ class SearchApiAlterBundleFilter extends SearchApiAbstractAlterCallback {
* {@inheritdoc}
*/
public function supportsIndex(SearchApiIndex $index) {
if ($this->isMultiEntityIndex($index)) {
$info = entity_get_info();
foreach ($index->options['datasource']['types'] as $type) {
if (isset($info[$type]) && self::hasBundles($info[$type])) {
return TRUE;
}
}
return FALSE;
}
return $index->getEntityType() && ($info = entity_get_info($index->getEntityType())) && self::hasBundles($info);
}
@@ -21,15 +30,24 @@ class SearchApiAlterBundleFilter extends SearchApiAbstractAlterCallback {
* {@inheritdoc}
*/
public function alterItems(array &$items) {
$info = entity_get_info($this->index->getEntityType());
if (self::hasBundles($info) && isset($this->options['bundles'])) {
$bundles = array_flip($this->options['bundles']);
$default = (bool) $this->options['default'];
if (!$this->supportsIndex($this->index) || !isset($this->options['bundles'])) {
return;
}
if ($this->isMultiEntityIndex()) {
$bundle_prop = 'item_bundle';
}
else {
$info = entity_get_info($this->index->getEntityType());
$bundle_prop = $info['entity keys']['bundle'];
foreach ($items as $id => $item) {
if (isset($bundles[$item->$bundle_prop]) == $default) {
unset($items[$id]);
}
}
$bundles = array_flip($this->options['bundles']);
$default = (bool) $this->options['default'];
foreach ($items as $id => $item) {
if (isset($bundles[$item->$bundle_prop]) == $default) {
unset($items[$id]);
}
}
}
@@ -38,31 +56,53 @@ class SearchApiAlterBundleFilter extends SearchApiAbstractAlterCallback {
* {@inheritdoc}
*/
public function configurationForm() {
$info = entity_get_info($this->index->getEntityType());
if (self::hasBundles($info)) {
if ($this->supportsIndex($this->index)) {
$options = array();
foreach ($info['bundles'] as $bundle => $bundle_info) {
$options[$bundle] = isset($bundle_info['label']) ? $bundle_info['label'] : $bundle;
if ($this->isMultiEntityIndex()) {
$info = entity_get_info();
$unsupported_types = array();
foreach ($this->index->options['datasource']['types'] as $type) {
if (isset($info[$type]) && self::hasBundles($info[$type])) {
foreach ($info[$type]['bundles'] as $bundle => $bundle_info) {
$options["$type:$bundle"] = $info[$type]['label'] . ' » ' . $bundle_info['label'];
}
}
else {
$unsupported_types[] = isset($info[$type]['label']) ? $info[$type]['label'] : $type;
}
}
if ($unsupported_types) {
$form['unsupported_types']['#markup'] = '<p>' . t('The following entity types do not contain any bundles: @types. All items of those types will therefore be included in the index.', array('@types' => implode(', ', $unsupported_types))) . '</p>';
}
}
$form = array(
'default' => array(
'#type' => 'radios',
'#title' => t('Which items should be indexed?'),
'#default_value' => isset($this->options['default']) ? $this->options['default'] : 1,
'#options' => array(
1 => t('All but those from one of the selected bundles'),
0 => t('Only those from the selected bundles'),
),
),
'bundles' => array(
'#type' => 'select',
'#title' => t('Bundles'),
'#default_value' => isset($this->options['bundles']) ? $this->options['bundles'] : array(),
'#options' => $options,
'#size' => min(4, count($options)),
'#multiple' => TRUE,
else {
$info = entity_get_info($this->index->getEntityType());
foreach ($info['bundles'] as $bundle => $bundle_info) {
$options[$bundle] = isset($bundle_info['label']) ? $bundle_info['label'] : $bundle;
}
}
if (!empty($this->index->options['datasource']['bundles'])) {
$form['message']['#markup'] = '<p>' . t("<strong>Note:</strong> This index is already restricted to certain bundles. If you use this data alteration, those will be reduced further. However, the index setting is better supported in the user interface and should therefore be prefered. For example, using this data alteration will not reduce the displayed total number of items to index (even though some of them will not be indexed). Consider creating a new index with appropriate bundle settings instead.") . '</p>';
$included_bundles = array_flip($this->index->options['datasource']['bundles']);
$options = array_intersect_key($options, $included_bundles);
}
$form['default'] = array(
'#type' => 'radios',
'#title' => t('Which items should be indexed?'),
'#default_value' => isset($this->options['default']) ? $this->options['default'] : 1,
'#options' => array(
1 => t('All but those from one of the selected bundles'),
0 => t('Only those from the selected bundles'),
),
);
$form['bundles'] = array(
'#type' => 'select',
'#title' => t('Bundles'),
'#default_value' => isset($this->options['bundles']) ? $this->options['bundles'] : array(),
'#options' => $options,
'#size' => min(4, count($options)),
'#multiple' => TRUE,
);
}
else {
$form = array(
@@ -81,10 +121,25 @@ class SearchApiAlterBundleFilter extends SearchApiAbstractAlterCallback {
* The entity type's entity_get_info() array.
*
* @return bool
* TRUE if the entity type has bundles, FASLE otherwise.
* TRUE if the entity type has bundles, FALSE otherwise.
*/
protected static function hasBundles(array $entity_info) {
return !empty($entity_info['entity keys']['bundle']) && !empty($entity_info['bundles']);
}
/**
* Determines whether the given index contains multiple types of entities.
*
* @param SearchApiIndex|null $index
* (optional) The index to examine. Defaults to the index set for this
* plugin.
*
* @return bool
* TRUE if the index is a multi-entity index, FALSE otherwise.
*/
protected function isMultiEntityIndex(SearchApiIndex $index = NULL) {
$index = $index ? $index : $this->index;
return $index->datasource() instanceof SearchApiCombinedEntityDataSourceController;
}
}
@@ -70,7 +70,7 @@ class SearchApiAlterLanguageControl extends SearchApiAbstractAlterCallback {
foreach ($list as $lang) {
$name = t($lang->name);
$native = $lang->native;
$languages[$lang->language] = ($name == $native) ? $name : "$name ($native)";
$languages[$lang->language] = check_plain(($name == $native) ? $name : "$name ($native)");
if (!$lang->enabled) {
$languages[$lang->language] .= ' [' . t('disabled') . ']';
}
@@ -0,0 +1,31 @@
<?php
/**
* @file
* Contains the SearchApiAlterUserStatus class.
*/
/**
* Filters out blocked user accounts.
*/
class SearchApiAlterUserStatus extends SearchApiAbstractAlterCallback {
/**
* {@inheritdoc}
*/
public function supportsIndex(SearchApiIndex $index) {
return $index->getEntityType() == 'user';
}
/**
* {@inheritdoc}
*/
public function alterItems(array &$items) {
foreach ($items as $id => $account) {
if (empty($account->status)) {
unset($items[$id]);
}
}
}
}
@@ -22,7 +22,7 @@
interface SearchApiDataSourceControllerInterface {
/**
* Constructs a new data source controller.
* Constructs an SearchApiDataSourceControllerInterface object.
*
* @param string $type
* The item type for which this controller is created.
@@ -47,7 +47,7 @@ interface SearchApiDataSourceControllerInterface {
* Loads items of the type of this data source controller.
*
* @param array $ids
* The IDs of the items to laod.
* The IDs of the items to load.
*
* @return array
* The loaded items, keyed by ID.
@@ -158,6 +158,10 @@ interface SearchApiDataSourceControllerInterface {
* @param SearchApiIndex[] $indexes
* The indexes for which items should be tracked.
*
* @return SearchApiIndex[]|null
* All indexes for which any items were added; or NULL if items were added
* for all of them.
*
* @throws SearchApiDataSourceException
* If any error state was encountered.
*/
@@ -179,6 +183,10 @@ interface SearchApiDataSourceControllerInterface {
* The concept of queued items will be removed in the Drupal 8 version of
* this module.
*
* @return SearchApiIndex[]|null
* All indexes for which any items were updated; or NULL if items were
* updated for all of them.
*
* @throws SearchApiDataSourceException
* If any error state was encountered.
*/
@@ -227,6 +235,10 @@ interface SearchApiDataSourceControllerInterface {
* @param SearchApiIndex[] $indexes
* The indexes for which the deletions should be tracked.
*
* @return SearchApiIndex[]|null
* All indexes for which any items were deleted; or NULL if items were
* deleted for all of them.
*
* @throws SearchApiDataSourceException
* If any error state was encountered.
*/
@@ -281,6 +293,69 @@ interface SearchApiDataSourceControllerInterface {
*/
public function getEntityType();
/**
* Form constructor for configuring the datasource for a given index.
*
* @param array $form
* The form returned by configurationForm().
* @param array $form_state
* The form state. $form_state['index'] will contain the edited index. If
* this key is empty, then a new index is being created. In case of an edit,
* $form_state['index']->options['datasource'] contains the previous
* settings for the datasource.
*
* @return array|false
* A form array for configuring this callback, or FALSE if no configuration
* is possible.
*/
public function configurationForm(array $form, array &$form_state);
/**
* Validation callback for the form returned by configurationForm().
*
* This method will only be called if that form was non-empty.
*
* @param array $form
* The form returned by configurationForm().
* @param array $values
* The part of the $form_state['values'] array corresponding to this form.
* @param array $form_state
* The complete form state.
*/
public function configurationFormValidate(array $form, array &$values, array &$form_state);
/**
* Submit callback for the form returned by configurationForm().
*
* This method will only be called if that form was non-empty.
*
* Any necessary changes to the submitted values should be made, afterwards
* they will automatically be stored as the index's "datasource" options. The
* method can also be used by the datasource controller to react to the
* possible change in its settings.
*
* @param array $form
* The form returned by configurationForm().
* @param array $values
* The part of the $form_state['values'] array corresponding to this form.
* @param array $form_state
* The complete form state.
*/
public function configurationFormSubmit(array $form, array &$values, array &$form_state);
/**
* Returns a summary of an index's current datasource configuration.
*
* @param SearchApiIndex $index
* The index whose datasource configuration should be summarized.
*
* @return string|null
* A translated string describing the index's current datasource
* configuration. Or NULL, if there is no configuration (or no description
* is available).
*/
public function getConfigurationSummary(SearchApiIndex $index);
}
/**
@@ -517,10 +592,14 @@ abstract class SearchApiAbstractDataSourceController implements SearchApiDataSou
* {@inheritdoc}
*/
public function trackItemInsert(array $item_ids, array $indexes) {
if (!$this->table) {
if (!$this->table || $item_ids === array()) {
return;
}
foreach ($indexes as $index) {
$this->checkIndex($index);
}
// Since large amounts of items can overstrain the database, only add items
// in chunks.
foreach (array_chunk($item_ids, 1000) as $chunk) {
@@ -528,7 +607,6 @@ abstract class SearchApiAbstractDataSourceController implements SearchApiDataSou
->fields(array($this->itemIdColumn, $this->indexIdColumn, $this->changedColumn));
foreach ($chunk as $item_id) {
foreach ($indexes as $index) {
$this->checkIndex($index);
$insert->values(array(
$this->itemIdColumn => $item_id,
$this->indexIdColumn => $index->id,
@@ -544,24 +622,29 @@ abstract class SearchApiAbstractDataSourceController implements SearchApiDataSou
* {@inheritdoc}
*/
public function trackItemChange($item_ids, array $indexes, $dequeue = FALSE) {
if (!$this->table) {
return;
if (!$this->table || $item_ids === array()) {
return NULL;
}
$index_ids = array();
$ret = array();
foreach ($indexes as $index) {
$this->checkIndex($index);
$index_ids[] = $index->id;
$update = db_update($this->table)
->fields(array(
$this->changedColumn => REQUEST_TIME,
))
->condition($this->indexIdColumn, $index->id)
->condition($this->changedColumn, 0, $dequeue ? '<=' : '=');
if ($item_ids !== FALSE) {
$update->condition($this->itemIdColumn, $item_ids, 'IN');
}
if ($update->execute()) {
$ret[] = $index;
}
}
$update = db_update($this->table)
->fields(array(
$this->changedColumn => REQUEST_TIME,
))
->condition($this->indexIdColumn, $index_ids, 'IN')
->condition($this->changedColumn, 0, $dequeue ? '<=' : '=');
if ($item_ids !== FALSE) {
$update->condition($this->itemIdColumn, $item_ids, 'IN');
}
$update->execute();
return $ret;
}
/**
@@ -569,7 +652,7 @@ abstract class SearchApiAbstractDataSourceController implements SearchApiDataSou
*/
public function trackItemQueued($item_ids, SearchApiIndex $index) {
$this->checkIndex($index);
if (!$this->table) {
if (!$this->table || $item_ids === array()) {
return;
}
$update = db_update($this->table)
@@ -587,7 +670,7 @@ abstract class SearchApiAbstractDataSourceController implements SearchApiDataSou
* {@inheritdoc}
*/
public function trackItemIndexed(array $item_ids, SearchApiIndex $index) {
if (!$this->table) {
if (!$this->table || $item_ids === array()) {
return;
}
$this->checkIndex($index);
@@ -604,18 +687,23 @@ abstract class SearchApiAbstractDataSourceController implements SearchApiDataSou
* {@inheritdoc}
*/
public function trackItemDelete(array $item_ids, array $indexes) {
if (!$this->table) {
return;
if (!$this->table || $item_ids === array()) {
return NULL;
}
$index_ids = array();
$ret = array();
foreach ($indexes as $index) {
$this->checkIndex($index);
$index_ids[] = $index->id;
$delete = db_delete($this->table)
->condition($this->indexIdColumn, $index->id)
->condition($this->itemIdColumn, $item_ids, 'IN');
if ($delete->execute()) {
$ret[] = $index;
}
}
db_delete($this->table)
->condition($this->itemIdColumn, $item_ids, 'IN')
->condition($this->indexIdColumn, $index_ids, 'IN')
->execute();
return $ret;
}
/**
@@ -659,6 +747,32 @@ abstract class SearchApiAbstractDataSourceController implements SearchApiDataSou
return array('indexed' => $indexed, 'total' => $total);
}
/**
* {@inheritdoc}
*/
public function configurationForm(array $form, array &$form_state) {
return FALSE;
}
/**
* {@inheritdoc}
*/
public function configurationFormValidate(array $form, array &$values, array &$form_state) {
}
/**
* {@inheritdoc}
*/
public function configurationFormSubmit(array $form, array &$values, array &$form_state) {
}
/**
* {@inheritdoc}
*/
public function getConfigurationSummary(SearchApiIndex $index) {
return NULL;
}
/**
* Checks whether the given index is valid for this datasource controller.
*
@@ -10,28 +10,69 @@
*/
class SearchApiEntityDataSourceController extends SearchApiAbstractDataSourceController {
/**
* Entity type info for this type.
*
* @var array
*/
protected $entityInfo;
/**
* The ID key of this entity type, if any.
*
* @var string|null
*/
protected $idKey;
/**
* The bundle key of this entity type, if any.
*
* @var string|null
*/
protected $bundleKey;
/**
* Cached return values for getBundles(), keyed by index machine name.
*
* @var array
*/
protected $bundles = array();
/**
* {@inheritdoc}
*/
public function __construct($type) {
parent::__construct($type);
$this->entityInfo = entity_get_info($this->entityType);
if (!empty($this->entityInfo['entity keys']['id'])) {
$this->idKey = $this->entityInfo['entity keys']['id'];
}
if (!empty($this->entityInfo['entity keys']['bundle'])) {
$this->bundleKey = $this->entityInfo['entity keys']['bundle'];
}
}
/**
* {@inheritdoc}
*/
public function getIdFieldInfo() {
$info = entity_get_info($this->entityType);
$properties = entity_get_property_info($this->entityType);
if (empty($info['entity keys']['id'])) {
throw new SearchApiDataSourceException(t("Entity type @type doesn't specify an ID key.", array('@type' => $info['label'])));
if (!$this->idKey) {
throw new SearchApiDataSourceException(t("Entity type @type doesn't specify an ID key.", array('@type' => $this->entityInfo['label'])));
}
$field = $info['entity keys']['id'];
if (empty($properties['properties'][$field]['type'])) {
throw new SearchApiDataSourceException(t("Entity type @type doesn't specify a type for the @prop property.", array('@type' => $info['label'], '@prop' => $field)));
if (empty($properties['properties'][$this->idKey]['type'])) {
throw new SearchApiDataSourceException(t("Entity type @type doesn't specify a type for the @prop property.", array('@type' => $this->entityInfo['label'], '@prop' => $this->idKey)));
}
$type = $properties['properties'][$field]['type'];
$type = $properties['properties'][$this->idKey]['type'];
if (search_api_is_list_type($type)) {
throw new SearchApiDataSourceException(t("Entity type @type uses list field @prop as its ID.", array('@type' => $info['label'], '@prop' => $field)));
throw new SearchApiDataSourceException(t("Entity type @type uses list field @prop as its ID.", array('@type' => $this->entityInfo['label'], '@prop' => $this->idKey)));
}
if ($type == 'token') {
$type = 'string';
}
return array(
'key' => $field,
'key' => $this->idKey,
'type' => $type,
);
}
@@ -103,24 +144,53 @@ class SearchApiEntityDataSourceController extends SearchApiAbstractDataSourceCon
// all items again without any key conflicts.
$this->stopTracking($indexes);
$entity_info = entity_get_info($this->entityType);
if (!empty($entity_info['base table'])) {
if (!empty($this->entityInfo['base table']) && $this->idKey) {
// Use a subselect, which will probably be much faster than entity_load().
// Assumes that all entities use the "base table" property and the
// "entity keys[id]" in the same way as the default controller.
$id_field = $entity_info['entity keys']['id'];
$table = $entity_info['base table'];
$table = $this->entityInfo['base table'];
// We could also use a single insert (with a JOIN in the nested query),
// We could also use a single insert (with a UNION in the nested query),
// but this method will be mostly called with a single index, anyways.
foreach ($indexes as $index) {
// Select all entity ids.
$query = db_select($table, 't');
$query->addField('t', $id_field, 'item_id');
$query->addField('t', $this->idKey, 'item_id');
$query->addExpression(':index_id', 'index_id', array(':index_id' => $index->id));
$query->addExpression('1', 'changed');
if ($bundles = $this->getIndexBundles($index)) {
$bundle_column = $this->bundleKey;
if (!db_field_exists($table, $bundle_column)) {
if ($this->entityType == 'taxonomy_term') {
$bundle_column = 'vid';
$bundles = db_query('SELECT vid FROM {taxonomy_vocabulary} WHERE machine_name IN (:bundles)', array(':bundles' => $bundles))->fetchCol();
}
elseif ($this->entityType == 'comment') {
// Comments are significantly more complicated, since they don't
// store their bundle explicitly in their database table. Instead,
// we need to get all the nodes from the enabled types and filter
// by those.
$bundle_column = 'nid';
$node_types = array();
foreach ($bundles as $bundle) {
if (substr($bundle, 0, 13) === 'comment_node_') {
$node_types[] = substr($bundle, 13);
}
}
if ($node_types) {
$bundles = db_query('SELECT nid FROM {node} WHERE type IN (:bundles)', array(':bundles' => $node_types))->fetchCol();
}
else {
return;
}
}
else {
$this->startTrackingFallback(array($index->machine_name => $index));
}
}
$query->condition($bundle_column, $bundles);
}
// INSERT ... SELECT ...
db_insert($this->table)
@@ -129,16 +199,165 @@ class SearchApiEntityDataSourceController extends SearchApiAbstractDataSourceCon
}
}
else {
// In the absence of a 'base table', use the slow entity_load().
parent::startTracking($indexes);
$this->startTrackingFallback($indexes);
}
}
/**
* Initializes tracking of the index status of items for the given indexes.
*
* Fallback for when the items cannot directly be loaded into
* {search_api_item} via "INSERT INTO … SELECT …".
*
* @param SearchApiIndex[] $indexes
* The indexes for which item tracking should be initialized.
*
* @throws SearchApiDataSourceException
* Thrown if any error state was encountered.
*
* @see SearchApiEntityDataSourceController::startTracking()
*/
protected function startTrackingFallback(array $indexes) {
// In the absence of a 'base table', use the slower way of retrieving the
// items and inserting them "manually". For each index we get the item IDs
// (since selected bundles might differ) and insert all of them as new.
foreach ($indexes as $index) {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', $this->entityType);
if ($bundles = $this->getIndexBundles($index)) {
$query->entityCondition('bundle', $bundles);
}
$result = $query->execute();
$ids = !empty($result[$this->entityType]) ? array_keys($result[$this->entityType]) : array();
if ($ids) {
$this->trackItemInsert($ids, array($index));
}
}
}
/**
* {@inheritdoc}
*/
protected function getAllItemIds() {
return array_keys(entity_load($this->entityType));
public function trackItemInsert(array $item_ids, array $indexes) {
$ret = array();
foreach ($indexes as $index_id => $index) {
$ids = $item_ids;
if ($bundles = $this->getIndexBundles($index)) {
$ids = drupal_map_assoc($ids);
foreach (entity_load($this->entityType, $ids) as $id => $entity) {
if (empty($bundles[$entity->{$this->bundleKey}])) {
unset($ids[$id]);
}
}
}
if ($ids) {
parent::trackItemInsert($ids, array($index));
$ret[$index_id] = $index;
}
}
return $ret;
}
/**
* {@inheritdoc}
*/
public function configurationForm(array $form, array &$form_state) {
$options = $this->getAvailableBundles();
if (!$options) {
return FALSE;
}
$form['bundles'] = array(
'#type' => 'checkboxes',
'#title' => t('Bundles'),
'#description' => t('Restrict the entity bundles that will be included in this index. Leave blank to include all bundles. This setting cannot be changed for existing indexes.'),
'#options' => array_map('check_plain', $options),
'#attributes' => array('class' => array('search-api-checkboxes-list')),
'#disabled' => !empty($form_state['index']),
);
if (!empty($form_state['index']->options['datasource'])) {
$form['bundles']['#default_value'] = drupal_map_assoc($form_state['index']->options['datasource']['bundles']);
}
return $form;
}
/**
* {@inheritdoc}
*/
public function configurationFormSubmit(array $form, array &$values, array &$form_state) {
if (!empty($values['bundles'])) {
$values['bundles'] = array_keys(array_filter($values['bundles']));
}
}
/**
* {@inheritdoc}
*/
public function getConfigurationSummary(SearchApiIndex $index) {
if ($bundles = $this->getIndexBundles($index)) {
$args['!bundles'] = implode(', ', array_intersect_key($this->getAvailableBundles(), $bundles));
return format_plural(count($bundles), 'Indexed bundle: !bundles.', 'Indexed bundles: !bundles.', $args);
}
return NULL;
}
/**
* Retrieves the available bundles for this entity type.
*
* @return array
* An array (which might be empty) mapping this entity type's bundle keys to
* their labels.
*/
protected function getAvailableBundles() {
if (!$this->bundleKey || empty($this->entityInfo['bundles'])) {
return array();
}
$bundles = array();
foreach ($this->entityInfo['bundles'] as $bundle => $bundle_info) {
$bundles[$bundle] = isset($bundle_info['label']) ? $bundle_info['label'] : $bundle;
}
return $bundles;
}
/**
* Computes the bundles that should be indexed for an index.
*
* @param SearchApiIndex $index
* The index for which to check.
*
* @return array
* An array containing all bundles that should be included in this index, as
* both the keys and values. An empty array means all current bundles should
* be included.
*
* @throws SearchApiException
* If the index doesn't belong to this datasource controller.
*/
protected function getIndexBundles(SearchApiIndex $index) {
$this->checkIndex($index);
if (!isset($this->bundles[$index->machine_name])) {
$this->bundles[$index->machine_name] = array();
if (!empty($index->options['datasource']['bundles'])) {
// We retrieve the available bundles here to check whether all of them
// are included by the index's setting. In this case, we return an empty
// array, too, to save on complexity.
// On the other hand, we still want to return deleted bundles since we
// do not want to suddenly include all bundles when all selected bundles
// were deleted.
$available = $this->getAvailableBundles();
foreach ($index->options['datasource']['bundles'] as $bundle) {
$this->bundles[$index->machine_name][$bundle] = $bundle;
unset($available[$bundle]);
}
if (!$available) {
$this->bundles[$index->machine_name] = array();
}
}
}
return $this->bundles[$index->machine_name];
}
}
@@ -0,0 +1,357 @@
<?php
/**
* @file
* Contains SearchApiCombinedEntityDataSourceController.
*/
/**
* Provides a datasource for indexing multiple types of entities.
*/
class SearchApiCombinedEntityDataSourceController extends SearchApiAbstractDataSourceController {
/**
* {@inheritdoc}
*/
protected $table = 'search_api_item_string_id';
/**
* {@inheritdoc}
*/
public function getIdFieldInfo() {
return array(
'key' => 'item_id',
'type' => 'string',
);
}
/**
* {@inheritdoc}
*/
public function loadItems(array $ids) {
$ids_by_type = array();
foreach ($ids as $id) {
list($type, $entity_id) = explode('/', $id);
$ids_by_type[$type][$entity_id] = $id;
}
$items = array();
foreach ($ids_by_type as $type => $type_ids) {
foreach (entity_load($type, array_keys($type_ids)) as $entity_id => $entity) {
$id = $type_ids[$entity_id];
$item = (object) array($type => $entity);
$item->item_id = $id;
$item->item_type = $type;
$item->item_entity_id = $entity_id;
$item->item_bundle = NULL;
try {
list(, , $bundle) = entity_extract_ids($type, $entity);
$item->item_bundle = $bundle ? "$type:$bundle" : NULL;
}
catch (EntityMalformedException $e) {
// Will probably make problems at some other place, but for extracting
// the bundle it is really not critical enough to fail on just
// ignore this exception.
}
$items[$id] = $item;
unset($type_ids[$entity_id]);
}
if ($type_ids) {
search_api_track_item_delete($type, array_keys($type_ids));
}
}
return $items;
}
/**
* {@inheritdoc}
*/
protected function getPropertyInfo() {
$info = array(
'item_id' => array(
'label' => t('ID'),
'description' => t('The combined ID of the item, containing both entity type and entity ID.'),
'type' => 'token',
),
'item_type' => array(
'label' => t('Entity type'),
'description' => t('The entity type of the item.'),
'type' => 'token',
'options list' => 'search_api_entity_type_options_list',
),
'item_entity_id' => array(
'label' => t('Entity ID'),
'description' => t('The entity ID of the item.'),
'type' => 'token',
),
'item_bundle' => array(
'label' => t('Bundle'),
'description' => t('The bundle of the item, if applicable.'),
'type' => 'token',
'options list' => 'search_api_combined_bundle_options_list',
),
'item_label' => array(
'label' => t('Label'),
'description' => t('The label of the item.'),
'type' => 'text',
// Since this needs a bit more computation than the others, we don't
// include it always when loading the item but use a getter callback.
'getter callback' => 'search_api_get_multi_type_item_label',
),
);
foreach ($this->getSelectedEntityTypeOptions() as $type => $label) {
$info[$type] = array(
'label' => $label,
'description' => t('The indexed entity, if it is of type %type.', array('%type' => $label)),
'type' => $type,
);
}
return array('property info' => $info);
}
/**
* {@inheritdoc}
*/
public function getItemId($item) {
return isset($item->item_id) ? $item->item_id : NULL;
}
/**
* {@inheritdoc}
*/
public function getItemLabel($item) {
return search_api_get_multi_type_item_label($item);
}
/**
* {@inheritdoc}
*/
public function getItemUrl($item) {
if ($item->item_type == 'file') {
return array(
'path' => file_create_url($item->file->uri),
'options' => array(
'entity_type' => 'file',
'entity' => $item,
),
);
}
$url = entity_uri($item->item_type, $item->{$item->item_type});
return $url ? $url : NULL;
}
/**
* {@inheritdoc}
*/
public function startTracking(array $indexes) {
if (!$this->table) {
return;
}
// We first clear the tracking table for all indexes, so we can just insert
// all items again without any key conflicts.
$this->stopTracking($indexes);
foreach ($indexes as $index) {
$types = $this->getEntityTypes($index);
// Wherever possible, use a sub-select instead of the much slower
// entity_load().
foreach ($types as $type) {
$entity_info = entity_get_info($type);
if (!empty($entity_info['base table'])) {
// Assumes that all entities use the "base table" property and the
// "entity keys[id]" in the same way as the default controller.
$id_field = $entity_info['entity keys']['id'];
$table = $entity_info['base table'];
// Select all entity ids.
$query = db_select($table, 't');
$query->addExpression("CONCAT(:prefix, t.$id_field)", 'item_id', array(':prefix' => $type . '/'));
$query->addExpression(':index_id', 'index_id', array(':index_id' => $index->id));
$query->addExpression('1', 'changed');
// INSERT ... SELECT ...
db_insert($this->table)
->from($query)
->execute();
unset($types[$type]);
}
}
// In the absence of a "base table", use the slow entity_load().
if ($types) {
foreach ($types as $type) {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', $type);
$result = $query->execute();
$ids = !empty($result[$type]) ? array_keys($result[$type]) : array();
if ($ids) {
foreach ($ids as $i => $id) {
$ids[$i] = $type . '/' . $id;
}
$this->trackItemInsert($ids, array($index), TRUE);
}
}
}
}
}
/**
* Starts tracking the index status for the given items on the given indexes.
*
* @param array $item_ids
* The IDs of new items to track.
* @param SearchApiIndex[] $indexes
* The indexes for which items should be tracked.
* @param bool $skip_type_check
* (optional) If TRUE, don't check whether the type matches the index's
* datasource configuration. Internal use only.
*
* @return SearchApiIndex[]|null
* All indexes for which any items were added; or NULL if items were added
* for all of them.
*
* @throws SearchApiDataSourceException
* If any error state was encountered.
*/
public function trackItemInsert(array $item_ids, array $indexes, $skip_type_check = FALSE) {
$ret = array();
foreach ($indexes as $index_id => $index) {
$ids = drupal_map_assoc($item_ids);
if (!$skip_type_check) {
$types = $this->getEntityTypes($index);
foreach ($ids as $id) {
list($type) = explode('/', $id);
if (!isset($types[$type])) {
unset($ids[$id]);
}
}
}
if ($ids) {
parent::trackItemInsert($ids, array($index));
$ret[$index_id] = $index;
}
}
return $ret;
}
/**
* {@inheritdoc}
*/
public function configurationForm(array $form, array &$form_state) {
$form['types'] = array(
'#type' => 'checkboxes',
'#title' => t('Entity types'),
'#description' => t('Select the entity types which should be included in this index.'),
'#options' => array_map('check_plain', search_api_entity_type_options_list()),
'#attributes' => array('class' => array('search-api-checkboxes-list')),
'#disabled' => !empty($form_state['index']),
'#required' => TRUE,
);
if (!empty($form_state['index']->options['datasource']['types'])) {
$form['types']['#default_value'] = $this->getEntityTypes($form_state['index']);
}
return $form;
}
/**
* {@inheritdoc}
*/
public function configurationFormSubmit(array $form, array &$values, array &$form_state) {
if (!empty($values['types'])) {
$values['types'] = array_keys(array_filter($values['types']));
}
}
/**
* {@inheritdoc}
*/
public function getConfigurationSummary(SearchApiIndex $index) {
if ($type_labels = $this->getSelectedEntityTypeOptions($index)) {
$args['!types'] = implode(', ', $type_labels);
return format_plural(count($type_labels), 'Indexed entity types: !types.', 'Indexed entity types: !types.', $args);
}
return NULL;
}
/**
* Retrieves the index for which the current method was called.
*
* Very ugly method which uses the stack trace to find the right object.
*
* @return SearchApiIndex
* The active index.
*
* @throws SearchApiException
* Thrown if the active index could not be determined.
*/
protected function getCallingIndex() {
foreach (debug_backtrace() as $trace) {
if (isset($trace['object']) && $trace['object'] instanceof SearchApiIndex) {
return $trace['object'];
}
}
// If there's only a single index on the site, it's also easy.
$indexes = search_api_index_load_multiple(FALSE);
if (count($indexes) === 1) {
return reset($indexes);
}
throw new SearchApiException('Could not determine the active index of the datasource.');
}
/**
* Returns the entity types for which this datasource is configured.
*
* Depends on the index from which this method is (indirectly) called.
*
* @param SearchApiIndex $index
* (optional) The index for which to get the enabled entity types. If not
* given, will be determined automatically.
*
* @return string[]
* The machine names of the datasource's enabled entity types, as both keys
* and values.
*
* @throws SearchApiException
* Thrown if the active index could not be determined.
*/
protected function getEntityTypes(SearchApiIndex $index = NULL) {
if (!$index) {
$index = $this->getCallingIndex();
}
if (isset($index->options['datasource']['types'])) {
return drupal_map_assoc($index->options['datasource']['types']);
}
return array();
}
/**
* Returns the selected entity type options for this datasource.
*
* Depends on the index from which this method is (indirectly) called.
*
* @param SearchApiIndex $index
* (optional) The index for which to get the enabled entity types. If not
* given, will be determined automatically.
*
* @return string[]
* An associative array, mapping the machine names of the enabled entity
* types to their labels.
*
* @throws SearchApiException
* Thrown if the active index could not be determined.
*/
protected function getSelectedEntityTypeOptions(SearchApiIndex $index = NULL) {
return array_intersect_key(search_api_entity_type_options_list(), $this->getEntityTypes($index));
}
}
@@ -19,7 +19,7 @@ class SearchApiException extends Exception {
*/
public function __construct($message = NULL) {
if (!$message) {
$message = t('An error occcurred in the Search API framework.');
$message = t('An error occurred in the Search API framework.');
}
parent::__construct($message);
}
@@ -115,7 +115,8 @@ class SearchApiIndex extends Entity {
public $item_type;
/**
* An array of options for configuring this index. The layout is as follows:
* An array of options for configuring this index. The layout is as follows
* (with all keys being optional):
* - cron_limit: The maximum number of items to be indexed per cron batch.
* - index_directly: Boolean setting whether entities are indexed immediately
* after they are created or updated.
@@ -150,6 +151,8 @@ class SearchApiIndex extends Entity {
* - weight: Used for sorting the processors.
* - settings: Processor-specific settings, configured via the processor's
* configuration form.
* - datasource: Datasource-specific settings, configured via the datasource's
* configuration form.
*
* @var array
*/
@@ -436,7 +439,6 @@ class SearchApiIndex extends Entity {
return $this->server()->query($this, $options);
}
/**
* Indexes items on this index.
*
@@ -932,7 +934,12 @@ class SearchApiIndex extends Entity {
$i = $only_indexed ? 1 : 0;
if (!isset($this->fulltext_fields[$i])) {
$this->fulltext_fields[$i] = array();
$fields = $only_indexed ? $this->options['fields'] : $this->getFields(FALSE);
if ($only_indexed) {
$fields = isset($this->options['fields']) ? $this->options['fields'] : array();
}
else {
$fields = $this->getFields(FALSE);
}
foreach ($fields as $key => $field) {
if (search_api_is_text_type($field['type'])) {
$this->fulltext_fields[$i][] = $key;
@@ -172,7 +172,7 @@ abstract class SearchApiAbstractProcessor implements SearchApiProcessorInterface
$default_fields = drupal_map_assoc(array_keys($this->options['fields']));
}
foreach ($fields as $name => $field) {
$field_options[$name] = $field['name'];
$field_options[$name] = check_plain($field['name']);
if (!empty($default_fields[$name]) || (!isset($this->options['fields']) && $this->testField($name, $field))) {
$default_fields[$name] = $name;
}
@@ -390,13 +390,15 @@ abstract class SearchApiAbstractProcessor implements SearchApiProcessorInterface
}
/**
* Determines whether to process data from the given field.
*
* @param $name
* The field's machine name.
* @param array $field
* The field's information.
*
* @return
* TRUE, iff the field should be processed.
* @return bool
* TRUE, if the field should be processed, FALSE otherwise.
*/
protected function testField($name, array $field) {
if (empty($this->options['fields'])) {
@@ -406,8 +408,13 @@ abstract class SearchApiAbstractProcessor implements SearchApiProcessorInterface
}
/**
* @return
* TRUE, iff the type should be processed.
* Determines whether fields of the given type should normally be processed.
*
* Defaults to processing text types, but can easily be overridden by
* subclasses.
*
* @return bool
* TRUE, if the type should be processed, FALSE otherwise.
*/
protected function testType($type) {
return search_api_is_text_type($type, array('text', 'tokens'));
@@ -86,12 +86,12 @@ class SearchApiHighlight extends SearchApiAbstractProcessor {
),
),
);
// Exclude certain fulltextfields
// Exclude certain fulltext fields.
$fields = $this->index->getFields();
$fulltext_fields = array();
foreach ($this->index->getFulltextFields() as $field) {
if (isset($fields[$field])) {
$fulltext_fields[$field] = $fields[$field]['name'] . ' (' . $field . ')';
$fulltext_fields[$field] = check_plain($fields[$field]['name'] . ' (' . $field . ')');
}
}
$form['exclude_fields'] = array(
@@ -120,7 +120,9 @@ class SearchApiHtmlFilter extends SearchApiAbstractProcessor {
);
}
$text = substr($text, $pos + 1);
preg_match('#^(/?)([-:_a-zA-Z]+)#', $text, $m);
if (!preg_match('#^(/?)([-:_a-zA-Z]+)#', $text, $m)) {
continue;
}
$text = substr($text, strpos($text, '>') + 1);
if ($m[1]) {
// Closing tag.
@@ -86,7 +86,9 @@ class SearchApiStopWords extends SearchApiAbstractProcessor {
}
/**
* @return
* Retrieves the processor's configured stopwords.
*
* @return array
* An array whose keys are the stopwords set in either the file or the text
* field.
*/
@@ -153,7 +153,9 @@ interface SearchApiQueryInterface {
*
* @param string $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.
* relevance) and 'search_api_id' (sort by item id) may be used. Also, if
* the search server supports the "search_api_random_sort" feature, the
* "search_api_random" special field can be used to sort randomly.
* @param string $order
* The order to sort items in - either 'ASC' or 'DESC'.
*
@@ -217,7 +219,10 @@ interface SearchApiQueryInterface {
* - 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.
* and 'results' always have to be set, all other entries are optional.
*
* @throws SearchApiException
* If an error prevented the search from completing.
*/
public function execute();
@@ -466,8 +471,8 @@ class SearchApiQuery implements SearchApiQueryInterface {
);
$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.'),
'description' => t('The query is interpreted as multiple keywords separated by spaces. ' .
'Keywords containing spaces may be "quoted". Quoted keywords must still be separated by spaces.'),
);
// @todo Add fourth mode for complicated expressions, e.g.: »"vanilla ice" OR (love NOT hate)«
return $modes;
@@ -586,6 +591,10 @@ class SearchApiQuery implements SearchApiQueryInterface {
'search_api_relevance' => array('type' => 'decimal'),
'search_api_id' => array('type' => 'integer'),
);
if ($this->getIndex()->server()->supportsFeature('search_api_random_sort')) {
$fields['search_api_random'] = array('type' => 'integer');
}
if (empty($fields[$field])) {
throw new SearchApiException(t('Trying to sort on unknown field @field.', array('@field' => $field)));
}
@@ -720,6 +729,9 @@ class SearchApiQuery implements SearchApiQueryInterface {
public function postExecute(array &$results) {
// Postprocess results.
$this->index->postprocessSearchResults($results, $this);
// Let modules alter the results.
drupal_alter('search_api_results', $results, $this);
}
/**
@@ -241,7 +241,7 @@ class SearchApiServer extends Entity {
/**
* Adds a new index to this server.
*
* If an exception in the service class implementation of this method occcurs,
* If an exception in the service class implementation of this method occurs,
* it will be caught and the operation saved as an pending server task.
*
* @see SearchApiServiceInterface::addIndex()
@@ -268,7 +268,7 @@ class SearchApiServer extends Entity {
* If the service class implementation of the method returns TRUE, this will
* automatically take care of marking the items on the index for re-indexing.
*
* If an exception in the service class implementation of this method occcurs,
* If an exception in the service class implementation of this method occurs,
* it will be caught and the operation saved as an pending server task.
*
* @see SearchApiServiceInterface::fieldsUpdated()
@@ -296,7 +296,7 @@ class SearchApiServer extends Entity {
/**
* Removes an index from this server.
*
* If an exception in the service class implementation of this method occcurs,
* If an exception in the service class implementation of this method occurs,
* it will be caught and the operation saved as an pending server task.
*
* @see SearchApiServiceInterface::removeIndex()
@@ -334,7 +334,7 @@ class SearchApiServer extends Entity {
/**
* Deletes indexed items from this server.
*
* If an exception in the service class implementation of this method occcurs,
* If an exception in the service class implementation of this method occurs,
* it will be caught and the operation saved as an pending server task.
*
* @see SearchApiServiceInterface::deleteItems()
@@ -420,7 +420,15 @@ abstract class SearchApiAbstractService implements SearchApiServiceInterface {
public function preDelete() {
$indexes = search_api_index_load_multiple(FALSE, array('server' => $this->server->machine_name));
foreach ($indexes as $index) {
$this->removeIndex($index);
// removeIndex() might throw exceptions, but this method mustn't.
try {
$this->removeIndex($index);
}
catch (SearchApiException $e) {
$variables['%index'] = $index->name;
$variables['%server'] = $this->server->name;
watchdog_exception('search_api', $e, '%type while trying to remove index %index from deleted server %server: !message in %function (line %line of %file).', $variables);
}
}
}
@@ -303,8 +303,9 @@ function search_api_admin_add_server_validate(array $form, array &$form_state) {
return;
}
$form_state['values']['options']['service'] = $service;
$values = isset($form_state['values']['options']['form']) ? $form_state['values']['options']['form'] : array();
$service->configurationFormValidate($form['options']['form'], $values, $form_state);
if (!empty($form_state['values']['options']['form'])) {
$service->configurationFormValidate($form['options']['form'], $form_state['values']['options']['form'], $form_state);
}
}
/**
@@ -630,7 +631,9 @@ function search_api_admin_server_edit(array $form, array &$form_state, SearchApi
* @see search_api_admin_server_edit_submit()
*/
function search_api_admin_server_edit_validate(array $form, array &$form_state) {
$form_state['server']->configurationFormValidate($form['options']['form'], $form_state['values']['options']['form'], $form_state);
if (!empty($form['options']['form']) && !empty($form_state['values']['options']['form'])) {
$form_state['server']->configurationFormValidate($form['options']['form'], $form_state['values']['options']['form'], $form_state);
}
}
/**
@@ -682,83 +685,126 @@ function search_api_admin_form_delete_submit($form, &$form_state) {
*
* @ingroup forms
*
* @see search_api_admin_add_index_ajax_callback()
* @see search_api_admin_add_index_validate()
* @see search_api_admin_add_index_submit()
*/
function search_api_admin_add_index(array $form, array &$form_state) {
drupal_set_title(t('Add index'));
$old_type = empty($form_state['values']['item_type']) ? '' : $form_state['values']['item_type'];
$form['#attached']['css'][] = drupal_get_path('module', 'search_api') . '/search_api.admin.css';
$form['#tree'] = TRUE;
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Index name'),
'#maxlength' => 50,
'#required' => TRUE,
);
$form['machine_name'] = array(
'#type' => 'machine_name',
'#maxlength' => 50,
'#machine_name' => array(
'exists' => 'search_api_index_load',
),
);
if (empty($form_state['step_one'])) {
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Index name'),
'#maxlength' => 50,
'#required' => TRUE,
);
$form['item_type'] = array(
'#type' => 'select',
'#title' => t('Item type'),
'#description' => t('Select the type of items that will be indexed in this index. ' .
'This setting cannot be changed afterwards.'),
'#options' => array(),
'#required' => TRUE,
);
foreach (search_api_get_item_type_info() as $type => $info) {
$form['item_type']['#options'][$type] = $info['name'];
$form['machine_name'] = array(
'#type' => 'machine_name',
'#maxlength' => 50,
'#machine_name' => array(
'exists' => 'search_api_index_load',
),
);
$form['item_type'] = array(
'#type' => 'select',
'#title' => t('Item type'),
'#description' => t('Select the type of items that will be indexed in this index. ' .
'This setting cannot be changed afterwards.'),
'#options' => array(),
'#required' => TRUE,
'#ajax' => array(
'callback' => 'search_api_admin_add_index_ajax_callback',
'wrapper' => 'search-api-datasource-options',
),
);
$form['datasource'] = array();
foreach (search_api_get_item_type_info() as $type => $info) {
$form['item_type']['#options'][$type] = $info['name'];
}
$form['enabled'] = array(
'#type' => 'checkbox',
'#title' => t('Enabled'),
'#description' => t('This will only take effect if you also select a server for the index.'),
'#default_value' => TRUE,
);
$form['description'] = array(
'#type' => 'textarea',
'#title' => t('Index description'),
);
$form['server'] = array(
'#type' => 'select',
'#title' => t('Server'),
'#description' => t('Select the server this index should reside on.'),
'#default_value' => '',
'#options' => array('' => t('< No server >'))
);
$servers = search_api_server_load_multiple(FALSE, array('enabled' => 1));
// List enabled servers first.
foreach ($servers as $server) {
if ($server->enabled) {
$form['server']['#options'][$server->machine_name] = $server->name;
}
}
foreach ($servers as $server) {
if (!$server->enabled) {
$form['server']['#options'][$server->machine_name] = t('@server_name (disabled)', array('@server_name' => $server->name));
}
}
$form['read_only'] = array(
'#type' => 'checkbox',
'#title' => t('Read only'),
'#description' => t('Do not write to this index or track the status of items in this index.'),
'#default_value' => FALSE,
);
$form['options']['index_directly'] = array(
'#type' => 'checkbox',
'#title' => t('Index items immediately'),
'#description' => t('Immediately index new or updated items instead of waiting for the next cron run. ' .
'This might have serious performance drawbacks and is generally not advised for larger sites.'),
'#default_value' => FALSE,
);
$form['options']['cron_limit'] = array(
'#type' => 'textfield',
'#title' => t('Cron batch size'),
'#description' => t('Set how many items will be indexed at once when indexing items during a cron run. ' .
'"0" means that no items will be indexed by cron for this index, "-1" means that cron should index all items at once.'),
'#default_value' => SEARCH_API_DEFAULT_CRON_LIMIT,
'#size' => 4,
'#attributes' => array('class' => array('search-api-cron-limit')),
'#element_validate' => array('element_validate_integer'),
);
}
$form['enabled'] = array(
'#type' => 'checkbox',
'#title' => t('Enabled'),
'#description' => t('This will only take effect if the selected server is also enabled.'),
'#default_value' => TRUE,
);
$form['description'] = array(
'#type' => 'textarea',
'#title' => t('Index description'),
);
$form['server'] = array(
'#type' => 'select',
'#title' => t('Server'),
'#description' => t('Select the server this index should reside on.'),
'#default_value' => '',
'#options' => array('' => t('< No server >'))
);
$servers = search_api_server_load_multiple(FALSE, array('enabled' => 1));
// List enabled servers first.
foreach ($servers as $server) {
$form['server']['#options'][$server->machine_name] = $server->name;
elseif (!$old_type) {
$old_type = $form_state['step_one']['item_type'];
}
$form['read_only'] = array(
'#type' => 'checkbox',
'#title' => t('Read only'),
'#description' => t('Do not write to this index or track the status of items in this index.'),
'#default_value' => FALSE,
if ($old_type) {
$datasource = search_api_get_datasource_controller($old_type);
$datasource_form = array();
$datasource_form = $datasource->configurationForm($datasource_form, $form_state);
if ($datasource_form) {
$form['datasource'] = $datasource_form;
$form['datasource']['#parents'] = array('options', 'datasource');
}
}
$form['datasource']['#prefix'] = '<div id="search-api-datasource-options">';
$form['datasource']['#suffix'] = '</div>';
$form['old_type'] = array(
'#type' => 'value',
'#value' => $old_type,
);
$form['options']['index_directly'] = array(
'#type' => 'checkbox',
'#title' => t('Index items immediately'),
'#description' => t('Immediately index new or updated items instead of waiting for the next cron run. ' .
'This might have serious performance drawbacks and is generally not advised for larger sites.'),
'#default_value' => FALSE,
);
$form['options']['cron_limit'] = array(
'#type' => 'textfield',
'#title' => t('Cron batch size'),
'#description' => t('Set how many items will be indexed at once when indexing items during a cron run. ' .
'"0" means that no items will be indexed by cron for this index, "-1" means that cron should index all items at once.'),
'#default_value' => SEARCH_API_DEFAULT_CRON_LIMIT,
'#size' => 4,
'#attributes' => array('class' => array('search-api-cron-limit')),
$form['datasource_config'] = array(
'#type' => 'value',
'#value' => !empty($datasource_form),
);
$form['submit'] = array(
@@ -769,22 +815,33 @@ function search_api_admin_add_index(array $form, array &$form_state) {
return $form;
}
/**
* AJAX submit callback for search_api_admin_add_index().
*
* Used for displaying the matching datasource configuration form for the
* selected item type.
*/
function search_api_admin_add_index_ajax_callback(array $form, array &$form_state) {
return $form['datasource'];
}
/**
* Form validation handler for search_api_admin_add_index().
*
* @see search_api_admin_add_index_submit()
*/
function search_api_admin_add_index_validate(array $form, array &$form_state) {
$name = $form_state['values']['machine_name'];
$values = $form_state['values'];
$name = $values['machine_name'];
if (is_numeric($name)) {
form_set_error('machine_name', t('The machine name must not be a pure number.'));
}
$cron_limit = $form_state['values']['options']['cron_limit'];
if ($cron_limit != '' . ((int) $cron_limit)) {
// We don't enforce stricter rules and treat all negative values as -1.
form_set_error('options[cron_limit]', t('The cron batch size must be an integer.'));
if (!$values['datasource_config'] || empty($values['item_type']) || $values['item_type'] != $values['old_type']) {
return;
}
$datasource = search_api_get_datasource_controller($values['item_type']);
$datasource->configurationFormValidate($form['datasource'], $form_state['values']['options']['datasource'], $form_state);
}
/**
@@ -794,10 +851,34 @@ function search_api_admin_add_index_validate(array $form, array &$form_state) {
*/
function search_api_admin_add_index_submit(array $form, array &$form_state) {
form_state_values_clean($form_state);
$values = $form_state['values'];
// Validation of whether the server of an index is enabled is done in the
if (!empty($form_state['step_one'])) {
$values += $form_state['step_one'];
unset($form_state['step_one']);
}
// The type was changed (or the form submitted without JS for the first time).
// If the new type has a configuration form, we have to display it now.
$datasource = search_api_get_datasource_controller($values['item_type']);
if ($values['item_type'] != $values['old_type']) {
$datasource_form = array();
if ($datasource->configurationForm($datasource_form, $form_state)) {
unset($values['options']['datasource']);
$form_state['step_one'] = $values;
$form_state['rebuild'] = TRUE;
drupal_set_message(t('Please specify further configuration options.'));
return;
}
}
// If the current type has a configuration form, call the datasource
// controller's config submit callback.
if ($values['datasource_config']) {
$datasource->configurationFormSubmit($form['datasource'], $values['options']['datasource'], $form_state);
}
// Validation of whether a server is set for the index is done in the
// SearchApiIndex::save() method.
search_api_index_insert($values);
@@ -857,6 +938,7 @@ function search_api_admin_index_view(SearchApiIndex $index, $action = NULL) {
'#machine_name' => $index->machine_name,
'#description' => $index->description,
'#item_type' => $index->item_type,
'#datasource_config' => $index->datasource()->getConfigurationSummary($index),
'#enabled' => $index->enabled,
'#server' => $server,
'#options' => $index->options,
@@ -889,6 +971,7 @@ function search_api_admin_index_view(SearchApiIndex $index, $action = NULL) {
* - machine_name: The index' machine name.
* - description: The index' description.
* - item_type: The type of items stored in this index.
* - datasource_config: A summary of the datasource's configuration.
* - enabled: Boolean indicating whether the index is enabled.
* - server: The server this index currently rests on, if any.
* - options: The index' options, like cron limit.
@@ -912,6 +995,7 @@ function theme_search_api_index(array $variables) {
$description = $variables['description'];
$enabled = $variables['enabled'];
$item_type = $variables['item_type'];
$datasource_config = $variables['datasource_config'];
$server = $variables['server'];
$options = $variables['options'];
$status = $variables['status'];
@@ -962,6 +1046,12 @@ function theme_search_api_index(array $variables) {
$info = check_plain($item_type);
$rows[] = _search_api_deep_copy($row);
if ($datasource_config) {
$label = t('Item type configuration');
$info = check_plain($datasource_config);
$rows[] = _search_api_deep_copy($row);
}
if ($server) {
$label = t('Server');
$info = l($server->name, 'admin/config/search/search_api/server/' . $server->machine_name);
@@ -1193,6 +1283,7 @@ function search_api_admin_index_status_form_submit(array $form, array &$form_sta
*
* @ingroup forms
*
* @see search_api_admin_index_edit_validate()
* @see search_api_admin_index_edit_submit()
*/
function search_api_admin_index_edit(array $form, array &$form_state, SearchApiIndex $index) {
@@ -1208,7 +1299,7 @@ function search_api_admin_index_edit(array $form, array &$form_state, SearchApiI
'#required' => TRUE,
);
try {
$enabled_fixed = !$index->enabled && !$index->server();
$enabled_fixed = !$index->server();
}
catch (Exception $e) {
watchdog_exception('search_api', $e);
@@ -1220,7 +1311,7 @@ function search_api_admin_index_edit(array $form, array &$form_state, SearchApiI
'#type' => 'checkbox',
'#title' => t('Enabled'),
'#default_value' => $index->enabled,
// Can't enable an index lying on a disabled server, or no server at all.
// Can't enable an index that's not lying on any server.
'#disabled' => $enabled_fixed,
);
$form['description'] = array(
@@ -1240,6 +1331,15 @@ function search_api_admin_index_edit(array $form, array &$form_state, SearchApiI
foreach ($servers as $server) {
$form['server']['#options'][$server->machine_name] = $server->name;
}
$datasource_form = !empty($form['options']['datasource']) ? $form['options']['datasource'] : array();
$datasource_form = $index->datasource()->configurationForm($datasource_form, $form_state);
if ($datasource_form) {
$form['options']['datasource'] = $datasource_form;
$form['options']['datasource']['#type'] = 'fieldset';
$form['options']['datasource']['#title'] = t('Datasource options');
}
$form['read_only'] = array(
'#type' => 'checkbox',
'#title' => t('Read only'),
@@ -1285,14 +1385,33 @@ function search_api_admin_index_edit(array $form, array &$form_state, SearchApiI
return $form;
}
/**
* Form validation handler for search_api_admin_index_edit().
*
* @see search_api_admin_index_edit_submit()
*/
function search_api_admin_index_edit_validate(array $form, array &$form_state) {
if (!empty($form['options']['datasource'])) {
$form_state['values']['options'] += array('datasource' => array());
$form_state['index']->datasource()->configurationFormValidate($form['options']['datasource'], $form_state['values']['options']['datasource'], $form_state);
}
}
/**
* Form submission handler for search_api_admin_index_edit().
*
* @see search_api_admin_index_edit_validate()
*/
function search_api_admin_index_edit_submit(array $form, array &$form_state) {
form_state_values_clean($form_state);
$values = $form_state['values'];
/** @var SearchApiIndex $index */
$index = $form_state['index'];
if (!empty($form['options']['datasource'])) {
$index->datasource()->configurationFormSubmit($form['options']['datasource'], $values['options']['datasource'], $form_state);
}
$values['options'] += $index->options;
$ret = $index->update($values);
@@ -1687,10 +1806,7 @@ function search_api_admin_index_fields(array $form, array &$form_state, SearchAp
// An array of option arrays for types, keyed by nesting level.
$types = array(0 => search_api_field_types());
$entity_types = entity_get_info();
// $boosts = drupal_map_assoc(array('0.1', '0.2', '0.3', '0.5', '0.8', '1.0', '2.0', '3.0', '5.0', '8.0', '13.0', '21.0'));
$boosts = drupal_map_assoc(array('0.1', '0.2', '0.3', '0.5', '0.8', '1.0', '2.0', '3.0', '5.0', '8.0', '13.0', '21.0', '100', '1000', '1010', '1020', '1030', '1040', '1050', '1060'));
$boosts = drupal_map_assoc(array('0.0', '0.1', '0.2', '0.3', '0.5', '0.8', '1.0', '2.0', '3.0', '5.0', '8.0', '13.0', '21.0'));
$fulltext_types = array(0 => array('text'));
// Add all custom data types with fallback "text" to fulltext types as well.
@@ -1833,6 +1949,7 @@ function search_api_admin_index_fields(array $form, array &$form_state, SearchAp
);
if ($additional) {
asort($additional);
reset($additional);
$form['additional'] = array(
'#type' => 'fieldset',
@@ -1986,6 +2103,9 @@ function _search_api_admin_get_fields(SearchApiIndex $index, EntityMetadataWrapp
* @param array $variables
* An associative array containing:
* - element: A render element representing the form.
*
* @return string
* The HTML for a field list form.
*/
function theme_search_api_admin_fields_table($variables) {
$form = $variables['element'];
@@ -2031,6 +2151,7 @@ function theme_search_api_admin_fields_table($variables) {
function search_api_admin_index_fields_submit(array $form, array &$form_state) {
$index = $form_state['index'];
$options = isset($index->options) ? $index->options : array();
$index_path = 'admin/config/search/search_api/index/' . $index->machine_name;
if ($form_state['values']['op'] == t('Save changes')) {
$fields = $form_state['values']['fields'];
$default_types = search_api_default_field_types();
@@ -2060,18 +2181,18 @@ function search_api_admin_index_fields_submit(array $form, array &$form_state) {
$ret = $index->update(array('options' => $options));
if ($ret) {
drupal_set_message(t('The indexed fields were successfully changed. ' .
'The index was cleared and will have to be re-indexed with the new settings.'));
$vars = array('@url' => $index_path);
drupal_set_message(t('The indexed fields were successfully changed. The index was cleared and will have to be <a href="@url">re-indexed</a> with the new settings.', $vars));
}
else {
drupal_set_message(t('No values were changed.'));
}
if (isset($index->options['data_alter_callbacks']) || isset($index->options['processors'])) {
$form_state['redirect'] = 'admin/config/search/search_api/index/' . $index->machine_name . '/fields';
$form_state['redirect'] = $index_path . '/fields';
}
else {
drupal_set_message(t('Please set up the indexing workflow.'));
$form_state['redirect'] = 'admin/config/search/search_api/index/' . $index->machine_name . '/workflow';
$form_state['redirect'] = $index_path . '/workflow';
}
return;
}
@@ -2086,7 +2207,7 @@ function search_api_admin_index_fields_submit(array $form, array &$form_state) {
else {
drupal_set_message(t('No values were changed.'));
}
$form_state['redirect'] = 'admin/config/search/search_api/index/' . $index->machine_name . '/fields';
$form_state['redirect'] = $index_path . '/fields';
}
/**
@@ -341,7 +341,27 @@ function hook_search_api_query_alter(SearchApiQueryInterface $query) {
// Exclude entities with ID 0. (Assume the ID field is always indexed.)
if ($query->getIndex()->getEntityType()) {
$info = entity_get_info($query->getIndex()->getEntityType());
$query->condition($info['entity keys']['id'], 0, '!=');
$query->condition($info['entity keys']['id'], 0, '<>');
}
}
/**
* Alter the search results before they are returned.
*
* @param array $results
* The results returned by the server, which may be altered. The data
* structure is the same as returned by SearchApiQueryInterface::execute().
* @param SearchApiQueryInterface $query
* The search query that was executed.
*/
function hook_search_api_results_alter(array &$results, SearchApiQueryInterface $query) {
if ($query->getOption('search id') == 'search_api_views:my_search_view:page') {
// Log the number of results.
$vars = array(
'@keys' => $query->getOriginalKeys(),
'@num' => $results['result count'],
);
watchdog('my_module', 'Search view with query "@keys" had @num results.', $vars, WATCHDOG_DEBUG);
}
}
@@ -564,15 +584,15 @@ function hook_default_search_api_index_alter(array &$defaults) {
* This function will be called for fields of the specific data type to convert
* all individual values of the field to the correct format.
*
* @param $value
* @param mixed $value
* The raw, single value, as extracted from an entity wrapper.
* @param $original_type
* @param string $original_type
* The original Entity API type of the value.
* @param $type
* @param string $type
* The custom data type to which the value should be converted. Can be ignored
* if the callback is only used for a single data type.
*
* @return
* @return mixed|null
* The converted value, if a conversion could be executed. NULL otherwise.
*
* @see hook_search_api_data_type_info()
@@ -71,9 +71,10 @@ function search_api_drush_command() {
'drush sapi-i default_node_index' => dt('Index items for the index with the machine name !name.', array('!name' => 'default_node_index')),
'drush sapi-i 1 100' => dt("Index a maximum number of !limit items (index's cron batch size items per batch run) for the index with the ID !id.", array('!limit' => 100, '!id' => 1)),
'drush sapi-i 1 100 10' => dt("Index a maximum number of !limit items (!batch_size items per batch run) for the index with the ID !id.", array('!limit' => 100, '!batch_size' => 10, '!id' => 1)),
'drush sapi-i 0 0 100' => dt("Index all items of all indexes with !batch_size items per batch run.", array('!batch_size' => 100)),
),
'arguments' => array(
'index_id' => dt('The numeric ID or machine name of an index.'),
'index_id' => dt('The numeric ID or machine name of an index. Set to 0 to index all indexes. Defaults to 0 (index all).'),
'limit' => dt("The number of items to index (index's cron batch size items per run). Set to 0 to index all items. Defaults to 0 (index all)."),
'batch_size' => dt("The number of items to index per batch run. Set to 0 to index all items at once. Defaults to the index's cron batch size."),
),
@@ -121,6 +122,39 @@ function search_api_drush_command() {
'aliases' => array('sapi-sis'),
);
$items['search-api-server-list'] = array(
'description' => 'List all search servers.',
'examples' => array(
'drush search-api-server-list' => dt('List all search servers.'),
'drush sapi-sl' => dt('Alias to list all search servers.'),
),
'aliases' => array('sapi-sl'),
);
$items['search-api-server-enable'] = array(
'description' => 'Enable a search server.',
'examples' => array(
'drush search-api-server-e my_solr_server' => dt('Enable the !server search server.', array('!server' => 'my_solr_server')),
'drush sapi-se my_solr_server' => dt('Alias to enable the !server search server.', array('!server' => 'my_solr_server')),
),
'arguments' => array(
'server_id' => dt('The numeric ID or machine name of a search server to enable.'),
),
'aliases' => array('sapi-se'),
);
$items['search-api-server-disable'] = array(
'description' => 'Disable a search server.',
'examples' => array(
'drush search-api-server-disable' => dt('Disable the !server search server.', array('!server' => 'my_solr_server')),
'drush sapi-sd' => dt('Alias to disable the !server search server.', array('!server' => 'my_solr_server')),
),
'arguments' => array(
'server_id' => dt('The numeric ID or machine name of a search server to disable.'),
),
'aliases' => array('sapi-sd'),
);
return $items;
}
@@ -293,6 +327,7 @@ function drush_search_api_index($index_id = NULL, $limit = NULL, $batch_size = N
if (search_api_drush_static(__FUNCTION__)) {
return;
}
$index_id = !empty($index_id) ? $index_id : NULL;
$indexes = search_api_drush_get_index($index_id);
if (empty($indexes)) {
return;
@@ -508,7 +543,8 @@ function search_api_drush_get_server($server_id = NULL) {
$servers = search_api_server_load_multiple($ids);
if (empty($servers)) {
drush_set_error(dt('Invalid server_id or no servers present.'));
// @todo: Maybe add logic to print table of all servers.
drush_print();
drush_search_api_server_list();
}
return $servers;
}
@@ -533,3 +569,75 @@ function search_api_drush_static($function) {
$index[$function] = TRUE;
return FALSE;
}
/**
* Lists all search servers.
*/
function drush_search_api_server_list() {
if (search_api_drush_static(__FUNCTION__)) {
return;
}
$servers = search_api_server_load_multiple(FALSE);
if (empty($servers)) {
drush_print(dt('There are no servers present.'));
return;
}
$rows[] = array(
dt('Machine name'),
dt('Name'),
dt('Status'),
);
foreach ($servers as $server) {
$row = array(
$server->machine_name,
$server->name,
$server->enabled ? dt('enabled') : dt('disabled'),
);
$rows[] = $row;
}
drush_print_table($rows);
}
/**
* Enables a search server.
*
* @param int|string $server_id
* The numeric ID or machine name of the server to enable.
*/
function drush_search_api_server_enable($server_id = NULL) {
if (!isset($server_id)) {
drush_print(dt('Please provide a valid server id.'));
return;
}
$server = search_api_server_load($server_id);
if (empty($server)) {
drush_print(dt('The server was not able to load.'));
return;
}
else {
$server->update(array('enabled' => 1));
drush_print(dt('The server was enabled successfully.'));
}
}
/**
* Disables a search server.
*
* @param int|string $server_id
* The numeric ID or machine name of the server to disable.
*/
function drush_search_api_server_disable($server_id = NULL) {
if (!isset($server_id)) {
drush_print(dt('Please provide a valid server id.'));
return;
}
$server = search_api_server_load($server_id);
if (empty($server)) {
drush_print(dt('The server was not able to load.'));
return;
}
else {
$server->update(array('enabled' => 0));
drush_print(dt('The server was disabled successfully.'));
}
}
@@ -16,9 +16,11 @@ files[] = includes/callback_language_control.inc
files[] = includes/callback_node_access.inc
files[] = includes/callback_node_status.inc
files[] = includes/callback_role_filter.inc
files[] = includes/callback_user_status.inc
files[] = includes/datasource.inc
files[] = includes/datasource_entity.inc
files[] = includes/datasource_external.inc
files[] = includes/datasource_multiple.inc
files[] = includes/exception.inc
files[] = includes/index_entity.inc
files[] = includes/processor.inc
@@ -34,9 +36,9 @@ files[] = includes/service.inc
configure = admin/config/search/search_api
; Information added by Drupal.org packaging script on 2014-12-26
version = "7.x-1.14"
; Information added by Drupal.org packaging script on 2016-02-26
version = "7.x-1.16+29-dev"
core = "7.x"
project = "search_api"
datestamp = "1419580682"
datestamp = "1456500713"
@@ -191,6 +191,35 @@ function search_api_schema() {
'primary key' => array('item_id', 'index_id'),
);
$schema['search_api_item_string_id'] = array(
'description' => 'Stores the items which should be indexed for each index, and their status. Used only for items with string IDs.',
'fields' => array(
'item_id' => array(
'description' => "The item's ID.",
'type' => 'varchar',
'length' => 64,
'not null' => TRUE,
),
'index_id' => array(
'description' => 'The {search_api_index}.id this item belongs to.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'changed' => array(
'description' => 'Either a flag or a timestamp to indicate if or when the item was changed since it was last indexed.',
'type' => 'int',
'size' => 'big',
'not null' => TRUE,
'default' => 1,
),
),
'indexes' => array(
'indexing' => array('index_id', 'changed'),
),
'primary key' => array('item_id', 'index_id'),
);
$schema['search_api_task'] = array(
'description' => 'Stores pending tasks for servers.',
'fields' => array(
@@ -1001,3 +1030,45 @@ function search_api_update_7117() {
->execute();
}
}
/**
* Adds the {search_api_item_string_id} table for items with string IDs.
*/
function search_api_update_7118() {
// Some users have reported that the table already existed for them, for
// whatever reason. Therefore, just bail if the table already exists, assuming
// it already looks as expected.
if (db_table_exists('search_api_item_string_id')) {
return;
}
$table = array(
'description' => 'Stores the items which should be indexed for each index, and their status. Used only for items with string IDs.',
'fields' => array(
'item_id' => array(
'description' => "The item's ID.",
'type' => 'varchar',
'length' => 64,
'not null' => TRUE,
),
'index_id' => array(
'description' => 'The {search_api_index}.id this item belongs to.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
'changed' => array(
'description' => 'Either a flag or a timestamp to indicate if or when the item was changed since it was last indexed.',
'type' => 'int',
'size' => 'big',
'not null' => TRUE,
'default' => 1,
),
),
'indexes' => array(
'indexing' => array('index_id', 'changed'),
),
'primary key' => array('item_id', 'index_id'),
);
db_create_table('search_api_item_string_id', $table);
}
@@ -2,7 +2,7 @@
/**
* @file
* Provides a flexible framework for implementing search servives.
* Provides a flexible framework for implementing search services.
*/
/**
@@ -270,6 +270,7 @@ function search_api_theme() {
'machine_name' => '',
'description' => NULL,
'item_type' => NULL,
'datasource_config' => NULL,
'enabled' => NULL,
'server' => NULL,
'options' => array(),
@@ -646,8 +647,9 @@ function search_api_search_api_index_insert(SearchApiIndex $index) {
* Implements hook_search_api_index_update().
*/
function search_api_search_api_index_update(SearchApiIndex $index) {
// Call the datasource update function with the table this module provides.
// Call the datasource update function with the tables this module provides.
search_api_index_update_datasource($index, 'search_api_item');
search_api_index_update_datasource($index, 'search_api_item_string_id');
// If the server was changed, we have to call the appropriate service class
// hook methods.
@@ -856,6 +858,8 @@ function search_api_entity_insert($entity, $type) {
list($id) = entity_extract_ids($type, $entity);
if (isset($id)) {
search_api_track_item_insert($type, array($id));
$combined_id = $type . '/' . $id;
search_api_track_item_insert('multiple', array($combined_id));
}
}
@@ -866,6 +870,8 @@ function search_api_entity_insert($entity, $type) {
* datasource controller and calls search_api_track_item_change() for the
* updated items.
*
* It also checks whether the entity's bundle changed and acts accordingly.
*
* @see search_api_search_api_item_type_info()
*/
function search_api_entity_update($entity, $type) {
@@ -874,9 +880,20 @@ function search_api_entity_update($entity, $type) {
if (!entity_get_property_info($type)) {
return;
}
list($id) = entity_extract_ids($type, $entity);
list($id, , $new_bundle) = entity_extract_ids($type, $entity);
// Check if the entity's bundle changed.
if (!empty($entity->original)) {
list(, , $old_bundle) = entity_extract_ids($type, $entity->original);
if ($new_bundle != $old_bundle) {
_search_api_entity_datasource_bundle_change($type, $id, $old_bundle, $new_bundle);
}
}
if (isset($id)) {
search_api_track_item_change($type, array($id));
$combined_id = $type . '/' . $id;
search_api_track_item_change('multiple', array($combined_id));
}
}
@@ -898,6 +915,28 @@ function search_api_entity_delete($entity, $type) {
list($id) = entity_extract_ids($type, $entity);
if (isset($id)) {
search_api_track_item_delete($type, array($id));
$combined_id = $type . '/' . $id;
search_api_track_item_delete('multiple', array($combined_id));
}
}
/**
* Implements hook_field_attach_rename_bundle().
*
* This is implemented on behalf of the SearchApiEntityDataSourceController
* datasource controller, to update any bundle settings that contain the changed
* bundle.
*/
function search_api_field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
foreach (search_api_index_load_multiple(FALSE, array('item_type' => $entity_type)) as $index) {
$bundles = &$index->options['datasource']['bundles'];
if (isset($bundles) && ($pos = array_search($bundle_old, $bundles)) !== FALSE) {
$bundles[$pos] = $bundle_new;
$index->save();
// Clear all caches that could contain the bundle information.
$index->resetCaches();
drupal_static_reset('search_api_get_datasource_controller');
}
}
}
@@ -935,16 +974,19 @@ function search_api_flush_caches() {
function search_api_search_api_item_type_info() {
$types = array();
foreach (entity_get_property_info() as $type => $property_info) {
if ($info = entity_get_info($type)) {
$types[$type] = array(
'name' => $info['label'],
'datasource controller' => 'SearchApiEntityDataSourceController',
'entity_type' => $type,
);
}
foreach (search_api_entity_type_options_list() as $type => $label) {
$types[$type] = array(
'name' => $label,
'datasource controller' => 'SearchApiEntityDataSourceController',
'entity_type' => $type,
);
}
$types['multiple'] = array(
'name' => t('Multiple types'),
'datasource controller' => 'SearchApiCombinedEntityDataSourceController',
);
return $types;
}
@@ -1026,6 +1068,11 @@ function search_api_search_api_alter_callback_info() {
'description' => t('Exclude unpublished nodes from the index. <strong>Caution:</strong> This only affects the indexed nodes themselves. If an enabled node has references to disabled nodes, those will still be indexed (or displayed) normally.'),
'class' => 'SearchApiAlterNodeStatus',
);
$callbacks['search_api_alter_user_status'] = array(
'name' => t('Exclude blocked users'),
'description' => t('Exclude blocked users from the index. <strong>Caution:</strong> This only affects the indexed users themselves. If an active user account includes a reference to a disabled user, that reference will still be indexed (or displayed) normally.'),
'class' => 'SearchApiAlterUserStatus',
);
return $callbacks;
}
@@ -1100,7 +1147,10 @@ function search_api_track_item_insert($type, array $item_ids) {
}
try {
search_api_get_datasource_controller($type)->trackItemInsert($item_ids, $indexes);
$returned_indexes = search_api_get_datasource_controller($type)->trackItemInsert($item_ids, $indexes);
if (isset($returned_indexes)) {
$indexes = $returned_indexes;
}
}
catch (SearchApiException $e) {
$vars['%item_type'] = $type;
@@ -1137,7 +1187,10 @@ function search_api_track_item_change($type, array $item_ids) {
return;
}
try {
search_api_get_datasource_controller($type)->trackItemChange($item_ids, $indexes);
$returned_indexes = search_api_get_datasource_controller($type)->trackItemChange($item_ids, $indexes);
if (isset($returned_indexes)) {
$indexes = $returned_indexes;
}
foreach ($indexes as $index) {
if (!empty($index->options['index_directly'])) {
// For indexes with the index_directly option set, queue the items to be
@@ -1212,7 +1265,10 @@ function search_api_track_item_delete($type, array $item_ids) {
$indexes = search_api_index_load_multiple(FALSE, $conditions);
if ($indexes) {
try {
search_api_get_datasource_controller($type)->trackItemDelete($item_ids, $indexes);
$changed_indexes = search_api_get_datasource_controller($type)->trackItemDelete($item_ids, $indexes);
if (isset($changed_indexes)) {
$indexes = $changed_indexes;
}
}
catch (SearchApiException $e) {
$vars['%item_type'] = $type;
@@ -1222,8 +1278,9 @@ function search_api_track_item_delete($type, array $item_ids) {
// Then, delete it from all servers. Servers of disabled indexes have to be
// considered, too!
unset($conditions['enabled']);
foreach (search_api_index_load_multiple(FALSE, $conditions) as $index) {
$conditions['enabled'] = 0;
$indexes = array_merge($indexes, search_api_index_load_multiple(FALSE, $conditions));
foreach ($indexes as $index) {
try {
if ($server = $index->server()) {
$server->deleteItems($item_ids, $index);
@@ -2043,8 +2100,8 @@ function _search_api_query_add_node_access($account, SearchApiQueryInterface $qu
* @param array $allowed
* Optionally, an array of allowed types.
*
* @return
* TRUE if $type is either one of the specified types, or a list of such
* @return bool
* TRUE if $type is either one of the specified types or a list of such
* values. FALSE otherwise.
*
* @see search_api_extract_inner_type()
@@ -2060,7 +2117,7 @@ function search_api_is_text_type($type, array $allowed = array('text')) {
* @param $type
* A string containing the type to check.
*
* @return
* @return bool
* TRUE iff $type is a list type ("list<*>").
*/
function search_api_is_list_type($type) {
@@ -2073,7 +2130,7 @@ function search_api_is_list_type($type) {
* @param $type
* A string containing the type to check.
*
* @return
* @return int
* The nesting level of the type. 0 for singular types, 1 for lists of
* singular types, etc.
*/
@@ -2100,7 +2157,7 @@ function search_api_list_nesting_level($type) {
* @param $nested_type
* Another type, determining the nesting level.
*
* @return
* @return string
* A list version of $type, as specified above.
*/
function search_api_nest_type($type, $nested_type) {
@@ -2117,7 +2174,7 @@ function search_api_nest_type($type, $nested_type) {
* @param $type
* A string containing the list type to process.
*
* @return
* @return string
* A string containing the primitive type contained within the list, e.g.
* "text" for "list<text>" (or for "list<list<text>>"). If $type is no list
* type, it is returned unchanged.
@@ -2139,7 +2196,7 @@ function search_api_extract_inner_type($type) {
*
* Modules implementing other datasource controllers, that use a table other
* than {search_api_item}, can use this function, too. It should be called
* uncoditionally in a hook_search_api_index_update() implementation. If this
* unconditionally in a hook_search_api_index_update() implementation. If this
* function isn't used, similar code should be added there.
*
* However, note that this is only necessary (and this function should only be
@@ -2177,6 +2234,9 @@ function search_api_index_update_datasource(SearchApiIndex $index, $table, $colu
* The $fields array with additional "value" and "original_type" keys set.
*/
function search_api_extract_fields(EntityMetadataWrapper $wrapper, array $fields, array $value_options = array()) {
$value_options += array(
'identifier' => TRUE,
);
// If $wrapper is a list of entities, we have to aggregate their field values.
$wrapper_info = $wrapper->info();
if (search_api_is_list_type($wrapper_info['type'])) {
@@ -2214,19 +2274,31 @@ function search_api_extract_fields(EntityMetadataWrapper $wrapper, array $fields
$info['original_type'] = $info['type'];
if (isset($wrapper->$field)) {
try {
$info['value'] = $wrapper->$field->value($value_options);
// For fulltext fields with options, also include the option labels.
if (search_api_is_text_type($info['type']) && $wrapper->$field->optionsList('view')) {
_search_api_add_option_values($info['value'], $wrapper->$field->optionsList('view'));
}
// Set the original type according to the field wrapper's info.
$property_info = $wrapper->$field->info();
$info['original_type'] = $property_info['type'];
// For entities, we extract the entity ID instead of the whole object.
// @todo Use 'identifier' => TRUE instead of always loading the object.
$t = search_api_extract_inner_type($property_info['type']);
if (isset($entity_infos[$t])) {
// If no object is set, set this field to NULL.
$info['value'] = $info['value'] ? _search_api_extract_entity_value($wrapper->$field, search_api_is_text_type($info['type'])) : NULL;
// Extract the basic value from the field wrapper.
$info['value'] = $wrapper->$field->value($value_options);
// For entities, we need to take care to differentiate between
// entities with ID 0 and empty fields. In the latter case, the
// wrapper's value() method returns, when called with "identifier =
// TRUE", FALSE instead of the (more logical) NULL.
$is_entity = isset($entity_infos[search_api_extract_inner_type($property_info['type'])]);
if ($is_entity && $info['value'] === FALSE) {
$info['value'] = NULL;
}
// If we index the field as fulltext, we also include the entity label
// or option list label, if applicable.
if (search_api_is_text_type($info['type']) && isset($info['value'])) {
if ($wrapper->$field->optionsList('view')) {
_search_api_add_option_values($info['value'], $wrapper->$field->optionsList('view'));
}
elseif ($is_entity) {
$info['value'] = _search_api_extract_entity_value($wrapper->$field, TRUE);
}
}
}
catch (EntityMetadataWrapperException $e) {
@@ -2245,10 +2317,6 @@ function search_api_extract_fields(EntityMetadataWrapper $wrapper, array $fields
foreach ($nested as $prefix => $nested_fields) {
if (isset($wrapper->$prefix)) {
$nested_fields = search_api_extract_fields($wrapper->$prefix, $nested_fields, $value_options);
# http://drupal.org/node/1873910#comment-6876200
// $subwrapper = $wrapper->$prefix;
// $subwrapper->language( $wrapper->language->value() );
// $nested_fields = search_api_extract_fields($subwrapper, $nested_fields, $value_options);
foreach ($nested_fields as $field => $info) {
$fields["$prefix:$field"] = $info;
}
@@ -2385,7 +2453,7 @@ function search_api_access_disable_page(Entity $entity) {
* @param Entity $entity
* The server or index for which the access to the delete page is checked.
*
* @return
* @return bool
* TRUE if the delete page can be accessed by the user, FALSE otherwise.
*/
function search_api_access_delete_page(Entity $entity) {
@@ -2500,7 +2568,7 @@ function search_api_server_clear($id) {
* @param $id
* The ID or machine name of the server to delete.
*
* @return
* @return int|false
* 1 on success, 0 or FALSE on failure.
*/
function search_api_server_delete($id) {
@@ -2711,7 +2779,7 @@ function search_api_index_disable($id) {
* @param $id
* The ID or machine name of the index to re-index.
*
* @return
* @return bool
* TRUE on success, FALSE on failure.
*/
function search_api_index_reindex($id) {
@@ -2735,7 +2803,7 @@ function _search_api_index_reindex(SearchApiIndex $index) {
* @param $id
* The ID or machine name of the index to clear.
*
* @return
* @return bool
* TRUE on success, FALSE on failure.
*/
function search_api_index_clear($id) {
@@ -2749,7 +2817,7 @@ function search_api_index_clear($id) {
* @param $id
* The ID or machine name of the index to delete.
*
* @return
* @return bool
* TRUE on success, FALSE on failure.
*/
function search_api_index_delete($id) {
@@ -2778,6 +2846,66 @@ function search_api_index_options_list() {
return $ret;
}
/**
* Options list callback for entity types.
*
* Will only include entity types which specify entity property information.
*
* @return string[]
* An array of entity type machine names mapped to their human-readable
* names.
*/
function search_api_entity_type_options_list() {
$types = array();
foreach (array_keys(entity_get_property_info()) as $type) {
$info = entity_get_info($type);
if ($info) {
$types[$type] = $info['label'];
}
}
return $types;
}
/**
* Options list callback for entity type bundles.
*
* Will include all bundles for all entity types which specify entity property
* information, in a format combining both entity type and bundle.
*
* @return string[]
* An array of bundle identifiers mapped to their human-readable names.
*/
function search_api_combined_bundle_options_list() {
$types = array();
foreach (array_keys(entity_get_property_info()) as $type) {
$info = entity_get_info($type);
if (!empty($info['bundles'])) {
foreach ($info['bundles'] as $bundle => $bundle_info) {
$types["$type:$bundle"] = $bundle_info['label'];
}
}
}
return $types;
}
/**
* Retrieves a human-readable label for a multi-type index item.
*
* Provided as a non-object alternative to
* SearchApiCombinedEntityDataSourceController::getItemLabel() so it can be used
* as a getter callback.
*
* @param object $item
* An item of the "multiple" item type.
*
* @return string|null
* Either a human-readable label for the item, or NULL if none is available.
*/
function search_api_get_multi_type_item_label($item) {
$label = entity_label($item->item_type, $item->{$item->item_type});
return $label ? $label : NULL;
}
/**
* Shutdown function which indexes all queued items, if any.
*/
@@ -2894,6 +3022,42 @@ function _search_api_deep_copy(array $array) {
return $copy;
}
/**
* Reacts to a change in the bundle of an entity.
*
* Used as a helper function in search_api_entity_update().
*
* @param $type
* The entity's type.
* @param $id
* The entity's ID.
* @param $old_bundle
* The entity's previous bundle.
* @param $new_bundle
* The entity's new bundle.
*/
function _search_api_entity_datasource_bundle_change($type, $id, $old_bundle, $new_bundle) {
$controller = search_api_get_datasource_controller($type);
$conditions = array(
'enabled' => 1,
'item_type' => $type,
'read_only' => 0,
);
foreach (search_api_index_load_multiple(FALSE, $conditions) as $index) {
if (!empty($index->options['datasource']['bundles'])) {
$bundles = drupal_map_assoc($index->options['datasource']['bundles']);
if (empty($bundles[$new_bundle]) != empty($bundles[$old_bundle])) {
if (empty($bundles[$new_bundle])) {
$controller->trackItemDelete(array($id), array($index));
}
else {
$controller->trackItemInsert(array($id), array($index));
}
}
}
}
}
/**
* Creates and sets a batch for indexing items.
*
@@ -3010,7 +3174,7 @@ function _search_api_batch_indexing_callback(SearchApiIndex $index, $batch_size,
* @param boolean $success
* Whether the batch finished successfully.
* @param array $results
* Detailed informations about the result.
* Detailed information about the result.
*/
function _search_api_batch_indexing_finished($success, $results) {
// Check if called from drush.
@@ -830,6 +830,7 @@ class SearchApiUnitTest extends DrupalWebTestCase {
$this->index = entity_create('search_api_index', array(
'id' => 1,
'name' => 'test',
'machine_name' => 'test',
'enabled' => 1,
'item_type' => 'user',
'options' => array(
@@ -859,6 +860,7 @@ class SearchApiUnitTest extends DrupalWebTestCase {
$this->checkIgnoreCaseProcessor();
$this->checkTokenizer();
$this->checkHtmlFilter();
$this->checkEntityDatasource();
}
/**
@@ -1122,4 +1124,75 @@ END;
$this->assertEqual($tmp[1]['name']['value'], $processed1, 'Text was correctly processed.');
}
/**
* Tests the entity datasource controller and its bundle setting.
*/
protected function checkEntityDatasource() {
// First, create the necessary content types.
$type = (object) array(
'type' => 'article',
'base' => 'article',
);
node_type_save($type);
$type->type = $type->base = 'page';
node_type_save($type);
// Now, create some nodes.
$node = (object) array(
'title' => 'Foo',
'type' => 'article',
);
node_save($node);
$nid1 = $node->nid;
$node = (object) array(
'title' => 'Bar',
'type' => 'article',
);
node_save($node);
$node = (object) array(
'title' => 'Baz',
'type' => 'page',
);
node_save($node);
// We can't use $this->index here, since users don't have bundles.
$index = entity_create('search_api_index', array(
'id' => 2,
'name' => 'test2',
'machine_name' => 'test2',
'enabled' => 1,
'item_type' => 'node',
'options' => array(
'fields' => array(
'nid' => array(
'type' => 'integer',
),
),
),
));
// Now start tracking and check whether the index status is correct.
$datasource = search_api_get_datasource_controller('node');
$datasource->startTracking(array($index));
$status = $datasource->getIndexStatus($index);
$this->assertEqual($status['total'], 3, 'Correct number of items marked for indexing on not bundle-specific index.');
$datasource->stopTracking(array($index));
// Once again, but with only indexing articles.
$index->options['datasource']['bundles'] = array('article');
drupal_static_reset('search_api_get_datasource_controller');
$datasource = search_api_get_datasource_controller('node');
$datasource->startTracking(array($index));
$status = $datasource->getIndexStatus($index);
$this->assertEqual($status['total'], 2, 'Correct number of items marked for indexing on bundle-specific index.');
$datasource->stopTracking(array($index));
// Now test that bundle renaming works.
$index->save();
field_attach_rename_bundle('node', 'article', 'foo');
$index = search_api_index_load('test2', TRUE);
$this->assertEqual($index->options['datasource']['bundles'], array('foo'), 'Bundle was correctly renamed in index settings.');
$index->delete();
}
}
@@ -10,9 +10,9 @@ files[] = search_api_test.module
hidden = TRUE
; Information added by Drupal.org packaging script on 2014-12-26
version = "7.x-1.14"
; Information added by Drupal.org packaging script on 2016-02-26
version = "7.x-1.16+29-dev"
core = "7.x"
project = "search_api"
datestamp = "1419580682"
datestamp = "1456500713"
@@ -1,4 +1,56 @@
Search API Solr search 1.6 (09/08/2014):
Search API Solr Search 1.x, dev (xxxx-xx-xx):
---------------------------------------------
- #2645366 by tedfordgif, drunken monkey: Fixed browser incorrectly filling the
HTTP Auth form fields.
- #2611716 by aditya_anurag, drunken monkey: Improved the method documentation
comments.
- #2599658 by Loparev, drunken monkey: Added the possibility to highlight
non-fulltext fields.
- #2598288 by ethan.han777, JeroenT, drunken monkey: Fixed potential notices in
the spellchecker code.
- #2564927 by thePanz: Added support for random sorting in grouped searches.
- #2527528 by maximpodorov, drunken monkey: Fixed searching of string fields
with leading/trailing spaces.
- #2513314 by fortis, drunken monkey: Fixed error for empty filters.
- #2551763 by drunken monkey: Fixed mention of INSTALL.txt in an error message.
Search API Solr Search 1.9 (2015-08-30):
----------------------------------------
- #2503829 by das-peter: Added support for grouping on "magic" fields.
- #2503617 by tobiasb: Fixed undefined "status_message" property in HTTP
response object.
- #2313591 by thePanz, nadavoid: Added support for random sorting.
- #2004596 by drunken monkey: Fixed workarounds for MLT problems.
- #2486533 by drunken monkey: Fixed the default operator in the Solr 5 configs.
- #2466897 by drunken monkey: Fixed Solr version options in server settings.
- #1918904 by arnested, ramlev, drunken monkey: Added an alter hook for
autocomplete suggestions.
- #2532812 by drunken monkey: Improved performance for filter-only queries.
- #2463523 by bmunslow: Fixed field boosts in multi-index searches.
Search API Solr Search 1.8 (2015-06-15):
----------------------------------------
- #2502511 by drunken monkey: Fixed index removal on Solr 5.
- #2441117 by drunken monkey: Fixed unnecessary reindexing after changing
fields' boosts.
Search API Solr Search 1.7 (2015-06-08):
----------------------------------------
- #2466489 by drunken monkey: Changed installation instructions to point to the
handbook.
- #2486533 by drunken monkey: Fixed default operator in Solr 5.
- #2456159 by drunken monkey: Updated config files to their latest version from
the common configs.
- #2442077 by drunken monkey, basvredeling: Added support for Solr 5.
- #2451037 by drunken monkey: Fixed timeout errors during indexing.
- #2054551 by paolomainardi, drunken monkey, lex0r: Added possibility to
retrieve Solr field values in multi-index searches.
- #1908990 by drunken monkey: Fixed various issues with excerpts.
- #2368399 by das-peter, drunken monkey: Added Support for location filtering
with a bounding box.
- #2333133 by drunken monkey: Fixed behavior of filters on fulltext fields.
Search API Solr Search 1.6 (2014-09-08):
----------------------------------------
- #2050961 by das-peter, drunken monkey: Added proximity/distance information
to search results.
@@ -10,7 +62,7 @@ Search API Solr search 1.6 (09/08/2014):
- #2270767 by RaF: Fixed search_api_solr_views_data_alter() not always
returning all virtual fields.
Search API Solr search 1.5 (05/23/2014):
Search API Solr Search 1.5 (2014-05-23):
----------------------------------------
- #2216895 by das-peter: Added support for empty/non-empty conditions on
location field types.
@@ -30,7 +82,7 @@ Search API Solr search 1.5 (05/23/2014):
only” queries.
- #2147573 by drunken monkey: Improved error handling.
Search API Solr search 1.4 (12/25/2013):
Search API Solr Search 1.4 (2013-12-25):
----------------------------------------
- #2157839 by drunken monkey, Nick_vh: Updated config files to the newest
version.
@@ -48,7 +100,7 @@ Search API Solr search 1.4 (12/25/2013):
- #2064377 by Nick_vh: Made configuration files compatible with Solr Cloud.
- #2107417 by Nick_vh: Fixed config files for Solr 4.5.
Search API Solr search 1.3 (10/23/2013):
Search API Solr Search 1.3 (2013-10-23):
----------------------------------------
- #2099683 by drunken monkey: Added support for 'virtual fields' in Views.
- #1997702 by ianthomas_uk, drunken monkey: Added "AUTO" mode for HTTP method.
@@ -58,7 +110,7 @@ Search API Solr search 1.3 (10/23/2013):
- #1882190 by corvus_ch, arnested, drunken monkey: Added optional index ID
prefixes.
Search API Solr search 1.2 (09/01/2013):
Search API Solr Search 1.2 (2013-09-01):
----------------------------------------
- #1246730 by febbraro, maciej.zgadzaj, drunken monkey: Added a way to alter
the Solr document when indexing.
@@ -69,7 +121,7 @@ Search API Solr search 1.2 (09/01/2013):
- #2045355 by drunken monkey, arpieb: Fixed result mapping of item IDs.
- #2050157 by izus: Fixed typo in stopwords.txt.
Search API Solr search 1.1 (07/21/2013):
Search API Solr Search 1.1 (2013-07-21):
----------------------------------------
- #1957730 by drunken monkey: Fixed filter query strings for negated filters.
- #2010818 by kenorb, drunken monkey: Added new Files tab showing all used solr
@@ -84,7 +136,7 @@ Search API Solr search 1.1 (07/21/2013):
multi-valued fields.
- #2008034 by bdecarne: Fixed highlighting in multi-index searches.
Search API Solr search 1.0 (06/09/2013):
Search API Solr Search 1.0 (2013-06-09):
----------------------------------------
- #1896080 by drunken monkey: Included additional required config files in the
module.
@@ -98,7 +150,7 @@ Search API Solr search 1.0 (06/09/2013):
support.
- #1549244 by cferthorney, drunken monkey: Added SSL Support for Solr servers.
Search API Solr search 1.0, RC 5 (05/17/2013):
Search API Solr Search 1.0, RC 5 (2013-05-17):
----------------------------------------------
- #1190462 by drunken monkey: Documented that enabling HTML filter makes sense.
- #1986284 by drunken monkey: Updated common configs to the latest version.
@@ -112,7 +164,7 @@ Search API Solr search 1.0, RC 5 (05/17/2013):
- #1978600 by chaby: Fixed hook_requirements() for install phase.
- #1976930 by drunken monkey: Fixed duplicate method in SearchApiSolrField.
Search API Solr search 1.0, RC 4 (04/22/2013):
Search API Solr Search 1.0, RC 4 (2013-04-22):
----------------------------------------------
- #1744250 by mollux, drunken monkey, das-peter: Added support for
location-based searches.
@@ -122,7 +174,7 @@ Search API Solr search 1.0, RC 4 (04/22/2013):
- #1900644 by Deciphered: Fixed facet handling for multi-index searches.
- #1897386 by drunken monkey, NIck_vh: Update the common schema.
Search API Solr search 1.0, RC 3 (01/06/2013):
Search API Solr Search 1.0, RC 3 (2013-01-06):
----------------------------------------------
- #1828260 by drunken monkey: Fixed filtering by index in multi-index searches.
- #1509380 by drunken monkey: Adopt common config files.
@@ -141,7 +193,7 @@ Search API Solr search 1.0, RC 3 (01/06/2013):
- #1299940 by drunken monkey: Fixed handling of empty response.
- #1507818 by larowlan: Fixed field boosts for standard request handler.
Search API Solr search 1.0, RC 2 (05/23/2012):
Search API Solr Search 1.0, RC 2 (2012-05-23):
----------------------------------------------
- Fixed escaping of error messages.
- #1480170 by kotnik: Fixed return value of hook_requirements().
@@ -151,14 +203,14 @@ Search API Solr search 1.0, RC 2 (05/23/2012):
- #1302406 by Steven Jones: Fixed autoload problem during installation.
- #1340244 by drunken monkey, alanomaly: Added more helpful error messages.
Search API Solr search 1.0, RC 1 (11/10/2011):
Search API Solr Search 1.0, RC 1 (2011-11-10):
----------------------------------------------
- #1308638 by drunken monkey: Adapted to new structure of field settings.
- #1308498 by zenlan, drunken monkey: Added flexibility for facet fields.
- #1319544 by drunken monkey: Fixed never delete contents of read-only indexes.
- #1309650 by jonhattan, drunken monkey: Added support for the Libraries API.
Search API Solr search 1.0, Beta 4 (09/08/2011):
Search API Solr Search 1.0, Beta 4 (2011-09-08):
------------------------------------------------
- #1230536 by thegreat, drunken monkey: Added support for OR facets.
- #1184002 by drunken monkey: Fixed support of the latest SolrPhpClient version.
@@ -181,7 +233,7 @@ Search API Solr search 1.0, Beta 4 (09/08/2011):
- #1184002 by drunken monkey: Fixed INSTALL.txt to reflect that the module
doesn't work with the latest Solr PHP Client version.
Search API Solr search 1.0, Beta 3 (06/06/2011):
Search API Solr Search 1.0, Beta 3 (2011-06-06):
------------------------------------------------
- #1111852 by miiimooo, drunken monkey: Added a 'More like this' feature.
- #1153306 by JoeMcGuire, drunken monkey: Added spellchecking support.
@@ -191,7 +243,7 @@ Search API Solr search 1.0, Beta 3 (06/06/2011):
- #1110820 by becw, drunken monkey: Added support for the Luke request handler.
- #1095956 by drunken monkey: Added Solr-specific index alter hook.
Search API Solr search 1.0, Beta 2 (03/04/2011):
Search API Solr Search 1.0, Beta 2 (2011-03-04):
------------------------------------------------
- #1071894 by drunken monkey: Fixed incorrect handling of boolean facets.
- #1071796: Add additional help for Solr-specific extensions.
@@ -204,7 +256,7 @@ Search API Solr search 1.0, Beta 2 (03/04/2011):
- #915174: Remove unnecessary files[] declarations from .info file.
- #984134: Add Solr-specific query alter hooks.
Search API Solr search 1.0, Beta 1 (11/29/2010):
Search API Solr Search 1.0, Beta 1 (2010-11-29):
------------------------------------------------
Basic functionality is in place and quite well-tested, including support for
facets and for multi-index searches.
@@ -1,72 +0,0 @@
Setting up Solr
---------------
In order for this module to work, you will first need to set up a Solr server.
For this, you can either purchase a server from a web Solr hosts or set up your
own Solr server on your web server (if you have the necessary rights to do so).
If you want to use a hosted solution, a number of companies are listed on the
module's project page [1]. Otherwise, please follow the instructions below.
A more detailed set of instructions is available at [2].
[1] https://drupal.org/project/search_api_solr
[2] https://drupal.org/node/1999310
As a pre-requisite for running your own Solr server, you'll need Java 6 or
higher.
Download the latest version of Solr 4.x from [3] and unpack the archive
somewhere outside of your web server's document tree.
[3] http://www.apache.org/dyn/closer.cgi/lucene/solr/
This module also supports Solr 3.x. For better performance and more features,
4.x should be used, though.
For small websites, using the example application, located in $SOLR/example/,
usually suffices. In any case, you can use it for developing and testing. The
following instructions will assume you are using the example application,
otherwise you should be able to substitute the corresponding paths.
CAUTION! For production sites, it is vital that you somehow prevent outside
access to the Solr server. Otherwise, attackers could read, corrupt or delete
all your indexed data. Using the example server WON'T prevent this by default.
If it is available, the probably easiest way of preventing this is to disable
outside access to the ports used by Solr through your server's network
configuration or through the use of a firewall.
Other options include adding basic HTTP authentication or renaming the solr/
directory to a random string of characters and using that as the path.
Before starting the Solr server you will have to make sure it uses the proper
configuration files. These are located in the solr-conf/ directory in this
module, in a sub-directory according to the Solr version you are using. Copy all
the files from that directory into Solr's configuration directory
($SOLR/example/solr/collection1/conf/ in case of the 4.x example application),
after backing up all files that would be overwritten.
NOTE: The mapping-ISOLatin1Accent.txt is only included in the module for
completeness' sake, as it is required to start the Solr server. It will be
usually advisable to just use the file of the example application in this case,
though, as it contains really useful definitions, while the file provided with
this module is empty, apart from some documentation. For licensing reasons, it
is not possible for us to include the definitions in the example config file in
the copy this module provides.
You can then start Solr. For the example application, go to $SOLR/example/ and
issue the following command (assuming Java is correctly installed):
java -jar start.jar &
Afterwards, go to [4] in your web browser to ensure Solr is running correctly.
[4] http://localhost:8983/solr/
You can then enable this module and create a new server, using the "Solr search"
service class. Enter the hostname, port and path corresponding to your Solr
server in the appropriate fields. The default values already correspond to the
example application, so you won't have to change the values if you use that.
If you are using HTTP Authentication to protect your Solr server you also have
to provide the appropriate user and password here.
NOTE: For Solr 4.x, the server's path should also contain the Solr core name.
E.g., when using the example application unchanged, set the path to
"/solr/collection1" instead of "/solr".
@@ -2,12 +2,10 @@ Solr search
-----------
This module provides an implementation of the Search API which uses an Apache
Solr search server for indexing and searching. Before enabling or using this
module, you'll have to follow the instructions given in INSTALL.txt first.
Solr search server for indexing and searching. You can find detailed
instructions for setting up Solr in the module's handbook [1].
For more detailed documentation, see the handbook [1].
[1] https://drupal.org/node/1999280
[1] https://www.drupal.org/node/1999280
Supported optional features
---------------------------
@@ -139,6 +137,11 @@ Hidden variables
what you are doing. Old indexed items will be lost when the hash is changed
and all items will have to be reindexed. Can only contain alphanumeric
characters.
- search_api_solr_highlight_prefix (default: "tm_")
The prefix of Solr fields for which field-level highlighting will be enabled.
Since the prefix of fields is used to determine the field type (by default),
this lets you enable highlighting for other field types. By default,
highlighting will be possible for all fulltext fields.
[8] http://wiki.apache.org/solr/UpdateXmlMessages#A.22commit.22_and_.22optimize.22
@@ -57,7 +57,7 @@ class SearchApiSolrService extends SearchApiAbstractService {
protected $request_handler = NULL;
/**
* Overrides SearchApiAbstractService::configurationForm().
* {@inheritdoc}
*/
public function configurationForm(array $form, array &$form_state) {
if ($this->options) {
@@ -176,6 +176,10 @@ class SearchApiSolrService extends SearchApiAbstractService {
'#type' => 'textfield',
'#title' => t('Username'),
'#default_value' => $options['http_user'],
// This prefix with no-op text and password field will keep most browsers
// from autocompleting these fields, which is hardly ever what the user
// wants.
'#prefix' => '<input type="text" style="display:none" /><input type="password" style="display:none" />',
);
$form['http']['http_pass'] = array(
'#type' => 'password',
@@ -222,9 +226,9 @@ class SearchApiSolrService extends SearchApiAbstractService {
'#description' => t('Specify the Solr version manually in case it cannot be retrived automatically. The version can be found in the Solr admin interface under "Solr Specification Version" or "solr-spec"'),
'#options' => array(
'' => t('Determine automatically'),
'1' => '1.4',
'3' => '3.x',
'4' => '4.x',
'5' => '5.x',
),
'#default_value' => $options['solr_version'],
);
@@ -271,7 +275,7 @@ class SearchApiSolrService extends SearchApiAbstractService {
}
/**
* Overrides SearchApiAbstractService::configurationFormValidate().
* {@inheritdoc}
*/
public function configurationFormValidate(array $form, array &$values, array &$form_state) {
if (isset($values['port']) && (!is_numeric($values['port']) || $values['port'] < 0 || $values['port'] > 65535)) {
@@ -280,7 +284,7 @@ class SearchApiSolrService extends SearchApiAbstractService {
}
/**
* Overrides SearchApiAbstractService::configurationFormSubmit().
* {@inheritdoc}
*/
public function configurationFormSubmit(array $form, array &$values, array &$form_state) {
// Since the form is nested into another, we can't simply use #parents for
@@ -321,6 +325,7 @@ class SearchApiSolrService extends SearchApiAbstractService {
'search_api_spellcheck',
'search_api_data_type_location',
'search_api_data_type_geohash',
'search_api_random_sort',
));
if (isset($supported[$feature])) {
return TRUE;
@@ -428,8 +433,8 @@ class SearchApiSolrService extends SearchApiAbstractService {
$status = 'error';
}
elseif (substr($stats_summary['@schema_version'], 0, 9) != 'drupal-4.') {
$variables['@url'] = url(drupal_get_path('module', 'search_api_solr') . '/INSTALL.txt');
$message = t('You are using an incompatible schema.xml configuration file. Please follow the instructions in the <a href="@url">INSTALL.txt</a> file for setting up Solr.', $variables);
$variables['@url'] = url('https://www.drupal.org/node/1999310');
$message = t('You are using an incompatible schema.xml configuration file. Please follow the instructions in <a href="@url">the handbook</a> for setting up Solr.', $variables);
drupal_set_message($message, 'error');
$status = 'error';
}
@@ -494,7 +499,7 @@ class SearchApiSolrService extends SearchApiAbstractService {
}
/**
* Overrides SearchApiAbstractService::addIndex().
* {@inheritdoc}
*/
public function addIndex(SearchApiIndex $index) {
if (module_exists('search_api_multi') && module_exists('search_api_views')) {
@@ -503,42 +508,39 @@ class SearchApiSolrService extends SearchApiAbstractService {
}
/**
* Overrides SearchApiAbstractService::fieldsUpdated().
* {@inheritdoc}
*/
public function fieldsUpdated(SearchApiIndex $index) {
if (module_exists('search_api_multi') && module_exists('search_api_views')) {
views_invalidate_cache();
}
return TRUE;
// Find out if anything changed enough to need re-indexing.
$old_fields = isset($index->original->options['fields']) ? $index->original->options['fields'] : array();
$new_fields = isset($index->options['fields']) ? $index->options['fields'] : array();
if (!$old_fields && !$new_fields) {
return FALSE;
}
if (array_diff_key($old_fields, $new_fields) || array_diff_key($new_fields, $old_fields)) {
return TRUE;
}
$old_field_names = $this->getFieldNames($index->original, TRUE);
$new_field_names = $this->getFieldNames($index, TRUE);
return $old_field_names != $new_field_names;
}
/**
* Overrides SearchApiAbstractService::removeIndex().
* {@inheritdoc}
*/
public function removeIndex($index) {
if (module_exists('search_api_multi') && module_exists('search_api_views')) {
views_invalidate_cache();
}
$index_id = is_object($index) ? $index->machine_name : $index;
// Only delete the index's data if the index isn't read-only.
if (!is_object($index) || empty($index->read_only)) {
$this->connect();
$index_id = $this->getIndexId($index_id);
// Since the index ID we use for indexing can contain arbitrary
// prefixes, we have to escape it for use in the query.
$index_id = call_user_func(array($this->connection_class, 'phrase'), $index_id);
$query = "index_id:$index_id";
if (!empty($this->options['site_hash'])) {
// We don't need to escape the site hash, as that consists only of
// alphanumeric characters.
$query .= ' hash:' . search_api_solr_site_hash();
}
$this->solr->deleteByQuery($query);
}
parent::removeIndex($index);
}
/**
* Implements SearchApiServiceInterface::indexItems().
* {@inheritdoc}
*/
public function indexItems(SearchApiIndex $index, array $items) {
$documents = array();
@@ -569,7 +571,9 @@ class SearchApiSolrService extends SearchApiAbstractService {
$doc->setField('site', $base_urls[$lang]);
}
// Now add all fields contained in the item, with dynamic fields.
// Now add all fields contained in the item, with dynamic fields. Also,
// gather the contents of all text fields to also add them to "content".
$text_content = '';
foreach ($item as $key => $field) {
// If the field is not known for the index, something weird has
// happened. We refuse to index the items and hope that the others are
@@ -585,8 +589,9 @@ class SearchApiSolrService extends SearchApiAbstractService {
$doc = NULL;
break;
}
$this->addIndexField($doc, $fields[$key], $field['value'], $field['type']);
$text_content[] = $this->addIndexField($doc, $fields[$key], $field['value'], $field['type']);
}
$doc->setField('content', implode("\n\n", array_filter($text_content)));
if ($doc) {
$documents[] = $doc;
@@ -643,6 +648,7 @@ class SearchApiSolrService extends SearchApiAbstractService {
$ret = array(
'search_api_id' => 'item_id',
'search_api_relevance' => 'score',
'search_api_random' => 'random',
);
// Add the names of any fields configured on the index.
@@ -692,30 +698,32 @@ class SearchApiSolrService extends SearchApiAbstractService {
* is the same as specified in SearchApiServiceInterface::indexItems().
*/
protected function addIndexField(SearchApiSolrDocument $doc, $key, $value, $type, $multi_valued = FALSE) {
$text_content = '';
// Don't index empty values (i.e., when field is missing).
if (!isset($value)) {
return;
return $text_content;
}
if (search_api_is_list_type($type)) {
$type = substr($type, 5, -1);
foreach ($value as $v) {
$this->addIndexField($doc, $key, $v, $type, TRUE);
$text_content .= $this->addIndexField($doc, $key, $v, $type, TRUE) . "\n\n";
}
return;
return trim($text_content);
}
switch ($type) {
case 'tokens':
foreach ($value as $v) {
$text_content .= $v['value'] . ' ';
$doc->addField($key, $v['value']);
}
return;
return trim($text_content);
case 'boolean':
$value = $value ? 'true' : 'false';
break;
case 'date':
$value = is_numeric($value) ? (int) $value : strtotime($value);
if ($value === FALSE) {
return;
return $text_content;
}
$value = format_date($value, 'custom', self::SOLR_DATE_FORMAT, 'UTC');
break;
@@ -732,6 +740,10 @@ class SearchApiSolrService extends SearchApiAbstractService {
else {
$doc->setField($key, $value);
}
if (search_api_is_text_type($type)) {
$text_content = $value;
}
return $text_content;
}
/**
@@ -764,6 +776,17 @@ class SearchApiSolrService extends SearchApiAbstractService {
*
* It is up to the caller to ensure $ids is a valid query when the method is
* called in this fashion.
*
* @param array|string $ids
* Either an array containing the ids of the items that should be deleted,
* or 'all' if all items should be deleted. Other formats might be
* recognized by implementing classes, but these are not standardized.
* @param SearchApiIndex $index
* The index from which items should be deleted, or NULL if all indexes on
* this server should be cleared (then, $ids has to be 'all').
*
* @throws SearchApiException
* If an error occurred while trying to delete the items.
*/
public function deleteItems($ids = 'all', SearchApiIndex $index = NULL) {
$this->connect();
@@ -790,13 +813,13 @@ class SearchApiSolrService extends SearchApiAbstractService {
if ($ids != 'all') {
$query[] = $query ? "($ids)" : $ids;
}
$this->solr->deleteByQuery($query ? implode(' ', $query) : '*:*');
$this->solr->deleteByQuery($query ? implode(' AND ', $query) : '*:*');
}
$this->scheduleCommit();
}
/**
* Implements SearchApiServiceInterface::search().
* {@inheritdoc}
*/
public function search(SearchApiQueryInterface $query) {
$time_method_called = microtime(TRUE);
@@ -820,10 +843,12 @@ class SearchApiSolrService extends SearchApiAbstractService {
$options = $query->getOptions();
$search_fields = $query->getFields();
// Get the index fields to be able to retrieve boosts.
$index_fields = $index->getFields();
$index_fields = $index->getFields() + array(
'search_api_relevance' => array('type' => 'decimal', 'indexed' => TRUE),
'search_api_id' => array('type' => 'integer', 'indexed' => TRUE),
);
$qf = array();
foreach ($search_fields as $f) {
$boost = '';
$boost = isset($index_fields[$f]['boost']) ? '^' . $index_fields[$f]['boost'] : '';
$qf[] = $fields[$f] . $boost;
}
@@ -845,6 +870,17 @@ class SearchApiSolrService extends SearchApiAbstractService {
if (substr($f, 0, 3) == 'ss_') {
$f = 'sort_' . substr($f, 3);
}
// The default Solr schema provides a virtual field named "random_SEED"
// that can be used to randomly sort the results; the field is available
// only at query-time.
if ($field == 'search_api_random') {
$params = $query->getOption('search_api_random_sort', array());
// Random seed: getting the value from parameters or computing a new one.
$seed = !empty($params['seed']) ? $params['seed'] : mt_rand();
$f = 'random_' . $seed;
}
$order = strtolower($order);
$sort[$field] = "$f $order";
}
@@ -862,11 +898,16 @@ class SearchApiSolrService extends SearchApiAbstractService {
$mlt_params['qt'] = 'mlt';
// The fields to look for similarities in.
$mlt_fl = array();
// Solr 4 (before 4.6) has a bug which results in numeric fields not being
// supported in MLT queries.
$mlt_no_numeric_fields = FALSE;
if ($version == 4) {
$system_info = $this->solr->getSystemInfo();
$mlt_no_numeric_fields = !isset($system_info->lucene->{'solr-spec-version'}) || version_compare($system_info->lucene->{'solr-spec-version'}, '4.6.0', '<');
}
foreach($mlt['fields'] as $f) {
// Solr 4 has a bug which results in numeric fields not being supported
// in MLT queries.
// Date fields don't seem to be supported at all.
if ($fields[$f][0] === 'd' || ($version == 4 && in_array($fields[$f][0], array('i', 'f')))) {
if ($fields[$f][0] === 'd' || ($mlt_no_numeric_fields && in_array($fields[$f][0], array('i', 'f')))) {
continue;
}
$mlt_fl[] = $fields[$f];
@@ -879,18 +920,40 @@ class SearchApiSolrService extends SearchApiAbstractService {
$id = $this->createId($index_id, $mlt['id']);
$id = call_user_func(array($this->connection_class, 'phrase'), $id);
$keys = 'id:' . $id;
// In (early versions of) Solr 5, facets aren't supported with MLT.
if ($version >= 5) {
$facet_params = array();
}
}
// Handle spatial filters.
if ($spatials = $query->getOption('search_api_location')) {
foreach ($spatials as $i => $spatial) {
if (empty($spatial['field']) || empty($spatial['lat']) || empty($spatial['lon'])) {
// Spatial options all need a field to do anything.
if (!isset($spatial['field'])) {
continue;
}
unset($radius);
$field = $fields[$spatial['field']];
$escaped_field = SearchApiSolrConnection::escapeFieldName($field);
// If proper bbox coordinates were given use them to filter.
if (isset($spatial['bbox'])) {
if ($version >= 4) {
$bbox = $spatial['bbox'];
$fq[] = $escaped_field . ':[' . (float) $bbox['bottom'] . ',' . (float) $bbox['left'] . ' TO ' . (float) $bbox['top'] . ',' . (float) $bbox['right'] . ']';
}
else {
$warnings[] = t('Filtering by a bounding box is not supported in Solr versions below 4.');
}
}
// Everything other than a bounding box filter requires a point, so stop
// here (for this option) if "lat" and "lon" aren't both set.
if (!isset($spatial['lat']) || !isset($spatial['lon'])) {
continue;
}
$point = ((float) $spatial['lat']) . ',' . ((float) $spatial['lon']);
// Prepare the filter settings.
@@ -1032,6 +1095,18 @@ class SearchApiSolrService extends SearchApiAbstractService {
if (substr($f, 0, 3) == 'ss_') {
$f = 'sort_' . substr($f, 3);
}
// The default Solr schema provides a virtual field named
// "random_SEED" that can be used to randomly sort the results;
// the field is available only at query-time.
if ($group_sort_field == 'search_api_random') {
$params = $query->getOption('search_api_random_sort', array());
// Random seed: getting the value from parameters or computing a
// new one.
$seed = !empty($params['seed']) ? $params['seed'] : mt_rand();
$f = 'random_' . $seed;
}
$order = strtolower($order);
$group_params['group.sort'][] = $f . ' ' . $order;
}
@@ -1275,8 +1350,8 @@ class SearchApiSolrService extends SearchApiAbstractService {
}
$output = '';
if (!empty($this->options['excerpt']) && !empty($response->highlighting->$id->spell)) {
foreach ($response->highlighting->$id->spell as $snippet) {
if (!empty($this->options['excerpt']) && !empty($response->highlighting->$id->content)) {
foreach ($response->highlighting->$id->content as $snippet) {
$snippet = strip_tags($snippet);
$snippet = preg_replace('/^.*>|<.*$/', '', $snippet);
$snippet = $this->formatHighlighting($snippet);
@@ -1288,8 +1363,10 @@ class SearchApiSolrService extends SearchApiAbstractService {
}
}
if (!empty($this->options['highlight_data'])) {
$prefix = variable_get('search_api_solr_highlight_prefix', 'tm_');
$prefix_length = strlen($prefix);
foreach ($field_mapping as $search_api_property => $solr_property) {
if (substr($solr_property, 0, 3) == 'tm_' && !empty($response->highlighting->$id->$solr_property)) {
if (substr($solr_property, 0, $prefix_length) == $prefix && !empty($response->highlighting->$id->$solr_property)) {
// Contrary to above, we here want to preserve HTML, so we just
// replace the [HIGHLIGHT] tags with the appropriate format.
$fields[$search_api_property] = $this->formatHighlighting($response->highlighting->$id->$solr_property);
@@ -1497,6 +1574,7 @@ class SearchApiSolrService extends SearchApiAbstractService {
protected function createFilterQueries(SearchApiQueryFilterInterface $filter, array $solr_fields, array $fields) {
$or = $filter->getConjunction() == 'OR';
$fq = array();
$prefix = '';
foreach ($filter->getFilters() as $f) {
if (is_array($f)) {
if (!isset($fields[$f[0]])) {
@@ -1508,10 +1586,10 @@ class SearchApiSolrService extends SearchApiAbstractService {
}
elseif ($f instanceof SearchApiQueryFilterInterface) {
$q = $this->createFilterQueries($f, $solr_fields, $fields);
if ($filter->getConjunction() != $f->getConjunction()) {
if ($filter->getConjunction() != $f->getConjunction() && count($q) > 1) {
// $or == TRUE means the nested filter has conjunction AND, and vice versa
$sep = $or ? ' ' : ' OR ';
$fq[] = count($q) == 1 ? reset($q) : '((' . implode(')' . $sep . '(', $q) . '))';
$fq[] = '((' . implode(')' . $sep . '(', $q) . '))';
}
else {
$fq = array_merge($fq, $q);
@@ -1520,15 +1598,20 @@ class SearchApiSolrService extends SearchApiAbstractService {
}
if (method_exists($filter, 'getTags')) {
foreach ($filter->getTags() as $tag) {
$tag = "{!tag=$tag}";
foreach ($fq as $i => $filter) {
$fq[$i] = $tag . $filter;
}
$prefix = "{!tag=$tag}";
// We can only apply one tag per filter.
break;
}
}
return ($or && count($fq) > 1) ? array('((' . implode(') OR (', $fq) . '))') : $fq;
if ($or && count($fq) > 1) {
$fq = array('((' . implode(') OR (', $fq) . '))');
}
if ($prefix) {
foreach ($fq as $i => $filter) {
$fq[$i] = $prefix . $filter;
}
}
return $fq;
}
/**
@@ -1550,7 +1633,6 @@ class SearchApiSolrService extends SearchApiAbstractService {
if ($value === NULL) {
return ($operator == '=' ? '*:* AND -' : '') . "$field:[* TO *]";
}
$value = trim($value);
$value = $this->formatFilterValue($value, search_api_extract_inner_type($field_info['type']));
switch ($operator) {
case '<>':
@@ -1584,6 +1666,8 @@ class SearchApiSolrService extends SearchApiAbstractService {
}
$value = format_date($value, 'custom', self::SOLR_DATE_FORMAT, 'UTC');
break;
case 'text':
return '(' . call_user_func(array($this->connection_class, 'escape'), $value) . ')';
}
return call_user_func(array($this->connection_class, 'phrase'), $value);
}
@@ -1652,7 +1736,7 @@ class SearchApiSolrService extends SearchApiAbstractService {
if (!empty($this->options['excerpt']) || !empty($this->options['highlight_data'])) {
$highlight_params['hl'] = 'true';
$highlight_params['hl.fl'] = 'spell';
$highlight_params['hl.fl'] = 'content';
$highlight_params['hl.simple.pre'] = '[HIGHLIGHT]';
$highlight_params['hl.simple.post'] = '[/HIGHLIGHT]';
$highlight_params['hl.snippets'] = 3;
@@ -1661,17 +1745,18 @@ class SearchApiSolrService extends SearchApiAbstractService {
}
if (!empty($this->options['highlight_data'])) {
$highlight_params['hl.fl'] = 'tm_*';
$highlight_params['hl.fl'] = variable_get('search_api_solr_highlight_prefix', 'tm_') . '*';
$highlight_params['hl.snippets'] = 1;
$highlight_params['hl.fragsize'] = 0;
if (!empty($this->options['excerpt'])) {
// If we also generate a "normal" excerpt, set the settings for the
// "spell" field (which we use to generate the excerpt) back to the
// "content" field (which we use to generate the excerpt) back to the
// above values.
$highlight_params['f.spell.hl.snippets'] = 3;
$highlight_params['f.spell.hl.fragsize'] = 70;
$highlight_params['f.content.hl.snippets'] = 3;
$highlight_params['f.content.hl.fragsize'] = 70;
// It regrettably doesn't seem to be possible to set hl.fl to several
// values, if one contains wild cards (i.e., "t_*,spell" wouldn't work).
// values, if one contains wild cards (i.e., "t_*,content" wouldn't
// work).
$highlight_params['hl.fl'] = '*';
}
}
@@ -1831,6 +1916,14 @@ class SearchApiSolrService extends SearchApiAbstractService {
$this->setRequestHandler($this->request_handler, $call_args);
}
$second_pass = !isset($this->options['autocorrect_suggest_words']) || $this->options['autocorrect_suggest_words'];
$alter_data = array(
'search' => $search,
'query' => $query,
'incomplete_key' => $incomplete_key,
'user_input' => $user_input,
);
for ($i = 0; $i < ($second_pass ? 2 : 1); ++$i) {
try {
// Send search request
@@ -1839,6 +1932,8 @@ class SearchApiSolrService extends SearchApiAbstractService {
$this->preQuery($call_args, $query);
$response = $this->solr->search($keys, $params, $http_method);
$alter_data['responses'][] = $response;
if (!empty($response->spellcheck->suggestions)) {
$replace = array();
foreach ($response->spellcheck->suggestions as $word => $data) {
@@ -1927,9 +2022,11 @@ class SearchApiSolrService extends SearchApiAbstractService {
}
// Change parameters for second query.
unset($params['facet.prefix']);
$keys = trim ($keys . ' ' . $incomplete_key);
$keys = trim($keys . ' ' . $incomplete_key);
}
drupal_alter('search_api_solr_autocomplete_suggestions', $suggestions, $alter_data);
return $suggestions;
}
@@ -1985,7 +2082,8 @@ class SearchApiSolrService extends SearchApiAbstractService {
$search_fields = $query->getFields();
$qf = array();
foreach ($search_fields as $f) {
$qf[] = $solr_fields[$f];
$boost = isset($fields[$f]['boost']) ? '^' . $fields[$f]['boost'] : '';
$qf[] = $solr_fields[$f] . $boost;
}
// Extract filters
@@ -1994,8 +2092,10 @@ class SearchApiSolrService extends SearchApiAbstractService {
// Restrict search to searched indexes.
$index_filter = array();
$indexes = array();
foreach ($query->getIndexes() as $index) {
$index_id = $this->getIndexId($index->machine_name);
$indexes[$index_id] = $index;
$index_filter[] = 'index_id:' . call_user_func(array($this->connection_class, 'phrase'), $index_id);
}
$fq[] = implode(' OR ', $index_filter);
@@ -2050,6 +2150,9 @@ class SearchApiSolrService extends SearchApiAbstractService {
if (!empty($highlight_params)) {
$params += $highlight_params;
}
if (!empty($this->options['retrieve_data'])) {
$params['fl'] = '*,score';
}
// Retrieve http method from server options.
$http_method = !empty($this->options['http_method']) ? $this->options['http_method'] : 'AUTO';
@@ -2074,16 +2177,44 @@ class SearchApiSolrService extends SearchApiAbstractService {
$results['results'] = array();
$tmp = array();
foreach ($response->response->docs as $id => $doc) {
if (isset($indexes[$doc->index_id])) {
$index = $indexes[$doc->index_id];
}
else {
$index = new SearchApiIndex(array('machine_name' => $doc->index_id));
}
$fields = $this->getFieldNames($index);
$field_options = $index->options['fields'];
$result = array(
'id' => $doc->item_id,
'id' => NULL,
'index_id' => $doc->index_id,
'score' => $doc->score,
'score' => NULL,
'fields' => array(),
);
$solr_id = $this->createId($doc->index_id, $result['id']);
$excerpt = $this->getExcerpt($response, $solr_id, $tmp, array());
$solr_id = $this->createId($doc->index_id, $doc->item_id);
foreach ($fields as $search_api_property => $solr_property) {
if (isset($doc->{$solr_property})) {
$result['fields'][$search_api_property] = $doc->{$solr_property};
// Date fields need some special treatment to become valid date values
// (i.e., timestamps) again.
if (isset($field_options[$search_api_property]['type'])
&& $field_options[$search_api_property]['type'] == 'date'
&& preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/', $result['fields'][$search_api_property])) {
$result['fields'][$search_api_property] = strtotime($result['fields'][$search_api_property]);
}
}
}
$excerpt = $this->getExcerpt($response, $solr_id, $result['fields'], $fields);
if ($excerpt) {
$result['excerpt'] = $excerpt;
}
// We can find the item id and score in the special 'search_api_*'
// properties. Mappings are provided for these properties in
// SearchApiSolrService::getFieldNames().
$result['id'] = $result['fields']['search_api_id'];
$result['score'] = $result['fields']['search_api_relevance'];
$results['results'][$id] = $result;
}
@@ -224,7 +224,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::ping().
* {@inheritdoc}
*/
public function ping($timeout = 2) {
$start = microtime(TRUE);
@@ -251,28 +251,28 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::setSoftCommit().
* {@inheritdoc}
*/
public function setSoftCommit($soft_commit) {
$this->soft_commit = (bool) $soft_commit;
}
/**
* Implements SearchApiSolrConnectionInterface::getSoftCommit().
* {@inheritdoc}
*/
public function getSoftCommit() {
return $this->soft_commit;
}
/**
* Implements SearchApiSolrConnectionInterface::setStreamContext().
* {@inheritdoc}
*/
public function setStreamContext($stream_context) {
$this->stream_context = $stream_context;
}
/**
* Implements SearchApiSolrConnectionInterface::getStreamContext().
* {@inheritdoc}
*/
public function getStreamContext() {
return $this->stream_context;
@@ -333,6 +333,9 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
/**
* Sets $this->luke with the metadata about the index from admin/luke.
*
* @param int $num_terms
* (optional) The number of "top terms" to return.
*/
protected function setLuke($num_terms = 0) {
if (empty($this->luke[$num_terms])) {
@@ -360,7 +363,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::getFields().
* {@inheritdoc}
*/
public function getFields($num_terms = 0) {
$fields = array();
@@ -371,7 +374,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::getLuke().
* {@inheritdoc}
*/
public function getLuke($num_terms = 0) {
if (!isset($this->luke[$num_terms])) {
@@ -381,7 +384,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::getSolrVersion().
* {@inheritdoc}
*/
public function getSolrVersion() {
// Allow for overrides by the user.
@@ -392,7 +395,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
$system_info = $this->getSystemInfo();
// Get our solr version number
if (isset($system_info->lucene->{'solr-spec-version'})) {
return $system_info->lucene->{'solr-spec-version'}[0];
return (int) $system_info->lucene->{'solr-spec-version'};
}
return 0;
}
@@ -430,7 +433,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::getStats().
* {@inheritdoc}
*/
public function getStats() {
if (!isset($this->stats)) {
@@ -440,7 +443,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::getStatsSummary().
* {@inheritdoc}
*/
public function getStatsSummary() {
$stats = $this->getStats();
@@ -506,7 +509,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::clearCache().
* {@inheritdoc}
*/
public function clearCache() {
if ($cid = $this->getCacheId()) {
@@ -545,7 +548,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::makeServletRequest().
* {@inheritdoc}
*/
public function makeServletRequest($servlet, array $params = array(), array $options = array()) {
// Add default params.
@@ -561,7 +564,19 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Central method for making a GET operation against this Solr Server
* Sends a GET request to the Solr server.
*
* @param string $url
* The URL to which the request should be sent.
* @param array $options
* Additional options for the request, as recognized by
* drupal_http_request().
*
* @return object
* The HTTP response, as returned by drupal_http_request().
*
* @throws SearchApiException
* If an error occurs, either during sending or on the server side.
*/
protected function sendRawGet($url, array $options = array()) {
$options['method'] = 'GET';
@@ -571,7 +586,19 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Central method for making a POST operation against this Solr Server
* Sends a PUT request to the Solr server.
*
* @param string $url
* The URL to which the request should be sent.
* @param array $options
* Additional options for the request, as recognized by
* drupal_http_request().
*
* @return object
* The HTTP response, as returned by drupal_http_request().
*
* @throws SearchApiException
* If an error occurs, either during sending or on the server side.
*/
protected function sendRawPost($url, array $options = array()) {
$options['method'] = 'POST';
@@ -588,6 +615,15 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
* Sends an HTTP request to Solr.
*
* This is just a wrapper around drupal_http_request().
*
* @param string $url
* The URL to which the request should be sent.
* @param array $options
* Additional options for the request, as recognized by
* drupal_http_request().
*
* @return object
* The HTTP response, as returned by drupal_http_request().
*/
protected function makeHttpRequest($url, array $options = array()) {
if (empty($options['method']) || $options['method'] == 'GET' || $options['method'] == 'HEAD') {
@@ -603,6 +639,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
$result = drupal_http_request($url, $options);
$result->status_message = isset($result->status_message) ? $result->status_message : '';
if (!isset($result->code) || $result->code < 0) {
$result->code = 0;
$result->status_message = 'Request failed';
@@ -630,12 +667,12 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::escape().
* {@inheritdoc}
*/
public static function escape($value, $version = 0) {
$replacements = array();
$specials = array('+', '-', '&&', '||', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', "\\");
$specials = array('+', '-', '&&', '||', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', "\\", 'AND', 'OR', 'NOT');
// Solr 4.x introduces regular expressions, making the slash also a special
// character.
if ($version >= 4) {
@@ -650,7 +687,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::escapePhrase().
* {@inheritdoc}
*/
public static function escapePhrase($value) {
$replacements['"'] = '\"';
@@ -659,14 +696,14 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::phrase().
* {@inheritdoc}
*/
public static function phrase($value) {
return '"' . self::escapePhrase($value) . '"';
}
/**
* Implements SearchApiSolrConnectionInterface::escapeFieldName().
* {@inheritdoc}
*/
public static function escapeFieldName($value) {
$value = str_replace(':', '\:', $value);
@@ -684,6 +721,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
* Additional query string to append to the URL.
*
* @return string
* The complete URL.
*/
protected function constructUrl($servlet, array $params = array(), $added_query_string = NULL) {
// PHP's built in http_build_query() doesn't give us the format Solr wants.
@@ -703,14 +741,14 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::getBaseUrl().
* {@inheritdoc}
*/
public function getBaseUrl() {
return $this->base_url;
}
/**
* Implements SearchApiSolrConnectionInterface::setBaseUrl().
* {@inheritdoc}
*/
public function setBaseUrl($url) {
$this->base_url = $url;
@@ -718,9 +756,9 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::update().
* {@inheritdoc}
*/
public function update($rawPost, $timeout = FALSE) {
public function update($rawPost, $timeout = 3600) {
if (empty($this->update_url)) {
// Store the URL in an instance variable since many updates may be sent
// via a single instance of this class.
@@ -734,7 +772,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::addDocuments().
* {@inheritdoc}
*/
public function addDocuments(array $documents, $overwrite = NULL, $commitWithin = NULL) {
$attr = '';
@@ -758,21 +796,21 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::commit().
* {@inheritdoc}
*/
public function commit($waitSearcher = TRUE, $timeout = 3600) {
return $this->optimizeOrCommit('commit', $waitSearcher, $timeout);
}
/**
* Implements SearchApiSolrConnectionInterface::deleteById().
* {@inheritdoc}
*/
public function deleteById($id, $timeout = 3600) {
return $this->deleteByMultipleIds(array($id), $timeout);
}
/**
* Implements SearchApiSolrConnectionInterface::deleteByMultipleIds().
* {@inheritdoc}
*/
public function deleteByMultipleIds(array $ids, $timeout = 3600) {
$rawPost = '<delete>';
@@ -786,7 +824,7 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::deleteByQuery().
* {@inheritdoc}
*/
public function deleteByQuery($rawQuery, $timeout = 3600) {
$rawPost = '<delete><query>' . htmlspecialchars($rawQuery, ENT_NOQUOTES, 'UTF-8') . '</query></delete>';
@@ -795,14 +833,14 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
}
/**
* Implements SearchApiSolrConnectionInterface::optimize().
* {@inheritdoc}
*/
public function optimize($waitSearcher = TRUE, $timeout = 3600) {
return $this->optimizeOrCommit('optimize', $waitSearcher, $timeout);
}
/**
* Sends an commit or optimize command to the Solr server.
* Sends a commit or optimize command to the Solr server.
*
* Will be synchronous unless $waitSearcher is set to FALSE.
*
@@ -900,26 +938,6 @@ class SearchApiSolrConnection implements SearchApiSolrConnectionInterface {
// search keys here. (With our normal service class, empty keys won't be
// set, but another module using this connection class might do that.)
unset($params['q'], $params['qf']);
// If we have filters set (which will nearly always be the case, since we
// have to filter by index), move them to the q.alt parameter where
// possible.
if (!empty($params['fq'])) {
$qalt = array();
foreach ($params['fq'] as $i => $fq) {
// Tagged and negative filters cannot be moved to q.alt.
if ($fq[0] !== '{' && $fq[0] !== '-') {
$qalt[] = "($fq)";
unset($params['fq'][$i]);
}
}
if ($qalt) {
$params['q.alt'] = implode(' ', $qalt);
}
if (empty($params['fq'])) {
unset($params['fq']);
}
}
}
// Build the HTTP query string. We have our own method for that since PHP's
@@ -158,8 +158,7 @@ interface SearchApiSolrConnectionInterface {
* @param string $rawPost
* The XML document to send to the Solr server's update service.
* @param int|false $timeout
* (optional) Maximum expected duration (in seconds). Defaults to not timing
* out.
* (optional) Maximum expected duration (in seconds).
*
* @return object
* A response object.
@@ -167,7 +166,7 @@ interface SearchApiSolrConnectionInterface {
* @throws SearchApiException
* If an error occurs during the service call
*/
public function update($rawPost, $timeout = FALSE);
public function update($rawPost, $timeout = 3600);
/**
* Adds an array of Solr Documents to the index all at once
@@ -229,7 +228,7 @@ interface SearchApiSolrConnectionInterface {
/**
* Sends a delete request for several documents, based on the document IDs.
*
* @param array $id
* @param array $ids
* The IDs of the documents which should be deleted. Expected to be UTF-8
* encoded.
* @param int|false $timeout
@@ -307,8 +306,8 @@ interface SearchApiSolrConnectionInterface {
*
* @param string $value
* The string to escape.
* @param string $version
* An integer representing major solr version release.
* @param int $version
* An integer representing the major solr version.
*
* @return string
* An escaped string suitable for passing to Solr.
@@ -23,8 +23,10 @@ class SearchApiSpellcheckSolr extends SearchApiSpellcheck {
if (isset($response->spellcheck->suggestions)) {
$suggestions = $response->spellcheck->suggestions;
foreach ($suggestions as $word => $data) {
foreach ($data->suggestion as $suggestion) {
$this->addSuggestion(new SearchApiSpellcheckSuggestion($word, $suggestion));
if (isset($data->suggestion)) {
foreach ($data->suggestion as $suggestion) {
$this->addSuggestion(new SearchApiSpellcheckSuggestion($word, $suggestion));
}
}
}
}
@@ -161,6 +161,24 @@ function search_api_solr_hook_search_api_data_type_info() {
);
}
/**
* Alter autocomplete suggestions returned from Solr servers.
*
* @param array $suggestions
* An array of suggestions to be altered, in the structure documented in
* SearchApiAutocompleteSuggesterInterface::getAutocompleteSuggestions().
* @param array $alter_data
* An associative array of data about the search, with the following keys:
* "search", "query", "incomplete_key", "user_input", which correspond to the
* arguments to SearchApiAutocompleteInterface::getAutocompleteSuggestions();
* and "responses", an array containing the Solr response objects used for
* constructing the suggestions.
*/
function hook_search_api_solr_autocomplete_suggestions_alter(array &$suggestions, array &$alter_data) {
// Always also suggest the original user input.
array_unshift($suggestions, trim($alter_data['user_input']));
}
/**
* @} End of "addtogroup hooks".
*/
@@ -11,9 +11,9 @@ files[] = includes/solr_connection.interface.inc
files[] = includes/solr_field.inc
files[] = includes/spellcheck.inc
; Information added by Drupal.org packaging script on 2014-09-08
version = "7.x-1.6"
; Information added by Drupal.org packaging script on 2016-02-23
version = "7.x-1.9+10-dev"
core = "7.x"
project = "search_api_solr"
datestamp = "1410186051"
datestamp = "1456233244"
@@ -10,7 +10,7 @@
http://wiki.apache.org/solr/SchemaXml
-->
<schema name="drupal-4.2-solr-3.x" version="1.3">
<schema name="drupal-4.3-solr-3.x" version="1.3">
<!-- attribute "name" is the name of this schema and is only used for display purposes.
Applications should change this to reflect the nature of the search collection.
version="1.2" is Solr's version number for the schema syntax and semantics. It should
@@ -211,6 +211,29 @@
<filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</analyzer>
<analyzer type="multiterm">
<charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="stopwords.txt"
enablePositionIncrements="true"
/>
<filter class="solr.WordDelimiterFilterFactory"
protected="protwords.txt"
generateWordParts="1"
generateNumberParts="1"
catenateWords="0"
catenateNumbers="0"
catenateAll="0"
splitOnCaseChange="1"
preserveOriginal="1"/>
<filter class="solr.LengthFilterFactory" min="2" max="100" />
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</analyzer>
</fieldType>
<!-- An unstemmed text field - good if one does not know the language of the field -->
@@ -248,6 +271,25 @@
<filter class="solr.LengthFilterFactory" min="2" max="100" />
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
<analyzer type="multiterm">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="stopwords.txt"
enablePositionIncrements="true"
/>
<filter class="solr.WordDelimiterFilterFactory"
protected="protwords.txt"
generateWordParts="1"
generateNumberParts="1"
catenateWords="0"
catenateNumbers="0"
catenateAll="0"
splitOnCaseChange="0"/>
<filter class="solr.LengthFilterFactory" min="2" max="100" />
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
<!-- Edge N gram type - for example for matching against queries with results
@@ -20,7 +20,7 @@
For more details about configurations options that may appear in
this file, see http://wiki.apache.org/solr/SolrConfigXml.
-->
<config name="drupal-4.2-solr-3.x">
<config name="drupal-4.3-solr-3.x">
<!-- In all configuration below, a prefix of "solr." for class names
is an alias that causes solr to search appropriate packages,
including org.apache.solr.(search|update|request|core|analysis)
@@ -871,6 +871,7 @@
</lst>
<arr name="last-components">
<str>spellcheck</str>
<str>elevator</str>
</arr>
</requestHandler>
@@ -10,7 +10,7 @@
http://wiki.apache.org/solr/SchemaXml
-->
<schema name="drupal-4.2-solr-4.x" version="1.3">
<schema name="drupal-4.3-solr-4.x" version="1.3">
<!-- attribute "name" is the name of this schema and is only used for display purposes.
Applications should change this to reflect the nature of the search collection.
version="1.2" is Solr's version number for the schema syntax and semantics. It should
@@ -211,6 +211,29 @@
<filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</analyzer>
<analyzer type="multiterm">
<charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="stopwords.txt"
enablePositionIncrements="true"
/>
<filter class="solr.WordDelimiterFilterFactory"
protected="protwords.txt"
generateWordParts="1"
generateNumberParts="1"
catenateWords="0"
catenateNumbers="0"
catenateAll="0"
splitOnCaseChange="1"
preserveOriginal="1"/>
<filter class="solr.LengthFilterFactory" min="2" max="100" />
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</analyzer>
</fieldType>
<!-- An unstemmed text field - good if one does not know the language of the field -->
@@ -248,6 +271,25 @@
<filter class="solr.LengthFilterFactory" min="2" max="100" />
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
<analyzer type="multiterm">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="stopwords.txt"
enablePositionIncrements="true"
/>
<filter class="solr.WordDelimiterFilterFactory"
protected="protwords.txt"
generateWordParts="1"
generateNumberParts="1"
catenateWords="0"
catenateNumbers="0"
catenateAll="0"
splitOnCaseChange="0"/>
<filter class="solr.LengthFilterFactory" min="2" max="100" />
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
<!-- Edge N gram type - for example for matching against queries with results
@@ -20,7 +20,7 @@
For more details about configurations options that may appear in
this file, see http://wiki.apache.org/solr/SolrConfigXml.
-->
<config name="drupal-4.2-solr-4.x" >
<config name="drupal-4.3-solr-4.x" >
<!-- In all configuration below, a prefix of "solr." for class names
is an alias that causes solr to search appropriate packages,
including org.apache.solr.(search|update|request|core|analysis)
@@ -880,6 +880,7 @@
</lst>
<arr name="last-components">
<str>spellcheck</str>
<str>elevator</str>
</arr>
</requestHandler>
@@ -1068,10 +1069,17 @@
<lst name="invariants">
<str name="qt">pinkPony</str>
<str name="q">solrpingquery</str>
<str name="omitHeader">false</str>
</lst>
<lst name="defaults">
<str name="echoParams">all</str>
</lst>
<!-- An optional feature of the PingRequestHandler is to configure the
handler with a "healthcheckFile" which can be used to enable/disable
the PingRequestHandler.
relative paths are resolved against the data dir
-->
<!-- <str name="healthcheckFile">server-enabled.txt</str> -->
</requestHandler>
<!-- Echo the request contents back to the client -->
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!--
This file allows you to boost certain search items to the top of search
results. You can find out an item's ID by searching directly on the Solr
server. The item IDs are in general constructed as follows:
Search API:
$document->id = $index_id . '-' . $item_id;
Apache Solr Search Integration:
$document->id = $site_hash . '/' . $entity_type . '/' . $entity->id;
If you want this file to be automatically re-loaded when a Solr commit takes
place (e.g., if you have an automatic script active which updates elevate.xml
according to newly-indexed data), place it into Solr's data/ directory.
Otherwise, place it with the other configuration files into the conf/
directory.
See http://wiki.apache.org/solr/QueryElevationComponent for more information.
-->
<elevate>
<!-- Example for ranking the node #1 first in searches for "example query": -->
<!--
<query text="example query">
<doc id="default_node_index-1" />
<doc id="7v3jsc/node/1" />
</query>
-->
<!-- Multiple <query> elements can be specified, contained in one <elevate>. -->
<!-- <query text="...">...</query> -->
</elevate>
@@ -0,0 +1,14 @@
# This file contains character mappings for the default fulltext field type.
# The source characters (on the left) will be replaced by the respective target
# characters before any other processing takes place.
# Lines starting with a pound character # are ignored.
#
# For sensible defaults, use the mapping-ISOLatin1Accent.txt file distributed
# with the example application of your Solr version.
#
# Examples:
# "À" => "A"
# "\u00c4" => "A"
# "\u00c4" => "\u0041"
# "æ" => "ae"
# "\n" => " "
@@ -0,0 +1,7 @@
#-----------------------------------------------------------------------
# This file blocks words from being operated on by the stemmer and word delimiter.
&amp;
&lt;
&gt;
&#039;
&quot;
@@ -0,0 +1,693 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!--
This is the Solr schema file. This file should be named "schema.xml" and
should be in the conf directory under the solr home
(i.e. ./solr/conf/schema.xml by default)
or located where the classloader for the Solr webapp can find it.
For more information, on how to customize this file, please see
http://wiki.apache.org/solr/SchemaXml
-->
<schema name="drupal-4.3-solr-5.x" version="1.5">
<!-- attribute "name" is the name of this schema and is only used for
display purposes. Applications should change this to reflect the nature
of the search collection.
version="1.2" is Solr's version number for the schema syntax and
semantics. It should not normally be changed by applications.
1.0: multiValued attribute did not exist, all fields are multiValued by
nature
1.1: multiValued attribute introduced, false by default
1.2: omitTermFreqAndPositions attribute introduced, true by default
except for text fields.
1.3: removed optional field compress feature
1.4: autoGeneratePhraseQueries attribute introduced to drive
QueryParser behavior when a single string produces multiple
tokens. Defaults to off for version >= 1.4
1.5: omitNorms defaults to true for primitive field types
(int, float, boolean, string...)
-->
<types>
<!-- field type definitions. The "name" attribute is
just a label to be used by field definitions. The "class"
attribute and any other attributes determine the real
behavior of the fieldType.
Class names starting with "solr" refer to java classes in the
org.apache.solr.analysis package.
-->
<!-- The StrField type is not analyzed, but indexed/stored verbatim.
- StrField and TextField support an optional compressThreshold which
limits compression (if enabled in the derived fields) to values which
exceed a certain size (in characters).
-->
<fieldType name="string" class="solr.StrField" sortMissingLast="true"/>
<!-- boolean type: "true" or "false" -->
<fieldType name="boolean" class="solr.BoolField" sortMissingLast="true"/>
<!--Binary data type. The data should be sent/retrieved in as Base64 encoded Strings -->
<fieldtype name="binary" class="solr.BinaryField"/>
<!-- The optional sortMissingLast and sortMissingFirst attributes are
currently supported on types that are sorted internally as strings.
- If sortMissingLast="true", then a sort on this field will cause documents
without the field to come after documents with the field,
regardless of the requested sort order (asc or desc).
- If sortMissingFirst="true", then a sort on this field will cause documents
without the field to come before documents with the field,
regardless of the requested sort order.
- If sortMissingLast="false" and sortMissingFirst="false" (the default),
then default lucene sorting will be used which places docs without the
field first in an ascending sort and last in a descending sort.
-->
<!-- numeric field types that can be sorted, but are not optimized for range queries -->
<fieldType name="integer" class="solr.TrieIntField" precisionStep="0" positionIncrementGap="0"/>
<fieldType name="float" class="solr.TrieFloatField" precisionStep="0" positionIncrementGap="0"/>
<fieldType name="long" class="solr.TrieLongField" precisionStep="0" positionIncrementGap="0"/>
<fieldType name="double" class="solr.TrieDoubleField" precisionStep="0" positionIncrementGap="0"/>
<!--
Note:
These should only be used for compatibility with existing indexes (created with older Solr versions)
or if "sortMissingFirst" or "sortMissingLast" functionality is needed. Use Trie based fields instead.
Numeric field types that manipulate the value into
a string value that isn't human-readable in its internal form,
but with a lexicographic ordering the same as the numeric ordering,
so that range queries work correctly.
-->
<fieldType name="sint" class="solr.TrieIntField" sortMissingLast="true"/>
<fieldType name="sfloat" class="solr.TrieFloatField" sortMissingLast="true"/>
<fieldType name="slong" class="solr.TrieLongField" sortMissingLast="true"/>
<fieldType name="sdouble" class="solr.TrieDoubleField" sortMissingLast="true"/>
<!--
Numeric field types that index each value at various levels of precision
to accelerate range queries when the number of values between the range
endpoints is large. See the javadoc for NumericRangeQuery for internal
implementation details.
Smaller precisionStep values (specified in bits) will lead to more tokens
indexed per value, slightly larger index size, and faster range queries.
A precisionStep of 0 disables indexing at different precision levels.
-->
<fieldType name="tint" class="solr.TrieIntField" precisionStep="8" positionIncrementGap="0"/>
<fieldType name="tfloat" class="solr.TrieFloatField" precisionStep="8" positionIncrementGap="0"/>
<fieldType name="tlong" class="solr.TrieLongField" precisionStep="8" positionIncrementGap="0"/>
<fieldType name="tdouble" class="solr.TrieDoubleField" precisionStep="8" positionIncrementGap="0"/>
<!--
The ExternalFileField type gets values from an external file instead of the
index. This is useful for data such as rankings that might change frequently
and require different update frequencies than the documents they are
associated with.
-->
<fieldType name="file" keyField="id" defVal="1" stored="false" indexed="false" class="solr.ExternalFileField" valType="float"/>
<!-- The format for this date field is of the form 1995-12-31T23:59:59Z, and
is a more restricted form of the canonical representation of dateTime
http://www.w3.org/TR/xmlschema-2/#dateTime
The trailing "Z" designates UTC time and is mandatory.
Optional fractional seconds are allowed: 1995-12-31T23:59:59.999Z
All other components are mandatory.
Expressions can also be used to denote calculations that should be
performed relative to "NOW" to determine the value, ie...
NOW/HOUR
... Round to the start of the current hour
NOW-1DAY
... Exactly 1 day prior to now
NOW/DAY+6MONTHS+3DAYS
... 6 months and 3 days in the future from the start of
the current day
Consult the TrieDateField javadocs for more information.
Note: For faster range queries, consider the tdate type
-->
<fieldType name="date" class="solr.TrieDateField" precisionStep="0" positionIncrementGap="0" sortMissingLast="true" omitNorms="true"/>
<!-- A Trie based date field for faster date range queries and date faceting. -->
<fieldType name="tdate" class="solr.TrieDateField" precisionStep="6" positionIncrementGap="0"/>
<!-- solr.TextField allows the specification of custom text analyzers
specified as a tokenizer and a list of token filters. Different
analyzers may be specified for indexing and querying.
The optional positionIncrementGap puts space between multiple fields of
this type on the same document, with the purpose of preventing false phrase
matching across fields.
For more info on customizing your analyzer chain, please see
http://wiki.apache.org/solr/AnalyzersTokenizersTokenFilters
-->
<!-- One can also specify an existing Analyzer class that has a
default constructor via the class attribute on the analyzer element
<fieldType name="text_greek" class="solr.TextField">
<analyzer class="org.apache.lucene.analysis.el.GreekAnalyzer"/>
</fieldType>
-->
<!-- A text field that only splits on whitespace for exact matching of words -->
<fieldType name="text_ws" class="solr.TextField" omitNorms="true" positionIncrementGap="100">
<analyzer>
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
<!-- A text field that uses WordDelimiterFilter to enable splitting and matching of
words on case-change, alpha numeric boundaries, and non-alphanumeric chars,
so that a query of "wifi" or "wi fi" could match a document containing "Wi-Fi".
Synonyms and stopwords are customized by external files, and stemming is enabled.
Duplicate tokens at the same position (which may result from Stemmed Synonyms or
WordDelim parts) are removed.
-->
<fieldType name="text" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
<charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<!-- in this example, we will only use synonyms at query time
<filter class="solr.SynonymFilterFactory" synonyms="index_synonyms.txt" ignoreCase="true" expand="false"/>
-->
<!-- Case insensitive stop word removal. -->
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="stopwords.txt"
/>
<filter class="solr.WordDelimiterFilterFactory"
protected="protwords.txt"
generateWordParts="1"
generateNumberParts="1"
catenateWords="1"
catenateNumbers="1"
catenateAll="0"
splitOnCaseChange="0"
preserveOriginal="1"/>
<filter class="solr.LengthFilterFactory" min="2" max="100" />
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</analyzer>
<analyzer type="query">
<charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="stopwords.txt"
/>
<filter class="solr.WordDelimiterFilterFactory"
protected="protwords.txt"
generateWordParts="1"
generateNumberParts="1"
catenateWords="0"
catenateNumbers="0"
catenateAll="0"
splitOnCaseChange="0"
preserveOriginal="1"/>
<filter class="solr.LengthFilterFactory" min="2" max="100" />
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</analyzer>
<analyzer type="multiterm">
<charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="stopwords.txt"
/>
<filter class="solr.WordDelimiterFilterFactory"
protected="protwords.txt"
generateWordParts="1"
generateNumberParts="1"
catenateWords="0"
catenateNumbers="0"
catenateAll="0"
splitOnCaseChange="1"
preserveOriginal="1"/>
<filter class="solr.LengthFilterFactory" min="2" max="100" />
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</analyzer>
</fieldType>
<!-- An unstemmed text field - good if one does not know the language of the field -->
<fieldType name="text_und" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" />
<filter class="solr.WordDelimiterFilterFactory"
protected="protwords.txt"
generateWordParts="1"
generateNumberParts="1"
catenateWords="1"
catenateNumbers="1"
catenateAll="0"
splitOnCaseChange="0"/>
<filter class="solr.LengthFilterFactory" min="2" max="100" />
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
<analyzer type="query">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="stopwords.txt"
/>
<filter class="solr.WordDelimiterFilterFactory"
protected="protwords.txt"
generateWordParts="1"
generateNumberParts="1"
catenateWords="0"
catenateNumbers="0"
catenateAll="0"
splitOnCaseChange="0"/>
<filter class="solr.LengthFilterFactory" min="2" max="100" />
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
<analyzer type="multiterm">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
<filter class="solr.StopFilterFactory"
ignoreCase="true"
words="stopwords.txt"
/>
<filter class="solr.WordDelimiterFilterFactory"
protected="protwords.txt"
generateWordParts="1"
generateNumberParts="1"
catenateWords="0"
catenateNumbers="0"
catenateAll="0"
splitOnCaseChange="0"/>
<filter class="solr.LengthFilterFactory" min="2" max="100" />
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
<!-- Edge N gram type - for example for matching against queries with results
KeywordTokenizer leaves input string intact as a single term.
see: http://www.lucidimagination.com/blog/2009/09/08/auto-suggest-from-popular-queries-using-edgengrams/
-->
<fieldType name="edge_n2_kw_text" class="solr.TextField" omitNorms="true" positionIncrementGap="100">
<analyzer type="index">
<tokenizer class="solr.KeywordTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.EdgeNGramFilterFactory" minGramSize="2" maxGramSize="25" />
</analyzer>
<analyzer type="query">
<tokenizer class="solr.KeywordTokenizerFactory"/>
<filter class="solr.LowerCaseFilterFactory"/>
</analyzer>
</fieldType>
<!-- Setup simple analysis for spell checking -->
<fieldType name="textSpell" class="solr.TextField" positionIncrementGap="100">
<analyzer>
<tokenizer class="solr.StandardTokenizerFactory" />
<filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
<filter class="solr.LengthFilterFactory" min="4" max="20" />
<filter class="solr.LowerCaseFilterFactory" />
<filter class="solr.RemoveDuplicatesTokenFilterFactory" />
</analyzer>
</fieldType>
<!-- This is an example of using the KeywordTokenizer along
With various TokenFilterFactories to produce a sortable field
that does not include some properties of the source text
-->
<fieldType name="sortString" class="solr.TextField" sortMissingLast="true" omitNorms="true">
<analyzer>
<!-- KeywordTokenizer does no actual tokenizing, so the entire
input string is preserved as a single token
-->
<tokenizer class="solr.KeywordTokenizerFactory"/>
<!-- The LowerCase TokenFilter does what you expect, which can be
when you want your sorting to be case insensitive
-->
<filter class="solr.LowerCaseFilterFactory" />
<!-- The TrimFilter removes any leading or trailing whitespace -->
<filter class="solr.TrimFilterFactory" />
<!-- The PatternReplaceFilter gives you the flexibility to use
Java Regular expression to replace any sequence of characters
matching a pattern with an arbitrary replacement string,
which may include back refrences to portions of the orriginal
string matched by the pattern.
See the Java Regular Expression documentation for more
infomation on pattern and replacement string syntax.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/package-summary.html
<filter class="solr.PatternReplaceFilterFactory"
pattern="(^\p{Punct}+)" replacement="" replace="all"
/>
-->
</analyzer>
</fieldType>
<!-- The "RandomSortField" is not used to store or search any
data. You can declare fields of this type it in your schema
to generate pseudo-random orderings of your docs for sorting
or function purposes. The ordering is generated based on the field
name and the version of the index. As long as the index version
remains unchanged, and the same field name is reused,
the ordering of the docs will be consistent.
If you want different psuedo-random orderings of documents,
for the same version of the index, use a dynamicField and
change the field name in the request.
-->
<fieldType name="rand" class="solr.RandomSortField" indexed="true" />
<!-- Fulltext type for matching words based on how they sound i.e.,
"phonetic matching".
-->
<fieldType name="phonetic" class="solr.TextField" >
<analyzer>
<tokenizer class="solr.StandardTokenizerFactory"/>
<filter class="solr.DoubleMetaphoneFilterFactory" inject="false"/>
</analyzer>
</fieldType>
<!-- since fields of this type are by default not stored or indexed,
any data added to them will be ignored outright. -->
<fieldType name="ignored" stored="false" indexed="false" multiValued="true" class="solr.StrField" />
<!-- This point type indexes the coordinates as separate fields (subFields)
If subFieldType is defined, it references a type, and a dynamic field
definition is created matching *___<typename>. Alternately, if
subFieldSuffix is defined, that is used to create the subFields.
Example: if subFieldType="double", then the coordinates would be
indexed in fields myloc_0___double,myloc_1___double.
Example: if subFieldSuffix="_d" then the coordinates would be indexed
in fields myloc_0_d,myloc_1_d
The subFields are an implementation detail of the fieldType, and end
users normally should not need to know about them.
-->
<fieldType name="point" class="solr.PointType" dimension="2" subFieldType="tdouble"/>
<!-- A specialized field for geospatial search. If indexed, this fieldType must not be multivalued. -->
<fieldType name="location" class="solr.LatLonType" subFieldType="tdouble"/>
<!-- A Geohash is a compact representation of a latitude longitude pair in a single field.
See http://wiki.apache.org/solr/SpatialSearch
-->
<fieldtype name="geohash" class="solr.GeoHashField"/>
<!-- Improved location type which supports advanced functionality like
filtering by polygons or other shapes, indexing shapes, multi-valued
fields, etc.
-->
<fieldType name="location_rpt" class="solr.SpatialRecursivePrefixTreeFieldType"
geo="true" distErrPct="0.025" maxDistErr="0.001" distanceUnits="kilometers" />
<!-- Spatial rectangle (bounding box) field. It supports most spatial predicates, and has
special relevancy modes: score=overlapRatio|area|area2D (local-param to the query). DocValues is recommended for
relevancy. -->
<fieldType name="bbox" class="solr.BBoxField"
geo="true" distanceUnits="kilometers" numberType="_bbox_coord" />
<fieldType name="_bbox_coord" class="solr.TrieDoubleField" precisionStep="8" docValues="true" stored="false"/>
</types>
<!-- Following is a dynamic way to include other types, added by other contrib modules -->
<xi:include href="schema_extra_types.xml" xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:fallback></xi:fallback>
</xi:include>
<!-- Valid attributes for fields:
name: mandatory - the name for the field
type: mandatory - the name of a field type from the <types> fieldType
section
indexed: true if this field should be indexed (searchable or sortable)
stored: true if this field should be retrievable
docValues: true if this field should have doc values. Doc values are
useful for faceting, grouping, sorting and function queries. Although not
required, doc values will make the index faster to load, more
NRT-friendly and more memory-efficient. They however come with some
limitations: they are currently only supported by StrField, UUIDField
and all Trie*Fields, and depending on the field type, they might
require the field to be single-valued, be required or have a default
value (check the documentation of the field type you're interested in
for more information)
multiValued: true if this field may contain multiple values per document
omitNorms: (expert) set to true to omit the norms associated with
this field (this disables length normalization and index-time
boosting for the field, and saves some memory). Only full-text
fields or fields that need an index-time boost need norms.
Norms are omitted for primitive (non-analyzed) types by default.
termVectors: [false] set to true to store the term vector for a
given field.
When using MoreLikeThis, fields used for similarity should be
stored for best performance.
termPositions: Store position information with the term vector.
This will increase storage costs.
termOffsets: Store offset information with the term vector. This
will increase storage costs.
required: The field is required. It will throw an error if the
value does not exist
default: a value that should be used if no value is specified
when adding a document.
-->
<fields>
<!-- The document id is usually derived from a site-spcific key (hash) and the
entity type and ID like:
Search Api :
The format used is $document->id = $index_id . '-' . $item_id
Apache Solr Search Integration
The format used is $document->id = $site_hash . '/' . $entity_type . '/' . $entity->id;
-->
<field name="id" type="string" indexed="true" stored="true" required="true" />
<!-- Add Solr Cloud version field as mentioned in
http://wiki.apache.org/solr/SolrCloud#Required_Config
-->
<field name="_version_" type="long" indexed="true" stored="true" multiValued="false"/>
<!-- Search Api specific fields -->
<!-- item_id contains the entity ID, e.g. a node's nid. -->
<field name="item_id" type="string" indexed="true" stored="true" />
<!-- index_id is the machine name of the search index this entry belongs to. -->
<field name="index_id" type="string" indexed="true" stored="true" />
<!-- copyField commands copy one field to another at the time a document
is added to the index. It's used either to index the same field differently,
or to add multiple fields to the same field for easier/faster searching. -->
<!-- Since sorting by ID is explicitly allowed, store item_id also in a sortable way. -->
<copyField source="item_id" dest="sort_search_api_id" />
<!-- Apache Solr Search Integration specific fields -->
<!-- entity_id is the numeric object ID, e.g. Node ID, File ID -->
<field name="entity_id" type="long" indexed="true" stored="true" />
<!-- entity_type is 'node', 'file', 'user', or some other Drupal object type -->
<field name="entity_type" type="string" indexed="true" stored="true" />
<!-- bundle is a node type, or as appropriate for other entity types -->
<field name="bundle" type="string" indexed="true" stored="true"/>
<field name="bundle_name" type="string" indexed="true" stored="true"/>
<field name="site" type="string" indexed="true" stored="true"/>
<field name="hash" type="string" indexed="true" stored="true"/>
<field name="url" type="string" indexed="true" stored="true"/>
<!-- label is the default field for a human-readable string for this entity (e.g. the title of a node) -->
<field name="label" type="text" indexed="true" stored="true" termVectors="true" omitNorms="true"/>
<!-- The string version of the title is used for sorting -->
<copyField source="label" dest="sort_label"/>
<!-- content is the default field for full text search - dump crap here -->
<field name="content" type="text" indexed="true" stored="true" termVectors="true"/>
<field name="teaser" type="text" indexed="false" stored="true"/>
<field name="path" type="string" indexed="true" stored="true"/>
<field name="path_alias" type="text" indexed="true" stored="true" termVectors="true" omitNorms="true"/>
<!-- These are the fields that correspond to a Drupal node. The beauty of having
Lucene store title, body, type, etc., is that we retrieve them with the search
result set and don't need to go to the database with a node_load. -->
<field name="tid" type="long" indexed="true" stored="true" multiValued="true"/>
<field name="taxonomy_names" type="text" indexed="true" stored="false" termVectors="true" multiValued="true" omitNorms="true"/>
<!-- Copy terms to a single field that contains all taxonomy term names -->
<copyField source="tm_vid_*" dest="taxonomy_names"/>
<!-- Here, default is used to create a "timestamp" field indicating
when each document was indexed.-->
<field name="timestamp" type="tdate" indexed="true" stored="true" default="NOW" multiValued="false"/>
<!-- This field is used to build the spellchecker index -->
<field name="spell" type="textSpell" indexed="true" stored="true" multiValued="true"/>
<!-- copyField commands copy one field to another at the time a document
is added to the index. It's used either to index the same field differently,
or to add multiple fields to the same field for easier/faster searching. -->
<copyField source="label" dest="spell"/>
<copyField source="content" dest="spell"/>
<copyField source="ts_*" dest="spell"/>
<copyField source="tm_*" dest="spell"/>
<!-- Dynamic field definitions. If a field name is not found, dynamicFields
will be used if the name matches any of the patterns.
RESTRICTION: the glob-like pattern in the name attribute must have
a "*" only at the start or the end.
EXAMPLE: name="*_i" will match any field ending in _i (like myid_i, z_i)
Longer patterns will be matched first. if equal size patterns
both match, the first appearing in the schema will be used. -->
<!-- A set of fields to contain text extracted from HTML tag contents which we
can boost at query time. -->
<dynamicField name="tags_*" type="text" indexed="true" stored="false" omitNorms="true"/>
<!-- For 2 and 3 letter prefix dynamic fields, the 1st letter indicates the data type and
the last letter is 's' for single valued, 'm' for multi-valued -->
<!-- We use long for integer since 64 bit ints are now common in PHP. -->
<dynamicField name="is_*" type="long" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="im_*" type="long" indexed="true" stored="true" multiValued="true"/>
<!-- List of floats can be saved in a regular float field -->
<dynamicField name="fs_*" type="float" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="fm_*" type="float" indexed="true" stored="true" multiValued="true"/>
<!-- List of doubles can be saved in a regular double field -->
<dynamicField name="ps_*" type="double" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="pm_*" type="double" indexed="true" stored="true" multiValued="true"/>
<!-- List of booleans can be saved in a regular boolean field -->
<dynamicField name="bm_*" type="boolean" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="bs_*" type="boolean" indexed="true" stored="true" multiValued="false"/>
<!-- Regular text (without processing) can be stored in a string field-->
<dynamicField name="ss_*" type="string" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="sm_*" type="string" indexed="true" stored="true" multiValued="true"/>
<!-- Normal text fields are for full text - the relevance of a match depends on the length of the text -->
<dynamicField name="ts_*" type="text" indexed="true" stored="true" multiValued="false" termVectors="true"/>
<dynamicField name="tm_*" type="text" indexed="true" stored="true" multiValued="true" termVectors="true"/>
<!-- Unstemmed text fields for full text - the relevance of a match depends on the length of the text -->
<dynamicField name="tus_*" type="text_und" indexed="true" stored="true" multiValued="false" termVectors="true"/>
<dynamicField name="tum_*" type="text_und" indexed="true" stored="true" multiValued="true" termVectors="true"/>
<!-- These text fields omit norms - useful for extracted text like taxonomy_names -->
<dynamicField name="tos_*" type="text" indexed="true" stored="true" multiValued="false" termVectors="true" omitNorms="true"/>
<dynamicField name="tom_*" type="text" indexed="true" stored="true" multiValued="true" termVectors="true" omitNorms="true"/>
<!-- Special-purpose text fields -->
<dynamicField name="tes_*" type="edge_n2_kw_text" indexed="true" stored="true" multiValued="false" omitTermFreqAndPositions="true" />
<dynamicField name="tem_*" type="edge_n2_kw_text" indexed="true" stored="true" multiValued="true" omitTermFreqAndPositions="true" />
<dynamicField name="tws_*" type="text_ws" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="twm_*" type="text_ws" indexed="true" stored="true" multiValued="true"/>
<!-- trie dates are preferred, so give them the 2 letter prefix -->
<dynamicField name="ds_*" type="tdate" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="dm_*" type="tdate" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="its_*" type="tlong" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="itm_*" type="tlong" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="fts_*" type="tfloat" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="ftm_*" type="tfloat" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="pts_*" type="tdouble" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="ptm_*" type="tdouble" indexed="true" stored="true" multiValued="true"/>
<!-- Binary fields can be populated using base64 encoded data. Useful e.g. for embedding
a small image in a search result using the data URI scheme -->
<dynamicField name="xs_*" type="binary" indexed="false" stored="true" multiValued="false"/>
<dynamicField name="xm_*" type="binary" indexed="false" stored="true" multiValued="true"/>
<!-- In rare cases a date rather than tdate is needed for sortMissingLast -->
<dynamicField name="dds_*" type="date" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="ddm_*" type="date" indexed="true" stored="true" multiValued="true"/>
<!-- Sortable fields, good for sortMissingLast support &
We use long for integer since 64 bit ints are now common in PHP. -->
<dynamicField name="iss_*" type="slong" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="ism_*" type="slong" indexed="true" stored="true" multiValued="true"/>
<!-- In rare cases a sfloat rather than tfloat is needed for sortMissingLast -->
<dynamicField name="fss_*" type="sfloat" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="fsm_*" type="sfloat" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="pss_*" type="sdouble" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="psm_*" type="sdouble" indexed="true" stored="true" multiValued="true"/>
<!-- In case a 32 bit int is really needed, we provide these fields. 'h' is mnemonic for 'half word', i.e. 32 bit on 64 arch -->
<dynamicField name="hs_*" type="integer" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="hm_*" type="integer" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="hss_*" type="sint" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="hsm_*" type="sint" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="hts_*" type="tint" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="htm_*" type="tint" indexed="true" stored="true" multiValued="true"/>
<!-- Unindexed string fields that can be used to store values that won't be searchable -->
<dynamicField name="zs_*" type="string" indexed="false" stored="true" multiValued="false"/>
<dynamicField name="zm_*" type="string" indexed="false" stored="true" multiValued="true"/>
<!-- Fields for location searches.
http://wiki.apache.org/solr/SpatialSearch#geodist_-_The_distance_function -->
<dynamicField name="points_*" type="point" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="pointm_*" type="point" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="locs_*" type="location" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="locm_*" type="location" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="geos_*" type="geohash" indexed="true" stored="true" multiValued="false"/>
<dynamicField name="geom_*" type="geohash" indexed="true" stored="true" multiValued="true"/>
<dynamicField name="bboxs_*" type="bbox" indexed="true" stored="true" multiValued="false" />
<dynamicField name="bboxm_*" type="bbox" indexed="true" stored="true" multiValued="true" />
<dynamicField name="rpts_*" type="location_rpt" indexed="true" stored="true" multiValued="false" />
<dynamicField name="rptm_*" type="location_rpt" indexed="true" stored="true" multiValued="true" />
<!-- Special fields for Solr 5 functionality. -->
<dynamicField name="phons_*" type="phonetic" indexed="true" stored="true" multiValued="false" />
<dynamicField name="phonm_*" type="phonetic" indexed="true" stored="true" multiValued="true" />
<!-- External file fields -->
<dynamicField name="eff_*" type="file"/>
<!-- Sortable version of the dynamic string field -->
<dynamicField name="sort_*" type="sortString" indexed="true" stored="false"/>
<copyField source="ss_*" dest="sort_*"/>
<!-- A random sort field -->
<dynamicField name="random_*" type="rand" indexed="true" stored="true"/>
<!-- This field is used to store access information (e.g. node access grants), as opposed to field data -->
<dynamicField name="access_*" type="integer" indexed="true" stored="false" multiValued="true"/>
<!-- The following causes solr to ignore any fields that don't already match an existing
field name or dynamic field, rather than reporting them as an error.
Alternately, change the type="ignored" to some other type e.g. "text" if you want
unknown fields indexed and/or stored by default -->
<dynamicField name="*" type="ignored" multiValued="true" />
</fields>
<!-- Following is a dynamic way to include other fields, added by other contrib modules -->
<xi:include href="schema_extra_fields.xml" xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:fallback></xi:fallback>
</xi:include>
<!-- Field to use to determine and enforce document uniqueness.
Unless this field is marked with required="false", it will be a required field
-->
<uniqueKey>id</uniqueKey>
<!-- Similarity is the scoring routine for each document vs. a query.
A custom Similarity or SimilarityFactory may be specified here, but
the default is fine for most applications.
For more info: http://wiki.apache.org/solr/SchemaXml#Similarity
-->
<!--
<similarity class="com.example.solr.CustomSimilarityFactory">
<str name="paramkey">param value</str>
</similarity>
-->
<!-- DEPRECATED: The defaultSearchField is consulted by various query parsers
when parsing a query string that isn't explicit about the field. Machine
(non-user) generated queries are best made explicit, or they can use the
"df" request parameter which takes precedence over this.
Note: Un-commenting defaultSearchField will be insufficient if your request
handler in solrconfig.xml defines "df", which takes precedence. That would
need to be removed.
<defaultSearchField>content</defaultSearchField> -->
<!-- DEPRECATED: The defaultOperator (AND|OR) is consulted by various query
parsers when parsing a query string to determine if a clause of the query
should be marked as required or optional, assuming the clause isn't already
marked by some operator. The default is OR, which is generally assumed so it
is not a good idea to change it globally here. The "q.op" request parameter
takes precedence over this.
<solrQueryParser defaultOperator="OR"/> -->
</schema>
@@ -0,0 +1,23 @@
<fields>
<!--
Example: Adding German dynamic field types to our Solr Schema.
If you enable this, make sure you have a folder called lang containing
stopwords_de.txt and synonyms_de.txt.
This also requires to enable the content in schema_extra_types.xml.
-->
<!--
<field name="label_de" type="text_de" indexed="true" stored="true" termVectors="true" omitNorms="true"/>
<field name="content_de" type="text_de" indexed="true" stored="true" termVectors="true"/>
<field name="teaser_de" type="text_de" indexed="false" stored="true"/>
<field name="path_alias_de" type="text_de" indexed="true" stored="true" termVectors="true" omitNorms="true"/>
<field name="taxonomy_names_de" type="text_de" indexed="true" stored="false" termVectors="true" multiValued="true" omitNorms="true"/>
<field name="spell_de" type="text_de" indexed="true" stored="true" multiValued="true"/>
<copyField source="label_de" dest="spell_de"/>
<copyField source="content_de" dest="spell_de"/>
<dynamicField name="tags_de_*" type="text_de" indexed="true" stored="false" omitNorms="true"/>
<dynamicField name="ts_de_*" type="text_de" indexed="true" stored="true" multiValued="false" termVectors="true"/>
<dynamicField name="tm_de_*" type="text_de" indexed="true" stored="true" multiValued="true" termVectors="true"/>
<dynamicField name="tos_de_*" type="text_de" indexed="true" stored="true" multiValued="false" termVectors="true" omitNorms="true"/>
<dynamicField name="tom_de_*" type="text_de" indexed="true" stored="true" multiValued="true" termVectors="true" omitNorms="true"/>
-->
</fields>
@@ -0,0 +1,34 @@
<types>
<!--
Example: Adding German language field types to our Solr Schema.
If you enable this, make sure you have a folder called lang containing
stopwords_de.txt and synonyms_de.txt.
For examples from other languages, see
./server/solr/configsets/sample_techproducts_configs/conf/schema.xml
from your Solr installation.
-->
<!--
<fieldType name="text_de" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
<charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.StopFilterFactory" words="lang/stopwords_de.txt" format="snowball" ignoreCase="true"/>
<filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" splitOnCaseChange="1" splitOnNumerics="1" catenateWords="1" catenateNumbers="1" catenateAll="0" protected="protwords.txt" preserveOriginal="1"/>
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.GermanLightStemFilterFactory"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</analyzer>
<analyzer type="query">
<charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.SynonymFilterFactory" synonyms="lang/synonyms_de.txt" ignoreCase="true" expand="true"/>
<filter class="solr.StopFilterFactory" words="lang/stopwords_de.txt" format="snowball" ignoreCase="true"/>
<filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" splitOnCaseChange="1" splitOnNumerics="1" catenateWords="0" catenateNumbers="0" catenateAll="0" protected="protwords.txt" preserveOriginal="1"/>
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.GermanLightStemFilterFactory"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</analyzer>
</fieldType>
-->
</types>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,80 @@
<!-- Spell Check
The spell check component can return a list of alternative spelling
suggestions.
http://wiki.apache.org/solr/SpellCheckComponent
-->
<searchComponent name="spellcheck" class="solr.SpellCheckComponent">
<str name="queryAnalyzerFieldType">textSpell</str>
<!-- Multiple "Spell Checkers" can be declared and used by this
component
-->
<!-- a spellchecker built from a field of the main index, and
written to disk
-->
<lst name="spellchecker">
<str name="name">default</str>
<str name="field">spell</str>
<str name="spellcheckIndexDir">spellchecker</str>
<str name="buildOnOptimize">true</str>
<!-- uncomment this to require terms to occur in 1% of the documents in order to be included in the dictionary
<float name="thresholdTokenFrequency">.01</float>
-->
</lst>
<!--
Adding German spellhecker index to our Solr index
This also requires to enable the content in schema_extra_types.xml and schema_extra_fields.xml
-->
<!--
<lst name="spellchecker">
<str name="name">spellchecker_de</str>
<str name="field">spell_de</str>
<str name="spellcheckIndexDir">./spellchecker_de</str>
<str name="buildOnOptimize">true</str>
</lst>
-->
<!-- a spellchecker that uses a different distance measure -->
<!--
<lst name="spellchecker">
<str name="name">jarowinkler</str>
<str name="field">spell</str>
<str name="distanceMeasure">
org.apache.lucene.search.spell.JaroWinklerDistance
</str>
<str name="spellcheckIndexDir">spellcheckerJaro</str>
</lst>
-->
<!-- a spellchecker that use an alternate comparator
comparatorClass be one of:
1. score (default)
2. freq (Frequency first, then score)
3. A fully qualified class name
-->
<!--
<lst name="spellchecker">
<str name="name">freq</str>
<str name="field">lowerfilt</str>
<str name="spellcheckIndexDir">spellcheckerFreq</str>
<str name="comparatorClass">freq</str>
<str name="buildOnCommit">true</str>
-->
<!-- A spellchecker that reads the list of words from a file -->
<!--
<lst name="spellchecker">
<str name="classname">solr.FileBasedSpellChecker</str>
<str name="name">file</str>
<str name="sourceLocation">spellings.txt</str>
<str name="characterEncoding">UTF-8</str>
<str name="spellcheckIndexDir">spellcheckerFile</str>
</lst>
-->
</searchComponent>

Some files were not shown because too many files have changed in this diff Show More