Browse Source

updated some more modules

Bachir Soussi Chiadmi 7 years ago
parent
commit
a0fadb0757
100 changed files with 7242 additions and 1217 deletions
  1. 339 0
      sites/all/modules/contrib/admin/node_clone/LICENSE.txt
  2. 54 0
      sites/all/modules/contrib/admin/node_clone/README.txt
  3. 47 0
      sites/all/modules/contrib/admin/node_clone/clone.api.php
  4. 13 0
      sites/all/modules/contrib/admin/node_clone/clone.info
  5. 21 0
      sites/all/modules/contrib/admin/node_clone/clone.install
  6. 340 0
      sites/all/modules/contrib/admin/node_clone/clone.module
  7. 258 0
      sites/all/modules/contrib/admin/node_clone/clone.pages.inc
  8. 62 0
      sites/all/modules/contrib/admin/node_clone/clone.rules.inc
  9. 18 0
      sites/all/modules/contrib/admin/node_clone/views/clone.views.inc
  10. 37 0
      sites/all/modules/contrib/admin/node_clone/views/views_handler_field_node_link_clone.inc
  11. 339 0
      sites/all/modules/contrib/dev/elements/LICENSE.txt
  12. 14 0
      sites/all/modules/contrib/dev/elements/README.txt
  13. 12 0
      sites/all/modules/contrib/dev/elements/elements.info
  14. 600 0
      sites/all/modules/contrib/dev/elements/elements.module
  15. 3 0
      sites/all/modules/contrib/dev/elements/elements.table.css
  16. 144 0
      sites/all/modules/contrib/dev/elements/elements.theme.inc
  17. 41 46
      sites/all/modules/contrib/fields/cer/README.txt
  18. 67 211
      sites/all/modules/contrib/fields/cer/cer.admin.inc
  19. 62 0
      sites/all/modules/contrib/fields/cer/cer.api.php
  20. 61 0
      sites/all/modules/contrib/fields/cer/cer.cer.inc
  21. 28 6
      sites/all/modules/contrib/fields/cer/cer.info
  22. 449 30
      sites/all/modules/contrib/fields/cer/cer.install
  23. 295 195
      sites/all/modules/contrib/fields/cer/cer.module
  24. 71 0
      sites/all/modules/contrib/fields/cer/cer.properties.field_collection.inc
  25. 56 0
      sites/all/modules/contrib/fields/cer/cer.properties.inc
  26. 9 0
      sites/all/modules/contrib/fields/cer/extensions/cer_commerce/cer_commerce.cer.inc
  27. 14 0
      sites/all/modules/contrib/fields/cer/extensions/cer_commerce/cer_commerce.info
  28. 15 0
      sites/all/modules/contrib/fields/cer/extensions/cer_commerce/cer_commerce.module
  29. 31 0
      sites/all/modules/contrib/fields/cer/extensions/cer_commerce/commerce_product_reference.inc
  30. 14 0
      sites/all/modules/contrib/fields/cer/extensions/cer_entity_settings/cer_entity_settings.info
  31. 110 0
      sites/all/modules/contrib/fields/cer/extensions/cer_entity_settings/cer_entity_settings.install
  32. 209 0
      sites/all/modules/contrib/fields/cer/extensions/cer_entity_settings/cer_entity_settings.module
  33. 67 0
      sites/all/modules/contrib/fields/cer/extensions/cer_entity_settings/cer_entity_settings.views_default.inc
  34. 61 0
      sites/all/modules/contrib/fields/cer/extensions/cer_entity_settings/plugins/entityreference/selection/CerPresetSelectionHandler.class.php
  35. 6 0
      sites/all/modules/contrib/fields/cer/extensions/cer_entity_settings/plugins/entityreference/selection/cer.inc
  36. 12 0
      sites/all/modules/contrib/fields/cer/extensions/cer_ief/cer_ief.info
  37. 94 0
      sites/all/modules/contrib/fields/cer/extensions/cer_ief/cer_ief.module
  38. 33 0
      sites/all/modules/contrib/fields/cer/extensions/cer_profile2/cer_profile2.cer.inc
  39. 13 0
      sites/all/modules/contrib/fields/cer/extensions/cer_profile2/cer_profile2.info
  40. 23 0
      sites/all/modules/contrib/fields/cer/extensions/cer_profile2/cer_profile2.install
  41. 55 0
      sites/all/modules/contrib/fields/cer/extensions/cer_profile2/cer_profile2.module
  42. 71 0
      sites/all/modules/contrib/fields/cer/extensions/cer_profile2/profile2.inc
  43. 17 0
      sites/all/modules/contrib/fields/cer/field_object/field_object.info
  44. 29 0
      sites/all/modules/contrib/fields/cer/field_object/field_object.install
  45. 151 0
      sites/all/modules/contrib/fields/cer/field_object/field_object.module
  46. 126 0
      sites/all/modules/contrib/fields/cer/field_object/includes/FieldChain.inc
  47. 103 0
      sites/all/modules/contrib/fields/cer/field_object/includes/FieldHierarchy.inc
  48. 127 0
      sites/all/modules/contrib/fields/cer/field_object/includes/FieldInstance.inc
  49. 0 457
      sites/all/modules/contrib/fields/cer/handler.inc
  50. 9 0
      sites/all/modules/contrib/fields/cer/help/cer.help.ini
  51. 17 0
      sites/all/modules/contrib/fields/cer/help/intro.html
  52. 49 0
      sites/all/modules/contrib/fields/cer/help/presets.html
  53. 82 0
      sites/all/modules/contrib/fields/cer/includes/CerEndPointIterator.inc
  54. 24 0
      sites/all/modules/contrib/fields/cer/includes/CerEntityContainerInterface.inc
  55. 159 0
      sites/all/modules/contrib/fields/cer/includes/CerField.inc
  56. 91 0
      sites/all/modules/contrib/fields/cer/includes/CerFieldChain.inc
  57. 107 0
      sites/all/modules/contrib/fields/cer/includes/CerFieldChainHandler.inc
  58. 306 0
      sites/all/modules/contrib/fields/cer/includes/CerFieldHandler.inc
  59. 75 0
      sites/all/modules/contrib/fields/cer/includes/CerPreset.inc
  60. 50 0
      sites/all/modules/contrib/fields/cer/includes/CerPresetController.inc
  61. 26 0
      sites/all/modules/contrib/fields/cer/includes/CerPresetFeaturesController.inc
  62. 71 0
      sites/all/modules/contrib/fields/cer/includes/CerPresetFinder.inc
  63. 155 0
      sites/all/modules/contrib/fields/cer/includes/CerPresetHandler.inc
  64. 220 0
      sites/all/modules/contrib/fields/cer/includes/CerUIController.inc
  65. 55 0
      sites/all/modules/contrib/fields/cer/includes/fields/entity_reference.inc
  66. 39 0
      sites/all/modules/contrib/fields/cer/includes/fields/field_collection.inc
  67. 41 0
      sites/all/modules/contrib/fields/cer/includes/fields/node_reference.inc
  68. 30 0
      sites/all/modules/contrib/fields/cer/includes/fields/taxonomy_term_reference.inc
  69. 18 0
      sites/all/modules/contrib/fields/cer/includes/fields/user_reference.inc
  70. 134 0
      sites/all/modules/contrib/fields/cer/tests/CerBasicTestCase.test
  71. 0 16
      sites/all/modules/contrib/fields/cer/tests/cer_tests.info
  72. 0 1
      sites/all/modules/contrib/fields/cer/tests/cer_tests.module
  73. 0 168
      sites/all/modules/contrib/fields/cer/tests/crud.test
  74. 0 67
      sites/all/modules/contrib/fields/cer/tests/fields.test
  75. 0 0
      sites/all/modules/contrib/panels/panels/CHANGELOG.txt
  76. 0 0
      sites/all/modules/contrib/panels/panels/KNOWN_ISSUES.txt
  77. 0 0
      sites/all/modules/contrib/panels/panels/LICENSE.txt
  78. 2 5
      sites/all/modules/contrib/panels/panels/README.txt
  79. 11 1
      sites/all/modules/contrib/panels/panels/UPGRADE.txt
  80. 0 0
      sites/all/modules/contrib/panels/panels/css/panels-dashboard.css
  81. 0 5
      sites/all/modules/contrib/panels/panels/css/panels.css
  82. 0 0
      sites/all/modules/contrib/panels/panels/css/panels_admin.css
  83. 23 8
      sites/all/modules/contrib/panels/panels/css/panels_dnd.css
  84. 0 0
      sites/all/modules/contrib/panels/panels/css/panels_page.css
  85. 0 0
      sites/all/modules/contrib/panels/panels/help/api.html
  86. 0 0
      sites/all/modules/contrib/panels/panels/help/display.html
  87. 0 0
      sites/all/modules/contrib/panels/panels/help/pane.html
  88. 0 0
      sites/all/modules/contrib/panels/panels/help/panels.help.ini
  89. 0 1
      sites/all/modules/contrib/panels/panels/help/plugin-layout.html
  90. 0 0
      sites/all/modules/contrib/panels/panels/help/plugins-layout.html
  91. 0 0
      sites/all/modules/contrib/panels/panels/help/plugins-style.html
  92. 93 0
      sites/all/modules/contrib/panels/panels/i18n_panels/README.txt
  93. 50 0
      sites/all/modules/contrib/panels/panels/i18n_panels/i18n_panels.i18n.inc
  94. 15 0
      sites/all/modules/contrib/panels/panels/i18n_panels/i18n_panels.info
  95. 27 0
      sites/all/modules/contrib/panels/panels/i18n_panels/i18n_panels.install
  96. 442 0
      sites/all/modules/contrib/panels/panels/i18n_panels/i18n_panels.module
  97. 0 0
      sites/all/modules/contrib/panels/panels/images/arrow-active.png
  98. 0 0
      sites/all/modules/contrib/panels/panels/images/arrow-down-light.png
  99. 0 0
      sites/all/modules/contrib/panels/panels/images/bg-content-modal.png
  100. 0 0
      sites/all/modules/contrib/panels/panels/images/bg-shade-dark.png

+ 339 - 0
sites/all/modules/contrib/admin/node_clone/LICENSE.txt

@@ -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.

+ 54 - 0
sites/all/modules/contrib/admin/node_clone/README.txt

@@ -0,0 +1,54 @@
+
+README file for the clone module for Drupal 7.x.
+
+The clone module allows users to make a copy of an existing node and then edit
+that copy. The authorship is set to the current user, the menu and url aliases
+are reset, and the (localized) words "Clone of" are inserted into the title to
+remind you that you are not editing the original node.
+
+Users with the "clone node" or "clone own nodes" permission can utilize this
+functionality. A "Clone content" local action link will appear on node pages.
+Depending on the setting you choose there are two possible actions that will
+occur when you click that tab. Each of these is a different cloning "method".
+
+The default method works by pre-populating the node form, rather than immediately
+saving a copy of the original node to the database.  Thus, your node will not
+be saved until you hit "Submit" (just like if you went to node/add/x).
+
+The alternative method that may be selected immediately saves the node (by
+default the user must confirm this action on a confirmation form). This may
+work better in some cases, but also means that the copied node may immediately
+show up on the front page or in RSS feeds even while you are editing it.
+
+This module makes reasonable checks on access permissions.  A user cannot clone
+a node unless they can use the input format of that node, and unless they have
+permission to create new nodes of that type based on a call to node_access().
+
+Settings can be accessed at admin/config/content/clone.  On this page you can
+set whether the publishing options are reset when making a clone of a node.
+This is set for each node type individually.
+
+This module seems to work with common node types, however YMMV, especially with
+nodes that have any sort of image or file  attachments.  In all cases, but
+especially if you are using a complex (non-core) field or custom node type,
+you should evaluate this module on a test site with a copy of your database
+before attempting to use it on a live site. On the settings page you may choose
+node types to be omitted from the cloning mechanism - no users will be able
+to clone a node of an omitted type. For example, if you use Field Collections,
+you may need to also enable the extra Field Collection Node Clone module from
+https://www.drupal.org/project/field_collection_node_clone Otherwise, the cloned
+node will reference the items in the original field collection.
+
+This module makes no attempt to respect field-level permissions set via
+the Field Permissions module, or any other module that implements
+field-level permissions hooks. You should test your configuration
+carefully or not allow access to the clone functionality for non-admins if
+you rely on field-level permissions for important site features.
+
+To install this module, copy the folder with all the files to the
+/sites/all/modules  OR /sites/default/modules directory of your Drupal
+installation and enable it at /admin/build/modules.  Two new permissions are
+available, but there are no changes to the database structure.
+
+Note: this module originally derived from code posted by Steve Ringwood
+(nevets@drupal) at http://drupal.org/node/73381#comment-137714

+ 47 - 0
sites/all/modules/contrib/admin/node_clone/clone.api.php

@@ -0,0 +1,47 @@
+<?php
+
+/**
+ * @file
+ * API documentation for the Node clone module.
+ */
+
+/**
+ * Alter the node before saving a clone.
+ *
+ * @param $node
+ *   Reference to the fully loaded node object being saved (the clone) that
+ *   can be altered as needed.
+ * @param array $context
+ *   An array of context describing the clone operation. The keys are:
+ *   - 'method' : Can be either 'prepopulate' or 'save-edit'.
+ *   - 'original_node' : The original fully loaded node object being cloned.
+ *
+ * @see clone_node_save()
+ * @see drupal_alter()
+ */
+function hook_clone_node_alter(&$node, $context) {
+  if ($context['original_node']->type == 'special') {
+    $node->special = special_something();
+  }
+}
+
+/**
+ * Alter the access to the ability to clone a given node.
+ *
+ * @param bool $access
+ *   Reference to the boolean determining if cloning should be allowed on a
+ *   given node.
+ * @param $node
+ *   The fully loaded node object being considered for cloning.
+ *
+ * @see clone_access_cloning()
+ * @see drupal_alter()
+ */
+function hook_clone_access_alter(&$access, $node) {
+  global $user;
+  // Only allow cloning of nodes posted to groups you belong to.
+  // This function doesn't really exist, but you get the idea...
+  if (!og_user_is_member_of_group_the_node_is_in($user, $node)) {
+    $access = FALSE;
+  }
+}

+ 13 - 0
sites/all/modules/contrib/admin/node_clone/clone.info

@@ -0,0 +1,13 @@
+name = "Node clone"
+description = "Allows users to clone (copy then edit) an existing node."
+core = 7.x
+
+files[] = views/views_handler_field_node_link_clone.inc
+configure = admin/config/content/clone
+
+; Information added by Drupal.org packaging script on 2016-10-21
+version = "7.x-1.0+2-dev"
+core = "7.x"
+project = "node_clone"
+datestamp = "1477055266"
+

+ 21 - 0
sites/all/modules/contrib/admin/node_clone/clone.install

@@ -0,0 +1,21 @@
+<?php
+/**
+ * @file
+ * Install & uninstall functions for Node_Clone module.
+ */
+
+/**
+ * Implementation of hook_uninstall.
+ */
+function clone_uninstall() {
+  variable_del('clone_method');
+  variable_del('clone_omitted');
+  variable_del('clone_nodes_without_confirm');
+  variable_del('clone_use_node_type_name');
+  variable_del('clone_menu_links');
+  $types = node_type_get_names();
+  foreach ($types as $type => $name) {
+    variable_del('clone_reset_' . $type);
+  }
+}
+

+ 340 - 0
sites/all/modules/contrib/admin/node_clone/clone.module

@@ -0,0 +1,340 @@
+<?php
+/**
+ * @file
+ * Allow users to make a copy of an item of content (a node) and then edit that copy.
+ */
+
+/**
+ * Implementation of hook_help().
+ */
+function clone_help($path, $arg) {
+  switch ($path) {
+    case 'admin/help#clone':
+      $output = '<p>' . t('The clone module allows users to make a copy of an existing node and then edit that copy. The authorship is set to the current user, the menu and url aliases are reset, and the words "Clone of" are inserted into the title to remind you that you are not editing the original node.') . '</p>';
+      $output .= '<p>' . t('Users with the "clone node" permission can utilize this functionality. A new tab will appear on node pages with the word "Clone".') . '</p>';
+      return $output;
+    case 'node/%/clone':
+      $method = variable_get('clone_method', 'prepopulate');
+      if ($method == 'prepopulate') {
+        return t('This clone will not be saved to the database until you submit.');
+      }
+  }
+}
+
+/**
+ * Implementation of hook_permission().
+ */
+function clone_permission() {
+  return array(
+    'clone node' => array('title' => t('Clone any node')),
+    'clone own nodes' => array('title' => t('Clone own nodes.')),
+  );
+}
+
+/**
+ * Implementation of hook_menu().
+ */
+function clone_menu() {
+  $items['admin/config/content/clone'] = array(
+    'access arguments' => array('administer site configuration'),
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('clone_settings'),
+    'title' => 'Node clone module',
+    'file' => 'clone.pages.inc',
+    'description' => 'Allows users to clone (copy then edit) an existing node.',
+  );
+  $items['node/%node/clone/%clone_token'] = array(
+    'access callback' => 'clone_access_cloning',
+    'access arguments' => array(1, TRUE, 3),
+    'page callback' => 'clone_node_check',
+    'page arguments' => array(1),
+    'title' => 'Clone content',
+    'title callback' => 'clone_action_link_title',
+    'title arguments' => array(1),
+    'weight' => 5,
+    'file' => 'clone.pages.inc',
+    'type' => MENU_LOCAL_ACTION,
+    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
+  );
+  return $items;
+}
+
+/**
+ * Implements a to_arg function for the clone local action.
+ *
+ * @param string $arg
+ *   The current argument value.
+ * @param array $map
+ *   The path arguments.
+ *
+ * @return string
+ *   Either 'confirm' or a CSRF token.
+ */
+function clone_token_to_arg($arg, $map) {
+  // Supply CSRF token if needed.
+  return clone_get_token($map[1]);
+}
+
+/**
+ * Get the token that needs to be added to the clone link.
+ *
+ * @param int $nid
+ *   The node ID of the node to be cloned
+ *
+ * @return string
+ *   Either 'confirm' or a CSRF token.
+ */
+function clone_get_token($nid) {
+  if (variable_get('clone_nodes_without_confirm', FALSE) && variable_get('clone_method', 'prepopulate') != 'prepopulate') {
+    return drupal_get_token('clone_access_cloning-' . $nid);
+  }
+  return 'confirm';
+}
+
+function clone_access_cloning($node, $check_token = FALSE, $token = FALSE) {
+  global $user;
+  // Check CSRF token if needed.
+  if ($check_token) {
+    if (!$token || $token !== clone_get_token($node->nid)) {
+      return FALSE;
+    }
+  }
+  // Check basic permissions first.
+  $access = clone_is_permitted($node->type) && (user_access('clone node') || ($user->uid && ($node->uid == $user->uid) && user_access('clone own nodes')));
+  // Make sure the user can view the original node content, and create a new one..
+  $access = $access && node_access('view', $node) && node_access('create', $node->type);
+  // Let other modules alter this.
+  drupal_alter("clone_access", $access, $node);
+  return $access;
+}
+
+function clone_is_permitted($type) {
+  $omitted = variable_get('clone_omitted', array());
+  return empty($omitted[$type]);
+}
+
+/**
+ * Menu title callback.
+ */
+function clone_action_link_title($node) {
+  // A hack to present a shorter title in contextual links.
+  if (current_path() != 'node/' . $node->nid) {
+    return t('Clone');
+  }
+  if (variable_get('clone_use_node_type_name', 0)) {
+    return t('Clone this !type', array('!type' => drupal_strtolower(node_type_get_name($node))));
+  }
+  return t('Clone content');
+}
+
+/**
+ * Implements hook_menu_local_tasks_alter
+ */
+function clone_menu_local_tasks_alter(&$data, $router_item, $root_path) {
+  // Remove tabs from the node clone form - these are confusing as they link to
+  // the the original node and its edit form.
+  if ($router_item['path'] == 'node/%/clone/%') {
+    $data['tabs'] = array();
+  }
+}
+
+/**
+ * Implementation of hook_node_type_delete().
+ */
+function clone_node_type_delete($info) {
+  variable_del('clone_reset_' . $info->type);
+}
+
+/**
+ * Implementation of hook_node_type_update().
+ */
+function clone_node_type_update($info) {
+  if (!empty($info->old_type) && $info->old_type != $info->type) {
+    if (variable_get('clone_reset_' . $info->old_type, FALSE)) {
+      variable_del('clone_reset_' . $info->old_type);
+      variable_set('clone_reset_' . $info->type, TRUE);
+    }
+  }
+}
+
+/**
+  * Implements hook_views_api.
+  */
+function clone_views_api() {
+  return array(
+    'api' => 3,
+    'path' => drupal_get_path('module', 'clone') . '/views',
+  );
+}
+
+/**
+ * Implementation of hook_admin_paths().
+ */
+function clone_admin_paths() {
+  if (variable_get('node_admin_theme')) {
+    $paths = array(
+      'node/*/clone/*' => TRUE,
+    );
+    return $paths;
+  }
+}
+
+/**
+ * Implements hook_form_BASE_FORM_ID_alter().
+ */
+function clone_form_node_form_alter(&$form, $form_state, $form_id) {
+  // Add the clone_from_original_nid value for node forms triggered by cloning.
+  // This will make sure the clone_from_original_nid property is still
+  // attached to the node when passing through hook_node_insert().
+  if (!empty($form['#node']->clone_from_original_nid)) {
+    $form['clone_from_original_nid'] = array(
+      '#type' => 'value',
+      '#value' => $form['#node']->clone_from_original_nid,
+    );
+  }
+}
+
+/**
+ * Implements hook_form_FORM_ID_alter().
+ */
+function clone_form_node_admin_content_alter(&$form, $form_state, $form_id) {
+  if (variable_get('clone_method', 'prepopulate') == 'prepopulate') {
+    $destination = drupal_get_destination();
+  }
+  else {
+    $destination = array();
+  }
+  // The property attribute changes in the $form array depending on the user role.
+  $property = isset($form['admin']['nodes']['#options']) ? '#options' : '#rows';
+  if (empty($form['admin']['nodes'][$property])) {
+    return;
+  }
+  // Expose a Clone operation on each node.
+  foreach ($form['admin']['nodes'][$property] as $nid => &$row) {
+    $node = node_load($nid);
+    if (clone_access_cloning($node)) {
+      // The structure of this form is different if there is just 1 or more
+      // than one operation.
+      if (!isset($row['operations']['data']['#links'])) {
+        $row['operations']['data']['#links'] = array();
+        $row['operations']['data']['#attributes']['class'] = array('links', 'inline');
+        $row['operations']['data']['#theme'] = 'links__node_operations';
+        if (isset($row['operations']['data']['#title'])) {
+          $title = $row['operations']['data']['#title'];
+          $row['operations']['data']['#links'][$title] = array(
+            'title' => $title,
+            'href' => $row['operations']['data']['#href'],
+            'query' => $row['operations']['data']['#options']['query'],
+          );
+          unset($row['operations']['data']['#type']);
+        }
+      }
+      $row['operations']['data']['#links']['clone'] = array(
+        'title' => t('clone'),
+        'href' => 'node/' . $nid . '/clone/' . clone_get_token($nid),
+        'query' => $destination,
+      );
+    }
+  }
+}
+
+/**
+ * Implements hook_action_info().
+ */
+function clone_action_info() {
+  return array(
+    'clone_action_clone' => array(
+      'type' => 'node',
+      'label' => t('Clone item'),
+      'configurable' => TRUE,
+      'hooks' => array('any' => TRUE),
+      'triggers' => array('any'),
+    ),
+  );
+}
+
+/**
+ * Action callback.
+ */
+function clone_action_clone($original_node, $context) {
+  module_load_include('inc', 'clone', 'clone.pages');
+  if (clone_is_permitted($original_node->type)) {
+    $val = !empty($context['clone_context']) ? $context['clone_context'] : array();
+    $node = _clone_node_prepare($original_node, !empty($val['prefix_title']));
+    if (isset($val['substitute_from']) && strlen($val['substitute_from']) && isset($val['substitute_to'])) {
+      $i = (!empty($val['substitute_case_insensitive']) ? 'i' : '');
+      $pattern = '#' . strtr($val['substitute_from'], array('#' => '\#')) . '#' . $i;
+      foreach (array('title') as $property) {
+        $new = preg_replace($pattern, $val['substitute_to'], $node->{$property});
+        if ($new) {
+          $node->{$property} = $new;
+        }
+      }
+      foreach (array('body') as $property) {
+        foreach ($node->{$property} as $lang => $row) {
+          foreach ($row as $delta => $data) {
+            foreach (array('value', 'summary') as $key) {
+              if (isset($node->{$property}[$lang][$delta][$key])) {
+                $new = preg_replace($pattern, $val['substitute_to'], $node->{$property}[$lang][$delta][$key]);
+                if ($new) {
+                  $node->{$property}[$lang][$delta][$key] = $new;
+                }
+              }
+            }
+          }
+        }
+      }
+    }
+    // Let other modules do special fixing up.
+    $context = array('method' => 'action', 'original_node' => $original_node, 'clone_context' => $val);
+    drupal_alter('clone_node', $node, $context);
+    node_save($node);
+    if (module_exists('rules')) {
+      rules_invoke_event('clone_node', $node, $original_node);
+    }
+  }
+  else {
+    drupal_set_message(t('Clone failed for %title : not permitted for nodes of type %type', array('%title' => $original_node->title, '%type' => $original_node->type)), 'warning');
+  }
+}
+
+/**
+ * Action form.
+ */
+function clone_action_clone_form($context) {
+ $form['clone_context'] = array(
+   '#tree' => TRUE,
+ );
+ $form['clone_context']['prefix_title'] = array(
+    '#title' => t('Prefix title'),
+    '#type' => 'checkbox',
+    '#description' => t('Should cloned node tiles be prefixed?'),
+    '#default_value' => isset($context['clone_context']['prefix_title']) ? $context['clone_context']['prefix_title'] : 1,
+  );
+ $form['clone_context']['substitute_from'] = array(
+    '#title' => t('Substitute from string'),
+    '#type' => 'textfield',
+    '#description' => t('String (or regex) to substitute from in title and body.'),
+    '#default_value' => isset($context['clone_context']['substitue_from']) ? $context['clone_context']['substitue_from'] : '',
+  );
+ $form['clone_context']['substitute_to'] = array(
+    '#title' => t('Substitute to string'),
+    '#type' => 'textfield',
+    '#description' => t('String (or regex) to substitute to in title and body.'),
+    '#default_value' => isset($context['clone_context']['substitue_to']) ?  $context['clone_context']['substitue_to'] : '',
+  );
+ $form['clone_context']['substitute_case_insensitive'] = array(
+    '#title' => t('Case insensitive substitution'),
+    '#type' => 'checkbox',
+    '#description' => t('Should the substituion match be case insensitive?'),
+    '#default_value' => isset($context['clone_context']['substitute_case_insensitive']) ? $context['clone_context']['substitute_case_insensitive'] : NULL,
+  );
+  return $form;
+}
+
+/**
+ * Action form submit.
+ */
+function clone_action_clone_submit($form, $form_state) {
+  return array('clone_context' => $form_state['values']['clone_context']);
+}

+ 258 - 0
sites/all/modules/contrib/admin/node_clone/clone.pages.inc

@@ -0,0 +1,258 @@
+<?php
+/**
+ * @file
+ * Additional functions for Node_Clone module.
+ */
+
+/**
+ * Menu callback to configure module settings.
+ */
+function clone_settings($form, &$form_state) {
+
+  $form['basic'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('General settings'),
+  );
+  $form['basic']['clone_method'] = array(
+    '#type' => 'radios',
+    '#title' => t('Method to use when cloning a node'),
+    '#options' => array('prepopulate' => t('Pre-populate the node form fields'), 'save-edit' => t('Save as a new node then edit')),
+    '#default_value' => variable_get('clone_method', 'prepopulate'),
+  );
+  $form['basic']['clone_nodes_without_confirm'] = array(
+    '#type' => 'radios',
+    '#title' => t('Confirmation mode when using the "Save as a new node then edit" method'),
+    '#default_value' => (int)variable_get('clone_nodes_without_confirm', 0),
+    '#options' => array(t('Require confirmation (recommended)'), t('Bypass confirmation')),
+    '#description' => t('A new node may be saved immediately upon clicking the "clone" link when viewing a node, bypassing the normal confirmation form.'),
+    '#states' => array(
+      // Only show this field when the clone method is save-edit.
+      'visible' => array(
+        ':input[name="clone_method"]' => array('value' => 'save-edit'),
+      ),
+    ),
+  );
+  $form['basic']['clone_menu_links'] = array(
+    '#type' => 'radios',
+    '#title' => t('Clone menu links'),
+    '#options' => array(0 => t('No'), 1 => t('Yes')),
+    '#default_value' => (int) variable_get('clone_menu_links', 0),
+    '#description' => t('Should any menu link for a node also be cloned?'),
+  );
+  $form['basic']['clone_use_node_type_name'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Use node type name in clone link'),
+    '#default_value' => (int) variable_get('clone_use_node_type_name', 0),
+    '#description' => t('If checked, the link to clone the node will contain the node type name, for example, "Clone this article", otherwise it will read "Clone content".'),
+  );
+
+  $form['publishing'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Should the publishing options ( e.g. published, promoted, etc) be reset to the defaults?'),
+  );
+  $types = node_type_get_names();
+
+  foreach ($types as $type => $name) {
+    $form['publishing']['clone_reset_' . $type] = array(
+      '#type' => 'checkbox',
+      '#title' => t('@s: reset publishing options when cloned', array('@s' => $name)),
+      '#default_value' => variable_get('clone_reset_' . $type, FALSE),
+    );
+  }
+
+  // Need the variable default key to be something that's never a valid node type.
+  $form['omit'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Content types that are not to be cloned - omitted due to incompatibility'),
+  );
+  $form['omit']['clone_omitted'] = array(
+    '#type' => 'checkboxes',
+    '#title' => t('Omitted content types'),
+    '#default_value' => variable_get('clone_omitted', array()),
+    '#options' => $types,
+    '#description' => t('Select any node types which should <em>never</em> be cloned. In other words, all node types where cloning will fail.'),
+  );
+
+  return system_settings_form($form);
+}
+
+/**
+ *  Menu callback: prompt the user to confirm the operation
+ */
+function clone_node_check($node) {
+
+  $method = variable_get('clone_method', 'prepopulate');
+
+  switch ($method) {
+    case 'save-edit':
+      if (variable_get('clone_nodes_without_confirm', FALSE)) {
+        $new_nid = clone_node_save($node->nid);
+        $options = array();
+        if (!empty($_GET['node-clone-destination'])) {
+          $options['query']['destination'] = $_GET['node-clone-destination'];
+        }
+        drupal_goto('node/' . $new_nid . '/edit', $options);
+      }
+      else {
+        return drupal_get_form('clone_node_confirm', $node);
+      }
+      break;
+    case 'prepopulate':
+    default:
+      return clone_node_prepopulate($node);
+      break;
+  }
+}
+
+/**
+ *  form builder: prompt the user to confirm the operation
+ */
+function clone_node_confirm($form, &$form_state, $node) {
+
+    $form['nid'] = array('#type' => 'value', '#value' => $node->nid);
+    return confirm_form($form,
+      t('Are you sure you want to clone %title?', array('%title' =>  $node->title)),
+      'node/' . $node->nid, '<p>' . t('This action will create a new node. You will then be redirected to the edit page for the new node.') . '</p>',
+      t('Clone'), t('Cancel'));
+}
+
+/**
+ *  Handle confirm form submission
+ */
+function clone_node_confirm_submit($form, &$form_state) {
+  if ($form_state['values']['confirm']) {
+    $new_nid = clone_node_save($form_state['values']['nid']);
+  }
+  $form_state['redirect'] = 'node/' . $new_nid . '/edit';
+}
+
+
+/**
+ * Create a new menu link cloned from another node.
+ *
+ * Returns NULL if no existing link, or links are not to be cloned.
+ */
+function clone_node_clone_menu_link($node) {
+  if (variable_get('clone_menu_links', FALSE) && function_exists('menu_node_prepare')) {
+    // This will fetch the existing menu link if the node had one.
+    menu_node_prepare($node);
+
+    if (!empty($node->menu['mlid'])) {
+      $old_link = $node->menu;
+      $link['link_title'] = t('Clone of !title', array('!title' => $old_link['link_title']));
+      $link['plid'] = $old_link['plid'];
+      $link['menu_name'] = $old_link['menu_name'];
+      $link['weight'] = $old_link['weight'];
+      $link['module'] = $old_link['module'];
+      // Use the value -1 because it casts to boolean TRUE in function
+      // menu_form_node_form_alter() in menu.module so the node form checkbox
+      // is selected, but in function menu_link_save() no existing link will
+      // match.
+      $link['mlid'] = -1;
+      $link['has_children'] = 0;
+      $link['hidden'] = $old_link['hidden'];
+      $link['customized'] = $old_link['customized'];
+      $link['options'] = $old_link['options'];
+      $link['expanded'] = $old_link['expanded'];
+      $link['description'] = $old_link['description'];
+      $link['language'] = isset($old_link['language']) ? $old_link['language'] : NULL;
+      // This is needed to get the link saved in function menu_node_save() when
+      // using the save-edit method.
+      $link['enabled'] = TRUE;
+      return $link;
+    }
+  }
+  return NULL;
+}
+
+/**
+ *  Clones a node - prepopulate a node editing form
+ */
+function clone_node_prepopulate($original_node) {
+  if (isset($original_node->nid)) {
+
+    if (clone_is_permitted($original_node->type)) {
+      $node = _clone_node_prepare($original_node, TRUE);
+      drupal_set_title($node->title);
+      // Let other modules do special fixing up.
+      $context = array('method' => 'prepopulate', 'original_node' => $original_node);
+      drupal_alter('clone_node', $node, $context);
+      // Make sure the file defining the node form is loaded.
+      $form_state = array();
+      $form_state['build_info']['args'] = array($node);
+      form_load_include($form_state, 'inc', 'node', 'node.pages');
+      return drupal_build_form($node->type . '_node_form', $form_state);
+    }
+  }
+}
+
+/**
+ *  Clones a node by directly saving it.
+ */
+function clone_node_save($nid, $account = NULL) {
+  if (is_numeric($nid)) {
+
+    $original_node = node_load($nid);
+    if (isset($original_node->nid) && clone_is_permitted($original_node->type)) {
+      $node = _clone_node_prepare($original_node, TRUE, $account);
+      // Let other modules do special fixing up.
+      $context = array('method' => 'save-edit', 'original_node' => $original_node);
+      drupal_alter('clone_node', $node, $context);
+
+      node_save($node);
+      if (module_exists('rules')) {
+        rules_invoke_event('clone_node', $node, $original_node);
+      }
+      return $node->nid;
+    }
+  }
+}
+
+/**
+ *  Prepares a node to be cloned.
+ */
+function _clone_node_prepare($original_node, $prefix_title = FALSE, $account = NULL) {
+  $node = clone $original_node;
+
+  if (!isset($account->uid)) {
+    $account = $GLOBALS['user'];
+  }
+
+  $node->nid = NULL;
+  $node->vid = NULL;
+  $node->tnid = NULL;
+  $node->log = NULL;
+  // Also handle modules that attach a UUID to the node.
+  $node->uuid = NULL;
+  $node->vuuid = NULL;
+
+  // Anyonmymous users don't have a name.
+  // @see: drupal_anonymous_user().
+  $node->name = isset($account->name) ? $account->name : NULL;
+  $node->uid = $account->uid;
+
+  $node->created = NULL;
+  $node->menu = clone_node_clone_menu_link($original_node);
+  if (isset($node->book['mlid'])) {
+    $node->book['mlid'] = NULL;
+    $node->book['has_children'] = 0;
+  }
+  $node->path = NULL;
+  $node->files = array();
+  if ($prefix_title) {
+    $node->title = t('Clone of !title', array('!title' => $node->title));
+  }
+  // Add an extra property as a flag.
+  $node->clone_from_original_nid = $original_node->nid;
+
+  if (variable_get('clone_reset_' . $node->type, FALSE)) {
+    $node_options = variable_get('node_options_' . $node->type, array('status', 'promote'));
+    // Fill in the default values.
+    foreach (array('status', 'moderate', 'promote', 'sticky', 'revision') as $key) {
+      // Cast to int since that's how they need to be saved to the DB.
+      $node->$key = (int) in_array($key, $node_options);
+    }
+  }
+  return $node;
+}
+

+ 62 - 0
sites/all/modules/contrib/admin/node_clone/clone.rules.inc

@@ -0,0 +1,62 @@
+<?php
+
+/**
+ * @file Node clone rules functions
+ */
+
+/**
+ * Implementation of hook_rules_event_info.
+ */
+function clone_rules_event_info() {
+  // Let rules know about the node clone event.
+  $items = array(
+    'clone_node' => array(
+      'label' => t('After cloning a node'),
+      'group' => t('Node'),
+      'variables' => array(
+        'cloned_node' => array('type' => 'node', 'label' => t('The cloned node')),
+        'original_node' => array('type' => 'node', 'label' => t('The original node')),
+      ),
+    ),
+  );
+  return $items;
+}
+
+/**
+ * Implements hook_rules_action_info().
+ */
+function clone_rules_action_info() {
+  $actions = array(
+    'clone_action_node_clone' => array(
+      'label' => t('Clone a node'),
+      'group' => t('Node'),
+      'parameter' => array(
+        'node' => array(
+          'type' => 'node',
+          'label' => t('Node to clone'),
+        ),
+      ),
+      'provides' => array(
+        'clone' => array(
+          'type' => 'node',
+          'label' => t('Cloned node'),
+        ),
+      ),
+    ),
+  );
+  return $actions;
+}
+
+/**
+ * Action callback for cloning a node.
+ * @param $node
+ *   The node to clone.
+ */
+function clone_action_node_clone($node) {
+  include_once drupal_get_path('module', 'clone') . '/clone.pages.inc';
+  $new_nid = clone_node_save($node->nid);
+  $new_node = entity_load_single('node', $new_nid);
+  return array(
+    'clone' => $new_node,
+  );
+}

+ 18 - 0
sites/all/modules/contrib/admin/node_clone/views/clone.views.inc

@@ -0,0 +1,18 @@
+<?php
+/**
+ * @file
+ * Views settings for Node_Clone module.
+ */
+
+/**
+* Implements hook_views_data_alter()
+*/
+function clone_views_data_alter(&$views_data) {
+  $views_data['node']['clone_node'] = array(
+    'field' => array(
+      'title' => t('Clone link'),
+      'help' => t('Provide a simple link to clone the node.'),
+      'handler' => 'views_handler_field_node_link_clone',
+    ),
+  );
+}

+ 37 - 0
sites/all/modules/contrib/admin/node_clone/views/views_handler_field_node_link_clone.inc

@@ -0,0 +1,37 @@
+<?php
+/**
+ * @file
+ * Views field handler for Node_Clone module.
+ */
+
+/**
+* Field handler to present a clone node link.
+*
+* Closely modeled after views/modules/node/views_handler_field_node_link_edit.inc
+*/
+class views_handler_field_node_link_clone extends views_handler_field_node_link {
+
+  /**
+   * Renders the link.
+   */
+  function render_link($node, $values) {
+
+    if (!clone_access_cloning($node)) {
+      return;
+    }
+
+    $this->options['alter']['make_link'] = TRUE;
+    $this->options['alter']['path'] = "node/{$node->nid}/clone/" . clone_get_token($node->nid);
+    $method = variable_get('clone_method', 'prepopulate');
+    $destination = drupal_get_destination();
+    if ($method == 'prepopulate') {
+      $this->options['alter']['query'] = $destination;
+    }
+    elseif (!empty($destination['destination'])) {
+      $this->options['alter']['query']['node-clone-destination'] = $destination['destination'];
+    }
+
+    $text = !empty($this->options['text']) ? $this->options['text'] : t('clone');
+    return $text;
+  }
+}

+ 339 - 0
sites/all/modules/contrib/dev/elements/LICENSE.txt

@@ -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.

+ 14 - 0
sites/all/modules/contrib/dev/elements/README.txt

@@ -0,0 +1,14 @@
+Description
+===========
+Elements intends to become a library that provides complex form elements for developers to use in their modules.
+
+
+Elements provided
+=================
+
+1. emailfield
+2. searchfield
+3. telfield
+4. urlfield
+5. numberfield
+6. rangefield

+ 12 - 0
sites/all/modules/contrib/dev/elements/elements.info

@@ -0,0 +1,12 @@
+name = Elements
+description = Provides a library of Form API elements.
+core = 7.x
+files[] = elements.module
+files[] = elements.theme.inc
+
+; Information added by drupal.org packaging script on 2013-09-30
+version = "7.x-1.4+2-dev"
+core = "7.x"
+project = "elements"
+datestamp = "1380576438"
+

+ 600 - 0
sites/all/modules/contrib/dev/elements/elements.module

@@ -0,0 +1,600 @@
+<?php
+
+/**
+ * Implements hook_element_info().
+ */
+function elements_element_info() {
+  $types['emailfield'] = array(
+    '#input' => TRUE,
+    '#size' => 60,
+    '#maxlength' => 128,
+    '#autocomplete_path' => FALSE,
+    '#process' => array('ajax_process_form', 'elements_process_pattern'),
+    '#element_validate' => array('elements_validate_email'),
+    '#theme' => 'emailfield',
+    '#theme_wrappers' => array('form_element'),
+  );
+  $types['searchfield'] = array(
+    '#input' => TRUE,
+    '#size' => 60,
+    '#maxlength' => 128,
+    '#autocomplete_path' => FALSE,
+    '#process' => array('ajax_process_form'),
+    '#theme' => 'searchfield',
+    '#theme_wrappers' => array('form_element'),
+  );
+  $types['telfield'] = array(
+    '#input' => TRUE,
+    '#size' => 20,
+    '#maxlength' => 64,
+    '#process' => array('ajax_process_form', 'elements_process_pattern'),
+    '#theme' => 'telfield',
+    '#theme_wrappers' => array('form_element'),
+  );
+  $types['urlfield'] = array(
+    '#input' => TRUE,
+    '#size' => 80,
+    '#maxlength' => 128,
+    '#autocomplete_path' => FALSE,
+    '#process' => array('ajax_process_form', 'elements_process_pattern'),
+    '#element_validate' => array('elements_validate_url'),
+    '#theme' => 'urlfield',
+    '#theme_wrappers' => array('form_element'),
+  );
+  $types['numberfield'] = array(
+    '#input' => TRUE,
+    '#step' => 1,
+    '#process' => array('ajax_process_form'),
+    '#element_validate' => array('elements_validate_number'),
+    '#theme' => 'numberfield',
+    '#theme_wrappers' => array('form_element'),
+  );
+  $types['rangefield'] = array(
+    '#input' => TRUE,
+    '#step' => 1,
+    '#min' => 0,
+    '#max' => 100,
+    '#process' => array('ajax_process_form'),
+    '#element_validate' => array('elements_validate_number'),
+    '#theme' => 'rangefield',
+    '#theme_wrappers' => array('form_element'),
+  );
+
+  // Backported table element from https://drupal.org/node/80855
+  $types['table'] = array(
+    '#header' => array(),
+    '#rows' => array(),
+    '#empty' => '',
+    // Properties for tableselect support.
+    '#input' => TRUE,
+    '#tree' => TRUE,
+    '#tableselect' => FALSE,
+    '#multiple' => TRUE,
+    '#js_select' => TRUE,
+    '#value_callback' => 'elements_table_value',
+    '#process' => array('elements_table_process'),
+    '#element_validate' => array('elements_table_validate'),
+    // Properties for tabledrag support.
+    // The value is a list of arrays that are passed to drupal_add_tabledrag().
+    // elements_pre_render_table() prepends the HTML ID of the table to each set
+    // of arguments.
+    // @see drupal_add_tabledrag()
+    '#tabledrag' => array(),
+    // Render properties.
+    '#pre_render' => array('elements_pre_render_table'),
+    '#theme' => 'table',
+  );
+
+  return $types;
+}
+
+/**
+ * Implements hook_element_info_alter().
+ */
+function elements_element_info_alter(&$types) {
+  // Add placeholder and pattern support to core form elements.
+  foreach (array_keys($types) as $type) {
+    switch ($type) {
+      case 'textfield':
+      case 'textarea':
+      case 'password':
+        $types[$type]['#process'][] = 'elements_process_placeholder';
+        $types[$type]['#process'][] = 'elements_process_pattern';
+        break;
+    }
+  }
+}
+
+/**
+ * Implements hook_theme().
+ */
+function elements_theme() {
+  return array(
+    'emailfield' => array(
+      'arguments' => array('element' => NULL),
+      'render element' => 'element',
+      'file' => 'elements.theme.inc',
+    ),
+    'searchfield' => array(
+      'arguments' => array('element' => NULL),
+      'render element' => 'element',
+      'file' => 'elements.theme.inc',
+    ),
+    'telfield' => array(
+      'arguments' => array('element' => NULL),
+      'render element' => 'element',
+      'file' => 'elements.theme.inc',
+    ),
+    'urlfield' => array(
+      'arguments' => array('element' => NULL),
+      'render element' => 'element',
+      'file' => 'elements.theme.inc',
+    ),
+    'numberfield' => array(
+      'arguments' => array('element' => NULL),
+      'render element' => 'element',
+      'file' => 'elements.theme.inc',
+    ),
+    'rangefield' => array(
+      'arguments' => array('element' => NULL),
+      'render element' => 'element',
+      'file' => 'elements.theme.inc',
+    ),
+  );
+}
+
+/**
+ * Return the autocompletion HTML for a form element.
+ *
+ * @param $element
+ *   The renderable element to process for autocompletion.
+ *
+ * @return
+ *   The rendered autocompletion element HTML, or an empty string if the field
+ *   has no autocompletion enabled.
+ */
+function elements_add_autocomplete(&$element) {
+  $extra = '';
+
+  if (!empty($element['#autocomplete_path']) && drupal_valid_path($element['#autocomplete_path'])) {
+    drupal_add_library('system', 'drupal.autocomplete');
+    $element['#attributes']['class'][] = 'form-autocomplete';
+
+    $attributes = array();
+    $attributes['type'] = 'hidden';
+    $attributes['id'] = $element['#attributes']['id'] . '-autocomplete';
+    $attributes['value'] = url($element['#autocomplete_path'], array('absolute' => TRUE));
+    $attributes['disabled'] = 'disabled';
+    $attributes['class'][] = 'autocomplete';
+    $extra = '<input' . drupal_attributes($attributes) . ' />';
+  }
+
+  return $extra;
+}
+
+/**
+ * #process callback for #placeholder form element property.
+ *
+ * @param $element
+ *   An associative array containing the properties and children of the
+ *   generic input element.
+ *
+ * @return
+ *   The processed element.
+ */
+function elements_process_placeholder($element) {
+  if (isset($element['#placeholder']) && !isset($element['#attributes']['placeholder'])) {
+    $element['#attributes']['placeholder'] = $element['#placeholder'];
+  }
+
+  return $element;
+}
+
+/**
+ * #process callback for #pattern form element property.
+ *
+ * @param $element
+ *   An associative array containing the properties and children of the
+ *   generic input element.
+ *
+ * @return
+ *   The processed element.
+ *
+ * @see elements_validate_pattern()
+ */
+function elements_process_pattern($element) {
+  if (isset($element['#pattern']) && !isset($element['#attributes']['pattern'])) {
+    $element['#attributes']['pattern'] = $element['#pattern'];
+    $element['#element_validate'][] = 'form_validate_pattern';
+  }
+
+  return $element;
+}
+
+/**
+ * #element_validate callback for #pattern form element property.
+ *
+ * @param $element
+ *   An associative array containing the properties and children of the
+ *   generic form element.
+ * @param $form_state
+ *   The $form_state array for the form this element belongs to.
+ *
+ * @see element_process_pattern()
+ */
+function elements_validate_pattern($element, &$form_state) {
+  if ($element['#value'] !== '') {
+    // The pattern must match the entire string and should have the same
+    // behavior as the RegExp object in ECMA 262.
+    // - Use bracket-style delimiters to avoid introducing a special delimiter
+    //   character like '/' that would have to be escaped.
+    // - Put in brackets so that the pattern can't interfere with what's
+    //   prepended and appended.
+    $pattern = '{^(?:' . $element['#pattern'] . ')$}';
+
+    if (!preg_match($pattern, $element['#value'])) {
+      form_error($element, t('%name field is not in the right format.', array('%name' => $element['#title'])));
+    }
+  }
+}
+
+/**
+ * Form element validation handler for #type 'email'.
+ *
+ * Note that #maxlength and #required is validated by _form_validate() already.
+ */
+function elements_validate_email(&$element, &$form_state) {
+  if ($element['#value'] && !valid_email_address($element['#value'])) {
+    form_error($element, t('The e-mail address %mail is not valid.', array('%mail' => $element['#value'])));
+  }
+}
+
+/**
+ * Form element validation handler for #type 'url'.
+ *
+ * Note that #maxlength and #required is validated by _form_validate() already.
+ */
+function elements_validate_url(&$element, &$form_state) {
+  if ($element['#value'] && !valid_url($element['#value'], TRUE)) {
+    form_error($element, t('The URL %url is not valid.', array('%url' => $element['#value'])));
+  }
+}
+
+/**
+ * Form element validation handler for #type 'number'.
+ *
+ * Note that #required is validated by _form_validate() already.
+ */
+function elements_validate_number(&$element, &$form_state) {
+  $value = $element['#value'];
+  if ($value === '') {
+    return;
+  }
+
+  $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
+
+  // Ensure the input is numeric.
+  if (!is_numeric($value)) {
+    form_error($element, t('%name must be a number.', array('%name' => $name)));
+    return;
+  }
+
+  // Ensure that the input is greater than the #min property, if set.
+  if (isset($element['#min']) && $value < $element['#min']) {
+    form_error($element, t('%name must be higher or equal to %min.', array('%name' => $name, '%min' => $element['#min'])));
+  }
+
+  // Ensure that the input is less than the #max property, if set.
+  if (isset($element['#max']) && $value > $element['#max']) {
+    form_error($element, t('%name must be below or equal to %max.', array('%name' => $name, '%max' => $element['#max'])));
+  }
+
+  if (isset($element['#step']) && strtolower($element['#step']) != 'any') {
+    // Check that the input is an allowed multiple of #step (offset by #min if
+    // #min is set).
+    $offset = isset($element['#min']) ? $element['#min'] : 0.0;
+
+    if (!elements_valid_number_step($value, $element['#step'], $offset)) {
+      form_error($element, t('%name is not a valid number.', array('%name' => $name)));
+    }
+  }
+}
+
+/**
+ * Verifies that a number is a multiple of a given step.
+ *
+ * The implementation assumes it is dealing with IEEE 754 double precision
+ * floating point numbers that are used by PHP on most systems.
+ *
+ * This is based on the number/range verification methods of webkit.
+ *
+ * @param $value
+ *   The value that needs to be checked.
+ * @param $step
+ *   The step scale factor. Must be positive.
+ * @param $offset
+ *   (optional) An offset, to which the difference must be a multiple of the
+ *   given step.
+ *
+ * @return bool
+ *   TRUE if no step mismatch has occured, or FALSE otherwise.
+ *
+ * @see http://opensource.apple.com/source/WebCore/WebCore-1298/html/NumberInputType.cpp
+ */
+function elements_valid_number_step($value, $step, $offset = 0.0) {
+  $double_value = (double) abs($value - $offset);
+
+  // The fractional part of a double has 53 bits. The greatest number that could
+  // be represented with that is 2^53. If the given value is even bigger than
+  // $step * 2^53, then dividing by $step will result in a very small remainder.
+  // Since that remainder can't even be represented with a single precision
+  // float the following computation of the remainder makes no sense and we can
+  // safely ignore it instead.
+  if ($double_value / pow(2.0, 53) > $step) {
+    return TRUE;
+  }
+
+  // Now compute that remainder of a division by $step.
+  $remainder = (double) abs($double_value - $step * round($double_value / $step));
+
+  // $remainder is a double precision floating point number. Remainders that
+  // can't be represented with single precision floats are acceptable. The
+  // fractional part of a float has 24 bits. That means remainders smaller than
+  // $step * 2^-24 are acceptable.
+  $computed_acceptable_error = (double) ($step / pow(2.0, 24));
+
+  return $computed_acceptable_error >= $remainder || $remainder >= ($step - $computed_acceptable_error);
+}
+
+/**
+ * Determines the value of a table form element.
+ *
+ * @param array $element
+ *   The form element whose value is being populated.
+ * @param array|false $input
+ *   The incoming input to populate the form element. If this is FALSE,
+ *   the element's default value should be returned.
+ *
+ * @return array
+ *   The data that will appear in the $form_state['values'] collection
+ *   for this element. Return nothing to use the default.
+ */
+function elements_table_value(array $element, $input = FALSE) {
+  // If #multiple is FALSE, the regular default value of radio buttons is used.
+  if (!empty($element['#tableselect']) && !empty($element['#multiple'])) {
+    // Contrary to #type 'checkboxes', the default value of checkboxes in a
+    // table is built from the array keys (instead of array values) of the
+    // #default_value property.
+    // @todo D8: Remove this inconsistency.
+    if ($input === FALSE) {
+      $element += array('#default_value' => array());
+      return drupal_map_assoc(array_keys(array_filter($element['#default_value'])));
+    }
+    else {
+      return is_array($input) ? drupal_map_assoc($input) : array();
+    }
+  }
+}
+
+/**
+ * Creates checkbox or radio elements to populate a tableselect table.
+ *
+ * @param $element
+ *   An associative array containing the properties and children of the
+ *   tableselect element.
+ *
+ * @return
+ *   The processed element.
+ */
+function elements_table_process($element, &$form_state) {
+  if ($element['#tableselect']) {
+    if ($element['#multiple']) {
+      $value = is_array($element['#value']) ? $element['#value'] : array();
+    }
+    // Advanced selection behaviour makes no sense for radios.
+    else {
+      $element['#js_select'] = FALSE;
+    }
+    // Add a "Select all" checkbox column to the header.
+    // @todo D8: Rename into #select_all?
+    if ($element['#js_select']) {
+      $element['#attached']['js'][] = 'misc/tableselect.js';
+      array_unshift($element['#header'], array('class' => array('select-all')));
+    }
+    // Add an empty header column for radio buttons or when a "Select all"
+    // checkbox is not desired.
+    else {
+      array_unshift($element['#header'], '');
+    }
+
+    if (!isset($element['#default_value']) || $element['#default_value'] === 0) {
+      $element['#default_value'] = array();
+    }
+    // Create a checkbox or radio for each row in a way that the value of the
+    // tableselect element behaves as if it had been of #type checkboxes or
+    // radios.
+    foreach (element_children($element) as $key) {
+      // Do not overwrite manually created children.
+      if (!isset($element[$key]['select'])) {
+        // Determine option label; either an assumed 'title' column, or the
+        // first available column containing a #title or #markup.
+        // @todo Consider to add an optional $element[$key]['#title_key']
+        //   defaulting to 'title'?
+        $title = '';
+        if (!empty($element[$key]['title']['#title'])) {
+          $title = $element[$key]['title']['#title'];
+        }
+        else {
+          foreach (element_children($element[$key]) as $column) {
+            if (isset($element[$key][$column]['#title'])) {
+              $title = $element[$key][$column]['#title'];
+              break;
+            }
+            if (isset($element[$key][$column]['#markup'])) {
+              $title = $element[$key][$column]['#markup'];
+              break;
+            }
+          }
+        }
+        if ($title !== '') {
+          $title = t('Update !title', array('!title' => $title));
+        }
+
+        // Prepend the select column to existing columns.
+        $element[$key] = array('select' => array()) + $element[$key];
+        $element[$key]['select'] += array(
+          '#type' => $element['#multiple'] ? 'checkbox' : 'radio',
+          '#title' => $title,
+          '#title_display' => 'invisible',
+
+          // @todo If rows happen to use numeric indexes instead of string keys,
+          //   this results in a first row with $key === 0, which is always FALSE.
+          '#return_value' => $key,
+          '#attributes' => $element['#attributes'],
+        );
+        $element_parents = array_merge($element['#parents'], array($key));
+        if ($element['#multiple']) {
+          $element[$key]['select']['#default_value'] = isset($value[$key]) ? $key : NULL;
+          $element[$key]['select']['#parents'] = $element_parents;
+        }
+        else {
+          $element[$key]['select']['#default_value'] = ($element['#default_value'] == $key ? $key : NULL);
+          $element[$key]['select']['#parents'] = $element['#parents'];
+          $element[$key]['select']['#id'] = drupal_html_id('edit-' . implode('-', $element_parents));
+        }
+      }
+    }
+  }
+
+  return $element;
+}
+
+/**
+ * #element_validate callback for #type 'table'.
+ *
+ * @param array $element
+ *   An associative array containing the properties and children of the
+ *   table element.
+ * @param array $form_state
+ *   The current state of the form.
+ */
+function elements_table_validate($element, &$form_state) {
+  // Skip this validation if the button to submit the form does not require
+  // selected table row data.
+  //if (empty($form_state['triggering_element']['#tableselect'])) {
+  //  return;
+  //}
+  if ($element['#multiple']) {
+    if (!is_array($element['#value']) || !count(array_filter($element['#value']))) {
+      form_error($element, t('No items selected.'));
+    }
+  }
+  elseif (!isset($element['#value']) || $element['#value'] === '') {
+    form_error($element, t('No item selected.'));
+  }
+}
+
+/**
+ * #pre_render callback to transform children of an element into #rows suitable for theme_table().
+ *
+ * This function converts sub-elements of an element of #type 'table' to be
+ * suitable for theme_table():
+ * - The first level of sub-elements are table rows. Only the #attributes
+ *   property is taken into account.
+ * - The second level of sub-elements is converted into columns for the
+ *   corresponding first-level table row.
+ *
+ * Simple example usage:
+ * @code
+ * $form['table'] = array(
+ *   '#type' => 'table',
+ *   '#header' => array(t('Title'), array('data' => t('Operations'), 'colspan' => '1')),
+ *   // Optionally, to add tableDrag support:
+ *   '#tabledrag' => array(
+ *     array('order', 'sibling', 'thing-weight'),
+ *   ),
+ * );
+ * foreach ($things as $row => $thing) {
+ *   $form['table'][$row]['#weight'] = $thing['weight'];
+ *
+ *   $form['table'][$row]['title'] = array(
+ *     '#type' => 'textfield',
+ *     '#default_value' => $thing['title'],
+ *   );
+ *
+ *   // Optionally, to add tableDrag support:
+ *   $form['table'][$row]['#attributes']['class'][] = 'draggable';
+ *   $form['table'][$row]['weight'] = array(
+ *     '#type' => 'textfield',
+ *     '#title' => t('Weight for @title', array('@title' => $thing['title'])),
+ *     '#title_display' => 'invisible',
+ *     '#size' => 4,
+ *     '#default_value' => $thing['weight'],
+ *     '#attributes' => array('class' => array('thing-weight')),
+ *   );
+ *
+ *   // The amount of link columns should be identical to the 'colspan'
+ *   // attribute in #header above.
+ *   $form['table'][$row]['edit'] = array(
+ *     '#type' => 'link',
+ *     '#title' => t('Edit'),
+ *     '#href' => 'thing/' . $row . '/edit',
+ *   );
+ * }
+ * @endcode
+ *
+ * @param array $element
+ *   A structured array containing two sub-levels of elements. Properties used:
+ *   - #tabledrag: The value is a list of arrays that are passed to
+ *     drupal_add_tabledrag(). The HTML ID of the table is prepended to each set
+ *     of arguments.
+ *
+ * @see elements_element_info()
+ * @see theme_table()
+ * @see drupal_process_attached()
+ * @see drupal_add_tabledrag()
+ */
+function elements_pre_render_table(array $element) {
+  foreach (element_children($element) as $first) {
+    $row = array('data' => array());
+    // Apply attributes of first-level elements as table row attributes.
+    if (isset($element[$first]['#attributes'])) {
+      $row += $element[$first]['#attributes'];
+    }
+    // Turn second-level elements into table row columns.
+    // @todo Do not render a cell for children of #type 'value'.
+    // @see http://drupal.org/node/1248940
+    foreach (element_children($element[$first]) as $second) {
+      // Assign the element by reference, so any potential changes to the
+      // original element are taken over.
+      $column = array('data' => &$element[$first][$second]);
+
+      // Apply wrapper attributes of second-level elements as table cell
+      // attributes.
+      //if (isset($element[$first][$second]['#wrapper_attributes'])) {
+      //  $column += $element[$first][$second]['#wrapper_attributes'];
+      //}
+
+      $row['data'][] = $column;
+    }
+    $element['#rows'][] = $row;
+  }
+
+  // Take over $element['#id'] as HTML ID attribute, if not already set.
+  element_set_attributes($element, array('id'));
+
+  // If the custom #tabledrag is set and there is a HTML ID, inject the table's
+  // HTML ID as first callback argument and attach the behavior.
+  if (!empty($element['#tabledrag']) && isset($element['#attributes']['id'])) {
+    foreach ($element['#tabledrag'] as &$args) {
+      array_unshift($args, $element['#attributes']['id']);
+    }
+    $element['#attached']['drupal_add_tabledrag'] = $element['#tabledrag'];
+  }
+
+  if (!empty($element['#tabledrag']) && !empty($element['#tableselect'])) {
+    $element['#attached']['css'][] = drupal_get_path('module', 'elements') . '/elements.table.css';
+  }
+
+  return $element;
+}

+ 3 - 0
sites/all/modules/contrib/dev/elements/elements.table.css

@@ -0,0 +1,3 @@
+.tabledrag-processed.table-select-processed th.select-all {
+  padding-left: 2.4em;
+}

+ 144 - 0
sites/all/modules/contrib/dev/elements/elements.theme.inc

@@ -0,0 +1,144 @@
+<?php
+
+/**
+ * @file
+ * The theme include file for the elements module.
+ *
+ * Contains the theme functions for all the elements module elements.
+ */
+
+/**
+ * Returns HTML for an emailfield form element.
+ *
+ * @param $variables
+ *   An associative array containing:
+ *   - element: An associative array containing the properties of the element.
+ *     Properties used: #title, #value, #description, #size, #maxlength,
+ *     #placeholder, #required, #attributes, #autocomplete_path.
+ *
+ * @ingroup themeable
+ */
+function theme_emailfield($variables) {
+  $element = $variables['element'];
+  $element['#attributes']['type'] = 'email';
+  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength', 'placeholder'));
+  _form_set_class($element, array('form-text', 'form-email'));
+
+  $extra = elements_add_autocomplete($element);
+  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
+
+  return $output . $extra;
+}
+
+/**
+ * Returns HTML for a searchfield form element.
+ *
+ * @param $variables
+ *   An associative array containing:
+ *   - element: An associative array containing the properties of the element.
+ *     Properties used: #title, #value, #description, #size, #maxlength,
+ *     #placeholder, #required, #attributes, #autocomplete_path.
+ *
+ * @ingroup themeable
+ */
+function theme_searchfield($variables) {
+  $element = $variables['element'];
+  $element['#attributes']['type'] = 'search';
+  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength', 'placeholder'));
+  _form_set_class($element, array('form-text', 'form-search'));
+
+  $extra = elements_add_autocomplete($element);
+  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
+
+  return $output . $extra;
+}
+
+/**
+ * Returns HTML for a telfield form element.
+ *
+ * @param $variables
+ *   An associative array containing:
+ *   - element: An associative array containing the properties of the element.
+ *     Properties used: #title, #value, #description, #size, #maxlength,
+ *     #placeholder, #required, #attributes.
+ *
+ * @ingroup themeable
+ */
+function theme_telfield($variables) {
+  $element = $variables['element'];
+  $element['#attributes']['type'] = 'tel';
+  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength', 'placeholder'));
+  _form_set_class($element, array('form-text', 'form-tel'));
+
+  $extra = elements_add_autocomplete($element);
+  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
+
+  return $output . $extra;
+}
+
+/**
+ * Returns HTML for an urlfield form element.
+ *
+ * @param $variables
+ *   An associative array containing:
+ *   - element: An associative array containing the properties of the element.
+ *     Properties used: #title, #value, #description, #size, #maxlength,
+ *     #placeholder, #required, #attributes, #autocomplete_path.
+ *
+ * @ingroup themeable
+ */
+function theme_urlfield($variables) {
+  $element = $variables['element'];
+  $element['#attributes']['type'] = 'url';
+  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength', 'placeholder'));
+  _form_set_class($element, array('form-text', 'form-url'));
+
+  $extra = elements_add_autocomplete($element);
+  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
+
+  return $output . $extra;
+}
+
+/**
+ * Returns HTML for a numberfield form element.
+ *
+ * @param $variables
+ *   An associative array containing:
+ *   - element: An associative array containing the properties of the element.
+ *     Properties used: #title, #value, #description, #min, #max, #placeholder,
+ *     #required, #attributes, #step.
+ *
+ * @ingroup themeable
+ */
+function theme_numberfield($variables) {
+  $element = $variables['element'];
+  $element['#attributes']['type'] = 'number';
+  element_set_attributes($element, array('id', 'name', 'value', 'step', 'min', 'max', 'placeholder'));
+  _form_set_class($element, array('form-text', 'form-number'));
+
+  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
+
+  return $output;
+}
+
+/**
+ * Returns HTML for a rangefield form element.
+ *
+ * @param $variables
+ *   An associative array containing:
+ *   - element: An associative array containing the properties of the element.
+ *     Properties used: #title, #value, #description, #min, #max, #attributes,
+ *     #step.
+ *
+ * @ingroup themeable
+ */
+function theme_rangefield($variables) {
+  $element = $variables['element'];
+  $element['#attributes']['type'] = 'range';
+  element_set_attributes($element, array('id', 'name', 'value', 'step', 'min', 'max'));
+  _form_set_class($element, array('form-text', 'form-range'));
+
+  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
+
+  return $output;
+}

+ 41 - 46
sites/all/modules/contrib/fields/cer/README.txt

@@ -1,57 +1,52 @@
 ACKNOWLEDGEMENTS
 
-As this is the next evolution of Corresponding Node References,
-I would like to say thanks for all the work done over on Corresponding Node
-References.
+This is the next generation of Corresponding Node References. So, thanks are due
+to everyone who ever worked on CNR!
 
 DESCRIPTION
 
-It syncs the entity reference between two entity types which have an entity
-reference to each other, so double editing entities is no longer needed. If one
-entity has a reference, the other entity also receives a reference to the saved
-entity if it is referenced in that entity.
+CER keeps reference fields in sync. If entity Alice references entity Bob, CER will make Bob back-reference Alice automatically, and it will continue to keep the two in sync if either one is changed or deleted. CER does this by way of “presets”, which are relationships you set up between reference-type fields.
+
+By “reference-type fields”, I mean any kind of field that references an entity. Out of the box, CER can integrate with the following field types:
+
+- Entity Reference
+- Node Reference
+- User Reference
+- Taxonomy Term Reference
+- Profile2 (using the cer_profile2 add-on module)
+- Commerce Product Reference (using the cer_commerce add-on module)
+
+CER has an object-oriented API you can use to integrate other kinds of fields, if you need to. For more information, see cer.api.php.
 
 DEPENDENCIES
 
-7.x: Entity Reference
-
-EXAMPLE
-
-Entity type A has an entity reference to entity type B and entity type B has an
-entity reference to entity type A. When you create entity X of type A and
-reference it to entity Y of type B entity Y will also receive an update in its
-entity reference field pointing to entity X.
-
-KNOWN ISSUES
-
-- Support for entity reference fields in field collections is still a work in progress.
-  CER has no native support for entities that are wrapped by other entities (i.e.,
-  field collections), and implementing this properly will require extensive changes
-  to many parts of CER. For this reason, field collection support is on hold until
-  a few other major issues in the queue are sorted out. The thread for field collection
-  support is http://drupal.org/node/1729666.
-
-- Support for multi-language entities is, at the time of this writing, flaky at best.
-  There is a patch to implement better multi-language support, available at
-  http://drupal.org/node/1961026. If this patch works well for you, PLEASE post
-  in that issue to say that it worked so that the patch can be reviewed by
-  the community before being committed into CER.
-
-- If you're updating CER from 1.x to 2.x, you should rebuild your theme registry.
-  This is because the reference labels on CER's admin page were made themeable
-  in 2.x, so you'll need to make Drupal recognize the new theme hook.
-
-INSTALL
-
-- To install enable the module at admin/build/modules
-- Create entity type A
-- Create entity type B
-- Create a entity reference field on entity type A pointing to entity B
-- Create a entity reference field on entity type B pointing to entity A
-- Go to the settings page at admin/config/system/cer. 
-  Select to enable the corresponding referencing for these node types pointing 
-  to each other.
-- Create some entities and reference them to each other
+- Entity API
+- CTools
+- Table Element
+
+CREATING PRESETS
+
+CER won’t do anything until you create at least one preset. To create a preset, visit admin/config/content/cer and click “Add a preset”. You will need Hierarchical Select installed to continue.
+
+Select the field you want to use for the left side of the preset, then click Continue. Another select field will appear; use it to choose the field to use for the right side of the preset. Click Save, and you’re all set!
+
+THINGS YOU SHOULD KNOW
+
+* If you’re updating from CER 1.x or 2.x, you MUST clear all your caches *before* running update.php so that new classes can be registered with the autoloader! If you don’t do this, you are likely to receive fatal errors during the update.
+
+* If you have Corresponding Node References installed, CER will disable it and take over its field relationships.
+
+* Everything CER does, it does in a normal security context. This can lead to unexpected behavior if you’re not aware of it. In other words, if you don’t have the permission to view a specific node, don’t expect CER to be able to reference it when logged in as you. Be mindful of your entity/field permissions!
+  
+* devel_generate does not play nicely with CER, especially where field collections are concerned. The results are utterly unpredictable.
+
+ROAD MAP
+
+If any of this stuff interests you, I wholeheartedly encourage you to submit patches or contribute in any way you can!
+
+- Moar automated test coverage
+- Performance enhancement
+- Documentation
 
 MAINTAINER
 

+ 67 - 211
sites/all/modules/contrib/fields/cer/cer.admin.inc

@@ -1,111 +1,88 @@
 <?php
 
 /**
- * @file
- * Administrative functionality, separated for performance purposes.
+ * Form builder to create or edit presets.
  */
+function cer_form(array $form, array &$form_state, CerPreset $preset, $do = 'edit', $entity_type = NULL) {
+  field_attach_form('cer', $preset, $form, $form_state);
 
-/**
- * The settings form.
- */
-function cer_settings_form($form = array(), &$form_state) {
-  $channels = array();
-
-  foreach (_cer_get_fields() as $field) {
-    // A field that hasn't been instantiated yet will not have a 'bundles' key, which
-    // means it's useless to us, so skip over it.
-    if (! isset($field['bundles'])) {
-      continue;
-    }
-
-    foreach ($field['bundles'] as $entity_type => $bundles) {
-      foreach ($bundles as $bundle) {
-        $instance = field_info_instance($entity_type, $field['field_name'], $bundle);
-        if ($instance) {
-          $channels = array_merge($channels, _cer_find_channels($instance));
-        }
-       }
-     }
-   }
-
-  if (empty($channels)) {
-    drupal_set_message(t('There are no entity reference fields that can correspond.'), 'warning');
-  }
-  else {
-    $mapping = array();
-    foreach ($channels as $count => $key) {
-      $formatted_key = str_replace(' ', '*', $key);
-
-      $mapping[$count] = $formatted_key;
+  $form['cer_right']['#id'] = 'edit-cer-right';
 
-      $form['values']["enabled_{$count}"] = array(
-        '#type' => 'checkbox',
-        '#default_value' => cer_preset_enabled($formatted_key),
-        '#title' => filter_xss(theme('cer_label', array('key' => $key))),
-      );
-    }
-
-    // We are using a hidden field to submit the configuration because on
-    // some systems the checkbox name length is limited, and using
-    // the key would cause the length to be too long. (Issue #558612)
-    $form['mapping'] = array(
-      '#type' => 'hidden',
-      '#value' => serialize($mapping),
-    );
+  $form['cer_left'][LANGUAGE_NONE]['#ajax'] = array(
+    'callback' => 'cer_update_right',
+    'wrapper' => $form['cer_right']['#id'],
+  );
 
-    $form['submit'] = array(
+  $form['actions'] = array(
+    'submit' => array(
       '#type' => 'submit',
       '#value' => t('Save'),
-    );
-  }
-
+    ),
+    '#weight' => 10,
+  );
 
   return $form;
 }
 
-/**
- * Submit function for settings form.
- */
-function cer_settings_form_submit($form, $form_state) {
-  ctools_include('export');
-  $query_values = array();
+function cer_form_submit(array &$form, array &$form_state) {
+  $preset = entity_ui_form_submit_build_entity($form, $form_state)->save();
 
-  $mapping = unserialize($form_state['values']['mapping']);
+  drupal_set_message(t('The preset has been saved.'));
+  $form_state['redirect'] = 'admin/config/content/cer';
+}
+
+function cer_update_right(array &$form, array &$form_state) {
+  $preset = $form_state['build_info']['args'][0];
+  field_attach_submit('cer', $preset, $form, $form_state, array('field_name' => 'cer_left'));
+
+  $left = $preset->wrapper->cer_left->chain->value();
+  $left_identifier = $left->__toString();
+  $left_re = $left->regex();
 
-  foreach ($form_state['values'] as $key => $value) {
-    $keys = explode('_', $key);
-    if ($keys[0] == 'enabled') {
-      $query_values[$mapping[$keys[1]]] = $value;
+  $hierarchy = new FieldHierarchy();
+  foreach (CerFieldChain::collectAll() as $chain) {
+    if (preg_match($left_re, $chain->__toString()) && preg_match($chain->regex(), $left_identifier)) {
+      $hierarchy->addChain($chain);
     }
   }
 
-  // load all existing presets
-  $presets = ctools_export_crud_load_all('cer');
+  $options = $hierarchy->options();
+  if ($options) {
+    $form['cer_right'][LANGUAGE_NONE]['#options'] = $options;
+  }
+  else {
+    drupal_set_message(t('There are no fields which can correspond with your selection.'), 'warning');
+  }
 
-  foreach ($query_values as $key => $value) {
-    // get preset object (create new one if it doesn't exist already).
-    $preset = empty($presets[$key]) ? ctools_export_crud_new('cer') : $presets[$key];
+  return $form['cer_right'];
+}
 
-    // set and save value
-    if (empty($preset->entity_types_content_fields)) {
-      $preset->entity_types_content_fields = $key;
-    }
-    $preset->enabled = $value;
-    ctools_export_crud_save('cer', $preset);
+/**
+ * Enables or disables a preset, depending on its current status. This callback
+ * is defined by CerUIController::hook_menu().
+ */
+function cer_toggle_preset(CerPreset $preset) {
+  $preset->wrapper->cer_enabled->set(! $preset->wrapper->cer_enabled->value());
+  $preset->save();
 
-    // remove from list of presets, so we know which ones are still used
-    if (isset($presets[$key])) {
-      unset($presets[$key]);
-    }
-  }
+  drupal_goto(isset($_GET['destination']) ? $_GET['destination'] : 'admin/config/content/cer');
+}
 
-  drupal_set_message(t('The configuration has been saved.'));
+/**
+ * Permanently inverts a preset (i.e., deletes the original). This callback
+ * is defined by CerUIController::hook_menu().
+ */
+function cer_invert_preset(CerPreset $original) {
+  $original->invert()->save();
+  $original->delete();
+
+  drupal_goto(isset($_GET['destination']) ? $_GET['destination'] : 'admin/config/content/cer');
 }
 
 /**
  * Allows batch updating of existing entities.
  */
-function cer_update_form($form = array(), &$form_state) {
+function cer_bulk_update_form(array $form, array &$form_state) {
   $form['type'] = array(
     '#type' => 'select',
     '#title' => t('Entity type'),
@@ -126,152 +103,31 @@ function cer_update_form($form = array(), &$form_state) {
 }
 
 /**
- * The update form.
- * Allows updating of current entitys.
+ * The update form. Allows bulk updating of current entities.
  */
-function cer_update_form_submit($form, &$form_state) {
+function cer_bulk_update_form_submit(array $form, array &$form_state) {
   $batch = array(
     'finished' => 'cer_batch_update_existing_finished',
     'title' => t('Processing'),
     'init_message' => t('Preparing to update corresponding entity references for existing entities...'),
     'progress_message' => t('Processing entities...'),
     'error_message' => t('Corresponding entity references - existing entity update has encountered an error.'),
+    'operations' => array(),
   );
 
   $entity_type = $form_state['values']['type'];
   $query = new EntityFieldQuery();
   $query->entityCondition('entity_type', $entity_type);
+  if ($entity_type == 'user') {
+    $query->entityCondition('entity_id', 0, '>');
+  }
   $result = $query->execute();
+
   if (isset($result[$entity_type])) {
-    foreach ($result[$entity_type] as $entity_id => $stub) {
+    foreach (array_keys($result[$entity_type]) as $entity_id) {
       $batch['operations'][] = array('cer_processing_entity', array('update', $entity_id, $entity_type));
     }
   }
-  batch_set($batch);
-}
-
-/**
- * The purpose of this function is to answer this question: I am a field instance. Which other
- * fields reference the entity that owns me? And of those instances, which ones can I reference?
- * The answer is returned as an array of CER keys: "entity1 bundle1 field1 entity2 bundle2 field2".
- *
- * @param array $instance
- *  Field instance info, as returned by field_info_instance().
- *
- * @return array
- */
-function _cer_find_channels($instance) {
-  $channels = array();
-
-  $my_id = $instance['entity_type'] . ' ' . $instance['bundle'] . ' ' . $instance['field_name'];
-  $my_info = field_info_field($instance['field_name']);
-  $my_targets = _cer_get_target_bundles($my_info);
-  $my_target_type = $my_info['settings']['target_type'];
-
-  $referrers = _cer_find_referrers($instance['entity_type'], $instance['bundle']);
-  foreach ($referrers as $referrer) {
-    if (isset($referrer['bundles'][$my_target_type])) {
-      if (empty($my_targets)) {
-        $bundles = $referrer['bundles'][$my_target_type];
-      }
-      else {
-        $bundles = array_intersect($referrer['bundles'][$my_target_type], $my_targets);
-      }
-      
-      foreach ($bundles as $bundle) {
-        $channels[] = "{$my_id} {$my_target_type} {$bundle} " . $referrer['field_name'];
-      }
-    }
-  }
-
-  return $channels;
-}
-
-/**
- * Find all fields that can reference the given entity type and bundle.
- *
- * @param $entity_type
- *  The entity type that can be referenced.
- * @param $bundle
- *  The bundle that can be referenced.
- *
- * @return array
- */ 
-function _cer_find_referrers($entity_type, $bundle) {
-  $referrers = array();
-  foreach (_cer_get_fields() as $field) {
-    if ($field['settings']['target_type'] == $entity_type) {
-      $target_bundles = _cer_get_target_bundles($field);
-      if (empty($target_bundles) || in_array($bundle, $target_bundles)) {
-        $referrers[] = $field;
-      }
-    }
-  }
-
-  return $referrers;
-}
-
-/**
- * Find all bundles reference-able by a given field. If all bundles are reference-able,
- * an empty array is returned.
- *
- * @param $field
- *  Field info array as returned by field_info_field().
- *
- * @return array
- */
-function _cer_get_target_bundles($field) {
-  $target_bundles = array();
-
-  // If the reference field is using a view, load the view and see if it's filtering by the entity
-  // type's bundle filter. If it is, the filter values are the target bundles. Otherwise,
-  // assume that all bundles can be referenced.
-  //
-  // @todo Support contextual filters?
-  //
-  // NOTE: Selection handlers (i.e., $field['settings']['handler']) are plugins owned by
-  // Entity Reference. There is no method defined to get an array of referenceable
-  // bundles, but hopefully, if CER gains enough traction in the community, such a
-  // method can be added to the EntityReference_SelectionHandler interface. This
-  // function could then be deprecated, which would be a more flexible, future-proof
-  // method of finding a field's target bundles.
-  //
-  if ($field['settings']['handler'] == 'views') {
-    $view_name = $field['settings']['handler_settings']['view']['view_name'];
-
-    $view = views_get_view($view_name);
-    if ($view) {
-      $view->set_display($field['settings']['handler_settings']['view']['display_name']);
-
-      $info = entity_get_info($field['settings']['target_type']);
-      if ($info['entity keys']['bundle'] && $handler = $view->display_handler->get_handler('filter', $info['entity keys']['bundle'])) {
-        $target_bundles = $handler->value;
-      }
-    }
-    else {
-      drupal_set_message(t('Could not get target bundles for %field (failed to load view %view).', array('%view' => $view_name, '%field' => $field['field_name'])), 'error');
-    }
-  }
-  elseif (isset($field['settings']['handler_settings']['target_bundles'])) {
-    $target_bundles = $field['settings']['handler_settings']['target_bundles'];
-  }
-  else {
-    $info = entity_get_info($field['settings']['target_type']);
-    $target_bundles = array_keys($info['bundles']);
-  }
 
-  return $target_bundles;
+  batch_set($batch);
 }
-
-/**
- * Get the Field API definitions for all entity reference fields.
- *
- * @return array
- */
-function _cer_get_fields() {
-  static $fields;
-  if (!isset($fields)) {
-    $fields = array_map('field_info_field', db_select('field_config', 'fc')->fields('fc', array('field_name'))->condition('type', 'entityreference')->execute()->fetchCol());
-  }  
-  return $fields;
-}

+ 62 - 0
sites/all/modules/contrib/fields/cer/cer.api.php

@@ -0,0 +1,62 @@
+<?php
+
+/**
+ * In order to create relationships between reference fields, CER needs to know
+ * about what reference fields are available, and how to handle them, which is
+ * what this hook is for. It should always return an array, even if there are
+ * no fields to expose. The ultimate goal of this hook is to define a flattened
+ * hierarchy of all the reference-type fields that CER can use.
+ *
+ * A reference-type field is any type of field that can refer to an entity.
+ * This is pretty broadly defined: for example, CER considers field collections
+ * to be reference-type fields, since they refer to entities of the
+ * field_collection_item type. Even though the field collection may be displayed
+ * as an embedded part of its host entity, at heart it's still just a reference
+ * to an entity.
+ */
+function hook_cer_fields() {
+  return array(
+    // The keys should refer to a single field instance on a single bundle of a single
+    // entity type, even for embedded entities like field collections (see below).
+    'node:article:field_related_pages' => array(
+      // At the very least, each field you return here needs to have a 'class' set,
+      // which is the class of the plugin which will handle this field. A CER field
+      // plugin must be a sub-class of CerField, and there must be a separate plugin
+      // for each *type* of field you want to integrate (CER provides support for
+      // most reference-type fields out of the box, though). The class you provide
+      // MUST be registered with the autoloader (i.e., you need to mention it in the
+      // files[] array in your module's info file).
+      'class' => 'CerEntityReferenceField',
+    ),
+    // A field collection field is a type of reference field, so you can expose these
+    // to CER too. If you want to refer to reference fields on field collections, you
+    // must define the parent fields too, as in this example.
+    'node:page:field_my_field_collection' => array(
+      'class' => 'CerFieldCollectionField',
+    ),
+    'field_collection_item:field_my_field_collection:field_related_articles' => array(
+      'class' => 'CerEntityReferenceField',
+      // For fields that are embedded in other entities (the prime example being field
+      // collections), the possible parents of the field need to be defined. The array
+      // of parents should be an array of keys that are present in the aggregated result
+      // of hook_cer_fields(). There could be many possible parents for a single field;
+      // each parent represents another possible "route" to this field. If you leave 
+      // this out, CER will try to automatically detect the parents.
+      'parents' => array(
+        'node:page:field_my_field_collection',
+      ),
+      // Embedded fields might *require* a parent. At the time of this writing, this
+      // really only applies to field collections. The "require parent" flag means that
+      // this field MUST have at least one parent, or CER won't use it. You can probably
+      // omit this key, and let CER detect the correct value.
+      'require parent' => TRUE,
+    ),
+  );
+}
+
+/**
+ * Alter the information gathered by hook_cer_fields().
+ */
+function hook_cer_fields_alter(array &$fields) {
+  // Do clever things here.
+}

+ 61 - 0
sites/all/modules/contrib/fields/cer/cer.cer.inc

@@ -0,0 +1,61 @@
+<?php
+
+/**
+ * @file
+ * Contains CER hook implementations.
+ */
+
+/**
+ * Implements hook_cer_fields().
+ */
+function cer_cer_fields() {
+  $fields = array();
+
+  if (module_exists('taxonomy')) {
+    $fields = array_merge($fields, _cer_collect_fields_of_type('taxonomy_term_reference', 'CerTaxonomyTermReferenceField'));
+  }
+  if (module_exists('entityreference')) {
+    $fields = array_merge($fields, _cer_collect_fields_of_type('entityreference', 'CerEntityReferenceField'));
+  }
+  if (module_exists('node_reference')) {
+    $fields = array_merge($fields, _cer_collect_fields_of_type('node_reference', 'CerNodeReferenceField'));
+  }
+  if (module_exists('user_reference')) {
+    $fields = array_merge($fields, _cer_collect_fields_of_type('user_reference', 'CerUserReferenceField'));
+  }
+  if (module_exists('field_collection')) {
+    $fields = array_merge($fields, _cer_collect_fields_of_type('field_collection', 'CerFieldCollectionField'));
+  }
+
+  return $fields;
+}
+
+/**
+ * Implmements hook_cer_fields_alter().
+ */
+function cer_cer_fields_alter(array &$fields) {
+  foreach (array_keys($fields) as $identifier) {
+    list ($entity_type, $bundle, $field) = explode(':', $identifier);
+
+    if ($entity_type == 'field_collection_item') {
+      $result = db_query("SELECT entity_type, bundle, field_name FROM {field_config_instance} WHERE field_name = :field_collection", array(':field_collection' => $bundle));
+
+      foreach ($result as $r) {
+        $fields[$identifier]['parents'][] = "{$r->entity_type}:{$r->bundle}:{$r->field_name}";
+      }
+
+      $fields[$identifier]['require parent'] = TRUE;
+    }
+  }
+}
+
+function _cer_collect_fields_of_type($field_type, $class) {
+  $fields = array();
+
+  $result = db_query("SELECT fci.entity_type, fci.bundle, fci.field_name FROM {field_config_instance} fci INNER JOIN {field_config} fc ON fc.id = fci.field_id WHERE fc.type = :type AND fc.deleted = 0 AND fci.deleted = 0", array(':type' => $field_type));
+  foreach ($result as $r) {
+    $fields["{$r->entity_type}:{$r->bundle}:{$r->field_name}"]['class'] = $class;
+  }
+
+  return $fields;
+}

+ 28 - 6
sites/all/modules/contrib/fields/cer/cer.info

@@ -2,15 +2,37 @@ name = Corresponding Entity References
 description = Syncs the entity references between entity types which have an entityreference to each other.
 core = 7.x
 package = Fields
-dependencies[] = entityreference
+configure = admin/config/content/cer
+
 dependencies[] = ctools
+dependencies[] = list
+dependencies[] = entity
+dependencies[] = field_object
+dependencies[] = elements
+
+files[] = includes/CerEndPointIterator.inc
+files[] = includes/CerEntityContainerInterface.inc
+files[] = includes/CerField.inc
+files[] = includes/CerFieldChain.inc
+files[] = includes/CerFieldChainHandler.inc
+files[] = includes/CerFieldHandler.inc
+files[] = includes/CerPreset.inc
+files[] = includes/CerPresetController.inc
+files[] = includes/CerPresetFeaturesController.inc
+files[] = includes/CerPresetFinder.inc
+files[] = includes/CerPresetHandler.inc
+files[] = includes/CerUIController.inc
+files[] = includes/fields/entity_reference.inc
+files[] = includes/fields/field_collection.inc
+files[] = includes/fields/node_reference.inc
+files[] = includes/fields/taxonomy_term_reference.inc
+files[] = includes/fields/user_reference.inc
 
-files[] = handler.inc
+files[] = tests/CerBasicTestCase.test
 
-configure = admin/config/system/cer
-; Information added by Drupal.org packaging script on 2014-08-08
-version = "7.x-2.x-dev"
+; Information added by Drupal.org packaging script on 2016-02-12
+version = "7.x-3.0-alpha7+25-dev"
 core = "7.x"
 project = "cer"
-datestamp = "1407528862"
+datestamp = "1455299962"
 

+ 449 - 30
sites/all/modules/contrib/fields/cer/cer.install

@@ -9,52 +9,471 @@
  * Implements hook_schema().
  */
 function cer_schema() {
-  $schema['cer'] = array(
-    'description' => t('Saves the content types and entity reference fields for which the corresponding entity reference is enabled'),
+  $schema = array();
+
+  // @see entity_exportable_schema_fields()
+  $schema['cer_preset'] = array(
     'fields' => array(
-      'entity_types_content_fields' => array('type' => 'varchar', 'length' => 200, 'not null' => TRUE, 'default' => ''),
-      'enabled' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
-    ),
-    'primary key' => array('entity_types_content_fields'),
-    'export' => array(
-      'key' => 'entity_types_content_fields',
-      'status' => 'enabled',
-      'primary key' => 'entity_types_content_fields',
-      'key name' => 'Corresponding entity reference',
-      'identifier' => 'cnr_obj',
-      'api' => array(
-        'api' => 'default_cer_presets',
-        'owner' => 'cer',
-        'minimum_version' => 1,
-        'current_version' => 1,
+      'pid' => array(
+        'type' => 'serial',
+        'not null' => TRUE,
+      ),
+      'identifier' => array(
+        'type' => 'text',
+        'size' => 'tiny',
+        'not null' => TRUE,
+        'description' => "The preset's machine-readable export identifier.",
+      ),
+      'status' => array(
+        'type' => 'int',
+        'size' => 'tiny',
+        'not null' => TRUE,
+        'default' => 0x01,  // ENTITY_CUSTOM
+        'description' => "The preset's exportable status.",
+      ),
+      'module' => array(
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => FALSE,
+        'default' => 'cer',
+        'description' => 'The module, if any, which exports this preset.',
       ),
     ),
+    'primary key' => array('pid'),
   );
+
   return $schema;
 }
 
+/**
+ * Implements hook_install().
+ */
+function cer_install() {
+  field_info_cache_clear();
+  $fields = _cer_field_definitions();
+  array_walk($fields, 'field_create_field');
+  $instances = _cer_field_instance_definitions();
+  array_walk($instances, 'field_create_instance');
+
+  if (module_exists('corresponding_node_references')) {
+    _cer_hijack_cnr();
+  }
+}
+
+/**
+ * Contains the default field definitions for presets.
+ */
+function _cer_field_definitions() {
+  $field_bases = array();
+
+  $field_bases[] = array(
+    'active' => 1,
+    'cardinality' => 1,
+    'deleted' => 0,
+    'entity_types' => array(),
+    'field_name' => 'cer_bidirectional',
+    'foreign keys' => array(),
+    'indexes' => array(
+      'value' => array(
+        0 => 'value',
+      ),
+    ),
+    'locked' => 0,
+    'module' => 'list',
+    'settings' => array(
+      'allowed_values' => array(
+        0 => 0,
+        1 => 1,
+      ),
+      'allowed_values_function' => '',
+    ),
+    'translatable' => 0,
+    'type' => 'list_boolean',
+  );
+
+  $field_bases[] = array(
+    'active' => 1,
+    'cardinality' => 1,
+    'deleted' => 0,
+    'entity_types' => array(),
+    'field_name' => 'cer_enabled',
+    'foreign keys' => array(),
+    'indexes' => array(
+      'value' => array(
+        0 => 'value',
+      ),
+    ),
+    'locked' => 1,
+    'module' => 'list',
+    'settings' => array(
+      'allowed_values' => array(
+        0 => 0,
+        1 => 1,
+      ),
+      'allowed_values_function' => '',
+    ),
+    'translatable' => 0,
+    'type' => 'list_boolean',
+  );
+
+  $field_bases[] = array(
+    'active' => 1,
+    'cardinality' => 1,
+    'deleted' => 0,
+    'entity_types' => array(),
+    'field_name' => 'cer_weight',
+    'foreign keys' => array(),
+    'indexes' => array(
+      'value' => array(
+        0 => 'value',
+      ),
+    ),
+    'locked' => 0,
+    'module' => 'list',
+    'settings' => array(
+      'allowed_values' => array(),
+      'allowed_values_function' => 'cer_weight_options',
+    ),
+    'translatable' => 0,
+    'type' => 'list_integer',
+  );
+
+  $field_bases[] = array(
+    'active' => 1,
+    'cardinality' => 1,
+    'deleted' => 0,
+    'entity_types' => array(),
+    'field_name' => 'cer_left',
+    'foreign keys' => array(
+      'field_instance' => array(
+        'columns' => array(
+          'fiid' => 'id',
+        ),
+        'table' => 'field_config_instance',
+      ),
+    ),
+    'indexes' => array(),
+    'locked' => 1,
+    'module' => 'field_object',
+    'settings' => array(),
+    'translatable' => 0,
+    'type' => 'field_object',
+  );
+
+  $field_bases[] = array(
+    'active' => 1,
+    'cardinality' => 1,
+    'deleted' => 0,
+    'entity_types' => array(),
+    'field_name' => 'cer_right',
+    'foreign keys' => array(
+      'field_instance' => array(
+        'columns' => array(
+          'fiid' => 'id',
+        ),
+        'table' => 'field_config_instance',
+      ),
+    ),
+    'indexes' => array(),
+    'locked' => 1,
+    'module' => 'field_object',
+    'settings' => array(),
+    'translatable' => 0,
+    'type' => 'field_object',
+  );
+
+  return $field_bases;
+}
+
+/**
+ * Contains the default field instance definitions for presets.
+ */
+function _cer_field_instance_definitions() {
+  $field_instances = array();
+
+  $field_instances[] = array(
+    'bundle' => 'cer',
+    'default_value' => array(
+      0 => array(
+        'value' => 1,
+      ),
+    ),
+    'deleted' => 0,
+    'description' => '',
+    'display' => array(
+      'default' => array(
+        'label' => 'above',
+        'module' => 'list',
+        'settings' => array(),
+        'type' => 'list_default',
+        'weight' => 1,
+      ),
+    ),
+    'entity_type' => 'cer',
+    'field_name' => 'cer_bidirectional',
+    'label' => 'Bidirectional',
+    'required' => 0,
+    'settings' => array(),
+    'widget' => array(
+      'active' => 1,
+      'module' => 'options',
+      'settings' => array(
+        'display_label' => 1,
+      ),
+      'type' => 'options_onoff',
+      'weight' => 3,
+    ),
+  );
+
+  $field_instances[] = array(
+    'bundle' => 'cer',
+    'default_value' => array(
+      0 => array(
+        'value' => 1,
+      ),
+    ),
+    'deleted' => 0,
+    'description' => '',
+    'display' => array(
+      'default' => array(
+        'label' => 'above',
+        'module' => 'list',
+        'settings' => array(),
+        'type' => 'list_default',
+        'weight' => 0,
+      ),
+    ),
+    'entity_type' => 'cer',
+    'field_name' => 'cer_enabled',
+    'label' => 'Enabled',
+    'required' => 0,
+    'settings' => array(),
+    'widget' => array(
+      'active' => 1,
+      'module' => 'options',
+      'settings' => array(
+        'display_label' => 1,
+      ),
+      'type' => 'options_onoff',
+      'weight' => 2,
+    ),
+  );
+
+  $field_instances[] = array(
+    'bundle' => 'cer',
+    'default_value' => array(
+      0 => array(
+        'value' => 0,
+      ),
+    ),
+    'deleted' => 0,
+    'description' => '',
+    'display' => array(
+      'default' => array(
+        'label' => 'above',
+        'module' => 'list',
+        'settings' => array(),
+        'type' => 'list_default',
+        'weight' => 4,
+      ),
+    ),
+    'entity_type' => 'cer',
+    'field_name' => 'cer_weight',
+    'label' => 'Weight',
+    'required' => 1,
+    'settings' => array(),
+    'widget' => array(
+      'active' => 1,
+      'module' => 'options',
+      'settings' => array(),
+      'type' => 'options_select',
+      'weight' => 4,
+    ),
+  );
+
+  $field_instances[] = array(
+    'bundle' => 'cer',
+    'default_value' => NULL,
+    'deleted' => 0,
+    'description' => '',
+    'display' => array(
+      'default' => array(
+        'label' => 'hidden',
+        'module' => NULL,
+        'settings' => array(),
+        'type' => 'field_object_default',
+        'weight' => 5,
+      ),
+    ),
+    'entity_type' => 'cer',
+    'field_name' => 'cer_left',
+    'label' => 'Left Field',
+    'required' => 1,
+    'settings' => array(
+      'function' => 'CerFieldChain::collectAll',
+    ),
+    'widget' => array(
+      'active' => 1,
+      'module' => 'options',
+      'settings' => array(),
+      'type' => 'options_select',
+      'weight' => 0,
+    ),
+  );
+
+  $field_instances[] = array(
+    'bundle' => 'cer',
+    'default_value' => NULL,
+    'deleted' => 0,
+    'description' => '',
+    'display' => array(
+      'default' => array(
+        'label' => 'hidden',
+        'module' => NULL,
+        'settings' => array(),
+        'type' => 'field_object_default',
+        'weight' => 6,
+      ),
+    ),
+    'entity_type' => 'cer',
+    'field_name' => 'cer_right',
+    'label' => 'Right Field',
+    'required' => 1,
+    'settings' => array(
+      'function' => 'CerFieldChain::collectAll',
+    ),
+    'widget' => array(
+      'active' => 1,
+      'module' => 'options',
+      'settings' => array(),
+      'type' => 'options_select',
+      'weight' => 1,
+    ),
+  );
+
+  return $field_instances;
+}
+
+/**
+ * Implements hook_uninstall().
+ */
+function cer_uninstall() {
+  variable_del('cer_debug');
+
+  // Delete fields created by cer_install()
+  field_delete_field('cer_left');
+  field_delete_field('cer_right');
+  field_delete_field('cer_bidirectional');
+  field_delete_field('cer_enabled');
+  field_delete_field('cer_weight');
+}
+
+/**
+ * Converts all CNR presets to CER presets, then disables CNR.
+ */
+function _cer_hijack_cnr() {
+  $cnr = db_query('SELECT * FROM {corresponding_node_references} WHERE 1')->fetchAll();
+
+  foreach ($cnr as $index => $preset) {
+    // Prepend 'node*' to each side of the preset. CNR, sensibly enough, assumes everything
+    // is on a node, but CER needs this specified explicitly.
+    $key = explode('*', $preset->node_types_content_fields);
+    $cnr[$index]->entity_types_content_fields = "node*{$key[0]}*{$key[1]}*node*{$key[2]}*{$key[3]}";
+  }
+  array_walk($cnr, '_cer_rebuild_preset');
+
+  module_disable(array('corresponding_node_references'));
+  drupal_set_message(t('Rebuilt CNR presets.'));
+}
+
 /**
  * Rename table to shorten module name.
  */
 function cer_update_7001() {
-  db_rename_table('corresponding_entity_references', 'cer');
+  if (db_table_exists('corresponding_entity_references')) {
+    db_rename_table('corresponding_entity_references', 'cer');
+  }
+}
+
+/**
+ * Creates the {cer_preset} table to store CerPreset entities, and rebuilds
+ * legacy presets.
+ */
+function cer_update_7005() {
+  // Register new classes with the autoloader.
+  registry_rebuild();
+
+  // Create the table for preset entities.
+  $tables = cer_schema();
+  db_create_table('cer_preset', $tables['cer_preset']);
+
+  // Install Field Reference, which powers the cer_left and cer_right fields.
+  if (! module_exists('field_object')) {
+    module_enable(array('field_object'));
+  }
+
+  // Create preset entities' fields.
+  cer_install();
+
+  // Convert legacy presets to entities, including 1.x, 2.x and the older
+  // 3.x schemas.
+  $old = db_select('cer')->fields('cer')->execute()->fetchAll();
+  $old = array_merge($old, module_invoke_all('cer_default_presets'));
+  array_walk($old, '_cer_rebuild_preset');
+
+  // So long, legacy table...
+  db_drop_table('cer');
+
+  // Delete defunct status variable maintained by CTools.
+  variable_del('default_cer');
+
+  if (module_exists('corresponding_node_references')) {
+    _cer_hijack_cnr();
+  }
 }
 
 /**
- * Disable presets which refer to fields that don't exist. (Issue #2122531)
+ * Rebuilds a legacy CER or CNR preset as a CerPreset entity.
  */
-function cer_update_7002() {
-  $presets = db_query('SELECT entity_types_content_fields FROM {cer} WHERE 1')->fetchCol();
+function _cer_rebuild_preset($old) {
+  if (isset($old->entity_types_content_fields)) {
+    $keys = explode('*', $old->entity_types_content_fields);
 
-  foreach ($presets as $preset) {
-    $keys = explode('*', $preset);
-    
-    $left = field_info_instance($keys[0], $keys[2], $keys[1]);
-    $right = field_info_instance($keys[3], $keys[5], $keys[4]);
+    $old->a = implode(':', array_slice($keys, 0, 3));
+    $old->b = implode(':', array_slice($keys, 3));
+  }
+  if (! isset($old->bidirectional)) {
+    $old->bidirectional = TRUE;
+  }
+  if (! isset($old->weight)) {
+    $old->weight = 0;
+  }
+  // If the 'enabled' flag doesn't exist, we can presume that this preset
+  // was exported in code generated by CTools, which means that it should
+  // have a 'disabled' flag, which we can invert to get the status.
+  if (! isset($old->enabled)) {
+    $old->enabled = (! $old->disabled);
+  }
 
-    if (empty($left) || empty($right)) {
-      db_query('UPDATE {cer} SET enabled = 0 WHERE entity_types_content_fields = :preset', array(':preset' => $preset));
-      drupal_set_message(t('CER preset %preset was disabled because it uses non-existent fields.', array('%preset' => $preset)), 'warning');
-    }
+  // Validate both field chains by trying to unpack them. If any field in
+  // either chain isn't exposed by hook_cer_fields(), an exception will be
+  // thrown and we can bail out with an error message.
+  try {
+    CerFieldChain::unpack($old->a);
+    CerFieldChain::unpack($old->b);
+  }
+  catch (Exception $e) {
+    $variables = array(
+      '%key' => "{$old->a}*{$old->b}",
+    );
+    return drupal_set_message(t('Could not rebuild preset %key because it refers to invalid fields.', $variables), 'error');
   }
+
+  $preset = new CerPreset();
+  $preset->wrapper->cer_left->set($old->a);
+  $preset->wrapper->cer_right->set($old->b);
+  $preset->wrapper->cer_enabled->set($old->enabled);
+  $preset->wrapper->cer_bidirectional->set($old->bidirectional);
+  $preset->wrapper->cer_weight->set($old->weight);
+  $preset->save();
 }

+ 295 - 195
sites/all/modules/contrib/fields/cer/cer.module

@@ -1,39 +1,64 @@
 <?php
 
 /**
- * @file
- * Main module file.
+ * Implements hook_entity_info().
  */
+function cer_entity_info() {
+  $info = array(
+    'cer' => array(
+      'label' => t('CER Preset'),
+      'entity class' => 'CerPreset',
+      'controller class' => 'CerPresetController',
+      'base table' => 'cer_preset',
+      'label callback' => 'entity_class_label',
+      'module' => 'cer',
+      'fieldable' => TRUE,
+      'entity keys' => array(
+        'id' => 'pid',
+        'name' => 'identifier', // This is the automatically generated export key.
+        'label' => 'identifier',  // The identifier will be the default label.
+      ),
+      'admin ui' => array(
+        'path' => 'admin/config/content/cer',
+        'file' => 'cer.admin.inc',
+        'controller class' => 'CerUIController',
+      ),
+      'exportable' => TRUE,
+      'features controller class' => 'CerPresetFeaturesController',
+      'access callback' => 'cer_access',
+    ),
+  );
+
+  if (variable_get('cer_enable_field_ui', FALSE)) {
+    $info['cer']['bundles']['cer']['admin']['path'] = $info['cer']['admin ui']['path'];
+  }
+
+  return $info;
+}
+
+/**
+ * Access callback for Entity UI.
+ */
+function cer_access($op, $preset = NULL, $account = NULL) {
+  return user_access('administer cer settings', $account);
+}
 
 /**
  * Implements hook_menu().
  */
 function cer_menu() {
-  $items = array();
-
-  $items['admin/config/system/cer'] = array(
-    'title' => 'Corresponding entity references',
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('cer_settings_form'),
-    'access arguments' => array('administer cer settings'),
-    'file' => 'cer.admin.inc',
-    'type' => MENU_NORMAL_ITEM,
-  );
-  $items['admin/config/system/cer/references'] = array(
-    'title' => 'References',
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('cer_settings_form'),
-    'access arguments' => array('administer cer settings'),
-    'file' => 'cer.admin.inc',
-    'type' => MENU_DEFAULT_LOCAL_TASK,
-  );
-  $items['admin/config/system/cer/update'] = array(
-    'title' => 'Update existing entities',
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('cer_update_form'),
-    'access arguments' => array('administer cer settings'),
-    'file' => 'cer.admin.inc',
-    'type' => MENU_LOCAL_TASK,
+  $info = cer_entity_info();
+  $prefix = $info['cer']['admin ui']['path'];
+
+  return array(
+    "{$prefix}/update" => array(
+      'title' => 'Bulk Update',
+      'page callback' => 'drupal_get_form',
+      'page arguments' => array('cer_bulk_update_form'),
+      'access arguments' => array('administer cer settings'),
+      'file' => 'cer.admin.inc',
+      'type' => MENU_LOCAL_TASK,
+    ),
   );
 
   return $items;
@@ -45,143 +70,94 @@ function cer_menu() {
 function cer_permission() {
   return array(
     'administer cer settings' => array(
-      'title' => t('Administer corresponding entity reference settings'),
+      'title' => t('Administer corresponding references'),
     )
   );
 }
 
-/**
- * Implements hook_help().
- */
-function cer_help($path, $arg) {
-  $output = '';
-  if ($path == 'admin/config/system/cer') {
-    $output .= t('Check which entity references should listen to each other. When checking a check box a reference on entity type A to entity B will automatically update the entity reference field on entity B adding an entry which points to entity A.');
-  }
-  elseif ($path == 'admin/config/system/cer/update') {
-    $output .= t('This will update all the existing entities for the selected content types so that their entity reference fields are in sync.');
-    $output .= '<br />';
-    $output .= t('This process may take a long time depending on the number of entities you are updating.');
-    $output .= '<br /><br />';
-    $output .= t('When the process is finished you will see a count of the number of entities that were updated.');
-  }
-  return $output;
-}
-
 /**
  * Implements hook_field_delete_instance().
  */
-function cer_field_delete_instance($instance) {
-  foreach (cer_preset_load_enabled() as $row) {
-    $keys = explode('*', $row->entity_types_content_fields);
-
-    if (($keys[0] == $instance['entity_type'] && $keys[1] == $instance['bundle'] && $keys[2] == $instance['field_name']) || ($keys[3] == $instance['entity_type'] && $keys[4] == $instance['bundle'] && $keys[5] == $instance['field_name'])) {
-      cer_preset_delete($row->entity_types_content_fields);
+function cer_field_delete_instance(array $instance) {
+  // Delete every CER preset which refers to the deleted field instance.
+  $filter = $instance['entity_type'] . ':' . $instance['bundle'] . ':' . $instance['field_name'];
+
+  $baseQuery = new EntityFieldQuery();
+  $baseQuery->entityCondition('entity_type', 'cer');
+  $baseQuery->fieldCondition('cer_enabled', 'value', TRUE);
+
+  $query = clone $baseQuery;
+  $query->fieldCondition('cer_left', 'path', $filter, 'CONTAINS');
+  $result = $query->execute();
+  if (isset($result['cer'])) {
+    foreach (entity_load('cer', array_keys($result['cer'])) as $preset) {
+      $preset->delete();
     }
   }
-}
-
-/**
- * Implements hook_field_delete_field().
- */
-function cer_field_delete_field($field) {
-  foreach (cer_preset_load_enabled() as $row) {
-    $keys = explode('*', $row->entity_types_content_fields);
 
-    if ($keys[2] == $field['field_name'] || $keys[5] == $field['field_name']) {
-      cer_preset_delete($row->entity_types_content_fields);
+  $query = clone $baseQuery;
+  $query->fieldCondition('cer_right', 'path', $filter, 'CONTAINS');
+  $result = $query->execute();
+  if (isset($result['cer'])) {
+    foreach (entity_load('cer', array_keys($result['cer'])) as $preset) {
+      $preset->delete();
     }
   }
 }
 
 /**
- * Implements hook_theme().
+ * Implements hook_node_insert().
  */
-function cer_theme() {
-  return array(
-    'cer_label' => array(
-      'variables' => array('key' => ''),
-    ),
-  );
-}
-
-function theme_cer_label($variables) {
-  $key = explode(' ', $variables['key']);
-  
-  $local = field_info_instance($key[0], $key[2], $key[1]);
-  $remote = field_info_instance($key[3], $key[5], $key[4]);
-
-  $message = 'Correspond <span title="!local_field">%local_label</span> on !local_entity(s) of type %local_bundle with <span title="!remote_field">%remote_label</span> on !remote_entity(s) of type %remote_bundle.';
-
-  $variables = array(
-    '%local_label' => $local['label'],
-    '!local_field' => $local['field_name'],
-    '!local_entity' => $local['entity_type'],
-    '%local_bundle' => $local['bundle'],
-    '%remote_label' => $remote['label'],
-    '!remote_field' => $remote['field_name'],
-    '!remote_entity' => $remote['entity_type'],
-    '%remote_bundle' => $remote['bundle'],
-  );
-
-  return t($message, $variables);
+function cer_node_insert(StdClass $node) {
+  // Write access grants *before* doing CER stuff in order to prevent a race condition.
+  // This tricky bug can easily rear its ugly head if you have an Entity Reference field,
+  // referencing nodes, and a node access module enabled.
+  //
+  // Entity Reference's bundled selection handlers will use either EntityFieldQuery or 
+  // Views, both of which are affected by node access grants (and rightfully so). 
+  // However, when creating a node, core invokes hook_node_save() *before* it writes the 
+  // grants to the database, which can cause EntityFieldQuery (or Views, unless 
+  // configured to disable SQL rewriting) to return no results if the user isn't the 
+  // superuser. Since CER asks the field backend to validate the reference, this can
+  // cause the reference to not be validated, and the cross-reference to fail.
+  //
+  // Really, this is a core issue and not a CER issue. Core should be invoking
+  // hook_node_save() AFTER it writes access info. But we can work around it by writing
+  // the access info, doing our own processing, and then clearing the access info
+  // so node_save() can write it cleanly. And that's what this does.
+  //
+  // Hear that, core devs? Fix it fix it fix it!
+  //
+  node_access_acquire_grants($node);
+  cer_processing_entity('insert', $node, 'node');
+  db_delete('node_access')->condition('nid', $node->nid)->execute();
 }
 
 /**
  * Implements hook_entity_insert().
  */
 function cer_entity_insert($entity, $type) {
-  cer_processing_entity('insert', $entity, $type);
+  if (! function_exists("cer_{$type}_insert")) {
+    cer_processing_entity('insert', $entity, $type);
+  }
 }
 
 /**
  * Implements hook_entity_update().
  */
 function cer_entity_update($entity, $type) {
-  cer_processing_entity('update', $entity, $type);
+  if (! function_exists("cer_{$type}_update")) {
+    cer_processing_entity('update', $entity, $type);
+  }
 }
 
 /**
  * Implements hook_entity_delete().
  */
 function cer_entity_delete($entity, $type) {
-  cer_processing_entity('delete', $entity, $type);
-}
-
-/**
- * Load enabled CER presets.
- */
-function cer_preset_load_enabled() {
-  ctools_include('export');
-  return ctools_export_load_object('cer', 'conditions', array('enabled' => 1));
-}
-
-/**
- * Return CER preset by key.
- */
-function cer_preset_load($key) {
-  ctools_include('export');
-  return ctools_export_crud_load('cer', $key);
-}
-
-/**
- * Return 1 if CER preset specified by given key is enabled.
- */
-function cer_preset_enabled($key) {
-  $preset = cer_preset_load($key);
-  return empty($preset) ? 0 : $preset->enabled;
-}
-
-/**
- * Deletes or disables a given CER preset.
- */
-function cer_preset_delete($key) {
-  ctools_include('export');
-
-  ctools_export_crud_delete('cer', $key);
-  ctools_export_crud_disable('cer', $key);
-
-  ctools_export_load_object_reset('cer');
+  if (! function_exists("cer_{$type}_delete")) {
+    cer_processing_entity('delete', $entity, $type);
+  }
 }
 
 /**
@@ -191,65 +167,73 @@ function cer_preset_delete($key) {
  *  The operation being performed on the entity (insert, update, or delete).
  *
  * @param object $entity
- *  The entity or the entity's id.
+ *  The entity object (optionally wrapped), or its ID.
  *
  * @param string $entity_type
- *  The entity type.
+ *  The entity type. If $entity is wrapped, this can be NULL since the entity
+ *  type is known by the wrapper.
  *
  * @param array $context
  *  Either the Batch API context (since this is the callback function used
  *  during bulk update) or NULL if we're not in a batch job.
  */
-function cer_processing_entity($op, $entity, $entity_type, &$context = NULL) {
-  // Load the entity if we're given an ID rather than an entity.
-  if (!is_object($entity)) {
-    $entity = entity_load($entity_type, array($entity));
-    $entity = reset($entity);
+function cer_processing_entity($op, $entity, $entity_type = NULL, array &$context = NULL) {
+  // Don't do anything if the MAINTENANCE_MODE flag is set. This isn't the same thing
+  // as user-facing maintenance mode, but rather is set when running, say, update.php
+  // or another relatively low-level operation. This was added to prevent CER from
+  // running while updating from 1.x or 2.x, since classes may not yet be registered
+  // yet and we don't want to cause fatal errors during update.
+  if (defined('MAINTENANCE_MODE')) {
+    return;
   }
-  // If the entity is of the wrong type, entity_extract_IDs() will throw
-  // EntityMalformedException and rightfully bail out here.
-  list (, , $bundle) = entity_extract_IDs($entity_type, $entity);
 
-  $result = cer_preset_load_enabled();
-
-  foreach ($result as $row) {
-    $keys = explode('*', $row->entity_types_content_fields);
+  // Don't process anything that hasn't got the cer data structure: this provides an
+  // opportunity for other modules to opt their entities out of CER processing.
+  if ($entity instanceof EntityStructureWrapper) {
+    try {
+      // If there is no such a property an exception will be thrown.
+      $entity->getPropertyInfo('cer');
+    }
+    catch (EntityMetadataWrapperException $e) {
+      return;
+    }
+  }
 
-    if ($keys[0] == $entity_type && $keys[1] == $bundle) {
-      try {
-        $handler = new CerHandler($row->entity_types_content_fields, $entity);
-        call_user_func(array($handler, $op));
-      }
-      catch (CerException $e) {
-        if (isset($context)) {
-          $context['results']['errors'][] = $e;
-        }
-        else {
-          throw $e;
-        }
-      }
+  if ($entity instanceof EntityDrupalWrapper) {
+    // Under certain circumstances, the cer struct may not be known to Entity
+    // API. So check for that before doing any actual processing. If it's not
+    // known yet, rebuild the property info cache and re-instantiate the
+    // wrapper with all the latest property definitions.
+    try {
+      $entity->getPropertyInfo('cer');
+    }
+    catch (EntityMetadataWrapperException $e) {
+      entity_property_info_cache_clear();
+      $entity = new EntityDrupalWrapper($entity->type(), $entity->value());
     }
 
-    if ($keys[3] == $entity_type && $keys[4] == $bundle) {
-      $preset = implode('*', array($keys[3], $keys[4], $keys[5], $keys[0], $keys[1], $keys[2]));
+    $finder = new CerPresetFinder($entity);
 
-      try {
-        $handler = new CerHandler($preset, $entity);
-        call_user_func(array($handler, $op));
-      }
-      catch (CerException $e) {
-        if (isset($context)) {
-          $context['results']['errors'][] = $e;
-        }
-        else {
-          throw $e;
-        }
+    foreach ($finder->execute() as $preset) {
+      $handler = new CerPresetHandler($preset, $entity);
+      $handler->$op();
+    }
+
+    if ($context) {
+      if (! isset($context['results']['count'])) {
+        $context['results']['count'] = 0;
       }
+      $context['results']['count']++;
     }
   }
+  elseif ($entity_type) {
+    if (is_numeric($entity)) {
+      $entity = entity_object_load($entity, $entity_type);
+    }
 
-  if (isset($context)) {
-    $context['results']['count']++;
+    if (is_object($entity) && empty($entity->cer_processed)) {
+      cer_processing_entity($op, new EntityDrupalWrapper($entity_type, $entity), NULL, $context);
+    }
   }
 }
 
@@ -280,39 +264,155 @@ function cer_batch_update_existing_finished($success, $results, $operations) {
 }
 
 /**
- * Implements hook_ctools_plugin_api().
+ * Implements hook_hook_info().
+ *
+ * @see cer.api.php for info about what these hooks do.
+ */
+function cer_hook_info() {
+  return array(
+    'cer_fields' => array(
+      'group' => 'cer',
+    ),
+    'cer_fields_alter' => array(
+      'group' => 'cer',
+    ),
+    // This is not used except when rebuilding legacy presets. It's here to
+    // ensure that MODULE.cer.inc is auto-loaded when loading legacy presets
+    // from code. (@see cer_update_7005())
+    'cer_default_presets' => array(
+      'group' => 'cer',
+    ),
+  );
+}
+
+/**
+ * Returns options for the cer_weight field.
+ */
+function cer_weight_options() {
+  $options = array();
+
+  for ($i = -50; $i <= 50; $i++) {
+    $options[$i] = $i;
+  }
+
+  return $options;
+}
+
+/**
+ * Implements hook_features_ignore().
  */
-function cer_ctools_plugin_api($owner, $api) {
-  if ($owner == 'cer' && $api == 'default_cer_presets') {
-    return array('version' => 1);
+function cer_features_ignore($component) {
+  $ignores = array();
+  if ($component == 'cer') {
+    $ignores['wrapper'] = 0;
   }
+  return $ignores;
 }
 
 /**
- * Update field data.
- *
- * @param $node the referenced node to be updated.
+ * Implements hook_features_override_ignore().
  */
-function _cer_update($entity_type, $entity) {
-  $entity->original = isset($entity->original) ? $entity->original : NULL;
+function cer_features_override_ignore($component) {
+  return cer_features_ignore($component);
+}
+
+/**
+ * Implements hook_entity_property_info().
+ */
+function cer_entity_property_info() {
+  $properties = array();
+
+  foreach (entity_get_info() as $entity_type => $entity_info) {
+    // Expose a 'cer' struct on every entity type so that we can get special
+    // entity-specific information during processing. This stuff is wrapped in
+    // a struct to avoid namespace collisions, which can be disastrous.
+    //
+    // @see Issue #2223467
+    //
+    $properties[$entity_type]['properties']['cer'] = array(
+      'label' => t('CER'),
+      'description' => t('Information about the entity, used internally by CER.'),
+      'type' => 'struct',
+      'getter callback' => 'cer_get_cer_struct',
+      'computed' => TRUE,
+      'property info' => array(
+        // lineage is a chain string, in the format used by {cer}.a and {cer}.b.
+        // e.g., node:article:field_related_pages.
+        'lineage' => array(
+          'label' => t('Context'),
+          'description' => t("The entity's lineage, represented as a string."),
+          'type' => 'text',
+          'getter callback' => 'cer_get_entity_lineage',
+          'computed' => TRUE,
+        ),
+        // The depth of the entity. The default callback will just return 1, since most
+        // entities don't live inside other entities (field collections are the main
+        // exception).
+        'depth' => array(
+          'label' => t('Depth'),
+          'description' => t("How deeply the entity is embedded."),
+          'type' => 'integer',
+          'getter callback' => 'cer_get_entity_depth',
+          'computed' => TRUE,
+        ),
+        // The default callback returns the original entity because, as with the depth
+        // property, most entities don't live inside other entities.
+        'owner' => array(
+          'label' => t('Owner'),
+          'description' => t('The top-level entity under which this one is embedded.'),
+          'type' => 'entity',
+          'getter callback' => 'cer_get_entity_owner',
+          'computed' => TRUE,
+        ),
+        // A wrapper around $entity->original that returns the current entity if there is
+        // no original version available (i.e., during bulk update).
+        'original' => array(
+          'label' => t('Original'),
+          'description' => t('The original entity (before update), or the current entity if an update has not occurred.'),
+          'type' => 'entity',
+          'getter callback' => 'cer_get_entity_original',
+          'computed' => TRUE,
+        ),
+      ),
+    );
+  }
 
-  $extract_ids = entity_extract_IDs($entity_type, $entity);
-  $id = array_shift($extract_ids);
+  return $properties;
+}
 
-  field_attach_presave($entity_type, $entity);
-  field_attach_update($entity_type, $entity);
+/**
+ * Implements hook_entity_property_info_alter().
+ */
+function cer_entity_property_info_alter(array &$info) {
+  // Add a 'chain' property to the cer_left and cer_right fields so we can
+  // easily get the field's value represented as a CerFieldChain.
+  $info['cer']['bundles']['cer']['properties']['cer_left']['property info'] =
+  $info['cer']['bundles']['cer']['properties']['cer_right']['property info'] = array(
+    'chain' => array(
+      'label' => t('Chain'),
+      'description' => t('A CER field chain to the field instance.'),
+      'type' => 'struct',
+      'getter callback' => 'cer_unpack_field_chain',
+      'computed' => TRUE,
+    ),
+  );
 
-  // Issue #2212499.
-  if ($entity_type == 'node') {
-    $entity->changed = time();
+  // Field collections are special. Because they live inside other entities (to
+  // potentially infinite levels of recursion), their CER property callbacks must be 
+  // able to recurse upwards through the chain of embedding.
+  if (module_exists('field_collection')) {
+    $struct = &$info['field_collection_item']['properties']['cer']['property info'];
 
-    db_update('node')
-      ->fields(array(
-        'changed' => $entity->changed,
-      ))
-      ->condition('nid', $id)
-      ->execute();
+    $struct['lineage']['getter callback'] = 'cer_get_field_collection_lineage';
+    $struct['lineage']['raw getter callback'] = 'cer_get_field_collection_lineage_array';
+    $struct['depth']['getter callback'] = 'cer_get_field_collection_depth';
+    $struct['owner']['getter callback'] = 'cer_get_field_collection_owner';
   }
+}
+
+// Include property callback functions
+module_load_include('inc', 'cer', 'cer.properties');
 
-  entity_get_controller($entity_type)->resetCache(array($id));
+if (module_exists('field_collection')) {
+  module_load_include('inc', 'cer', 'cer.properties.field_collection');
 }

+ 71 - 0
sites/all/modules/contrib/fields/cer/cer.properties.field_collection.inc

@@ -0,0 +1,71 @@
+<?php
+
+/**
+ * @file
+ * Contains entity property callback functions for the 'cer' struct exposed
+ * to Entity API on field collections.
+ *
+ * @see cer_entity_property_info_alter().
+ */
+
+/**
+ * Gets a field collection's lineage as a string, e.g.
+ * node:page:field_my_collection::field_collection_item:field_my_collection:%
+ */
+function cer_get_field_collection_lineage(array $data, array $options, $property, $data_type, array $info) {
+  return implode('::', $info['raw getter callback']($data, $options, $property, $data_type, $info));
+}
+
+/**
+ * Gets a field collection's lineage as an array.
+ */
+function cer_get_field_collection_lineage_array(array $data, array $options, $property, $data_type, array $info) {
+  $collection = $data[1];
+
+  // If this is the innermost entity, $options['lineage'] will be empty.
+  if (! isset($options['lineage'])) {
+    $options['lineage'][] = "field_collection_item:{$collection->field_name}:";
+  }
+
+  $data[0] = $collection->hostEntityType();
+  $data[1] = $collection->hostEntity();
+  list (, , $host_bundle) = entity_extract_IDs($data[0], $data[1]);
+  array_unshift($options['lineage'], $data[0] . ":{$host_bundle}:{$collection->field_name}");
+
+  // If this field collection is hosted in another field collection, recurse
+  // upward. Otherwise, we're done; return the lineage array.
+  if ($data[0] == 'field_collection_item') {
+    return cer_get_field_collection_lineage_array($data, $options, $property, $data_type, $info);
+  }
+  else {
+    return $options['lineage'];
+  }
+}
+
+/**
+ * Gets the zero-based depth of a field collection.
+ */
+function cer_get_field_collection_depth(array $data, array $options, $property, $data_type, array $info) {
+  $lineage = cer_get_field_collection_lineage_array($data, $options, $property, $data_type, $info);
+  return (sizeof($lineage) - 1);
+}
+
+/**
+ * Gets the ultimate owner of a field collection -- that is, the top-level entity
+ * under which it's embedded. This could be any kind of entity that's not a field
+ * collection item.
+ */
+function cer_get_field_collection_owner(array $data, array $options, $property, $data_type, array $info) {
+  // If the entity is a field collection item, recurse upward. Otherwise,
+  // return the wrapped entity.
+  if ($data[0] == 'field_collection_item') {
+    $data[0] = $data[1]->hostEntityType();
+    $data[1] = $data[1]->hostEntity();
+    
+    $self = __FUNCTION__;
+    return $self($data, $options, $property, $data_type, $info);
+  }
+  else {
+    return new EntityDrupalWrapper($data[0], $data[1]);
+  }
+}

+ 56 - 0
sites/all/modules/contrib/fields/cer/cer.properties.inc

@@ -0,0 +1,56 @@
+<?php
+
+/**
+ * @file
+ * Contains entity property callback functions for the 'cer' struct exposed
+ * to Entity API.
+ */
+
+/**
+ * Unpacks the cer_left and cer_right values into a CerFieldChain object.
+ */
+function cer_unpack_field_chain($data, array $options, $property, $entity_type, array $info) {
+  return CerFieldChain::unpack($data);
+}
+
+/**
+ * Creates a parent struct for the lineage, depth, owner, and original properties.
+ * All that these other callbacks really need is the entity type and object, so
+ * that's what this returns.
+ */ 
+function cer_get_cer_struct($entity, array $options, $property, $entity_type, array $info) {
+  return array( $entity_type, $entity );
+}
+
+/**
+ * Gets the lineage of the entity as a string, in the format entity_type:bundle:%
+ */
+function cer_get_entity_lineage(array $data, array $options, $property, $data_type, array $info) {
+  list (, , $bundle) = entity_extract_IDs($data[0], $data[1]);
+  return $data[0] . ":{$bundle}:";
+}
+
+/**
+ * Gets the entity depth as an integer. cer_entity_property_info_alter() overrides this
+ * callback for field collections, and for all other entity types it's 0 (top level).
+ */
+function cer_get_entity_depth(array $data, array $options, $property, $data_type, array $info) {
+  return 0;
+}
+
+/**
+ * Gets the ultimate owner of the entity as an EntityDrupalWrapper. cer_entity_property_info_alter()
+ * overrides this callback for field collections, and for all other entity types the entity
+ * owns itself.
+ */
+function cer_get_entity_owner(array $data, array $options, $property, $data_type, array $info) {
+  return new EntityDrupalWrapper($data[0], $data[1]);
+}
+
+/**
+ * Gets the original entity, before update. If no update has taken place, the current
+ * entity is returned.
+ */
+function cer_get_entity_original(array $data, array $options, $property, $data_type, array $info) {
+  return new EntityDrupalWrapper($data[0], (isset($data[1]->original) ? $data[1]->original : $data[1]));
+}

+ 9 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_commerce/cer_commerce.cer.inc

@@ -0,0 +1,9 @@
+<?php
+
+/**
+ * Implements hook_cer_fields().
+ */
+function cer_commerce_cer_fields() {
+  module_load_include('inc', 'cer', 'cer.cer');
+  return _cer_collect_fields_of_type('commerce_product_reference', 'CerCommerceProductReferenceField');
+}

+ 14 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_commerce/cer_commerce.info

@@ -0,0 +1,14 @@
+name = "CER Commerce"
+core = "7.x"
+description = "Provides a CER plugin for Commerce's Product Reference fields."
+dependencies[] = cer
+dependencies[] = commerce_product_reference
+
+files[] = commerce_product_reference.inc
+
+; Information added by Drupal.org packaging script on 2016-02-12
+version = "7.x-3.0-alpha7+25-dev"
+core = "7.x"
+project = "cer"
+datestamp = "1455299962"
+

+ 15 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_commerce/cer_commerce.module

@@ -0,0 +1,15 @@
+<?php
+
+/**
+ * Implements hook_cer_insert().
+ */
+function cer_commerce_cer_insert(CerPreset $preset) {
+  // Prevents a race condition when deleting Commerce products which are referred to
+  // by Product Reference fields managed by CER.
+  if ($preset->wrapper->cer_right->chain->value()->end() instanceof CerCommerceProductReferenceField) {
+    $preset->wrapper->cer_bidirectional->set(FALSE);
+    $preset->save();
+
+    drupal_set_message(t('In order to prevent a race condition, bidirectionality has been disabled for this preset.'), 'warning');
+  }
+}

+ 31 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_commerce/commerce_product_reference.inc

@@ -0,0 +1,31 @@
+<?php
+
+/**
+ * @file
+ * Contains a CER plugin for Commerce's Product Reference fields.
+ */
+ 
+class CerCommerceProductReferenceField extends CerField {
+
+  /**
+   * Implements CerField::getTargetType().
+   */
+  public function getTargetType() {
+    return 'commerce_product';
+  }
+
+  /**
+   * Overrides CerField::getTargetBundles().
+   */
+  public function getTargetBundles() {
+    // Product reference fields store their referenceable types by instance
+    // instead of by field, so the $this->settings variable we inherit
+    // from CerField is useless here.
+    $instance = field_info_instance($this->entityType, $this->name, $this->bundle);
+    $types = $instance['settings']['referenceable_types'];
+
+    return ($types ? $types : parent::getTargetBundles());
+  }
+
+}
+ 

+ 14 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_entity_settings/cer_entity_settings.info

@@ -0,0 +1,14 @@
+name = "CER Entity Settings"
+core = "7.x"
+description = "Allows administrators and content authors to override CER settings for individual entities."
+
+dependencies[] = cer
+dependencies[] = entityreference
+dependencies[] = views
+
+; Information added by Drupal.org packaging script on 2016-02-12
+version = "7.x-3.0-alpha7+25-dev"
+core = "7.x"
+project = "cer"
+datestamp = "1455299962"
+

+ 110 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_entity_settings/cer_entity_settings.install

@@ -0,0 +1,110 @@
+<?php
+
+/**
+ * Implements hook_install().
+ */
+function cer_entity_settings_install() {
+  $fields = array();
+
+  $fields[] = array(
+    'active' => 1,
+    'cardinality' => FIELD_CARDINALITY_UNLIMITED,
+    'deleted' => 0,
+    'entity_types' => array(),
+    'field_name' => 'cer_settings',
+    'foreign keys' => array(
+      'cer_preset' => array(
+        'columns' => array(
+          'target_id' => 'pid',
+        ),
+        'table' => 'cer_preset',
+      ),
+    ),
+    'indexes' => array(
+      'target_id' => array(
+        0 => 'target_id',
+      ),
+    ),
+    'locked' => TRUE,
+    'module' => 'entityreference',
+    'settings' => array(
+      // This field uses a simple custom selection handler that selects CER
+      // presets which apply to the given entity.
+      'handler' => 'cer',
+      'handler_settings' => array(
+        'behaviors' => array(
+          'views-select-list' => array(
+            'status' => 0,
+          ),
+        ),
+      ),
+      'target_type' => 'cer',
+    ),
+    'translatable' => 0,
+    'type' => 'entityreference',
+  );
+
+  $fields[] = array(
+    'active' => 1,
+    'cardinality' => 1,
+    'deleted' => 0,
+    'entity_types' => array(),
+    'field_name' => 'cer_store_settings',
+    'foreign keys' => array(),
+    'indexes' => array(
+      'value' => array(
+        0 => 'value',
+      ),
+    ),
+    'locked' => TRUE,
+    'module' => 'list',
+    'settings' => array(
+      'allowed_values' => array(
+        0 => 0,
+        1 => 1,
+      ),
+      'allowed_values_function' => '',
+    ),
+    'translatable' => 0,
+    'type' => 'list_boolean',
+  );
+
+  array_walk($fields, 'field_create_field');
+
+  $query = new EntityFieldQuery();
+  $result = $query->entityCondition('entity_type', 'cer')->execute();
+  if (isset($result['cer'])) {
+    foreach (entity_load('cer', array_keys($result['cer'])) as $preset) {
+      cer_entity_settings_cer_update($preset);
+    }
+  }
+}
+
+/**
+ * Implements hook_uninstall().
+ */
+function cer_entity_settings_uninstall() {
+  field_delete_field('cer_settings');
+  field_delete_field('cer_store_settings');
+}
+
+/**
+ * Implements hook_update_dependencies().
+ */
+function cer_entity_settings_update_dependencies() {
+  return array(
+    'cer_entity_settings' => array(
+      7001 => array(
+        'cer' => 7005,
+      ),
+    ),
+  );
+}
+
+/**
+ * Drops the cer_entity_settings database table.
+ */
+function cer_entity_settings_update_7001() {
+  db_drop_table('cer_entity_settings');
+  cer_entity_settings_install();
+}

+ 209 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_entity_settings/cer_entity_settings.module

@@ -0,0 +1,209 @@
+<?php
+
+/**
+ * Implements hook_views_api().
+ */
+function cer_entity_settings_views_api() {
+  return array('api' => 3);
+}
+
+/**
+ * Implements hook_query_TAG_alter().
+ */
+function cer_entity_settings_query_cer_presets_alter(QueryAlterableInterface $query) {
+  $entity = $query->getMetaData('entity');
+
+  $instance = field_info_instance($entity->type(), 'cer_settings', $entity->getBundle());
+  if ($instance) {
+    $IDs = array();
+
+    foreach ($entity->cer_settings as $preset) {
+      $IDs[] = $preset->getIdentifier();
+    }
+
+    // If no presets were selected, guarantee an empty result set by selecting
+    // the non-existent preset ID 0.
+    if (empty($IDs)) {
+      $IDs[] = 0;
+    }
+    $query->getMetaData('entity_field_query')->entityCondition('entity_id', $IDs, 'IN');
+
+    if (! $entity->cer_store_settings->value()) {
+      $queue = &drupal_static('cer_entity_settings_exit', array());
+      $queue[ $entity->type() ][ $entity->getIdentifier() ] = $entity;
+    }
+  }
+}
+
+/**
+ * Implements hook_exit().
+ */
+function cer_entity_settings_exit() {
+  $queue = drupal_static(__FUNCTION__, array());
+
+  foreach ($queue as $entity_type => $entities) {
+    foreach ($entities as $entity) {
+      // Clear out the stored settings.
+      $entity->cer_settings->set(NULL);
+
+      $entity = $entity->value();
+      $entity->cer_processed = TRUE;
+      entity_save($entity_type, $entity);
+    }
+  }
+}
+
+/**
+ * Implements hook_cron().
+ */
+function cer_entity_settings_cron($field = NULL) {
+  // Delete defunct instances of the given field. An instance is considered
+  // defunct if there are no presets which refer the entity type and bundle
+  // on which it's instantiated.
+  if (isset($field)) {
+    $view = views_get_view('cer_endpoint_in_use');
+
+    $field = field_info_field($field);
+
+    // Loop through every instance of the field, executing the view for each one.
+    foreach ($field['bundles'] as $entity_type => $bundles) {
+      foreach ($bundles as $bundle) {
+        $view->set_exposed_input(array(
+          'left' => "{$entity_type}:{$bundle}:",
+          'right' => "{$entity_type}:{$bundle}:",
+        ));
+        $view->execute();
+
+        if (empty($view->result)) {
+          $instance = field_info_instance($entity_type, $field['field_name'], $bundle);
+
+          if ($instance) {
+            // Do NOT delete the field if this is the last instance of it. We
+            // clean up our own fields during uninstall.
+            field_delete_instance($instance, FALSE);
+          }
+        }
+      }
+    }
+  }
+  else {
+    call_user_func(__FUNCTION__, 'cer_settings');
+    call_user_func(__FUNCTION__, 'cer_store_settings');
+  }
+}
+
+/**
+ * Implements hook_ctools_plugin_directory().
+ */
+function cer_entity_settings_ctools_plugin_directory($owner, $plugin_type) {
+  return "plugins/{$owner}/{$plugin_type}";
+}
+
+/**
+ * Implements hook_cer_insert().
+ */
+function cer_entity_settings_cer_insert(CerPreset $preset) {
+  cer_entity_settings_cer_update($preset);
+}
+
+/**
+ * Implements hook_cer_update().
+ */
+function cer_entity_settings_cer_update(CerPreset $preset) {
+  _cer_entity_settings_create_instance($preset->wrapper->cer_left->chain->value());
+  _cer_entity_settings_create_instance($preset->wrapper->cer_right->chain->value());
+}
+
+/**
+ * Instantiates the cer_settings and cer_store_settings fields at the head of
+ * the given chain, if they aren't already there.
+ */
+function _cer_entity_settings_create_instance(FieldChain $chain) {
+  $field = $chain->current();
+
+  $instance = field_info_instance($field->entityType, 'cer_settings', $field->bundle);
+  if (empty($instance)) {
+    $instance = array(
+      'bundle' => $field->bundle,
+      'default_value' => NULL,
+      'deleted' => 0,
+      'description' => '',
+      'display' => array(
+        'default' => array(
+          'label' => 'above',
+          'module' => 'entityreference',
+          'settings' => array(
+            'link' => FALSE,
+          ),
+          'type' => 'entityreference_label',
+          'weight' => 1,
+        ),
+      ),
+      'entity_type' => $field->entityType,
+      'field_name' => 'cer_settings',
+      'label' => t('Synchronize this @entity_type with...', array(
+        '@entity_type' => $field->entityTypeLabel,
+      )),
+      'required' => 0,
+      'settings' => array(
+      ),
+      'widget' => array(
+        'active' => 1,
+        'module' => 'options',
+        'settings' => array(
+          'match_operator' => 'CONTAINS',
+          'path' => '',
+          'size' => 60,
+        ),
+        'type' => 'options_buttons',
+        'weight' => 1,
+      ),
+    );
+    field_create_instance($instance);
+  }
+
+  $instance = field_info_instance($field->entityType, 'cer_store_settings', $field->bundle);
+  if (empty($instance)) {
+    $instance = array(
+      'bundle' => $field->bundle,
+      'default_value' => array(
+        0 => array(
+          'value' => 1,
+        ),
+      ),
+      'deleted' => 0,
+      'description' => '',
+      'display' => array(
+        'default' => array(
+          'label' => 'above',
+          'module' => 'list',
+          'settings' => array(),
+          'type' => 'list_default',
+          'weight' => 2,
+        ),
+        'teaser' => array(
+          'label' => 'above',
+          'settings' => array(),
+          'type' => 'hidden',
+          'weight' => 0,
+        ),
+      ),
+      'entity_type' => $field->entityType,
+      'field_name' => 'cer_store_settings',
+      'label' => t('Remember these settings'),
+      'required' => 0,
+      'settings' => array(
+      ),
+      'widget' => array(
+        'active' => 1,
+        'module' => 'options',
+        'settings' => array(
+          'display_label' => 1,
+        ),
+        'type' => 'options_onoff',
+        'weight' => 2,
+      ),
+    );
+    field_create_instance($instance);
+  }
+}

+ 67 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_entity_settings/cer_entity_settings.views_default.inc

@@ -0,0 +1,67 @@
+<?php
+
+/**
+ * Implements hook_views_default_views().
+ */
+function cer_entity_settings_views_default_views() {
+  $views = array();
+
+  $view = new view();
+  $view->name = 'cer_endpoint_in_use';
+  $view->description = '';
+  $view->tag = 'CER Entity Settings';
+  $view->base_table = 'cer_preset';
+  $view->human_name = 'CER Endpoints in Use';
+  $view->core = 7;
+  $view->api_version = '3.0';
+  $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
+
+  /* Display: Master */
+  $handler = $view->new_display('default', 'Master', 'default');
+  $handler->display->display_options['use_more_always'] = FALSE;
+  $handler->display->display_options['access']['type'] = 'none';
+  $handler->display->display_options['cache']['type'] = 'none';
+  $handler->display->display_options['query']['type'] = 'views_query';
+  $handler->display->display_options['exposed_form']['type'] = 'basic';
+  $handler->display->display_options['pager']['type'] = 'none';
+  $handler->display->display_options['pager']['options']['offset'] = '0';
+  $handler->display->display_options['style_plugin'] = 'default';
+  $handler->display->display_options['row_plugin'] = 'entity';
+  $handler->display->display_options['row_options']['view_mode'] = 'default';
+  $handler->display->display_options['filter_groups']['groups'] = array(
+    1 => 'OR',
+  );
+  /* Filter criterion: CER Preset: Left Field (cer_left) */
+  $handler->display->display_options['filters']['cer_left_path']['id'] = 'cer_left_path';
+  $handler->display->display_options['filters']['cer_left_path']['table'] = 'field_data_cer_left';
+  $handler->display->display_options['filters']['cer_left_path']['field'] = 'cer_left_path';
+  $handler->display->display_options['filters']['cer_left_path']['operator'] = 'starts';
+  $handler->display->display_options['filters']['cer_left_path']['group'] = 1;
+  $handler->display->display_options['filters']['cer_left_path']['exposed'] = TRUE;
+  $handler->display->display_options['filters']['cer_left_path']['expose']['operator_id'] = 'cer_left_path_op';
+  $handler->display->display_options['filters']['cer_left_path']['expose']['label'] = 'Left Field';
+  $handler->display->display_options['filters']['cer_left_path']['expose']['operator'] = 'cer_left_path_op';
+  $handler->display->display_options['filters']['cer_left_path']['expose']['identifier'] = 'left';
+  $handler->display->display_options['filters']['cer_left_path']['expose']['remember_roles'] = array(
+    2 => '2',
+    1 => 0,
+  );
+  /* Filter criterion: CER Preset: Right Field (cer_right) */
+  $handler->display->display_options['filters']['cer_right_path']['id'] = 'cer_right_path';
+  $handler->display->display_options['filters']['cer_right_path']['table'] = 'field_data_cer_right';
+  $handler->display->display_options['filters']['cer_right_path']['field'] = 'cer_right_path';
+  $handler->display->display_options['filters']['cer_right_path']['operator'] = 'starts';
+  $handler->display->display_options['filters']['cer_right_path']['group'] = 1;
+  $handler->display->display_options['filters']['cer_right_path']['exposed'] = TRUE;
+  $handler->display->display_options['filters']['cer_right_path']['expose']['operator_id'] = 'cer_right_path_op';
+  $handler->display->display_options['filters']['cer_right_path']['expose']['label'] = 'Right Field';
+  $handler->display->display_options['filters']['cer_right_path']['expose']['operator'] = 'cer_right_path_op';
+  $handler->display->display_options['filters']['cer_right_path']['expose']['identifier'] = 'right';
+  $handler->display->display_options['filters']['cer_right_path']['expose']['remember_roles'] = array(
+    2 => '2',
+    1 => 0,
+  );
+  $views[$view->name] = $view;
+
+  return $views;
+}

+ 61 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_entity_settings/plugins/entityreference/selection/CerPresetSelectionHandler.class.php

@@ -0,0 +1,61 @@
+<?php
+
+class CerPresetSelectionHandler implements EntityReference_SelectionHandler {
+
+  private $entity;
+
+  public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
+    return new CerPresetSelectionHandler($entity_type, $entity);
+  }
+
+  public function __construct($entity_type, $entity) {
+    if ($entity_type && $entity) {
+      $this->entity = new EntityDrupalWrapper($entity_type, $entity);
+    }
+  }
+
+  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
+    $options = array();
+
+    if ($this->entity) {
+      $finder = new CerPresetFinder($this->entity);
+      $finder->execute();
+
+      foreach ($finder->result['cer'] as $preset) {
+        $options['cer'][$preset->pid] = $preset->label_variables['@right'];
+      }
+
+      foreach ($finder->result['cer__invert'] as $preset) {
+        $options['cer'][$preset->pid] = $preset->label_variables['@left'];
+      }
+    }
+
+    return $options;
+  }
+
+  public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
+    return sizeof($this->getReferencableEntities());
+  }
+
+  public function validateReferencableEntities(array $IDs) {
+    // Don't bother validating preset IDs.
+    return $IDs;
+  }
+
+  public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
+    return NULL;
+  }
+
+  public function entityFieldQueryAlter(SelectQueryInterface $query) {
+    // NOP
+  }
+
+  public function getLabel($entity) {
+    return entity_label('cer', $entity);
+  }
+
+  public static function settingsForm($field, $instance) {
+    return array();
+  }
+
+}

+ 6 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_entity_settings/plugins/entityreference/selection/cer.inc

@@ -0,0 +1,6 @@
+<?php
+
+$plugin = array(
+  'title' => t('CER Presets'),
+  'class' => 'CerPresetSelectionHandler',
+);

+ 12 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_ief/cer_ief.info

@@ -0,0 +1,12 @@
+name = "CER Inline Entity Form"
+core = "7.x"
+description = "Provides an option to hide CER fields on Inline Entity Forms."
+dependencies[] = cer
+dependencies[] = inline_entity_form
+
+; Information added by Drupal.org packaging script on 2016-02-12
+version = "7.x-3.0-alpha7+25-dev"
+core = "7.x"
+project = "cer"
+datestamp = "1455299962"
+

+ 94 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_ief/cer_ief.module

@@ -0,0 +1,94 @@
+<?php
+
+/**
+ * @file
+ * Provides an option to hide CER fields on inline entity forms. Spun off
+ * from Issue #2240371.
+ */
+
+/**
+ * Implements hook_form_FORM_ID_alter().
+ */
+function cer_ief_form_field_ui_field_edit_form_alter(array &$form, array &$form_state) {
+  // Add options to hide corresponding entity reference fields on inline entity forms.
+  $instance = $form['#instance'];
+  if ($instance['widget']['type'] == 'inline_entity_form') {
+    // Build a filter to fetch matching CER presets for this field instance.
+    $entity_type = $instance['entity_type'];
+    $bundle = $instance['bundle'];
+    $field_name = $instance['field_name'];
+    $filter = "{$entity_type}:{$bundle}:{$field_name}";
+
+    if ($presets = _cer_filter_presets($filter)) {
+      // There are available CER configurations for this IEF instance.
+      // Add option to hide field(s) on referenced entities.
+      $ief_settings = &$form['instance']['widget']['settings']['type_settings'];
+      $ief_settings['hide_cer_fields'] = array(
+        '#type' => 'checkbox',
+        '#title' => t('Hide corresponding entity reference field(s) on form.'),
+        '#default_value' => !empty($instance['widget']['settings']['type_settings']['hide_cer_fields']),
+      );
+      // @todo Add checkbox for each corresponding field?
+      // foreach ($presets as $preset) etc.
+    }
+  }
+}
+
+/**
+ * Implements hook_field_widget_form_alter().
+ *
+ * @todo This could be cached into an array and only rebuilt when a contextual
+ * field instance is updated or CER pattern added/removed.
+ */
+function cer_ief_field_widget_form_alter(array &$element, array &$form_state, array $context) {
+  // Only concerns fields within Inline Entity Forms.
+  if (isset($context['form']['#ief_id'])) {
+    // Get the form ID.
+    $ief_id = $context['form']['#ief_id'];
+
+    // Get instance information for the IEF field.
+    $ief_field_instance = $form_state['inline_entity_form'][$ief_id]['instance'];
+
+    // Check if "hide" is enabled on the IEF that is holding this field.
+    $hide_cer_fields = !empty($ief_field_instance['widget']['settings']['type_settings']['hide_cer_fields']);
+
+    if ($hide_cer_fields) {
+      // Get available CER chains. We use an ordinary static as this will be called for
+      // each field that belongs to an IEF with 'hide' enabled -- could be a lot.
+      static $plugins;
+
+      if (! isset($plugins)) {
+        // Load available CER field keys into a map. The actual plugin info isn't needed.
+        // We use drupal_map_assoc() so we can do isset() checks for plugins instead
+        // of calling in_array().
+        $plugins = drupal_map_assoc(array_keys(CerField::getPluginInfo()));
+      }
+
+      // Set up filter chains for the affected entities. The left chain is for the entity
+      // that has the IEF field on it, and the right chain is for the entity *in* the IEF.
+      $left_chain = $ief_field_instance['entity_type'] . ':' . $ief_field_instance['bundle'] . ':' . $ief_field_instance['field_name'];
+      $right_chain = $context['instance']['entity_type'] . ':' . $context['instance']['bundle'] . ':' . $context['instance']['field_name'];
+      // Ensure that both fields are CER fields. If they're not, bail out.
+      if (! isset($plugins[$left_chain], $plugins[$right_chain])) {
+        return;
+      }
+
+      // If a preset from parent to IEF exists, prevent access to the field.
+      foreach (_cer_filter_presets($left_chain) as $preset) {
+        // Check if the preset's right hand points to the instance found in the IEF.
+        if (strpos($preset->right, $right_chain) === 0) {
+          $match = TRUE;
+        }
+        elseif ($preset->bidirectional && strpos($preset->left, $right_chain) === 0) {
+          $match = TRUE;
+        }
+
+        // Matching chain found. Prevent access to this field and return.
+        if (isset($match)) {
+          $element['#access'] = FALSE;
+          return;
+        }
+      }
+    }
+  }
+}

+ 33 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_profile2/cer_profile2.cer.inc

@@ -0,0 +1,33 @@
+<?php
+
+/**
+ * Implements hook_cer_fields().
+ */
+function cer_profile2_cer_fields() {
+  $fields = array();
+
+  // Create a fake field for each Profile2 type.
+  foreach (array_keys(profile2_get_types()) as $profile_type) {
+    // Profiles can only be attached to user accounts.
+    $fields["user:user:profile_{$profile_type}"]['class'] = 'CerProfile2Field';
+  }
+
+  return $fields;
+}
+
+/**
+ * Implements hook_cer_fields_alter().
+ */
+function cer_profile2_cer_fields_alter(array &$fields) {
+  foreach (array_keys($fields) as $identifier) {
+    list ($entity_type, $bundle) = explode(':', $identifier);
+
+    // If this field is instantiated on a Profile2, make CER treat it like a field
+    // collection by first setting its parent field, and setting the 'require parent'
+    // flag so that CER won't allow it to stand alone in a field chain.
+    if ($entity_type == 'profile2') {
+      $fields[$identifier]['parents'][] = "user:user:profile_{$bundle}";
+      $fields[$identifier]['require parent'] = TRUE;
+    }
+  }
+}

+ 13 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_profile2/cer_profile2.info

@@ -0,0 +1,13 @@
+name = "CER Profile2"
+core = "7.x"
+description = "Allows CER to relate user references to Profile2 fields."
+dependencies[] = cer
+dependencies[] = profile2
+
+files[] = profile2.inc
+; Information added by Drupal.org packaging script on 2016-02-12
+version = "7.x-3.0-alpha7+25-dev"
+core = "7.x"
+project = "cer"
+datestamp = "1455299962"
+

+ 23 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_profile2/cer_profile2.install

@@ -0,0 +1,23 @@
+<?php
+
+/**
+ * Implements hook_disable().
+ */
+function cer_profile2_disable() {
+  foreach (entity_load('cer', FALSE) as $preset) {
+    if (_cer_profile2_is_profile2_preset($preset)) {
+      $preset->wrapper->cer_enabled->set(FALSE);
+    }
+  }
+}
+
+/**
+ * Implements hook_uninstall().
+ */
+function cer_profile2_uninstall() {
+  foreach (entity_load('cer', FALSE) as $preset) {
+    if (_cer_profile2_is_profile2_preset($preset)) {
+      entity_delete('cer', $preset->pid);
+    }
+  }
+}

+ 55 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_profile2/cer_profile2.module

@@ -0,0 +1,55 @@
+<?php
+
+define('CER_PROFILE2_PATTERN', '/^user:user:profile_/');
+
+/**
+ * Returns if either side of a preset refers to a profile2.
+ *
+ * @param \CerPreset $preset
+ *  The preset to test.
+ *
+ * @return bool
+ */
+function _cer_profile2_is_profile2_preset(CerPreset $preset) {
+  return preg_match(CER_PROFILE2_PATTERN, $preset->wrapper->cer_left->value()) || preg_match(CER_PROFILE2_PATTERN, $preset->wrapper->cer_right->value());
+}
+
+/**
+ * Implements hook_entity_property_info_alter().
+ */
+function cer_profile2_entity_property_info_alter(array &$info) {
+  $struct = &$info['profile2']['properties']['cer']['property info'];
+
+  $struct['lineage']['getter callback'] = 'cer_profile2_get_profile2_lineage';
+  $struct['depth']['getter callback'] = 'cer_profile2_get_profile2_depth';
+  $struct['owner']['getter callback'] = 'cer_profile2_get_profile2_owner';
+}
+
+/**
+ * Entity API getter callback. Returns the lineage of a Profile2 entity.
+ *
+ * @return string
+ */
+function cer_profile2_get_profile2_lineage(array $data, array $options, $property, $data_type, array $info) {
+  return 'user:user:profile_' . $data[1]->type . ':profile2:' . $data[1]->type . ':';
+}
+
+/**
+ * Entity API getter callback. Returns the depth of a Profile2. This is always
+ * 1, since the profile is embedded directly under the user account as far
+ * as CER is concerned.
+ *
+ * @return integer
+ */
+function cer_profile2_get_profile2_depth(array $data, array $options, $property, $data_type, array $info) {
+  return 1;
+}
+
+/**
+ * Entity API getter callback. Returns the user account which owns a Profile2.
+ *
+ * @return EntityDrupalWrapper.
+ */
+function cer_profile2_get_profile2_owner(array $data, array $options, $property, $data_type, array $info) {
+  return new EntityDrupalWrapper('user', $data[1]->user());
+}

+ 71 - 0
sites/all/modules/contrib/fields/cer/extensions/cer_profile2/profile2.inc

@@ -0,0 +1,71 @@
+<?php
+
+/**
+ * @file
+ * Contains a CER field plugin for referencing Profile2 entities. These references
+ * are not actually fields at all, so this plugin is really more of a bridge to
+ * trick CER into thinking that Profile2 is a reference field.
+ */
+
+class CerProfile2Field extends CerField implements CerEntityContainerInterface {
+
+  protected $profileType;
+
+  /**
+   * @override CerField::__construct().
+   */
+  public function __construct(array $plugin) {
+    $this->plugin = $plugin;
+    list ($this->entityType, $this->bundle, $this->name) = explode(':', $plugin['identifier']);
+
+    $info = entity_get_info($this->entityType);
+    // These "fields" can only be instantiated on user accounts, which are
+    // normally not bundleable. However, there could be a module in the wild
+    // which makes accounts bundleable, so let's not be presumptuous here.
+    $this->isBundleable = (boolean) $info['entity keys']['bundle'];
+    $this->entityTypeLabel = $info['label'];
+    $this->bundleLabel = $info['bundles'][$this->bundle]['label'];
+    // An account can only have one profile of this type.
+    $this->cardinality = 1;
+    $this->fieldTypeLabel = t('Profile');
+
+    // Load the Profile2 type information
+    $this->profileType = profile2_get_types(subStr($this->name, 8));
+    $this->label = $this->profileType->label;
+  }
+
+  /**
+   * Implements CerField::getTargetType().
+   */
+  public function getTargetType() {
+    // In effect, this "field" will "point to" Profile2 entities.
+    return 'profile2';
+  }
+
+  /**
+   * @override CerField::getTargetBundles().
+   */
+  public function getTargetBundles() {
+    // This field can only "reference" one type of profile. There'll be
+    // a separate instance of this plugin for each Profile2 type.
+    return (array) $this->profileType->type;
+  }
+
+  /**
+   * Implements CerEntityContainerInterface::createInnerEntity().
+   */
+  public function createInnerEntity(EntityDrupalWrapper $owner) {
+    $init = array(
+      'user' => $owner->value(),
+      'type' => $this->profileType,
+    );
+
+    // Create a blank profile for this user, and save it. The "reference" is implied
+    // by the existence of the profile.
+    $profile = profile2_create($init);
+    $profile->save();
+
+    return $profile;
+  }
+
+}

+ 17 - 0
sites/all/modules/contrib/fields/cer/field_object/field_object.info

@@ -0,0 +1,17 @@
+name = "Field Object"
+description = "Provides a field type that can refer to field instances."
+
+core = "7.x"
+
+dependencies[] = options
+
+files[] = includes/FieldChain.inc
+files[] = includes/FieldHierarchy.inc
+files[] = includes/FieldInstance.inc
+
+; Information added by Drupal.org packaging script on 2016-02-12
+version = "7.x-3.0-alpha7+25-dev"
+core = "7.x"
+project = "cer"
+datestamp = "1455299962"
+

+ 29 - 0
sites/all/modules/contrib/fields/cer/field_object/field_object.install

@@ -0,0 +1,29 @@
+<?php
+
+/**
+ * Implements hook_field_schema().
+ */
+function field_object_field_schema(array $field) {
+  return array(
+    'columns' => array(
+      'path' => array(
+        'type' => 'text',
+        'size' => 'tiny',
+        'description' => 'The path to the instance, represented as text.',
+      ),
+    ),
+  );
+}
+
+/**
+ * Fixes issue #2331553, and probably others.
+ */
+function field_object_update_7001() {
+  db_update('field_config')
+    ->fields(array(
+      'type' => 'field_object',
+      'module' => 'field_object',
+    ))
+    ->condition('field_name', array('cer_left', 'cer_right'))
+    ->execute();
+}

+ 151 - 0
sites/all/modules/contrib/fields/cer/field_object/field_object.module

@@ -0,0 +1,151 @@
+<?php
+
+/**
+ * Implements hook_theme().
+ */
+function field_object_theme() {
+  return array(
+    'field_object_label' => array(
+      'variables' => array(
+        'field' => array(),
+        'instance' => array(),
+      ),
+    ),
+  );
+}
+
+/**
+ * Implements hook_field_info().
+ */
+function field_object_field_info() {
+  return array(
+    'field_object' => array(
+      'label' => t('Field Reference'),
+      'description' => t('Refers to a field instance.'),
+      'settings' => array(),
+      'instance_settings' => array(
+        'function' => NULL,
+      ),
+      'default_widget' => 'options_select',
+      'default_formatter' => 'field_object_label',
+      'no_ui' => TRUE,
+      'property_type' => 'text',
+    ),
+  );
+}
+
+/**
+ * Implements hook_field_widget_info_alter().
+ */
+function field_object_field_widget_info_alter(array &$info) {
+  $info['options_select']['field types'][] = 'field_config_reference';
+}
+
+/**
+ * Implements hook_field_formatter_info().
+ */
+function field_object_field_formatter_info() {
+  return array(
+    'field_object_label' => array(
+      'label' => t('Label'),
+      'description' => t("The field instance's label."),
+      'field types' => array('field_object'),
+      'settings' => array(),
+    ),
+  );
+}
+
+/**
+ * Implements hook_field_is_empty().
+ */
+function field_object_field_is_empty(array $item, array $field) {
+  return empty($item['path']);
+}
+
+/**
+ * Implements hook_field_formatter_view().
+ */
+function field_object_field_formatter_view($entity_type, $entity, array $field, array $instance, $language, array $items, array $display) {
+  $element = array();
+
+  foreach ($items as $delta => $item) {
+    $label = array();
+
+    foreach (_field_object_expand_path($item['path']) as $field) {
+      $label[] = theme('field_object_label', $field);
+    }
+
+    $element[$delta]['#markup'] = implode(' » ', $label);
+  }
+
+  return $element;
+}
+
+/**
+ * Implements hook_options_list().
+ */
+function field_object_options_list(array $field, array $instance, $entity_type, $entity) {
+  return _field_object_build_hierarchy($field, $instance, $entity_type, $entity)->options();
+}
+
+/**
+ * Renders a human-readable label for a field instance, including the entity
+ * type and (if applicable) bundle that hosts it.
+ */
+function theme_field_object_label(array $variables) {
+  $instance = $variables['instance'];
+
+  $output = '';
+
+  if ($instance['entity_type'] != 'field_collection_item') {
+    $entity_type = entity_get_info($instance['entity_type']);
+    $output = $entity_type['label'] . ' » ';
+
+    if ($entity_type['entity keys']['bundle']) {
+      $output .= $entity_type['bundles'][ $instance['bundle'] ]['label'] . ' » ';
+    }
+  }
+
+  return $output . $instance['label'];
+}
+
+/**
+ * Helper function. Builds a FieldHierarchy object for the widget builder.
+ */
+function _field_object_build_hierarchy(array $field, array $instance, $entity_type, $entity) {
+  $hierarchy = new FieldHierarchy();
+
+  // The instance should define a function which returns an array of FieldChain
+  // objects to be added to the hierarchy.
+  $function = $instance['settings']['function'];
+
+  if ($function && is_callable($function)) {
+    $arguments = func_get_args();
+    $chains = (array) call_user_func_array($function, $arguments);
+
+    array_walk($chains, array($hierarchy, 'addChain'));
+  }
+
+  return $hierarchy;
+}
+
+/**
+ * Helper function. Expands a field reference's path value into an array
+ * of field and instance definitions.
+ */
+function _field_object_expand_path($path) {
+  $output = array();
+
+  foreach (explode('::', $path) as $instance) {
+    list ($entity_type, $bundle, $field) = explode(':', $instance);
+
+    $output[] = array(
+      'field' =>
+        field_info_field($field),
+      'instance' =>
+        field_info_instance($entity_type, $field, $bundle),
+    );
+  }
+
+  return $output;
+}

+ 126 - 0
sites/all/modules/contrib/fields/cer/field_object/includes/FieldChain.inc

@@ -0,0 +1,126 @@
+<?php
+
+/**
+ * @file
+ * Contains the FieldChain class.
+ */
+
+/**
+ * @class
+ * A doubly linked list of FieldInstance objects.
+ */
+class FieldChain implements SeekableIterator {
+
+  protected $chain = array();
+
+  protected $index = 0;
+
+  /**
+   * Magic post-unserialization callback. Provides every field in the chain
+   * with a reference to its parent (if any) and child (if any), effectively
+   * turning the chain into a doubly linked list.
+   */
+  public function __wakeup() {
+    foreach ($this->chain as $field) {
+      if (isset($parent)) {
+        $field->parent($parent)->child($field);
+      }
+      $parent = $field;
+    }
+  }
+
+  /**
+   * Represents this chain as a machine-readable string, separating the fields
+   * with a T_PAAMAYIM_NEKUDOTAYIM (or, as we call it on planet Earth, a
+   * double colon).
+   */
+  public function __toString() {
+    $key = array();
+
+    foreach ($this->chain as $field) {
+      $key[] = $field->__toString();
+    }
+
+    return implode('::', $key);
+  }
+
+  /**
+   * Prepends a field instance to this chain. If $completed is passed, we'll
+   * try to find the parents of the instance and recurse upwards, building
+   * a tree of "routes" to the instance.
+   */
+  public function addField(FieldInstance $field, array &$completed = NULL) {
+    array_unshift($this->chain, $field);
+    $this->__wakeup();
+
+    if (isset($completed)) {
+      $parents = $field->getParents();
+
+      if ($parents) {
+        foreach ($parents as $parent) {
+          $branch = clone $this;
+          $branch->addField($parent, $completed);
+        }
+      }
+      else {
+        $completed[] = $this;
+      }
+    }
+  }
+
+  /**
+   * Returns the last field in the chain.
+   */
+  public function end() {
+    return end($this->chain);
+  }
+
+  /**
+   * Implements SeekableIterator::seek().
+   */
+  public function seek($position) {
+    if ($position >= 0 && $position < sizeof($this->chain)) {
+      $this->index = $position;
+    }
+    else {
+      throw new OutOfBoundsException(t('Cannot seek to invalid position %position.', array('%position' => $position)));
+    }
+  }
+
+  /**
+   * Implements Iterator::current().
+   */
+  public function current() {
+    return $this->chain[$this->index];
+  }
+
+  /**
+   * Implements Iterator::key().
+   */
+  public function key() {
+    return $this->current()->__toString();
+  }
+  
+  /**
+   * Implements Iterator::next().
+   */
+  public function next() {
+    $this->index++;
+  }
+  
+  /**
+   * Implements Iterator::rewind().
+   */
+  public function rewind() {
+    $this->index = 0;
+  }
+
+  /**
+   * Implements Iterator::valid().
+   */
+  public function valid() {
+    return ($this->index < sizeof($this->chain));
+  }
+
+} 
+ 

+ 103 - 0
sites/all/modules/contrib/fields/cer/field_object/includes/FieldHierarchy.inc

@@ -0,0 +1,103 @@
+<?php
+
+/**
+ * @file
+ * Contains the FieldHierarchy class.
+ */
+
+class FieldHierarchy implements Countable {
+
+  /**
+   * @var array
+   *  The flattened hierarchy data.
+   */
+  protected $data = array();
+
+  const ROOT = 'root';
+
+  public function __get($property) {
+    return $this->{$property};
+  }
+
+  public function options($key = FieldHierarchy::ROOT, $parent = NULL, $depth = -1) {
+    $options = array();
+
+    $item = $this->data[$key];
+
+    if (isset($item['label'])) {
+      $options[$key] = str_repeat('-', $depth) . $item['label'];
+    }
+
+    if (isset($item['children'])) {
+      foreach ($item['children'] as $child) {
+        $options = array_merge($options, $this->options($child, $key, $depth + 1));
+      }
+    }
+
+    return $options;
+  }
+
+  /**
+   * Add an item of any type to the hierarchy.
+   */
+  public function add($item_key, $label = NULL, $parent = FieldHierarchy::ROOT) {
+    if (!array_key_exists($item_key, $this->data)) {
+      $this->data[$item_key]['label'] = isset($label) ? $label : $item_key;
+    }
+
+    if (!isset($this->data[$parent]['children'])) {
+      $this->data[$parent]['children'] = array();
+    }
+
+    if (!in_array($item_key, $this->data[$parent]['children'])) {
+      $this->data[$parent]['children'][] = $item_key;
+    }
+  }
+
+  /**
+   * Adds a single field plugin to the hierarchy.
+   */
+  public function addField(FieldInstance $field) {
+    $bundle_key = "{$field->entityType}:{$field->bundle}";
+
+    if ($field->isBundleable) {
+      $this->add($field->entityType, $field->entityTypeLabel);
+      $this->add($bundle_key, $field->bundleLabel, $field->entityType);
+    }
+    else {
+      $this->add($bundle_key, $field->entityTypeLabel);
+    }
+
+    $field_key = "{$bundle_key}:{$field->name}";
+    $this->add($field_key, $field->label, $bundle_key);
+  }
+
+  /**
+   * Adds an entire field chain to the hierarchy.
+   */
+  public function addChain(FieldChain $chain) {
+    $parents = array();
+
+    foreach ($chain as $field) {
+      if ($field->requireParent()) {
+        $parent_key = implode('::', $parents);
+        $field_key = "{$parent_key}::{$field}";
+
+        $this->add($field_key, $field->label, $parent_key);
+      }
+      else {
+        $this->addField($field);
+      }
+
+      $parents[] = $field->__toString();
+    }
+  }
+
+  /**
+   * @implements Countable::count().
+   */  
+  public function count() {
+    return sizeof($this->data);
+  }
+
+}

+ 127 - 0
sites/all/modules/contrib/fields/cer/field_object/includes/FieldInstance.inc

@@ -0,0 +1,127 @@
+<?php
+
+class FieldInstance {
+
+  /**
+   * @var string
+   * The instance's entity type.
+   */
+  public $entityType;
+
+  /**
+   * @var string
+   * The instance bundle.
+   */
+  public $bundle;
+
+  /**
+   * @var string
+   * The field's machine name.
+   */
+  public $name;
+
+  /**
+   * @var boolean
+   * Whether or not this instance's entity type supports bundles.
+   */
+  public $isBundleable;
+
+  /**
+   * @var string
+   * The human-readable label of the instance's entity type.
+   */
+  public $entityTypeLabel;
+
+  /**
+   * @var string
+   * The human-readable label of the instance's bundle.
+   */
+  public $bundleLabel;
+
+  /**
+   * @var integer
+   * The cardinality (maximum values) the field supports, or
+   * FIELD_CARDINALITY_UNLIMITED.
+   */
+  public $cardinality;
+
+  /**
+   * @var string
+   * The instance's label.
+   */
+  public $label;
+
+  /**
+   * @var FieldInstance
+   * The parent of this instance, if any.
+   */
+  protected $parent;
+
+  /**
+   * @var FieldInstance
+   * The child of this instance, if any.
+   */
+  protected $child;
+
+  public function __construct($entity_type, $bundle, $field_name) {
+    $this->entityType = $entity_type;
+    $this->bundle = $bundle;
+    $this->name = $field_name;
+
+    // Get info about the entity type and bundle hosting this field instance.
+    $info = entity_get_info($entity_type);
+    $this->isBundleable = (boolean) $info['entity keys']['bundle'];
+    $this->entityTypeLabel = $info['label'];
+    $this->bundleLabel = $info['bundles'][$bundle]['label'];
+
+    // Get global info about the field.
+    $info = field_info_field($field_name);
+    $this->cardinality = $info['cardinality'];
+
+    // Finally, get info about the field instance.
+    $instance = field_info_instance($entity_type, $field_name, $bundle);
+    $this->label = $instance['label'];
+  }
+
+  public function __toString() {
+    return "{$this->entityType}:{$this->bundle}:{$this->name}";
+  }
+
+  /**
+   * Get or set the parent of this field instance.
+   */
+  public function parent(FieldInstance $parent = NULL) {
+    if ($parent) {
+      $this->parent = $parent;
+    }
+    return $this->parent;
+  }
+
+  /**
+   * Get or set the child of this field instance.
+   */
+  public function child(FieldInstance $child = NULL) {
+    if ($child) {
+      $this->child = $child;
+    }
+    return $this->child;
+  }
+
+  /**
+   * Determine if this field requires a parent. An example of this would be
+   * a field that is instantiated on a field collection (which is itself
+   * a field).
+   */
+  public function requireParent() {
+    return FALSE;
+  }
+
+  /**
+   * Return the parents of this field instance as an array of FieldInstance
+   * objects. If there are no parents, return an empty array.
+   */
+  public function getParents() {
+    return array();
+  }
+
+}

+ 0 - 457
sites/all/modules/contrib/fields/cer/handler.inc

@@ -1,457 +0,0 @@
-<?php
-
-/**
- * @file
- * Contains base code for CER handlers, which are objects responsible for
- * creating, updating and deleting corresponding references between entities.
- */
-
-/**
- * Exception related to CER operations.
- */
-class CerException extends Exception {
-}
-
-interface CerHandlerInterface {
-
-  /**
-   * @constructor
-   *
-   * @param string $preset
-   *  The CER preset string, in the format:
-   *  entity_a*bundle_a*field_a*entity_b*bundle_b*field_b.
-   *
-   * @param $entity.
-   *  The local (home) entity to be wrapped by this instance.
-   */
-  public function __construct($preset, $entity);
-
-  /**
-   * Create reciprocal references on referenced entities after the
-   * local entity has been created.
-   */
-  public function insert();
-
-  /**
-   * Delete reciprocal references on entities the local entity is no
-   * longer referencing, and create new reciprocal references, after
-   * the local entity has been updated.
-   */
-  public function update();
-
-  /**
-   * Delete all reciprocal references after the local entity is deleted.
-   */
-  public function delete();
-  
-  /**
-   * Check if $entity is referenced by the local entity.
-   *
-   * @param object $entity
-   *  The remote entity.
-   *
-   * @return boolean
-   */
-  public function references($entity);
-
-  /**
-   * Check if the local entity is referenced by $entity.
-   *
-   * @param object $entity
-   *  The remote entiy.
-   *
-   * @return boolean
-   */
-  public function referencedBy($entity);
-  
-  /**
-   * Check if the remote entity can reference the local entity, and vice-versa.
-   *
-   * @param object $entity
-   *  The remote entity.
-   *
-   * @return boolean
-   */
-  public function referenceable($entity);
-
-  /**
-   * Create a reference to the local entity on the remote entity, and vice-versa
-   * if needed. Should throw CerException if the reference(s) can't be created
-   * for any reason.
-   *
-   * @param object $entity
-   */
-  public function reference($entity);
-
-  /**
-   * Delete all references to the remote entity from the local entity,
-   * and delete reciprocal references from the remote entity.
-   *
-   * @param object $entity.
-   */
-  public function dereference($entity);
-
-}
-
-/**
- * @class
- * Base class for CER handlers. All this does is parse the preset
- * and store instance info about the local and remote fields.
- */
-abstract class CerHandlerBase {
-
-  /**
-   * Local field instance definition.
-   */
-  protected $local;
-
-  /**
-   * Remote field instance definition.
-   */
-  protected $remote;
-
-  public function __construct($preset) {
-    $keys = explode('*', $preset);
-
-    if (sizeof($keys) != 6) {
-      throw new CerException(t('Invalid configuration: @preset', array('@preset' => $preset)));
-    }
-
-    $this->local = field_info_instance($keys[0], $keys[2], $keys[1]);
-    if ($this->local) {
-      $this->local['field'] = field_info_field($keys[2]);
-    }
-    else {
-      throw new CerException(t('Local field instance does not exist.'));
-    }
-
-    $this->remote = field_info_instance($keys[3], $keys[5], $keys[4]);
-    if ($this->remote) {
-      $this->remote['field'] = field_info_field($keys[5]);
-    }
-    else {
-      throw new CerException(t('Remote field instance does not exist.'));
-    }
-  }
-
-}
-
-/**
- * @class
- * Generic CER handler with rudimentary language handling.
- */
-class CerHandler extends CerHandlerBase implements CerHandlerInterface {
-
-  /**
-   * The local (home) entity.
-   */
-  protected $entity;
-
-  /**
-   * The local entity's ID.
-   */
-  protected $id;
-
-  /**
-   * Implements CerHandlerInterface::__construct().
-   */
-  public function __construct($preset, $entity) {
-    parent::__construct($preset);
-
-    // If $entity is of the wrong type, entity_extract_IDs()
-    // will throw EntityMalformedException here.
-    $extract_ids = entity_extract_IDs($this->local['entity_type'], $entity);
-    $this->id = array_shift($extract_ids);
-
-    $this->entity = $entity;
-  }
-
-  /**
-   * Implements CerHandlerInterface::insert().
-   */
-  public function insert($ids = NULL) {
-
-    if (empty($ids)) {
-      $entities = $this->getReferencedEntities();
-    }
-    else {
-      $entities = entity_load($this->remote['entity_type'], $ids);
-    }
-
-    foreach ($entities as $referenced_entity) {
-      $this->reference($referenced_entity);
-      _cer_update($this->remote['entity_type'], $referenced_entity);
-    }
-  }
-
-  /**
-   * Implements CerHandlerInterface::update().
-   */
-  public function update() {
-    $original = isset($this->entity->original) ? $this->entity->original : $this->entity;
-
-    $deleted = array_diff($this->getReferenceIDs($original, $this->local), $this->getLocalReferenceIDs());
-    if ($deleted) {
-      $entities = entity_load($this->remote['entity_type'], $deleted);
-      foreach ($entities as $referenced_entity) {
-        $this->dereference($referenced_entity);
-        _cer_update($this->remote['entity_type'], $referenced_entity);
-      }
-    }
-
-    $added = array_diff($this->getLocalReferenceIDs(), $this->getReferenceIDs($original, $this->local));
-
-    if (!empty($added)) {
-      $this->insert($added);
-    }
-  }
-
-  /**
-   * Implements CerHandlerInterface::delete().
-   */
-  public function delete() {
-    foreach ($this->getReferencedEntities() as $referenced_entity) {
-      $this->dereference($referenced_entity);
-      _cer_update($this->remote['entity_type'], $referenced_entity);
-    }
-  }
-
-  /**
-   * Implements CerHandlerInterface::references().
-   */  
-  public function references($entity) {
-    return in_array($this->getRemoteEntityID($entity), $this->getLocalReferenceIDs());
-  }
-
-  /**
-   * Implements CerHandlerInterface::referencedBy().
-   */
-  public function referencedBy($entity) {
-    return in_array($this->id, $this->getRemoteReferenceIDs($entity));
-  }
-
-  /**
-   * Implements CerHandlerInterface::referenceable().
-   */
-  public function referenceable($entity) {
-    $id = $this->getRemoteEntityID($entity);
-
-    $allowed = array(
-      entityreference_get_selection_handler(
-        $this->local['field'],
-        $this->local,
-        $this->local['entity_type'],
-        $this->entity
-      )
-        ->validateReferencableEntities(array($id)),
-      entityreference_get_selection_handler(
-        $this->remote['field'],
-        $this->remote,
-        $this->remote['entity_type'],
-        $entity
-      )
-        ->validateReferencableEntities(array($this->id)),
-    );
-
-    return in_array($id, $allowed[0]) && in_array($this->id, $allowed[1]);
-  }
-
-  /**
-   * Implements CerHandlerInterface::reference().
-   */
-  public function reference($entity) {
-    if ($this->referenceable($entity)) {
-      try {
-        $this->addReferenceTo($entity);
-      }
-      catch (CerException $e) {
-        // Fail silently
-      }
-    
-      try {
-        $this->addReferenceFrom($entity);
-      }
-      catch (CerException $e) {
-        // Fail silently
-      }
-    }
-    else {
-      $variables = array(
-        '!local_field' => $this->local['field_name'],
-        '!local_type' => $this->local['entity_type'],
-        '!local_id' => $this->id,
-        '!remote_field' => $this->remote['field_name'],
-        '!remote_type' => $this->remote['entity_type'],
-        '!remote_id' => $this->getRemoteEntityID($entity),
-      );
-      watchdog('cer', 'Failed to reference !remote_field on !remote_type !remote_id from !local_field on !local_type !local_id.', $variables, WATCHDOG_ERROR);
-    }
-  }
-
-  /**
-   * Implements CerHandlerInterface::dereference().
-   */
-  public function dereference($entity) {
-    if ($this->references($entity)) {
-      $id = $this->getRemoteEntityID($entity);
-
-      foreach ($this->entity->{$this->local['field_name']} as $language => $references) {
-        foreach ($references as $delta => $reference) {
-          if ($reference['target_id'] == $id) {
-            unset($this->entity->{$this->local['field_name']}[$language][$delta]);
-          }
-        }
-      }
-    }
-
-    if ($this->referencedBy($entity)) {
-      foreach ($entity->{$this->remote['field_name']} as $language => $references) {
-        foreach ($references as $delta => $reference) {
-          if ($reference['target_id'] == $this->id) {
-            unset($entity->{$this->remote['field_name']}[$language][$delta]);
-          }
-        }
-      }
-    }
-  }
-
-  /**
-   * Creates a reference to the local entity on the remote entity. Throws CerException
-   * if the local entity is already referenced by the remote entity, or if the remote
-   * field cannot hold any more values.
-   *
-   * @param object $entity
-   *  The remote entity.
-   */ 
-  protected function addReferenceFrom($entity) {
-    if ($this->referencedBy($entity)) {
-      throw new CerException(t('Cannot create duplicate reference from remote entity.'));
-    }
-    elseif ($this->filled($this->getRemoteReferenceIDs($entity), $this->remote['field'])) {
-      throw new CerException(t('Remote field cannot support any more references.'));
-    }
-    else {
-      $languages = field_available_languages($this->remote['entity_type'], $this->remote['field']);
-      foreach ($languages as $language) {
-        $entity->{$this->remote['field_name']}[$language][] = array('target_id' => $this->id);
-      }
-    }
-  }
-
-  /**
-   * Creates a reference to the remote entity on the local entity. Throws CerException
-   * if the local entity already references the remote entity, or if the field cannot
-   * hold any more values.
-   *
-   * @param object $entity
-   *  The remote entity.
-   */
-  protected function addReferenceTo($entity) {
-    $id = $this->getRemoteEntityID($entity);
-
-    if ($this->references($entity)) {
-      throw new CerException(t('Cannot create duplicate reference to remote entity.'));
-    }
-    elseif ($this->filled($this->getLocalReferenceIDs(), $this->local['field'])) {
-      throw new CerException(t('Local field cannot support any more references.'));
-    }
-    else {
-      $languages = field_available_languages($this->local['entity_type'], $this->local['field']);
-      foreach ($languages as $language) {
-        $this->entity->{$this->local['field_name']}[$language][] = array('target_id' => $id);
-      }
-    }
-  }
-
-  /**
-   * Get the ID of the remote entity. If the entity is of the wrong type,
-   * EntityMalformedException will be thrown.
-   *
-   * @param object $entity
-   *  The remote entity.
-   *
-   * @return mixed
-   *  The remote entity ID.
-   */
-  protected function getRemoteEntityID($entity) {
-    $extract_ids = entity_extract_IDs($this->remote['entity_type'], $entity);
-    return array_shift($extract_ids);
-  }
-
-  /**
-   * Gets all the entities referenced by the local entity.
-   *
-   * @return array
-   *  Array of fully loaded referenced entities keyed by ID, or empty
-   *  array if nothing has been referenced.
-   */
-  protected function getReferencedEntities() {
-    $IDs = $this->getLocalReferenceIDs();
-    return $IDs ? entity_load($this->remote['entity_type'], $IDs) : array();
-  }
-
-  /**
-   * Gets the IDs of the entities referenced by the local entity.
-   *
-   * @return array
-   *  Array of entity IDs, empty array if there are no references.
-   */
-  protected function getLocalReferenceIDs() {
-    return $this->getReferenceIDs($this->entity, $this->local);
-  }
-
-  /**
-   * Gets the IDs of the entities referenced by $entity.
-   *
-   * @param object $entity
-   *  The remote entity.
-   *
-   * @return array
-   *  Array of entity IDs, empty array if there are no references.
-   */
-  protected function getRemoteReferenceIDs($entity) {
-    return $this->getReferenceIDs($entity, $this->remote);
-  }
-
-  /**
-   * Check if a field can support any more values. Formerly known as
-   * "reference overloading".
-   *
-   * @param array $references
-   *  The values in the field.
-   *
-   * @param $field
-   *  Field definition (i.e., from field_info_field).
-   *
-   * @return boolean
-   */
-  private function filled($references, $field) {
-    return $field['cardinality'] != FIELD_CARDINALITY_UNLIMITED && sizeof($references) >= $field['cardinality'];
-  }
-
-  /**
-   * Gets all the referenced entity IDs from a specific field on $entity.
-   *
-   * @param object $entity
-   *  The entity to scan for references.
-   *
-   * @param array $field
-   *  Field or instance definition.
-   *
-   * @return array
-   *  Array of unique IDs, empty if there are no references or the field
-   *  does not exist on $entity.
-   */
-  private function getReferenceIDs($entity, $field) {
-    $IDs = array();
-    if (isset($entity->{$field['field_name']})) {
-      foreach ($entity->{$field['field_name']} as $references) {
-        foreach ($references as $reference) {
-          $IDs[] = $reference['target_id'];
-        }
-      }
-    }
-    return array_unique(array_filter($IDs));
-  }
-
-}

+ 9 - 0
sites/all/modules/contrib/fields/cer/help/cer.help.ini

@@ -0,0 +1,9 @@
+[intro]
+title = Introduction
+file = intro
+weight = 1
+
+[presets]
+title = Presets
+file = presets
+weight = 2

+ 17 - 0
sites/all/modules/contrib/fields/cer/help/intro.html

@@ -0,0 +1,17 @@
+<p>CER's purpose is to keep reference fields synchronized with each other.
+For example, if you have a node (&quot;Alice&quot;) with a user reference field,
+and a user (&quot;Bob&quot;) with a node reference field, and you make Alice 
+reference Bob, CER will automatically give Bob a back-reference to Alice. If 
+Alice subsequently dereferences Bob, Bob will automatically deference Alice. 
+Or, if Alice is deleted, Bob will lose his reference to Alice. CER does all
+this transparently.</p>
+
+<p>CER is a powerful module. It lets you create relationships between different
+&quot;reference-type&quot; fields. A <dfn>reference-type</dfn> field is, simply,
+any kind of field that references another entity. Out of the box, CER supports 
+Entity  Reference, Node Reference, User Reference, and core Taxonomy Term 
+Reference fields. It also includes a pair of add-on modules supporting Profile2
+and Commerce Product Reference fields. CER also has an object-oriented plugin 
+API that you can leverage if you need to support other types of reference 
+fields or alter CER's behavior. (More information about CER's API 
+can be found in cer.api.php.)</p>

+ 49 - 0
sites/all/modules/contrib/fields/cer/help/presets.html

@@ -0,0 +1,49 @@
+<p>When you install CER, it won’t do anything at all until you create at least
+one <dfn>preset</dfn>. A preset is a relationship between two reference field
+instances, which are referred to as the left and right fields, respectively.
+When a change occurs in the left field, the right field will react &mdash; and
+vice-versa.</p>
+
+<p>An example: suppose you have a user reference field called Author, and it 
+lives on Page nodes. You also have a node reference field called My Pages, and 
+it lives on users. You can set up a preset that looks like this:</p>
+
+<p>Node: Page: Author &lt;--&gt; User: My Pages</p>
+
+<p>In this case, Author is the left field and My Pages is the right field. When
+the Author field is changed on a Page node, the referenced user(s) will be
+given a back-reference to that node.</p>
+
+<p>By default, presets are <dfn>bidirectional</dfn>. This means that a change 
+on either side of the preset will affect the other side. The previous example 
+is bidirectional: you can change Author or My Pages, and the other side 
+will react accordingly.</p>
+
+<p>It's possible to make a preset <dfn>one-directional</dfn>, which means that 
+the right side will react when the left side changes, but NOT the other way 
+around. In a one-directional preset, changes to the right field will have no 
+effect on the left field.</p>
+
+<p>A one-directional version of the above example would look like this:</p>
+
+<p>Node: Page: Author —&gt; User: My Pages</p>
+
+<p>So what this means is that, in a bidirectional preset, it really doesn't 
+matter which field is the left one and which is the right one. They’ll affect 
+each other equally. But in a one-directional preset, it <em>does</em> matter 
+which side you're on. CER allows you to &quot;invert&quot; (flip) a 
+one-directional preset.</p>
+
+<p>Internally, CER treats all reference-type fields the same way, which allows 
+you to put a different kind of field on either side of a preset. You don't 
+have to necessarily relate a node reference field to another node reference 
+field. You could relate a node reference field to a user reference field. The 
+only restriction is that each side of the preset must be able to reference the 
+other side. So, to again use our example, Author needs to be able to reference 
+users, and My Pages needs to be able to reference nodes (of the Page type). 
+CER won't let you create relationships between fields that can’t actually 
+relate.</p>
+
+<p>CER presets are entities built on top of Entity API, and they can be 
+imported and exported just like any other exportable entity type, including
+support for Features.</p>

+ 82 - 0
sites/all/modules/contrib/fields/cer/includes/CerEndPointIterator.inc

@@ -0,0 +1,82 @@
+<?php
+
+/**
+ * @file
+ * Contains CerEndPointIterator.
+ */
+
+/**
+ * @class
+ * The purpose of this iterator is to wrap around all the "endpoints" in a field chain.
+ * An endpoint is a CerFieldHandler for a field that hasn't got a child. This is necessary
+ * in order to support infinite levels of embedded entities (read: field collections).
+ * This class is only instantiated by CerFieldChainHandler if its initial field handler
+ * has a child (@see CerFieldHandler::__construct()).
+ */
+class CerEndPointIterator implements RecursiveIterator {
+
+  /**
+   * @var CerField
+   */
+  protected $field;
+
+  /**
+   * @var CerFieldHandler
+   */
+  protected $handler;
+
+  public function __construct(CerField $field, EntityDrupalWrapper $entity) {
+    $this->field = $field;
+    $this->handler = $field->getHandler($entity);
+  }
+
+  /**
+   * Implements Iterator::current().
+   */
+  public function current() {
+    return $this->field->child()->getHandler($this->handler->current());
+  }
+
+  /**
+   * Implements Iterator::key().
+   */
+  public function key() {
+    return $this->handler->key();
+  }
+
+  /**
+   * Implements Iterator::next().
+   */
+  public function next() {
+    $this->handler->next();
+  }
+
+  /**
+   * Implements Iterator::rewind().
+   */
+  public function rewind() {
+    $this->handler->rewind();
+  }
+
+  /**
+   * Implements Iterator::handler().
+   */
+  public function valid() {
+    return $this->handler->valid();
+  }
+
+  /**
+   * Implements RecursiveIterator::hasChildren().
+   */
+  public function hasChildren() {
+    return ($this->field->child() instanceof CerEntityContainerInterface);
+  }
+
+  /**
+   * Implements RecursiveIterator::getChildren().
+   */
+  public function getChildren() {
+    return new CerEndPointIterator($this->field->child(), $this->handler->current());
+  }
+
+}

+ 24 - 0
sites/all/modules/contrib/fields/cer/includes/CerEntityContainerInterface.inc

@@ -0,0 +1,24 @@
+<?php
+
+/**
+ * @interface
+ *
+ * This interface should be implemented by field plugins which can create embedded
+ * entities on the fly.
+ *
+ * The prime example is field collections. CER might need to add a backreference on
+ * a field which is in a field collection, yet there might be no field collection items
+ * on which to add the reference. In that case, a new field collection item must be
+ * be created and referenced properly by the owner.
+ */
+interface CerEntityContainerInterface {
+
+  /**
+   * Creates an embedded entity.
+   *
+   * @return EntityDrupalWrapper
+   *  The newly created embedded entity, in a metadata wrapper.
+   */
+  public function createInnerEntity(EntityDrupalWrapper $owner);
+
+}

+ 159 - 0
sites/all/modules/contrib/fields/cer/includes/CerField.inc

@@ -0,0 +1,159 @@
+<?php
+
+/**
+ * @file
+ * Contains the base class for CER field plugins.
+ *
+ * A field plugin tells CER how to interact with fields of a certain type. If a particular
+ * field type integrates with Entity API, its CER plugin can be as simple as extending
+ * CerField and implementing the getTargetType() method.
+ *
+ * @todo
+ * More info about extending CerFieldHandler to further customize field plugins.
+ */
+
+/**
+ * @class
+ * Represents a single field instance.
+ */
+abstract class CerField extends FieldInstance {
+
+  /**
+   * @var array
+   * The plugin definition.
+   */
+  protected $plugin;
+
+  /**
+   * @var array
+   */
+  protected $settings = array();
+  
+  /**
+   * @var string
+   */
+  public $fieldTypeLabel;
+
+  /**
+   * Gets the type of entity that can be referenced by this field, e.g. 'node'.
+   *
+   * @return string
+   */
+  abstract public function getTargetType();
+
+  /**
+   * Constructor. Pretty self-explanatory!
+   */
+  public function __construct(array $plugin) {
+    // Store a copy of our plugin definition.
+    $this->plugin = $plugin;
+
+    list ($entity_type, $bundle, $field_name) = explode(':', $plugin['identifier']);
+    parent::__construct($entity_type, $bundle, $field_name);
+
+    // Store a copy of the field settings for convenience. At the time of this
+    // writing, this is needed by the Entity Reference, Node Reference,
+    // and Term Reference plugins.
+    $info = field_info_field($this->name);
+    $this->settings = $info['settings'];
+
+    $type_info = field_info_field_types($info['type']);
+    $this->fieldTypeLabel = $type_info['label'];
+  }
+
+  /**
+   * Returns a CerFieldHandler subclass instance for the given entity.
+   *
+   * @param object $entity
+   *  The entity to be wrapped by the handler.
+   *
+   * @return CerFieldHandler
+   */
+  public function getHandler(EntityDrupalWrapper $entity) {
+    return new $this->plugin['handler']($this, $entity);
+  }
+
+  /**
+   * Returns the bundles that this field instance can reference.
+   *
+   * @return array
+   */
+  public function getTargetBundles() {
+    $info = entity_get_info($this->getTargetType());
+    return array_keys($info['bundles']);
+  }
+
+  /**
+   * Overridden.
+   */
+  public function requireParent() {
+    return $this->plugin['require parent'];
+  }
+
+  /**
+   * Overridden.
+   */
+  public function getParents() {
+    return array_map('CerField::getPlugin', $this->plugin['parents']);
+  }
+
+  /**
+   * Returns information about a particular field plugin by its identifier, or all
+   * available plugins (i.e., defined by hook_cer_fields()) if no identifier is given.
+   * The aggregated result of hook_cer_fields() is statically cached.
+   */
+  public static function getPluginInfo($identifier = NULL) {
+    $info = &drupal_static(__METHOD__);
+
+    if (! isset($info)) {
+      $info = module_invoke_all('cer_fields');
+
+      foreach ($info as $key => &$field) {
+        $field += array(
+          'identifier' =>
+            $key,
+          'parents' =>
+            array(),
+          'require parent' =>
+            FALSE,
+          'handler' =>
+            'CerFieldHandler',
+        );
+      }
+      drupal_alter('cer_fields', $info);
+    }
+
+    return ($identifier ? (isset($info[$identifier]) ? $info[$identifier] : NULL) : $info);
+  }
+
+  /**
+   * Returns a single field plugin instance, by its identifier. All plugin instances
+   * are statically cached.
+   *
+   * @param string $identifier
+   *  The plugin's identifier, in the format entity_type:bundle:field_name.
+   *
+   * @return CerField
+   *
+   * @throws Exception if there's no plugin for the given identifier. Why so harsh, you
+   * ask? Because CerFieldChain::unpack() utterly depends on being able to get plugin
+   * instances for every field in the chain, and if it can't, it could result in myriad
+   * weird and serious problems. Throwing an exception will head that off at the pass.
+   */
+  public static function getPlugin($identifier) {
+    $instances = &drupal_static(__METHOD__);
+    
+    if (! isset($instances[$identifier])) {
+      $info = self::getPluginInfo($identifier);
+      if ($info) {
+        $instances[$identifier] = new $info['class']($info);
+      }
+      else {
+        throw new Exception("Cannot get instance of invalid plugin $identifier.");
+      }
+    }
+
+    return $instances[$identifier];
+  }
+
+}

+ 91 - 0
sites/all/modules/contrib/fields/cer/includes/CerFieldChain.inc

@@ -0,0 +1,91 @@
+<?php
+
+/**
+ * @file
+ *  Contains the CerFieldChain class.
+ */
+
+class CerFieldChain extends FieldChain {
+
+  /**
+   * Convenience method. Returns a handler for this chain in the context of
+   * the given entity.
+   *
+   * @return CerFieldChainHandler
+   */
+  public function getHandler(EntityDrupalWrapper $entity) {
+    return new CerFieldChainHandler($this, $entity);
+  }
+
+  /**
+   * Gets a regular expression to match field chain identifiers that this chain
+   * can reference, e.g. /^node:(page|article):/
+   */
+  public function regex() {
+    $end = $this->end();
+    return '/^' . $end->getTargetType() . ':(' . implode('|', $end->getTargetBundles()) . '):/';
+  }
+
+  /**
+   * Returns a Features export pipe for this chain, including every field and
+   * field instance in it.
+   */  
+  public function export() {
+    $pipe = array();
+
+    foreach ($this->chain as $field) {
+      $pipe['field_instance'][] = "{$field->entityType}-{$field->bundle}-{$field->name}";
+    }
+
+    return $pipe;
+  }
+
+  /**
+   * Returns an array of every possible field chain for every field defined in
+   * hook_cer_fields().
+   *
+   * @return array
+   */
+  public static function collectAll() {
+    $chains = array();
+
+    foreach (array_keys(CerField::getPluginInfo()) as $identifier) {
+      $chains = array_merge($chains, self::collect($identifier));
+    }
+
+    return $chains;
+  }
+
+  /**
+   * Returns an array of every possible field chain for a single field,
+   * identified by its key in hook_cer_fields().
+   *
+   * @return array
+   */
+  public static function collect($identifier) {
+    $chains = array();
+
+    $chain = new CerFieldChain();
+    $chain->addField(CerField::getPlugin($identifier), $chains);
+
+    return $chains;
+  }
+
+  /**
+   * Constructs and returns a CerFieldChain object from an encoded string
+   * of field plugin identifiers glued together with ::.
+   *
+   * @return CerFieldChain
+   */
+  public static function unpack($identifier) {
+    $chain = new CerFieldChain();
+
+    foreach (array_reverse(explode('::', $identifier)) as $field) {
+      $chain->addField(CerField::getPlugin($field));
+    }
+    
+    return $chain;
+  }
+
+} 
+ 

+ 107 - 0
sites/all/modules/contrib/fields/cer/includes/CerFieldChainHandler.inc

@@ -0,0 +1,107 @@
+<?php
+
+/**
+ * @file
+ * Contains the CerFieldChainHandler object.
+ */
+
+/**
+ * @class
+ * Wraps around every CerFieldHandler object in a chain. In any given chain, there
+ * could be many entities that need to be processed -- think about multi-value field
+ * collections embedded within other multi-value field collections, and you quickly
+ * see how extensive the recursion can be. CER needs to be able to handle crazy
+ * scenarios like that and still perform add/delete operations transparently. That's
+ * what this guy does.
+ */
+class CerFieldChainHandler {
+
+  /**
+   * @var CerFieldChain
+   */
+  protected $chain;
+
+  /**
+   * @var EntityDrupalWrapper
+   */
+  protected $entity;
+
+  /**
+   * @var array or RecursiveIteratorIterator
+   */
+  protected $handlers;
+
+  public function __construct(CerFieldChain $chain, EntityDrupalWrapper $entity) {
+    $this->chain = $chain;
+    $this->entity = $entity;
+
+    $chain->__wakeup();
+    $chain->seek($entity->cer->depth->value());
+
+    $field = $chain->current();
+
+    // If the field has a child, there could be extensive recusion here. So we'll need
+    // to iterate over the entire chain recursively -- luckily, SPL provides the
+    // RecursiveIteratorIterator class for this purpose. But if there are no children,
+    // we don't need to recurse; the only handler we'll need to load is the current
+    // field's, for the current entity.
+    if ($field->child()) {
+      $this->handlers = new RecursiveIteratorIterator(new CerEndPointIterator($field, $entity));
+    }
+    else {
+      // Wrap the handler in an array, just to normalize things internally.
+      $this->handlers = array( $field->getHandler($entity) );
+    }
+  }
+
+  /**
+   * Returns the IDs of every entity referenced in this chain. If there are no references,
+   * an empty array is returned.
+   *
+   * @return array
+   */
+  public function getIDs() {
+    $IDs = array();
+
+    foreach ($this->handlers as $handler) {
+      $IDs = array_merge($handler->getIDs(), $IDs);
+    }
+
+    return array_unique($IDs);
+  }
+
+  /**
+   * Adds a reference to the given entity.
+   */
+  public function add(EntityDrupalWrapper $entity) {
+    $owner = $this->entity;
+
+    foreach ($this->chain as $field) {
+      // If the current field implements CerEntityContainerInterface, we can
+      // create an entity on-the-fly to receive the reference, if there isn't
+      // one already.
+      if ($field instanceof CerEntityContainerInterface) {
+        $items = $field->getHandler($owner);
+
+        // If there is are items which could receive the reference, seek to the
+        // last one. Otherwise, create one.
+        if (sizeof($items) == 0) {
+          $owner = $field->createInnerEntity($owner);
+        }
+        else {
+          $items->seek(-1);
+          $owner = $items->current();
+        }
+      }
+    }
+
+    $field->getHandler($owner)->add($entity);
+  }
+
+  public function delete(EntityDrupalWrapper $entity) {
+    foreach ($this->handlers as $handler) {
+      $handler->delete($entity);
+    }
+  }
+
+}

+ 306 - 0
sites/all/modules/contrib/fields/cer/includes/CerFieldHandler.inc

@@ -0,0 +1,306 @@
+<?php
+
+/**
+ * @file
+ * Contains CerFieldHandler.
+ */
+ 
+/**
+ * @class
+ * Handles low-level operations for a single field on a single entity. Exposes
+ * methods to add, delete and check for references. This will also iterate over
+ * the references, returning each one as an EntityDrupalWrapper object.
+ */
+class CerFieldHandler implements Countable, SeekableIterator {
+
+  /**
+   * @var CerField
+   */
+  protected $field;
+
+  /**
+   * @var EntityDrupalWrapper
+   */
+  protected $entity;
+
+  /**
+   * @var EntityMetadataWrapper
+   */
+  protected $value;
+
+  /**
+   * @var integer
+   */
+  protected $delta = 0;
+  
+  /**
+   * @var boolean
+   */
+  protected $isMultiValue;
+
+  public function __construct(CerField $field, EntityDrupalWrapper $entity) {
+    $this->field = $field;
+    $this->entity = $entity;
+    $this->value = $entity->{ $field->name };
+    $this->isMultiValue = ($this->value instanceof EntityListWrapper);
+
+    $this->rewind();
+  }
+
+  /**
+   * Adds a reference to $entity, validating it first.
+   *
+   * @param EntityDrupalWrapper $entity
+   *  The wrapped entity to reference.
+   */
+  public function add(EntityDrupalWrapper $entity) {
+    if ($this->validate($entity)) {
+      $this->write();
+    }
+  }
+
+  /**
+   * Deletes all references to $entity.
+   *
+   * @param EntityDrupalWrapper $entity
+   *  The wrapped entity to dereference.
+   */
+  public function delete(EntityDrupalWrapper $entity) {
+    $entityID = $entity->getIdentifier();
+
+    if ($this->isMultiValue) {
+      foreach ($this->value as $delta => $ref) {
+        if ($entityID == $ref->getIdentifier()) {
+          $this->value[$delta]->set(NULL);
+        }
+      }
+    }
+    elseif ($entityID == $this->value->getIdentifier()) {
+      $this->value->set(NULL);
+    }
+
+    $this->write();
+  }
+
+  /**
+   * Validates a potential reference. After doing a cardinality check, the
+   * reference is validated through the Field Attach API, allowing the module
+   * which owns the field to do its normal validation logic. If validation
+   * fails, the error(s) are logged.
+   *
+   * @param EntityDrupalWrapper $entity
+   *  The wrapped entity to validate.
+   *
+   * @return boolean
+   */
+  protected function validate(EntityDrupalWrapper $entity) {
+    // Before we do anything else, check that the field has enough space to add the
+    // reference. If there isn't, bail out so we don't blindly overwrite existing
+    // field data.
+    if ($this->checkCardinality()) {
+      // Keep the previous value so we can restore it if validation fails.
+      $prev_value = $this->value->value();
+
+      if ($this->isMultiValue) {
+        $value = $this->value->value();
+        $value[] = $entity->value();
+        $this->value->set($value);
+      }
+      else {
+        $this->value->set( $entity->value() );
+      }
+
+      // Leverage the Field Attach API to validate the reference. If errors occur,
+      // field_attach_validate() throws FieldValidationException, containing an array
+      // of every validation error.
+      try {
+        // Only validate this field.
+        field_attach_validate($this->entity->type(), $this->entity->value(), array('field_name' => $this->field->name));
+
+        return TRUE;
+      }
+      catch (FieldValidationException $e) {
+        foreach ($e->errors as $field) {
+          foreach ($field as $language) {
+            foreach ($language as $errors) {
+              foreach ($errors as $error) {
+                $this->logError($error['message'], $entity);
+              }
+            }
+          }
+        }
+        $this->value->set($prev_value);
+      }
+    }
+    else {
+      $this->logError('Cannot add reference to !that_link from !field_label on !this_link because there are no more slots available.', $entity);
+    }
+
+    return FALSE;
+  }
+
+  /**
+   * Checks that there are enough slots in the field to add a reference.
+   *
+   * @return boolean
+   */
+  protected function checkCardinality() {
+    return ($this->field->cardinality == FIELD_CARDINALITY_UNLIMITED ? TRUE : ($this->field->cardinality > $this->count()));
+  }
+
+  /**
+   * Saves changes to the entity and resets the iterator.
+   */
+  protected function write() {
+    $entity_type = $this->entity->type();
+    $entityID = $this->entity->getIdentifier();
+    $entity = $this->entity->value();
+
+    $entity->cer_processed = TRUE;
+    entity_save($entity_type, $entity);
+
+    // Reload the entity we just saved and cleared from the static cache.
+    $entities = entity_load($entity_type, (array) $entityID);
+    $this->entity->set($entities[$entityID]);
+
+    $this->__construct($this->field, $this->entity);
+  }
+
+  /**
+   * Logs an error, optionally against a specific entity. If the cer_debug
+   * variable is set, the error will also be set as a message.
+   *
+   * @param string $message
+   *  The untranslated message to log.
+   *
+   * @param EntityDrupalWrapper $entity
+   *  The entity that has caused the error, if any.
+   */
+  protected function logError($message, EntityDrupalWrapper $entity = NULL) {
+    $variables = array(
+      '!field_name' => $this->field->name,
+      '!field_type' => $this->field->fieldTypeLabel,
+      '!field_label' => $this->field->label,
+    );
+
+    $variables['!this_type'] = $this->entity->type();
+    $variables['!this_label'] = $this->entity->label();
+
+    // If the entity has a URI, provide a link to it. Otherwise, its "link"
+    // will just be an unlinked label. Entity API doesn't reliably expose a url
+    // property on entities, and there doesn't appear to be a way to check for
+    // it without risking an EntityMetadataWrapperException. So I need to use
+    // this clunky BS instead...ugh.
+    $this_uri = entity_uri($this->entity->type(), $this->entity->value());
+    if (isset($this_uri)) {
+      $variables['!this_url'] = url($this_uri['path'], $this_uri['options']);
+      $variables['!this_link'] = l($this->entity->label(), $this_uri['path'], $this_uri['options']);
+    }
+    else {
+      $variables['!this_link'] = $this->entity->label();
+    }
+
+    if ($entity) {
+      $variables['!that_type'] = $entity->type();
+      $variables['!that_label'] = $entity->label();
+
+      // If the entity has a URI, link to it.
+      $that_uri = entity_uri($entity->type(), $entity->value());
+      if (isset($that_uri)) {
+        $variables['!that_url'] = url($that_uri['path'], $that_uri['options']);
+        $variables['!that_link'] = l($entity->label(), $that_uri['path'], $that_uri['options']);
+      }
+      else {
+        $variables['!that_link'] = $entity->label();
+      }
+    }
+
+    watchdog('cer', $message, $variables, WATCHDOG_ERROR);
+
+    if (variable_get('cer_debug', FALSE)) {
+      drupal_set_message(t($message, $variables), 'error');
+    }
+  }
+
+  public function getIDs() {
+    $IDs = array();
+
+    if ($this->isMultiValue) {
+      foreach ($this->value as $ref) {
+        $IDs[] = $ref->raw();
+      }
+    }
+    else {
+      $IDs[] = $this->value->raw();
+    }
+
+    return array_unique(array_filter($IDs));
+  }
+
+  /**
+   * Implements Countable::count().
+   */
+  public function count() {
+    if ($this->isMultiValue) {
+      return sizeof($this->value);
+    }
+    else {
+      return ($this->value->value() ? 1 : 0);
+    }
+  }
+
+  /**
+   * Implements SeekableIterator::seek().
+   */
+  public function seek($position) {
+    $length = $this->count();
+
+    if ($position < 0) {
+      $position += $length;
+    }
+
+    if ($position >= 0 && $position < $length) {
+      $this->delta = $position;
+    }
+    else {
+      throw new OutOfBoundsException(t('Cannot seek to invalid position.'));
+    }
+  }
+
+  /**
+   * Implements Iterator::current().
+   */
+  public function current() {
+    return ($this->isMultiValue ? $this->value[$this->delta] : $this->value);
+  }
+
+  /**
+   * Implements Iterator::key().
+   */
+  public function key() {
+    return $this->current()->getIdentifier();
+  }
+
+  /**
+   * Implements Iterator::next().
+   */
+  public function next() {
+    $this->delta++;
+  }
+  
+  /**
+   * Implements Iterator::rewind().
+   */
+  public function rewind() {
+    $this->delta = 0;
+  }
+
+  /**
+   * Implements Iterator::valid().
+   */
+  public function valid() {
+    return ($this->delta < $this->count());
+  }
+
+}
+ 

+ 75 - 0
sites/all/modules/contrib/fields/cer/includes/CerPreset.inc

@@ -0,0 +1,75 @@
+<?php
+
+/**
+ * @file
+ * Contains the entity class for CER presets.
+ */
+
+class CerPreset extends Entity {
+
+  /**
+   * @var integer
+   * The preset's numeric ID in the database.
+   */
+  public $pid = 0;
+
+  /**
+   * @var string
+   * The export identifier, in the format $this->cer_left*$this->cer_right.
+   */
+  public $identifier;
+
+  /**
+   * @var EntityMetadataWrapper
+   * A metadata wrapper around this preset, for convenience.
+   */
+  public $wrapper;
+
+  /**
+   * @var integer
+   * The exportable status of this preset.
+   */
+  public $status = 0x01;  // ENTITY_CUSTOM
+
+  /**
+   * @var string
+   * The module exporting this preset.
+   */
+  public $module = 'cer';
+
+  /**
+   * Overrides Entity::__construct().
+   */
+  public function __construct(array $values = array()) {
+    parent::__construct($values, 'cer');
+    $this->wrapper = new EntityDrupalWrapper('cer', $this);
+  }
+
+  /**
+   * Overrides Entity::label().
+   */
+  public function label() {
+    return isset($this->label_variables) ? t('@left !operator @right', $this->label_variables) : $this->defaultLabel();
+  }
+
+  /**
+   * Overrides Entity::save().
+   */
+  public function save() {
+    // Generate the export identifier automagically before saving.
+    $this->identifier = $this->wrapper->cer_left->value() . '*' . $this->wrapper->cer_right->value();
+    parent::save();
+  }
+
+  public function invert() {
+    $init = get_object_vars($this);
+
+    unset($init['pid'], $init['wrapper'], $init['identifier'], $init['status']);
+
+    $buf = $init['cer_left'];
+    $init['cer_left'] = $init['cer_right'];
+    $init['cer_right'] = $buf;
+
+    return entity_create('cer', $init);
+  }
+}

+ 50 - 0
sites/all/modules/contrib/fields/cer/includes/CerPresetController.inc

@@ -0,0 +1,50 @@
+<?php
+
+/**
+ * The controller class for CerPreset entities.
+ */
+class CerPresetController extends EntityAPIControllerExportable {
+
+  /**
+   * Overridden.
+   */
+  public function export($entity, $prefix = '') {
+    $variables = get_object_vars($entity);
+    
+    // I really wish Entity API tried to notify the entity that it's being
+    // exported so that it could clean itself up first, but it doesn't. So we
+    // gotta do this bizness.
+    unset($variables['pid'], $variables['wrapper'], $variables['status'], $variables['module'], $variables['label_variables'], $variables['uid']);
+    // Features 2.x checks for overriddenness using sorted keys, which means
+    // that if the variables aren't key-sorted the presets will always be
+    // considered overridden, even if they actually aren't.
+    ksort($variables);
+
+    return entity_var_json_export($variables, $prefix);
+  }
+
+  /**
+   * Overridden.
+   */
+  protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
+    parent::attachLoad($queried_entities, $revision_id);
+
+    foreach ($queried_entities as $preset) {
+      // Attach variables used to build the human-readable preset label. These
+      // need to be attached after the Field API has done its magic (i.e.,
+      // during parent::attachLoad()), since the label depends on field values.
+      // @see CerPreset::label().
+      $fields = field_attach_view('cer', $preset, 'default');
+
+      $preset->label_variables = array(
+        '@left' =>
+          render($fields['cer_left'][0]),
+        '@right' =>
+          render($fields['cer_right'][0]),
+        '!operator' =>
+          $preset->wrapper->cer_bidirectional->value() ? '<>' : '>',
+      );
+    }
+  }
+
+}

+ 26 - 0
sites/all/modules/contrib/fields/cer/includes/CerPresetFeaturesController.inc

@@ -0,0 +1,26 @@
+<?php
+
+/**
+ * Contains the controller class for exporting CER presets via Features.
+ */
+
+class CerPresetFeaturesController extends EntityDefaultFeaturesController {
+
+  /**
+   * Overridden.
+   */
+  public function export($data, &$export, $module = '') {
+    $pipe = parent::export($data, $export, $module);
+
+    // Every field in both chains may need to export additional things (the
+    // field base and instance definitions at least, plus any extra dependencies).
+    // All that logic is delegated to CerFieldChain.
+    foreach (entity_load_multiple_by_name($this->type, $data) as $preset) {
+      $pipe = array_merge_recursive($pipe, $preset->wrapper->cer_left->chain->value()->export());
+      $pipe = array_merge_recursive($pipe, $preset->wrapper->cer_right->chain->value()->export());
+    }
+
+    return $pipe;
+  }
+
+}

+ 71 - 0
sites/all/modules/contrib/fields/cer/includes/CerPresetFinder.inc

@@ -0,0 +1,71 @@
+<?php
+
+/**
+ * This class is a unified way for CER to find the presets that apply to a given
+ * entity. The result set is segmented into two parts: presets where the entity
+ * is on the left side, and bidirectional presets with the entity on the right
+ * side (i.e., the ones which need to be inverted before use). The execute()
+ * method will return a merged and sorted array of presets, but the segmented
+ * result set is exposed to the world as well for other uses (i.e., CER Entity
+ * Settings' selection handler).
+ */
+class CerPresetFinder extends EntityFieldQuery {
+
+  public $result = array();
+
+  protected $entity;
+
+  public function __construct(EntityDrupalWrapper $entity) {
+    $this->entity = $entity;
+
+    $this
+      ->entityCondition('entity_type', 'cer')
+      ->addTag('cer_presets')
+      ->addMetaData('entity', $entity);
+  }
+
+  public function execute() {
+    $lineage = $this->entity->cer->lineage->value();
+
+    $this->result['cer'] = $this
+      ->fieldCondition('cer_enabled', 'value', TRUE)
+      ->fieldCondition('cer_left', 'path', $lineage, 'STARTS_WITH')
+      ->_load(parent::execute());
+
+    $this->fieldConditions = array();
+
+    $this->result['cer__invert'] = $this
+      ->fieldCondition('cer_enabled', 'value', TRUE)
+      ->fieldCondition('cer_bidirectional', 'value', TRUE)
+      ->fieldCondition('cer_right', 'path', $lineage, 'STARTS_WITH')
+      ->_load(parent::execute());
+      
+    $result = $this->result['cer'];
+    foreach ($this->result['cer__invert'] as $preset) {
+      $result[] = $preset->invert();
+    }
+    usort($result, array($this, '_sort'));
+
+    return $result;
+  }
+
+  private function _load(array $result) {
+    return isset($result['cer']) ? entity_load('cer', array_keys($result['cer'])) : array();
+  }
+
+  private function _sort(CerPreset $a, CerPreset $b) {
+    $a_weight = $a->wrapper->cer_weight->value();
+    $b_weight = $b->wrapper->cer_weight->value();
+
+    if ($a_weight > $b_weight) {
+      return 1;
+    }
+    elseif ($b_weight > $a_weight) {
+      return -1;
+    }
+    else {
+      return 0;
+    }
+  }
+
+}

+ 155 - 0
sites/all/modules/contrib/fields/cer/includes/CerPresetHandler.inc

@@ -0,0 +1,155 @@
+<?php
+
+/**
+ * @file
+ *  Contains CerPresetHandler.
+ */
+
+/**
+ * @class
+ * Contains the logic for performing CER operations on a single entity, 
+ * using a single preset.
+ */
+class CerPresetHandler {
+
+  /**
+   * @var CerFieldChain
+   */
+  protected $left;
+  
+  /**
+   * @var CerFieldChain
+   */
+  protected $right;
+
+  /**
+   * @var EntityDrupalWrapper
+   */
+  protected $entity;
+
+  /**
+   * @var array
+   */
+  protected $refIDs;
+
+  public function __construct(CerPreset $preset, EntityDrupalWrapper $entity) {
+    $this->left = $preset->wrapper->cer_left->chain->value();
+    $this->right = $preset->wrapper->cer_right->chain->value();
+    $this->entity = $entity;
+
+    // Store the current set of reference IDs so that we only need to instantiate
+    // the left handler once.
+    $this->refIDs = $this->left->getHandler( $entity )->getIDs();
+  }
+
+  /**
+   * Process an entity insert. This loops through the referenced entity $IDs and
+   * adds a reference to this entity if the reference doesn't already have one.
+   */
+  public function insert(array $IDs = array()) {
+    // If no IDs were passed in, use the current reference set.
+    $IDs = ($IDs ? $IDs : $this->refIDs);
+
+    // Get this entity's ID right now, so we don't have to keep calling
+    // $this->entity->cer->owner->getIdentifier(). Hooray for micro-optimization!
+    $myID = $this->entity->cer->owner->getIdentifier();
+
+    foreach ($this->load( $IDs ) as $ref) {
+      $handler = $this->right->getHandler( $ref );
+
+      // Only create the backreference if the reference doesn't already reference
+      // this entity (which it might, if there is more than one preset that references
+      // a single field instance).
+      if (! in_array($myID, $handler->getIDs())) {
+        $handler->add( $this->entity->cer->owner );
+      }
+    }
+  }
+
+  /**
+   * Process an entity update. This could be either a normal update done by a user,
+   * or a bulk update.
+   */
+  public function update() {
+    // Get the previous set of reference IDs. $entity->cer->original will return either
+    // $entity->original, if it exists, or the current entity. So, if this is a bulk
+    // update, $originalIDs will be identical to $this->refIDs.
+    $originalIDs = $this->left->getHandler( $this->entity->cer->original )->getIDs();
+
+    // If there are any references that were in the previous set but not the current
+    // set, delete those backreferences. Under normal circumstances, there will be
+    // nothing to delete during a bulk update, since the previous set and current
+    // set should be identical.
+    $deleted = array_diff($originalIDs, $this->refIDs);
+    if ($deleted) {
+      $this->delete($deleted);
+    }
+
+    // If the previous set is identical to the current set, we'll be processing
+    // all existing references (see the first line of $this->insert()).
+    $added = array_diff($this->refIDs, $originalIDs);
+    $this->insert($added);
+  }
+
+  /**
+   * Process an entity delete. Loops through the referenced entity IDs and clears
+   * their references to this entity.
+   */
+  public function delete(array $IDs = array()) {
+    // As with $this->insert(), we can process a specific set of references or
+    // everything in the current set.
+    $IDs = ($IDs ? $IDs : $this->refIDs);
+
+    foreach ($this->load( $IDs ) as $ref) {
+      $this->right->getHandler( $ref )->delete( $this->entity->cer->owner );
+    }
+  }
+  
+  /**
+   * Loads referenced entities. This might seem like a convenience method, but it
+   * is a critical part CER's core logic.
+   *
+   * @param array $IDs
+   *  Array of entity IDs to load.
+   *
+   * @return array
+   *  The requested entities, wrapped by EntityDrupalWrapper. If nothing could be
+   *  loaded, an empty array is returned.
+   */
+  protected function load(array $IDs) {
+    if (empty($IDs)) {
+      return array();
+    }
+
+    $this->right->rewind();
+    $right = $this->right->current();
+    $entity_type = $right->entityType;
+
+    $query = new EntityFieldQuery();
+    $query->entityCondition('entity_type', $entity_type);
+    $query->entityCondition('entity_id', $IDs);
+
+    // If the right entity type has bundles, we need to filter by that too. If we don't,
+    // we could run into a bug where, if the left field can reference multiple bundles,
+    // we might try to modify the wrong entity. Essentially, the loading of referenced
+    // entities should be as targeted as possible to prevent ambiguities and buggery.
+    if ($right->isBundleable) {
+      $query->entityCondition('bundle', $right->bundle);
+    }
+
+    $result = $query->execute();
+    if (isset($result[$entity_type])) {
+      $result[$entity_type] = entity_load($entity_type, array_keys($result[$entity_type]));
+      
+      foreach ($result[$entity_type] as $id => $entity) {
+        $result[$entity_type][$id] = new EntityDrupalWrapper($entity_type, $entity);
+      }
+
+      return $result[$entity_type];
+    }
+    else {
+      return array();
+    }
+  }
+
+} 

+ 220 - 0
sites/all/modules/contrib/fields/cer/includes/CerUIController.inc

@@ -0,0 +1,220 @@
+<?php
+
+/**
+ * Contains the controller class for CER's UI (i.e., preset management pages),
+ * used by Entity API.
+ */
+
+class CerUIController extends EntityDefaultUIController {
+
+  public function hook_menu() {
+    $items = parent::hook_menu();
+
+    $items[$this->path]['title'] = t('Corresponding Entity References');
+    $items["{$this->path}/list"]['title'] = t('Presets');
+
+    $this->setTitle($items["{$this->path}/add"], t('Add preset'));
+    $this->setTitle($items["{$this->path}/import"], t('Import preset'));
+
+    $items["{$this->path}/manage/%entity_object/toggle"] = $this->createCallback('cer_toggle_preset', 'update');
+    $items["{$this->path}/manage/%entity_object/invert"] = $this->createCallback('cer_invert_preset', 'create');
+
+    // Don't provide a page for cloning a preset.
+    unset($items["{$this->path}/manage/%entity_object/clone"]);
+
+    return $items;
+  }
+
+  private function createCallback($function, $operation, array $init = array()) {
+    return $init + array(
+      'type' => MENU_CALLBACK,
+      'page callback' => $function,
+      'page arguments' => array(5),
+      'load arguments' => array('cer'),
+      'access callback' => 'entity_access',
+      'access arguments' => array($operation, 'cer'),
+      'file' => 'cer.admin.inc',
+      'file path' => drupal_get_path('module', 'cer'),
+    );
+  }
+
+  /**
+   * Sets a static title on a menu item.
+   */
+  private function setTitle(array &$item, $title) {
+    $item['title'] = $title;
+    unset($item['title callback'], $item['title arguments']);
+  }
+
+  public function operationForm($form, &$form_state, $entity, $action) {
+    switch ($action) {
+      case 'delete':
+        return confirm_form($form, t('Are you sure you want to delete this preset?'), $this->path, t('@left will no longer synchronize with @right.', $entity->label_variables));
+
+      default:
+        return parent::operationForm($form, $form_state, $entity, $action);
+    }
+  }
+
+  public function overviewForm($form, &$form_state) {
+    $form = parent::overviewForm($form, $form_state);
+
+    $form['actions'] = array(
+      'update' => array(
+        '#type' => 'submit',
+        '#value' => t('Save changes'),
+      ),
+      '#type' => 'actions',
+    );
+
+    return $form;
+  }
+
+  public function overviewFormSubmit($form, &$form_state) {
+    foreach ($form_state['values']['table'] as $id => $values) {
+      $preset = entity_object_load($id, $this->entityType);
+      
+      $preset->wrapper->cer_enabled->set($values['cer_enabled'][LANGUAGE_NONE][0]['value']);
+      $preset->wrapper->cer_bidirectional->set($values['cer_bidirectional'][LANGUAGE_NONE][0]['value']);
+      $preset->wrapper->cer_weight->set($values['cer_weight'][LANGUAGE_NONE][0]['value']);
+
+      $preset->save();
+    }
+
+    drupal_set_message(t('The changes have been saved.'));
+  }
+
+  public function overviewTable($conditions = array()) {
+    $render = array(
+      '#header' => array(
+        t('Left Field'),
+        t('Right Field'),
+        t('Status'),
+        t('Enabled'),
+        t('Bidirectional'),
+        t('Weight'),
+        t('Operations'),
+      ),
+      '#tabledrag' => array(
+        array(
+          'action' => 'order',
+          'relationship' => 'sibling',
+          'group' => 'cer-weight',
+        ),
+      ),
+      '#empty' => t('None.'),
+      '#type' => 'table',
+    );
+
+    $query = new EntityFieldQuery();
+    $query->entityCondition('entity_type', $this->entityType);
+
+    // Add all conditions to query.
+    foreach ($conditions as $key => $value) {
+      $query->propertyCondition($key, $value);
+    }
+
+    if ($this->overviewPagerLimit) {
+      $query->pager($this->overviewPagerLimit);
+    }
+    
+    $query->fieldOrderBy('cer_weight', 'value');
+
+    $results = $query->execute();
+    $entities = isset($results['cer']) ? entity_load('cer', array_keys($results['cer'])) : array();
+
+    foreach ($entities as $entity) {
+      $render[$entity->pid] = $this->overviewTableRow($conditions, $entity->pid, $entity);
+    }
+
+    return $render;
+  }
+
+  protected function overviewTableRow($conditions, $id, $entity, $additional_cols = array()) {
+    $render_fields = field_attach_view($this->entityType, $entity, 'default');
+
+    $render_fields['cer_left']['#label_display'] = 'inline';
+    $render_fields['cer_left']['#title'] = $entity->wrapper->cer_left->chain->value()->end()->fieldTypeLabel;
+    $row['cer_left'] = $render_fields['cer_left'];
+
+    $render_fields['cer_right']['#label_display'] = 'inline';
+    $render_fields['cer_right']['#title'] = $entity->wrapper->cer_right->chain->value()->end()->fieldTypeLabel;
+    $row['cer_right'] = $render_fields['cer_right'];
+
+    $row['status'] = array(
+      '#theme' => 'entity_status',
+      '#status' => $entity->status,
+    );
+
+    $form_fields = array();
+    $form_state = form_state_defaults();
+    $form_state['build_info']['form_id'] = 'cer_overview_form';
+    field_attach_form($this->entityType, $entity, $form_fields, $form_state);
+
+    unset($form_fields['cer_enabled'][LANGUAGE_NONE]['#title']);
+    $row['cer_enabled'] = $form_fields['cer_enabled'];
+
+    unset($form_fields['cer_bidirectional'][LANGUAGE_NONE]['#title']);
+    $row['cer_bidirectional'] = $form_fields['cer_bidirectional'];
+
+    unset($form_fields['cer_weight'][LANGUAGE_NONE]['#title']);
+    $form_fields['cer_weight'][LANGUAGE_NONE]['#attributes']['class'][] = 'cer-weight';
+    $row['cer_weight'] = $form_fields['cer_weight'];
+
+    // Add in any passed additional cols.
+    foreach ($additional_cols as $key => $col) {
+      $row[$key] = $col;
+    }
+
+    // I like drop buttons more than an inline set of links.
+    $links = array(
+      'toggle' => array(
+        'title' => $entity->wrapper->cer_enabled->value() ? t('disable') : t('enable'),
+        'href' => "{$this->path}/manage/{$id}/toggle",
+        'query' => drupal_get_destination(),
+      ),
+      'edit' => array(
+        'title' => t('edit'),
+        'href' => "{$this->path}/manage/{$id}",
+      ),
+    );
+
+    // If the preset is one-directional, expose a link to invert it.
+    if (! $entity->wrapper->cer_bidirectional->value()) {
+      $links['invert'] = array(
+        'title' => t('invert'),
+        'href' => "{$this->path}/manage/{$id}/invert",
+        'query' => drupal_get_destination(),
+      );
+    }
+
+    if (entity_has_status($this->entityType, $entity, ENTITY_OVERRIDDEN)) {
+      $links['revert'] = array(
+        'title' => t('revert'),
+        'href' => "{$this->path}/manage/{$id}/revert",
+        'query' => drupal_get_destination(),
+      );
+    }
+    else {
+      $links['delete'] = array(
+        'title' => t('delete'),
+        'href' => "{$this->path}/manage/{$id}/delete",
+        'query' => drupal_get_destination(),
+      );
+    }
+    $links['export'] = array(
+      'title' => t('export'),
+      'href' => "{$this->path}/manage/{$id}/export",
+    );
+
+    $row['operations'] = array(
+      '#theme' => 'links__ctools_dropbutton',
+      '#links' => $links,
+    );
+
+    $row['#attributes']['class'][] = 'draggable';
+
+    return $row;
+  }
+
+}

+ 55 - 0
sites/all/modules/contrib/fields/cer/includes/fields/entity_reference.inc

@@ -0,0 +1,55 @@
+<?php
+
+/**
+ * @file
+ * Contains the CER plugin for Entity Reference fields.
+ */
+ 
+class CerEntityReferenceField extends CerField {
+
+  /**
+   * Implements CerField::getTargetType().
+   */
+  public function getTargetType() {
+    return $this->settings['target_type'];
+  }
+  
+  /**
+   * @override CerField::getTargetBundles().
+   */
+  public function getTargetBundles() {
+    $bundles = array();
+
+    // If the reference field is using a view, load the view and see if it's filtering by the entity
+    // type's bundle filter. If it is, the filter values are the target bundles. Otherwise,
+    // assume that all bundles can be referenced.
+    //
+    // @todo Support contextual filters?
+    //
+    // NOTE: Selection handlers (i.e., $field['settings']['handler']) are plugins owned by
+    // Entity Reference. There is no method defined to get an array of referenceable
+    // bundles, but hopefully, if CER gains enough traction in the community, such a
+    // method can be added to the EntityReference_SelectionHandler interface. This
+    // function could then be deprecated, which would be a more flexible, future-proof
+    // method of finding a field's target bundles.
+    //
+    if ($this->settings['handler'] == 'views') {
+      $view = views_get_view($this->settings['handler_settings']['view']['view_name']);
+      $view->set_display($this->settings['handler_settings']['view']['display_name']);
+
+      $info = entity_get_info($this->getTargetType());
+      if (isset($info['entity keys']['bundle'])) {
+        $handler = $view->display_handler->get_handler('filter', $info['entity keys']['bundle']);
+        if ($handler) {
+          $bundles = $handler->value;
+        }
+      }
+    }
+    else {
+      $bundles = $this->settings['handler_settings']['target_bundles'];
+    }
+
+    return ($bundles ? $bundles : parent::getTargetBundles());
+  }
+
+}

+ 39 - 0
sites/all/modules/contrib/fields/cer/includes/fields/field_collection.inc

@@ -0,0 +1,39 @@
+<?php
+
+/**
+ * @file
+ * Contains the CER plugin for Field Collection fields.
+ */
+
+class CerFieldCollectionField extends CerField implements CerEntityContainerInterface {
+
+  /**
+   * Implements CerField::getTargetType().
+   */
+  public function getTargetType() {
+    return 'field_collection_item';
+  }
+
+  /**
+   * @override CerField::getTargetBundles().
+   */
+  public function getTargetBundles() {
+    return array($this->name);
+  }
+
+  /**
+   * Implements CerEntityContainerInterface::createInnerEntity().
+   */
+  public function createInnerEntity(EntityDrupalWrapper $owner) {
+    // Create an empty field collection item.
+    $collection = new EntityDrupalWrapper('field_collection_item', entity_create('field_collection_item', array('field_name' => $this->name)));
+    $collection->host_entity->set( $owner );
+    $collection->save(TRUE);
+
+    // 'Reference' the newly created field collection item.
+    $this->getHandler($owner)->add($collection);
+
+    return $collection;
+  }
+
+}

+ 41 - 0
sites/all/modules/contrib/fields/cer/includes/fields/node_reference.inc

@@ -0,0 +1,41 @@
+<?php
+
+/**
+ * @file
+ * Contains the CER plugin for Node Reference fields.
+ */
+ 
+class CerNodeReferenceField extends CerField {
+
+  /**
+   * Implements CerField::getTargetType().
+   */
+  public function getTargetType() {
+    return 'node';
+  }
+
+  /**
+   * @override CerField::getTargetBundles().
+   */
+  public function getTargetBundles() {
+    $bundles = array();
+
+    $view = $this->settings['view']['view_name'];
+    if ($view) {
+      $view = views_get_view($view);
+      $view->set_display($this->settings['view']['view_display']);
+
+      $handler = $view->display_handler->get_handler('filter', 'type');
+      if ($handler) {
+        $bundles = $handler->value;
+      }
+    }
+    else {
+      $bundles = array_filter($this->settings['referenceable_types']);
+    }
+
+    return ($bundles ? $bundles : parent::getTargetBundles());
+  }
+
+}
+ 

+ 30 - 0
sites/all/modules/contrib/fields/cer/includes/fields/taxonomy_term_reference.inc

@@ -0,0 +1,30 @@
+<?php
+
+/**
+ * @file
+ * Contains the CER plugin for Taxonomy Term Reference fields.
+ */
+ 
+class CerTaxonomyTermReferenceField extends CerField {
+
+  /**
+   * Implements CerField::getTargetType().
+   */
+  public function getTargetType() {
+    return 'taxonomy_term';
+  }
+  
+  /**
+   * @override CerField::getTargetBundles().
+   */
+  public function getTargetBundles() {
+    $bundles = array();
+
+    foreach ($this->settings['allowed_values'] as $item) {
+      $bundles[] = $item['vocabulary'];
+    }
+
+    return $bundles;
+  }
+
+}

+ 18 - 0
sites/all/modules/contrib/fields/cer/includes/fields/user_reference.inc

@@ -0,0 +1,18 @@
+<?php
+
+/**
+ * @file
+ * Contains the CER plugin for User Reference fields.
+ */
+
+class CerUserReferenceField extends CerField {
+
+  /**
+   * Implements CerField::getTargetType().
+   */
+  public function getTargetType() {
+    return 'user';
+  }
+
+}
+ 

+ 134 - 0
sites/all/modules/contrib/fields/cer/tests/CerBasicTestCase.test

@@ -0,0 +1,134 @@
+<?php
+
+class CerBasicTestCase extends DrupalWebTestCase {
+
+  /**
+   * A user account under which the tests will be conducted.
+   *
+   * @var StdClass
+   */
+  protected $author;
+
+  /**
+   * A node that references $this->author.
+   *
+   * @var StdClass
+   */
+  protected $node;
+
+  public static function getInfo() {
+    return array(
+      'name' => 'Basic',
+      'description' => "Tests CER's basic CRUD functionality.",
+      'group' => 'CER',
+    );
+  }
+
+  public function setUp() {
+    // Turns out you have to enable your own module in the friggin' test, if
+    // you want your own classes to be available. Lawsy me and other such
+    // utterances...SimpleTest is teh suck.
+    parent::setUp('entity', 'ctools', 'entityreference', 'field_object', 'cer');
+
+    $field = array(
+      'type' => 'entityreference',
+      'cardinality' => 1,
+      'field_name' => 'field_author',
+      'settings' => array(
+        'target_type' => 'user',
+      ),
+    );
+    field_create_field($field);
+
+    $instance = array(
+      'field_name' => $field['field_name'],
+      'entity_type' => 'node',
+      'bundle' => 'page',
+    );
+    field_create_instance($instance);
+
+    $field = array(
+      'type' => 'entityreference',
+      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
+      'field_name' => 'field_pages',
+      'settings' => array(
+        'target_type' => 'node',
+      ),
+      'handler_settings' => array(
+        'target_bundles' => array('page'),
+      ),
+    );
+    field_create_field($field);
+
+    $instance = array(
+      'field_name' => $field['field_name'],
+      'entity_type' => 'user',
+      'bundle' => 'user',
+    );
+    field_create_instance($instance);
+
+    /** @var CerPreset $preset */
+    $preset = entity_create('cer', array());
+    $preset->wrapper->cer_left->set('node:page:field_author');
+    $preset->wrapper->cer_right->set('user:user:field_pages');
+    $preset->wrapper->cer_bidirectional->set(TRUE);
+    $preset->wrapper->cer_enabled->set(TRUE);
+    $preset->save();
+
+    $this->author = $this->drupalCreateUser();
+
+    $this->node = $this->drupalCreateNode(array(
+      'field_author' => array(
+        LANGUAGE_NONE => array(
+          array('target_id' => $this->author->uid),
+        ),
+      ),
+    ));
+  }
+
+  public function testCreate() {
+    $author = $this->reload('user', $this->author);
+    $this->assertEqual(1, $author->field_pages->count());
+    $this->assertEqual($this->node->nid, $author->field_pages[0]->nid->value());
+  }
+
+  public function testUpdateDereference() {
+    // Dereference the node from the user.
+    $this->author->field_pages = array();
+    user_save($this->author);
+
+    // Reload $this->node from the database so we get the latest field values.
+    $this->assertNull($this->reload('node', $this->node)->field_author->value());
+  }
+
+  public function testUpdateChangeTarget() {
+    $target = $this->drupalCreateUser();
+
+    $this->node->field_author[LANGUAGE_NONE][0]['target_id'] = $target->uid;
+    node_save($this->node);
+
+    // The original author should no longer reference the node.
+    $this->assertEqual(0, $this->reload('user', $this->author)->field_pages->count());
+
+    /** @var EntityDrupalWrapper $target */
+    $target = $this->reload('user', $target);
+    $this->assertEqual(1, $target->field_pages->count());
+    $this->assertEqual($this->node->nid, $target->field_pages[0]->nid->value());
+  }
+
+  public function testDelete() {
+    node_delete($this->node->nid);
+    $this->assertEqual(0, $this->reload('user', $this->author)->field_pages->count());
+  }
+
+  /**
+   * @return EntityDrupalWrapper
+   */
+  protected function reload($entity_type, $entity) {
+    list ($id) = entity_extract_IDs($entity_type, $entity);
+    $entities = entity_load($entity_type, array($id), NULL, TRUE);
+
+    return entity_metadata_wrapper($entity_type, $entities[$id]);
+  }
+
+}

+ 0 - 16
sites/all/modules/contrib/fields/cer/tests/cer_tests.info

@@ -1,16 +0,0 @@
-name = "CER Tests"
-core = "7.x"
-description = "Automated tests for CER."
-hidden = TRUE
-
-dependencies[] = simpletest
-dependencies[] = cer
-
-files[] = crud.test
-files[] = fields.test
-; Information added by Drupal.org packaging script on 2014-08-08
-version = "7.x-2.x-dev"
-core = "7.x"
-project = "cer"
-datestamp = "1407528862"
-

+ 0 - 1
sites/all/modules/contrib/fields/cer/tests/cer_tests.module

@@ -1 +0,0 @@
-<?php

+ 0 - 168
sites/all/modules/contrib/fields/cer/tests/crud.test

@@ -1,168 +0,0 @@
-<?php
-
-class CerCrudTest extends DrupalWebTestCase {
-
-  public static function getInfo() {
-    return array(
-      'name' => 'CRUD',
-      'group' => 'Corresponding Entity Reference',
-      'description' => 'Tests basic CER functionality.',
-    );
-  }
-
-  public function setUp() {
-    parent::setUp('field', 'field_sql_storage', 'ctools', 'entityreference', 'cer');
-
-    field_create_field(array(
-      'field_name' => 'field_user',
-      'type' => 'entityreference',
-      'cardinality' => -1,
-      'settings' => array(
-        'target_type' => 'user',
-      ),
-    ));
-    field_create_field(array(
-      'field_name' => 'field_node',
-      'type' => 'entityreference',
-      'cardinality' => -1,
-      'settings' => array(
-        'target_type' => 'node',
-      ),
-    ));
-
-    field_create_instance(array(
-      'field_name' => 'field_user',
-      'entity_type' => 'node',
-      'bundle' => 'page',
-    ));
-    field_create_instance(array(
-      'field_name' => 'field_node',
-      'entity_type' => 'user',
-      'bundle' => 'user',
-    ));
-
-    db_insert('cer')->fields(array(
-      'entity_types_content_fields' => 'node*page*field_user*user*user*field_node',
-      'enabled' => TRUE,
-    ))->execute();
-  }
-
-  public function testImplicitReferenceCreation() {
-    $uid = $this->drupalCreateUser()->uid;
-    
-    $referrers = array();
-    for ($i = 0; $i < 5; $i++) {
-      $referrers[] = $this->drupalCreateNode(array(
-        'type' => 'page',
-        'field_user' => array(
-          'und' => array(
-            array('target_id' => $uid),
-          ),
-        ),
-      ))->nid;
-    }
-
-    $references = array();
-    foreach (user_load($uid, TRUE)->field_node['und'] as $reference) {
-      $references[] = $reference['target_id'];
-    }
-    $this->assertFalse(array_diff($referrers, $references), 'Creating 5 referrers to a single entity creates 5 corresponding references on that entity.', 'CER');
-  }
-
-  public function testDuplicateReferencePrevention() {
-    $uid = $this->drupalCreateUser()->uid;
-
-    $this->drupalCreateNode(array(
-      'type' => 'page',
-      'field_user' => array(
-        'und' => array(
-          array('target_id' => $uid),
-          array('target_id' => $uid),
-        ),
-      ),
-    ));
-
-    $account = user_load($uid, TRUE);
-    $this->assertEqual(sizeof($account->field_node['und']), 1, 'Creating two references to an entity from a single referrer creates one corresponding reference.', 'CER');
-  }
-
-  public function testExplicitReferenceCreation() {
-    $uid = $this->drupalCreateNode()->uid;
-
-    $node = $this->drupalCreateNode(array('type' => 'page'));
-    $node->field_user['und'][0]['target_id'] = $uid;
-    node_save($node);
-
-    $account = user_load($uid, TRUE);
-    $this->assertEqual($account->field_node['und'][0]['target_id'], $node->nid, 'Creating an explicit reference between to unrelated entities creates a corresponding reference.', 'CER');
-  }
-
-  public function testExplicitDereference() {
-    $uid = $this->drupalCreateUser()->uid;
-
-    $nid = $this->drupalCreateNode(array(
-      'type' => 'page',
-      'field_user' => array(
-        'und' => array(
-          array('target_id' => $uid),
-        ),
-      ),
-    ))->nid;
-
-    $account = user_load($uid, TRUE);
-    $account->field_node = array();
-    user_save($account);
-
-    $node = node_load($nid, NULL, TRUE);
-    $this->assertFalse($node->field_user, 'Explicitly clearing a reference from the referenced entity clears the corresponding reference on the referrer.', 'CER');
-  }
-
-  public function testReferrerDeletion() {
-    $uid = $this->drupalCreateUser()->uid;
-    
-    $referrers = array();
-    for ($i = 0; $i < 5; $i++) {
-      $referrers[] = $this->drupalCreateNode(array(
-        'type' => 'page',
-        'field_user' => array(
-          'und' => array(
-            array('target_id' => $uid),
-          ),
-        ),
-      ))->nid;
-    }
-
-    node_delete($referrers[0]);
-
-    $references = array();
-    foreach (user_load($uid, TRUE)->field_node['und'] as $reference) {
-      $references[] = $reference['target_id'];
-    }
-    $this->assertFalse(in_array($referrers[0], $references), 'Deleting a referrer clears corresponding reference on the referenced entity.', 'CER');
-  }
-
-  public function testReferencedEntityDeletion() {
-    $uid = $this->drupalCreateUser()->uid;
-
-    $referrers = array();
-    for ($i = 0; $i < 5; $i++) {
-      $referrers[] = $this->drupalCreateNode(array(
-        'type' => 'page',
-        'field_user' => array(
-          'und' => array(
-            array('target_id' => $uid),
-          ),
-        ),
-      ))->nid;
-    }
-    user_delete($uid);
-
-    $cleared = 0;
-    foreach ($referrers as $nid) {
-      $node = node_load($nid, NULL, TRUE);
-      $cleared += (int) empty($node->field_user);
-    }
-    $this->assertEqual($cleared, sizeof($referrers), 'Deleting a referenced entity clears all references to it.', 'CER');
-  }
-
-}

+ 0 - 67
sites/all/modules/contrib/fields/cer/tests/fields.test

@@ -1,67 +0,0 @@
-<?php
-
-class CerFieldTestCase extends DrupalWebTestCase {
-
-  public static function getInfo() {
-    return array(
-      'name' => 'Fields',
-      'group' => 'Corresponding Entity Reference',
-      'description' => 'Tests integration with the Field API.',
-    );
-  }
-
-  public function setUp() {
-    parent::setUp('field', 'field_sql_storage', 'ctools', 'entityreference', 'cer');
-
-    field_create_field(array(
-      'field_name' => 'field_user',
-      'type' => 'entityreference',
-      'cardinality' => -1,
-      'settings' => array(
-        'target_type' => 'user',
-      ),
-    ));
-    field_create_field(array(
-      'field_name' => 'field_node',
-      'type' => 'entityreference',
-      'cardinality' => -1,
-      'settings' => array(
-        'target_type' => 'node',
-      ),
-    ));
-
-    field_create_instance(array(
-      'field_name' => 'field_user',
-      'entity_type' => 'node',
-      'bundle' => 'page',
-    ));
-    field_create_instance(array(
-      'field_name' => 'field_node',
-      'entity_type' => 'user',
-      'bundle' => 'user',
-    ));
-    
-    ctools_include('export');
-
-    $preset = ctools_export_crud_new('cer');
-    $preset->entity_types_content_fields = 'node*page*field_user*user*user*field_node';
-    $preset->enabled = TRUE;
-
-    ctools_export_crud_save('cer', $preset);
-  }
-
-  public function testFieldInstanceDelete() {
-    field_delete_instance(field_info_instance('user', 'field_node', 'user'));
-
-    $preset = cer_preset_load('node*page*field_user*user*user*field_node');
-    $this->assertNull($preset, 'Deleting a field instance clears CER presets for that instance.');
-  }
-
-  public function testFieldDelete() {
-    field_delete_field('field_user');
-
-    $preset = cer_preset_load('node*page*field_user*user*user*field_node');
-    $this->assertNull($preset, 'Deleting a field clears CER presets for that field.');
-  }
-
-}

+ 0 - 0
sites/all/modules/contrib/panels/panels/CHANGELOG.txt


+ 0 - 0
sites/all/modules/contrib/panels/panels/KNOWN_ISSUES.txt


+ 0 - 0
sites/all/modules/contrib/panels/panels/LICENSE.txt


+ 2 - 5
sites/all/modules/contrib/panels/panels/README.txt

@@ -1,6 +1,3 @@
+Welcome to Panels 3
 
-Welcome to Panels 3.
-
-A little documentation should go here, but Panels 3 is alsoi a beast - you're
-best off checking the online handbook on Drupal.org, or this issue:
-http://drupal.org/node/887560. 
+Documentation is available at https://www.drupal.org/node/496278

+ 11 - 1
sites/all/modules/contrib/panels/panels/UPGRADE.txt

@@ -11,7 +11,7 @@ Upgrading from Panels-6.x-3.x to Panels-7.x-3.x
 
   - panels_plugin_get_function() deprecated.
 
-  - panels_required_context removed. These were deprecated long ago and 
+  - panels_required_context removed. These were deprecated long ago and
     existed only to prevent crashes.
 
   - panels_optional_context removed.
@@ -20,3 +20,13 @@ Upgrading from Panels-6.x-3.x to Panels-7.x-3.x
 
   - display_renderer class is now in 'renderer', not 'handler'.
 
+Upgrading task handlers from Panels 7.x-3.5 or older to Panels 7.x-3.6 and newer:
+
+  - You must specify a storage type for any panels display using your custom task handler.
+    For examples, see panels_update_7306.
+
+  - When creating whatever stores the panel, a storage id and storage type must be defined.
+    See panels_mini.module for examples inside panels_mini_save and panels_mini_panels_cache_get.
+
+  - A display access plugin must be defined.
+    See panels_mini/plugins/panels_storage/panels_mini.inc for an example plugin.

+ 0 - 0
sites/all/modules/contrib/panels/panels/css/panels-dashboard.css


+ 0 - 5
sites/all/modules/contrib/panels/panels/css/panels.css

@@ -40,11 +40,6 @@ div.panel-pane:hover div.panel-hide {
   margin-top: -1.5em;
 }
 
-div.panel-pane div.node {
-  margin: 0;
-  padding: 0;
-}
-
 div.panel-pane div.feed a {
   float: right;
 }

+ 0 - 0
sites/all/modules/contrib/panels/panels/css/panels_admin.css


+ 23 - 8
sites/all/modules/contrib/panels/panels/css/panels_dnd.css

@@ -175,7 +175,7 @@ div.panels-set-title-hide .panel-pane-is-title {
   margin: 0;
 }
 
-.panel-portlet .buttons input {
+.panel-portlet .buttons input, .panel-portlet .buttons button {
   margin: 0;
   padding: 0;
   display: inline;
@@ -305,11 +305,19 @@ a.close img {
   background: url(../images/bg-content-modal.png);
   height: 100%;
   margin: -1em;
-  padding-top: 1em;
+  padding-bottom: 1em;
   padding-left: 175px;
   position: relative;
 }
 
+.panels-section-columns-quickfilter {
+  padding-top: 1em;
+  padding-left: 1em;
+  padding-bottom: 1em;
+  margin-bottom: 1em;
+  background-color: #EEEEEE;
+}
+
 .panels-section-columns {
   height: 100%;
   overflow: auto;
@@ -369,22 +377,29 @@ a.close img {
   text-align: left;
 }
 
+.content-type-button a {
+  display: inline-block;
+  width: 99%;
+}
+
+.content-type-button a:focus {
+  border: 1px dotted black;
+}
+
 .content-type-button img {
   border: 2px solid white;
-  float: left;
 }
 
 .content-type-button img:hover {
   border: 2px solid blue;
 }
 
-.content-type-button div {
+.content-type-button div,
+.content-type-button span {
   width: 85%;
+  position: relative;
   top: -5px;
-  left: 2px;
-  float: left;
-  padding-left: 3px;
-  padding-top: 5px;
+  left: 3px;
 }
 
 #panels-preview .modal-throbber-wrapper {

+ 0 - 0
sites/all/modules/contrib/panels/panels/css/panels_page.css


+ 0 - 0
sites/all/modules/contrib/panels/panels/help/api.html


+ 0 - 0
sites/all/modules/contrib/panels/panels/help/display.html


+ 0 - 0
sites/all/modules/contrib/panels/panels/help/pane.html


+ 0 - 0
sites/all/modules/contrib/panels/panels/help/panels.help.ini


File diff suppressed because it is too large
+ 0 - 1
sites/all/modules/contrib/panels/panels/help/plugin-layout.html


File diff suppressed because it is too large
+ 0 - 0
sites/all/modules/contrib/panels/panels/help/plugins-layout.html


+ 0 - 0
sites/all/modules/contrib/panels/panels/help/plugins-style.html


+ 93 - 0
sites/all/modules/contrib/panels/panels/i18n_panels/README.txt

@@ -0,0 +1,93 @@
+
+This module provides by default the ability to translate panel display and
+panel pane titles.
+Further it introduced an extension to the ctools content_types plugin.
+You can now define translatable settings which will be registered in i18n.
+Out of the box the module extends the custom content content_type to allow
+translation of the content.
+
+Requirements:
+   Ctools 7.x-1.x-dev (Jan 28-2014 or newer)
+   Panels 7.x-3.x-dev (Jan 28-2014 or newer)
+
+Plugin definition extension:
+------------------------------
+
+This example shows how the content_type custom is extended:
+
+#### Default: ####
+/**
+ * Plugins are described by creating a $plugin array which will be used
+ * by the system that includes this file.
+ */
+$plugin = array(
+  'title' => t('Custom content'),
+  'no title override' => TRUE,
+  'defaults' => array('admin_title' => '', 'title' => '', 'body' => '', 'format' => filter_fallback_format(), 'substitute' => TRUE),
+  'js' => array('misc/autocomplete.js', 'misc/textarea.js', 'misc/collapse.js'),
+  // Make sure the edit form is only used for some subtypes.
+  'edit form' => '',
+  'add form' => '',
+  'edit text' => t('Edit'),
+  'all contexts' => TRUE,
+);
+
+#### Extended Configuration: ####
+/**
+ * Plugins are described by creating a $plugin array which will be used
+ * by the system that includes this file.
+ */
+$plugin = array(
+  'title' => t('Custom content'),
+  'no title override' => TRUE,
+  'defaults' => array('admin_title' => '', 'title' => '', 'body' => '', 'format' => filter_fallback_format(), 'substitute' => TRUE),
+  'js' => array('misc/autocomplete.js', 'misc/textarea.js', 'misc/collapse.js'),
+  // Make sure the edit form is only used for some subtypes.
+  'edit form' => '',
+  'add form' => '',
+  'edit text' => t('Edit'),
+  'all contexts' => TRUE,
+  'i18n_settings' = array(
+    'title',
+    'body' => array('format' => 'plain_text'),
+    'items|0|title'
+  ),
+);
+
+The new key "i18n_settings" defines an array with the settings that are
+translatable. The array contains the names of the settings, they have to be
+available in the "defaults" array of the content definition. If you need to
+define a format use the name of the setting as the array item key and as item
+another array with the detail configuration. E.g
+'i18n_settings' = array('body' => array('format' => 'plain_text'))
+
+If i18n_settings is a string it's used as callback. The expected return is an
+array equal to the one used in the fix configuration.
+You can even declare nested settings  as translatable, to do so use '|' as
+delimiter.
+E.g. 'items|0|title' is evaluated as $settings['items'][0]['title']
+
+#### Callback: ####
+/**
+ * Plugins are described by creating a $plugin array which will be used
+ * by the system that includes this file.
+ */
+$plugin = array(
+  'title' => t('Custom content'),
+  'no title override' => TRUE,
+  'defaults' => array('admin_title' => '', 'title' => '', 'body' => '', 'format' => filter_fallback_format(), 'substitute' => TRUE),
+  'js' => array('misc/autocomplete.js', 'misc/textarea.js', 'misc/collapse.js'),
+  // Make sure the edit form is only used for some subtypes.
+  'edit form' => '',
+  'add form' => '',
+  'edit text' => t('Edit'),
+  'all contexts' => TRUE,
+  'i18n_settings' => 'ctools_custom_content_type_i18n_settings',
+);
+
+function ctools_custom_content_type_i18n_settings($conf) {
+  return array(
+    'title',
+    'body' => array('format' => $conf['format']),
+  );
+}

+ 50 - 0
sites/all/modules/contrib/panels/panels/i18n_panels/i18n_panels.i18n.inc

@@ -0,0 +1,50 @@
+<?php
+/**
+ * @file
+ * Internationalization (i18n) hooks
+ */
+
+/**
+ * Implements hook_i18n_object_info().
+ */
+function i18n_panels_i18n_object_info() {
+  $info['pane_configuration'] = array(
+    'title' => t('Pane Configuration'),
+    'key' => 'uuid',
+    'string translation' => array(
+      'textgroup' => 'panels',
+      'type' => 'pane_configuration',
+      'properties' => array(
+        'title' => t('Pane Title'),
+      ),
+    ),
+  );
+  $info['display_configuration'] = array(
+    'title' => t('Display Configuration'),
+    'key' => 'uuid',
+    'string translation' => array(
+      'textgroup' => 'panels',
+      'type' => 'display_configuration',
+      'properties' => array(
+        'title' => t('Display Title'),
+      ),
+    ),
+  );
+
+  return $info;
+}
+
+/**
+ * Implements hook_i18n_string_info().
+ */
+function i18n_panels_i18n_string_info() {
+  $groups['panels'] = array(
+    'title' => t('Panels'),
+    'description' => t('Translatable panels items: display and pane configuration items. E.g. Title.'),
+    // This group doesn't have strings with format.
+    'format' => FALSE,
+    // This group can list all strings.
+    'list' => FALSE,
+  );
+  return $groups;
+}

+ 15 - 0
sites/all/modules/contrib/panels/panels/i18n_panels/i18n_panels.info

@@ -0,0 +1,15 @@
+name = Panels translation
+description = Supports translatable panels items.
+dependencies[] = i18n
+dependencies[] = panels
+dependencies[] = i18n_string
+dependencies[] = i18n_translation
+package = Multilingual - Internationalization
+core = 7.x
+
+; Information added by Drupal.org packaging script on 2016-10-16
+version = "7.x-3.8"
+core = "7.x"
+project = "panels"
+datestamp = "1476582295"
+

+ 27 - 0
sites/all/modules/contrib/panels/panels/i18n_panels/i18n_panels.install

@@ -0,0 +1,27 @@
+<?php
+
+/**
+ * @file
+ * Internationalization (i18n) submodule: Panels translation.
+ */
+
+/**
+ * Implements hook_requirements().
+ */
+function i18n_panels_requirements($phase) {
+  $requirements = array();
+  // Check only for status report, to allow update / install.
+  if ($phase == 'runtime') {
+    // Check if the panels module runs with uuids.
+    $requirements['uuid'] = array(
+      'title' => t('Panels uuid support.'),
+      'severity' => REQUIREMENT_OK,
+      'value' => t('Available'),
+    );
+    if (!db_field_exists('panels_pane', 'uuid')) {
+      $requirements['uuid']['severity'] = REQUIREMENT_ERROR;
+      $requirements['uuid']['value'] = t('Not found. Please apply the provided patches and run the update script.');
+    }
+  }
+  return $requirements;
+}

+ 442 - 0
sites/all/modules/contrib/panels/panels/i18n_panels/i18n_panels.module

@@ -0,0 +1,442 @@
+<?php
+
+/**
+ * @file
+ * Internationalization (i18n) submodule: Panels translation.
+ */
+
+/**
+ * Fetch the i18n_settings of the content type if there are any.
+ *
+ * @param stdClass $pane
+ *   The pane to deal with.
+ *
+ * @return array|false
+ *   Settings or FALSE if none are present.
+ */
+function i18n_panels_get_i18n_settings($pane) {
+  ctools_include('content');
+  $content_type = ctools_get_content_type($pane->type);
+  if (isset($content_type['i18n_settings'])) {
+    if (is_string($content_type['i18n_settings']) && function_exists($content_type['i18n_settings'])) {
+      $content_type['i18n_settings'] = $content_type['i18n_settings']($pane->configuration);
+    }
+  }
+  // Provide the override title string as translation for all panes that have
+  // this setting enabled.
+  if (isset($pane->configuration['override_title']) && $pane->configuration['override_title']) {
+    if (isset($content_type['i18n_settings']) && is_array($content_type['i18n_settings'])) {
+      $content_type['i18n_settings'][] = 'override_title_text';
+    }
+    else {
+      $content_type['i18n_settings'] = array('override_title_text');
+    }
+  }
+  return isset($content_type['i18n_settings']) ? $content_type['i18n_settings'] : FALSE;
+}
+
+/**
+ * Returns the translation object of the pane.
+ *
+ * @param stdClass $pane
+ *   The pane to deal with.
+ *
+ * @return stdClass|FALSE
+ *   Returns FALSE if no translation is necessary.
+ */
+function i18n_panels_get_i18n_translation_object($pane) {
+  $translation_object = array();
+
+  // Handle content type specific i18n settings.
+  if ($i18n_settings = i18n_panels_get_i18n_settings($pane)) {
+    // Register translatable settings.
+    foreach ($i18n_settings as $i18n_setting => $settings) {
+      if (!is_array($settings)) {
+        $i18n_setting = $settings;
+        $settings = array('format' => 'plain_text');
+      }
+      $translation_object[$i18n_setting] = NULL;
+      $key_exists = FALSE;
+      // Ensure a nested setting is "unpacked".
+      $config_value = drupal_array_get_nested_value($pane->configuration, explode('|', $i18n_setting), $key_exists);
+      // If we reached the end of the nested setting use the value as source.
+      if ($key_exists) {
+        $translation_object[$i18n_setting] = array(
+          'string' => $config_value,
+          'format' => $settings['format'],
+        );
+        $translation_object['panels_i18n_settings'][$i18n_setting] = $settings;
+      }
+    }
+  }
+
+  // Check if this pane has a custom title enabled.
+  if (!empty($pane->configuration['override_title'])) {
+    $translation_object['title']['string'] = $pane->configuration['override_title_text'];
+  }
+  if (!empty($translation_object)) {
+    return (object) $translation_object;
+  }
+  return FALSE;
+}
+
+/**
+ * Implements hook_panels_pane_insert().
+ *
+ * @param stdClass $pane
+ *   The pane to deal with.
+ */
+function i18n_panels_panels_pane_insert($pane) {
+  i18n_panels_panels_pane_update($pane);
+}
+
+/**
+ * Implements hook_panels_pane_update().
+ *
+ * @param stdClass $pane
+ *   The pane to deal with.
+ */
+function i18n_panels_panels_pane_update($pane) {
+  if ($translation_object = i18n_panels_get_i18n_translation_object($pane)) {
+    $translation_object->uuid = $pane->uuid;
+    $status = i18n_string_object_update('pane_configuration', $translation_object);
+  }
+}
+
+/**
+ * Implements hook_panels_pane_delete().
+ *
+ * @param array $pids
+ *   Array with the panel ids to delete.
+ */
+function i18n_panels_panels_pane_delete($pids) {
+  if (!empty($pids)) {
+    // Fetch the uuids from the db.
+    $uuids = db_select('panels_pane')
+      ->fields('panels_pane', array('uuid'))
+      ->condition('pid', $pids)
+      ->execute()
+      ->fetchCol();
+    foreach ($uuids as $uuid) {
+      // Create dummy pane with uuid as property.
+      $pane = (object) array('uuid' => $uuid);
+      i18n_string_object_remove('pane_configuration', $pane);
+    }
+  }
+}
+
+/**
+ * Implements hook_panels_pane_prerender().
+ *
+ * @param stdClass $pane
+ *   The pane to deal with.
+ */
+function i18n_panels_panels_pane_prerender($pane) {
+  // Check if this pane has translations.
+  if (isset($pane->uuid) && $translation_object = i18n_panels_get_i18n_translation_object($pane)) {
+    $translation_object->uuid = $pane->uuid;
+    // Send to translation.
+    $translation_object = i18n_string_object_translate('pane_configuration', $translation_object);
+    unset($translation_object->uuid, $translation_object->i18n_settings);
+    foreach ($translation_object as $i18n_setting => $translated_setting) {
+      if ($i18n_setting != 'panels_i18n_settings') {
+        if (is_array($translated_setting)) {
+          $translated_setting = $translated_setting['string'];
+        }
+        drupal_array_set_nested_value($pane->configuration, explode('|', $i18n_setting), $translated_setting);
+      }
+    }
+  }
+}
+
+/**
+ * Implements hook_panels_display_save().
+ *
+ * @param panels_display $display
+ *   The display to deal with.
+ */
+function i18n_panels_panels_display_save($display) {
+  $status = i18n_string_object_update('display_configuration', $display);
+}
+
+/**
+ * Implements hook_panels_display_delete().
+ *
+ * @param int $did
+ *   Id of the display to delete.
+ */
+function i18n_panels_panels_delete_display($did) {
+  // Fetch uuid to delete the translations.
+  $uuid = db_select('panels_display')
+    ->fields('panels_display', array('uuid'))
+    ->condition('did', $did)
+    ->execute()
+    ->fetchColumn();
+  // Build a dummy display.
+  $display = (object) array('uuid' => $uuid);
+
+  // Check if this display was just saved in the db.
+  if (!_18n_panels_is_exported_panels_display($display)) {
+    // If the display was just saved in the db remove all translations.
+    i18n_string_object_remove('display_configuration', $display);
+    // Remove related pane translations too.
+    $pids = db_select('panels_pane')
+      ->fields('panels_pane', array('pid'))
+      ->condition('did', $did)
+      ->execute()
+      ->fetchCol();
+    i18n_panels_panels_pane_delete($pids);
+  }
+  else {
+    // If the display is exported leave the translated strings but give the user
+    // a hint how to clean up.
+    drupal_set_message(
+      t(
+        'The reverted panels display(s) were exported, please run a <a href="!link">string refresh</a> to update the translatable strings.',
+        array('!link' => url('admin/config/regional/translate/i18n_string'))
+      ),
+      'warning',
+      FALSE
+    );
+  }
+}
+
+/**
+ * Implements hook_panels_pre_render().
+ *
+ * This function must not rely on the passed $renderer parameter. The parameter
+ * could be empty because this function is reused in i18n_ctools_render_alter().
+ * @todo Check if a drupal_alter() in panels_display::get_title() is applicable.
+ *
+ * @see i18n_ctools_render_alter()
+ *
+ * @param panels_display $display
+ *   The display to deal with.
+ * @param panels_renderer_standard $renderer
+ *   The renderer to deal with.
+ */
+function i18n_panels_panels_pre_render(&$display, $renderer) {
+  // Avoid double translations.
+  if (!isset($display->i18n_panels_title_translated)) {
+    $translation = i18n_string_object_translate('display_configuration', $display);
+    if (is_array($translation->title)) {
+      $display->title = $translation->title['string'];
+    }
+    else {
+      $display->title = $translation->title;
+    }
+    $display->i18n_panels_title_translated = TRUE;
+  }
+}
+
+/**
+ * Implements hook_ctools_render_alter().
+ *
+ * Under some circumstances the title of the panel page is set before
+ * hook_panels_pre_render() is fired. Such cases can be handled with this hook.
+ * @todo Check if a drupal_alter() in panels_display::get_title() is applicable.
+ */
+function i18n_ctools_render_alter(&$info, $page, $context) {
+  // @todo Find a better way to detect a panels page.
+  if ($page === TRUE && !empty($info['content']['#display']) && $info['content']['#display'] instanceof panels_display) {
+    i18n_panels_panels_pre_render($info['content']['#display'], NULL);
+    // Set the info title. This is used to set the page title.
+    $info['title'] = $info['content']['#display']->get_title();
+  }
+}
+
+
+/**
+ * Implements hook_ctools_plugin_post_alter().
+ *
+ * Register some translatable configuration settings for plugins.
+ *
+ */
+function i18n_panels_ctools_plugin_post_alter(&$plugin, $plugin_type_info) {
+  if ($plugin_type_info['type'] == 'content_types') {
+    // Modify custom content.
+    if ($plugin['name'] == 'custom') {
+      // Register callback to get the translatable settings.
+      $plugin['i18n_settings'] = 'ctools_custom_content_type_i18n_settings';
+    }
+  }
+}
+
+/**
+ * Callback to provide the translatable settings appropriate to the config.
+ *
+ * @param array $conf
+ *   Content type configuration.
+ *
+ * @return array
+ *   i18n_settings configuration.
+ */
+function ctools_custom_content_type_i18n_settings($conf) {
+  return array(
+    'title',
+    'body' => array('format' => $conf['format']),
+  );
+}
+
+/**
+ * Implements hook_i18n_string_list_TEXTGROUP_alter().
+ *
+ * Necessary to support the dynamic translatable settings defined by ctools
+ * content types.
+ */
+function i18n_panels_i18n_string_list_panels_alter(&$strings, $type = NULL, $object = NULL) {
+  if (isset($object->panels_i18n_settings)) {
+    foreach ($object->panels_i18n_settings as $i18n_setting => $settings) {
+      if (isset($object->{$i18n_setting})) {
+        $strings['panels'][$type][$object->uuid][$i18n_setting] = $object->{$i18n_setting};
+      }
+    }
+  }
+}
+
+/**
+ * Implements hook_i18n_string_list().
+ *
+ * @todo Figure out a generic solution to fetch exported displays.
+ */
+function i18n_panels_i18n_string_list($group) {
+  $strings = array();
+  if ($group == 'panels') {
+
+    // Fetch all available displays.
+    $displays = _18n_panels_fetch_all_panel_displays();
+
+    foreach ($displays as $display) {
+      if (empty($display->uuid)) {
+        drupal_set_message(t('The display %display has no uuid, please resave or re-export it.', array('%display' => $display->did)), 'warning');
+        continue;
+      }
+      // Avoid duplicated runs _18n_panels_fetch_all_panel_displays() probably
+      // returns the same display twice, one for the db based and one for the
+      // exported one.
+      if (isset($strings['panels']['display_configuration'][$display->uuid])) {
+        continue;
+      }
+      $strings['panels']['display_configuration'][$display->uuid]['title']['string'] = $display->title;
+      foreach ($display->content as $pane) {
+        if (empty($pane->uuid)) {
+          // Fetch exported uuid and validate it.
+          $uuid = str_replace('new-', '', $pane->pid);
+          if (!panels_uuid_is_valid($uuid)) {
+            drupal_set_message(t('The pane %pane has no uuid, please resave or re-export it.', array('%pane' => $pane->pid)), 'warning');
+            continue;
+          }
+          $pane->uuid = $uuid;
+        }
+        if ($translation_object = i18n_panels_get_i18n_translation_object($pane)) {
+          // Split up all strings and add them to the list.
+          $pane_strings = (array) $translation_object;
+          unset($pane_strings['panels_i18n_settings']);
+          foreach ($pane_strings as $key => $pane_string) {
+            $strings['panels']['pane_configuration'][$pane->uuid][$key] = $pane_string;
+          }
+        }
+      }
+    }
+  }
+  return $strings;
+}
+
+/**
+ * Checks if the give display is exported or only stored in the db.
+ *
+ * @return boolean
+ *   TRUE if the display is available from code.
+ */
+function _18n_panels_is_exported_panels_display($display) {
+  if (isset($display->uuid)) {
+    $displays = _18n_panels_fetch_all_panel_displays();
+    return isset($displays['exported-' . $display->uuid]);
+  }
+  return FALSE;
+}
+
+/**
+ * Returns a list of really all available panel displays.
+ *
+ * The list is statically cached. Use the parameter $reset to refresh the list
+ * during the same request.
+ * Probably returns the same display twice - once with the db based and once
+ * the exported one.
+ *
+ * @todo I bet there are better ways to solve this mess.
+ *
+ * @param boolean $reset
+ *   Reset the static cache.
+ *
+ * @return array
+ *   List of all panel displays.
+ */
+function _18n_panels_fetch_all_panel_displays($reset = FALSE) {
+  $displays = &drupal_static(__FUNCTION__, array());
+  if (!empty($displays) && !$reset) {
+    return $displays;
+  }
+
+  // Fetch db based displays.
+  $dids = db_select('panels_display')->fields('panels_display', array('did'))->execute()->fetchCol();
+  $displays = panels_load_displays($dids);
+
+  // Fetch exported displays.
+  ctools_include('export');
+  foreach (ctools_export_crud_load_all('panels_display') as $panels_display) {
+    if (!empty($panels_display->uuid)) {
+      $displays['exported-' . $panels_display->uuid] = $panels_display;
+    }
+  }
+
+  // Fetch mini panels.
+  $mini_panels = ctools_export_crud_load_all('panels_mini');
+  foreach ($mini_panels as $pane) {
+    if (!empty($pane->display->uuid)) {
+      $displays['exported-' . $pane->display->uuid] = $pane->display;
+    }
+  }
+
+  // Fetch in page manager embedded displays.
+  if (module_exists('page_manager')) {
+    module_load_include('inc', 'page_manager', 'page_manager.admin');
+    $tasks = page_manager_get_tasks_by_type('page');
+    $pages = array('operations' => array(), 'tasks' => array());
+    page_manager_get_pages($tasks, $pages);
+
+    foreach ($pages['tasks'] as $task) {
+      $page = page_manager_cache_load($task);
+      $task_info = page_manager_get_task_subtasks($page->task);
+      foreach ($page->handler_info as $id => $info) {
+        $page_manager_handler = $page->handlers[$id];
+        if ($page_manager_handler->handler == 'panel_context') {
+
+          // @todo Is there really no better way to check this?
+          $is_exported = ($page_manager_handler->export_type == (EXPORT_IN_CODE | EXPORT_IN_DATABASE) || (isset($page->subtask['storage']) && $page->subtask['storage'] == t('Overridden')));
+
+          if (!empty($page_manager_handler->conf['display'])) {
+            $panels_display = $page_manager_handler->conf['display'];
+            $displays['exported-' . $panels_display->uuid] = $panels_display;
+          }
+          elseif ($is_exported && isset($page_manager_handler->conf['did'])) {
+            $panels_display = panels_load_display($page_manager_handler->conf['did']);
+            if (isset($panels_display->uuid)) {
+              $displays['exported-' . $panels_display->uuid] = $panels_display;
+            }
+          }
+        }
+      }
+    }
+  }
+
+  // Fetch panelizer displays.
+  if (module_exists('panelizer')) {
+    // Fetch all default handlers.
+    $panelizer_defaults = ctools_export_crud_load_all('panelizer_defaults');
+    foreach ($panelizer_defaults as $panelizer_default) {
+      $displays['exported-' . $panelizer_default->display->uuid] = $panelizer_default->display;
+    }
+  }
+  return $displays;
+}

+ 0 - 0
sites/all/modules/contrib/panels/panels/images/arrow-active.png


+ 0 - 0
sites/all/modules/contrib/panels/panels/images/arrow-down-light.png


+ 0 - 0
sites/all/modules/contrib/panels/panels/images/bg-content-modal.png


+ 0 - 0
sites/all/modules/contrib/panels/panels/images/bg-shade-dark.png


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