Install DISTCACHE on RHEL6 [SOLVED]

Installing distcache on RHEL6 can be tricky. Let’s see how to do it…

cd /home/miguelm/invenio113/prerequisites/distcache
wget http://sourceforge.net/projects/distcache/files/latest/download?source=files
tar -xzvf distcache-1.5.1.tar.gz
cd distcache-1.5.1

If you try to compile as is, you will get errors:

proto_fd.c: In function 'addr_parse':
proto_fd.c:177: error: 'LONG_MIN' undeclared (first use in this function)
proto_fd.c:177: error: (Each undeclared identifier is reported only once
proto_fd.c:177: error: for each function it appears in.)
proto_fd.c:177: error: 'LONG_MAX' undeclared (first use in this function)

To get rid of them, you just have to include in distcache-1.5.1/libnal/proto_fd.c as in:

#define SYS_GENERATING_LIB
 
#include <libsys/pre.h>
#include <libnal/nal.h>
#include "nal_internal.h" 
#include "ctrl_fd.h" 
#include <libsys/post.h>
#include <limits.h>
 
/**************************/
/* predeclare our vtables */
/**************************/
...

Now you can compile with no errors…

./configure --prefix=/usr
make
make install

CDS Invenio 1: The new file uploader explained

Those who have used Invenio since 0.9x version will notice a new useful websubmit element in Invenio 1.

This new useful element is Upload_Files. Older versions just had a file input element (for instance, DEMOTHE_FILE) which allowed just one file to be uploaded.

This is the code of the Upload_Files element:

"""
This is an example of element that creates a file upload interface.
Clone it, customize it and integrate it into your submission. Then add function 
'Move_Uploaded_Files_to_Storage' to your submission functions list, in order for files 
uploaded with this interface to be attached to the record. More information in 
the WebSubmit admin guide.
"""
import os
from invenio.websubmit_managedocfiles import create_file_upload_interface
from invenio.websubmit_functions.Shared_Functions import ParamFromFile
 
indir = ParamFromFile(os.path.join(curdir, 'indir'))
doctype = ParamFromFile(os.path.join(curdir, 'doctype'))
access = ParamFromFile(os.path.join(curdir, 'access'))
try:
    sysno = int(ParamFromFile(os.path.join(curdir, 'SN')).strip())
except:
    sysno = -1
ln = ParamFromFile(os.path.join(curdir, 'ln'))
 
"""
Run the following to get the list of parameters of function 'create_file_upload_interface':
echo -e 'from invenio.websubmit_managedocfiles import create_file_upload_interface as f\nprint f.__doc__' | python
"""
text = create_file_upload_interface(recid=sysno,
                                 print_outside_form_tag=False,
                                 include_headers=True,
                                 ln=ln,
                                 doctypes_and_desc=[('main','Normativa/Modificacion'),
                                                    ('additional','Texto integrado')],
                                 can_revise_doctypes=['*'],
                                 can_describe_doctypes=['main'],
                                 can_delete_doctypes=['additional'],
                                 can_rename_doctypes=['main'],
                                 sbm_indir=indir, sbm_doctype=doctype, sbm_access=access)[1]

Using this new file uploader you can upload several files at a time.

This is how the element is rendered by default:
Captura de pantalla 2014-05-22 a la(s) 13.30.43

When you add this element to your forms, you will also have to add the Move_Uploaded_Files_to_Storage function in the submission. As in:
Invenio websubmit functions

By default the file path will be stored in a 8654_u MARCXML tag, subfield code a.
The information supplied in “Description” field will be mapped to a 8564_u MARCXML tag, subfield code y.
The data entered in “Name” field will be used to rename the fulltext file.

Here is an example of how Invenio builds a 8564_u tag using this new file uploader:
Invenio websubmit functions

I wanted to add a “comment” input field to this File Uploader form. I took a look at the code and… well, Invenio guys have already thought about this!! Notice the “commentBox” div in the code:

<div id="reviseControl">
    <table class="reviseControlBrowser"></table><input type="button" onclick="display_revise_panel(this, 'add', '', true, false, true, true, true, '', '', '', true, '', '<select id=&quot;fileDoctype&quot; name=&quot;fileDoctype&quot; onchange=&quot;var idx=this.selectedIndex;var doctype=this.options[idx].value;updateForm(doctype,{\'main\': \'\'},{},{});&quot;><option value=&quot;main&quot;>Main document</option>\n<option value=&quot;additional&quot;>Figure, schema, etc.</option></select>');updateForm('main', {'main': ''}, {}, {});return false;" value="Añadir otro fichero"/></div></div>
<div id="balloon" style="display:none;">
<input type="hidden" name="fileAction" value="" />
<input type="hidden" name="fileTarget" value="" />
  <table>
    <tr>
      <td class="topleft">&nbsp;</td>
      <td class="top">&nbsp;</td>
      <td class="topright">&nbsp;</td>
    </tr>
    <tr>
      <td class="left" vertical-align="center" width="24"><img alt=" " src="../img/balloon_arrow_left_shadow.png" /></td>
      <td class="center">
        <table id="balloonReviseFile">
          <tr>
            <td><label for="balloonReviseFileInput">Escoja el fichero:</label><br/>
              <div style="display:none" id="fileDoctypesRow"></div>
              <div id="balloonReviseFileInputBlock"><input type="file" name="myfile" id="balloonReviseFileInput" size="20" /></div>
                          <!--  <input type="file" name="myfile" id="balloonReviseFileInput" size="20" onchange="var name=getElementById('rename');var filename=this.value.split('/').pop().split('.')[0];name.value=filename;"/> -->
              <div id="renameBox" style=""><label for="rename">Nombre:</label><br/><input type="text" name="rename" id="rename" size="20" autocomplete="off"/></div>
              <div id="descriptionBox" style=""><label for="description">Descripción:</label><br/><input type="text" name="description" id="description" size="20" autocomplete="off"/></div>
              <div id="commentBox" style=""><label for="comment">Comentario:</label><br/><textarea name="comment" id="comment" rows="3"/></textarea></div>
              <div id="restrictionBox" style="display:none"><select style="display:none" id="fileRestriction" name="fileRestriction"></select></div>
              <div id="keepPreviousVersions" style="display:none"><input type="checkbox" id="balloonReviseFileKeep" name="keepPreviousFiles" checked="checked" /><label for="balloonReviseFileKeep">Guardar las versiones anteriores</label>&nbsp;<small>[<a href="" onclick="alert('Puede decidir esconder o no versiones anteriores de este archivo.');return false;">?</a>]</small></div>
              <p id="warningFormats" style="display:none"><img src="http://155.210.11.63/img/warning.png" alt="Warning"/> Los formatos alternativos para la versión actual de este archivo serán borrados&nbsp;[<a href="" onclick="alert('Cuando revise un archivo, los formatos adicionales que haya subido previamente serán borrados, ya que no estarían sincronizados con el nuevo archivo.');return false;">?</a>]</p>
              <div style="text-align:right;margin-top:5px"><input type="button" value="Cancelar" onclick="javascript:hide_revise_panel();"/> <input type="submit" value="Subir"/></div>
            </td>
          </tr>
        </table>
      </td>
      <td class="right">&nbsp;</td>
    </tr>
    <tr>
      <td class="bottomleft">&nbsp;</td>
      <td class="bottom">&nbsp;</td>
      <td class="bottomright">&nbsp;</td>
    </tr>
  </table>
</div>

However this box has a display:none attribute. So, how can we make the box visible?

Easy.

If you look at the Upload_Files element code, you will notice that the function producing that output is create_file_upload_interface. That function has a lot of parameters that can be listed using:

echo -e 'from invenio.websubmit_managedocfiles import create_file_upload_interface as f\nprint f.__doc__' | python

If you want the “Comment” box to be displayed, just add the parameter can_comment_doctypes=['*'] to the code, as in:

"""
This is an example of element that creates a file upload interface.
Clone it, customize it and integrate it into your submission. Then add function 
'Move_Uploaded_Files_to_Storage' to your submission functions list, in order for files 
uploaded with this interface to be attached to the record. More information in 
the WebSubmit admin guide.
"""
import os
from invenio.websubmit_managedocfiles import create_file_upload_interface
from invenio.websubmit_functions.Shared_Functions import ParamFromFile
 
indir = ParamFromFile(os.path.join(curdir, 'indir'))
doctype = ParamFromFile(os.path.join(curdir, 'doctype'))
access = ParamFromFile(os.path.join(curdir, 'access'))
try:
    sysno = int(ParamFromFile(os.path.join(curdir, 'SN')).strip())
except:
    sysno = -1
ln = ParamFromFile(os.path.join(curdir, 'ln'))
 
"""
Run the following to get the list of parameters of function 'create_file_upload_interface':
echo -e 'from invenio.websubmit_managedocfiles import create_file_upload_interface as f\nprint f.__doc__' | python
"""
text = create_file_upload_interface(recid=sysno,
                                 print_outside_form_tag=False,
                                 include_headers=True,
                                 ln=ln,
                                 doctypes_and_desc=[('main','Normativa/Modificacion'),
                                                    ('additional','Texto integrado')],
                                 can_revise_doctypes=['*'],
                                 can_comment_doctypes=['*'],
                                 can_describe_doctypes=['main'],
                                 can_delete_doctypes=['additional'],
                                 can_rename_doctypes=['main'],
                                 sbm_indir=indir, sbm_doctype=doctype, sbm_access=access)[1]

And now the commentBox is visible 🙂

invenio submit fulltext websubmit element file uploader

This new “comment” field is mapped to 8564_u subfield z. Example:

invenio several files upload, file uploader

invenio file uploader resulting marcxml

There are several other parameters of function create_file_upload_interface still to be explored…

root@invenio1:/opt/invenio/lib/python/invenio/websubmit_functions# echo -e 'from invenio.websubmit_managedocfiles import create_file_upload_interface as f\nprint f.__doc__' | python
/usr/local/lib/python2.6/dist-packages/pkg_resources.py:2535: DeprecationWarning: functions overriding warnings.showwarning() must support the 'line' argument
  warn(stacklevel = level+1, *args, **kw)
/usr/lib/python2.6/dist-packages/Ft/Lib/ImportUtil.py:362: UserWarning: Module _hashlib was already imported from None, but /usr/local/lib/python2.6/dist-packages is being added to sys.path
  from pkg_resources import get_provider, resource_filename
 
    Returns the HTML for the file upload interface.
 
    @param recid: the id of the record to edit files
    @type recid: int or None
 
    @param form: the form sent by the user's browser in response to a
                 user action. This is used to read and record user's
                 actions.
    @param form: as returned by the interface handler.
 
    @param print_outside_form_tag: display encapsulating <form> tag or
                                   not
    @type print_outside_form_tag: boolean
 
    @param print_envelope: (internal parameter) if True, return the
                           encapsulating initial markup, otherwise
                           skip it.
    @type print_envelope: boolean
 
    @param include_headers: include javascript and css headers in the
                            body of the page. If you set this to
                            False, you must take care of including
                            these headers in your page header. Setting
                            this parameter to True is useful if you
                            cannot change the page header.
    @type include_headers: boolean
 
    @param ln: language
    @type ln: string
 
    @param minsize: the minimum size (in bytes) allowed for the
                    uploaded files. Files not big enough are
                    discarded.
    @type minsize: int
 
    @param maxsize: the maximum size (in bytes) allowed for the
                    uploaded files. Files too big are discarded.
    @type maxsize: int
 
    @param doctypes_and_desc: the list of doctypes (like 'Main' or
                              'Additional') and their description that users
                              can choose from when adding new files.
                                - When no value is provided, users cannot add new
                                  file (they can only revise/delete/add format)
                                - When a single value is given, it is used as
                                  default doctype for all new documents
 
                              Order is relevant
                              Eg:
                              [('main', 'Main document'), ('additional', 'Figure, schema. etc')]
    @type doctypes_and_desc: list(tuple(string, string))
 
    @param restrictions_and_desc: the list of restrictions (like 'Restricted' or
                         'No Restriction') and their description that
                         users can choose from when adding or revising
                         files. Restrictions can then be configured at
                         the level of WebAccess.
                           - When no value is provided, no restriction is
                             applied
                           - When a single value is given, it is used as
                             default resctriction for all documents.
                           - The first value of the list is used as default
                             restriction if the user if not given the
                             choice of the restriction. Order is relevant
 
                         Eg:
                         [('', 'No restriction'), ('restr', 'Restricted')]
    @type restrictions_and_desc: list(tuple(string, string))
 
    @param can_delete_doctypes: the list of doctypes that users are
                                allowed to delete.
                                Eg: ['main', 'additional']
                                Use ['*'] for "all doctypes"
    @type can_delete_doctypes: list(string)
 
    @param can_revise_doctypes: the list of doctypes that users are
                                allowed to revise
                                Eg: ['main', 'additional']
                                Use ['*'] for "all doctypes"
    @type can_revise_doctypes: list(string)
 
    @param can_describe_doctypes: the list of doctypes that users are
                                  allowed to describe
                                  Eg: ['main', 'additional']
                                  Use ['*'] for "all doctypes"
    @type can_describe_doctypes: list(string)
 
    @param can_comment_doctypes: the list of doctypes that users are
                                 allowed to comment
                                 Eg: ['main', 'additional']
                                 Use ['*'] for "all doctypes"
    @type can_comment_doctypes: list(string)
 
    @param can_keep_doctypes: the list of doctypes for which users can
                         choose to keep previous versions visible when
                         revising a file (i.e. 'Keep previous version'
                         checkbox). See also parameter 'keepDefault'.
                         Note that this parameter is ~ignored when
                         revising the attributes of a file (comment,
                         description) without uploading a new
                         file. See also parameter
                         Move_Uploaded_Files_to_Storage.force_file_revision
                         Eg: ['main', 'additional']
                         Use ['*'] for "all doctypes"
    @type can_keep_doctypes: list(string)
 
 
    @param can_add_format_to_doctypes: the list of doctypes for which users can
                              add new formats. If there is no value,
                              then no 'add format' link nor warning
                              about losing old formats are displayed.
                              Eg: ['main', 'additional']
                              Use ['*'] for "all doctypes"
    @type can_add_format_to_doctypes: list(string)
 
    @param can_restrict_doctypes: the list of doctypes for which users can
                             choose the access restrictions when adding or
                             revising a file. If no value is given:
                               - no restriction is applied if none is defined
                                 in the 'restrictions' parameter.
                               - else the *first* value of the 'restrictions'
                                 parameter is used as default restriction.
 
                             Eg: ['main', 'additional']
                             Use ['*'] for "all doctypes"
    @type can_restrict_doctypes : list(string)
 
    @param can_rename_doctypes: the list of doctypes that users are allowed
                           to rename (when revising)
                           Eg: ['main', 'additional']
                           Use ['*'] for "all doctypes"
    @type can_rename_doctypes: list(string)
 
    @param can_name_new_files: if user can choose the name of the files they
                         upload or not
    @type can_name_new_files: boolean
 
    @param doctypes_to_default_filename: Rename uploaded files to admin-chosen
                                 values. List here the the files in
                                 current submission directory that
                                 contain the names to use for each doctype.
                                 Eg:
                                 {'main': RN', 'additional': 'additional_filename'}
 
                                 If the same doctype is submitted
                                 several times, a"-%i" suffix is added
                                 to the name defined in the file.
 
                                 The default filenames are overriden
                                 by user-chosen names if you allow
                                 'can_name_new_files' or
                                 'can_rename_doctypes'.
    @type doctypes_to_default_filename: dict
 
    @param max_files_for_doctype: the maximum number of files that users can
                          upload for each doctype.
                          Eg: {'main': 1, 'additional': 2}
 
                          Do not specify the doctype here to have an
                          unlimited number of files for a given
                          doctype.
    @type max_files_for_doctype: dict
 
    @param create_related_formats: if uploaded files get converted to
                                     whatever format we can or not
    @type create_related_formats: boolean
 
    @param keep_default: the default behaviour for keeping or not previous
                     version of files when users cannot choose (no
                     value in can_keep_doctypes).
                     Note that this parameter is ignored when revising
                     the attributes of a file (comment, description)
                     without uploading a new file. See also parameter
                     Move_Uploaded_Files_to_Storage.force_file_revision
    @type keep_default: boolean
 
    @param show_links: if we display links to files when possible or
                         not
    @type show_links: boolean
 
    @param file_label: the label for the file field
    @type file_label: string
 
    @param filename_label: the label for the file name field
    @type filename_label: string
 
    @param description_label: the label for the description field
    @type description_label: string
 
    @param comment_label: the label for the comments field
    @type comment_label: string
 
    @param restriction_label: the label in front of the restrictions list
    @type restriction_label: string
 
    @param sbm_indir: the submission indir parameter, in case the
                      function is used in a WebSubmit submission
                      context.
                      This value will be used to retrieve where to
                      read the current state of the interface and
                      store uploaded files
    @type sbm_indir : string
 
    @param sbm_doctype: the submission doctype parameter, in case the
                        function is used in a WebSubmit submission
                        context.
                        This value will be used to retrieve where to
                        read the current state of the interface and
                        store uploaded files
    @type sbm_doctype: string
 
    @param sbm_access: the submission access parameter. Must be
                       specified in the context of WebSubmit
                       submission, as well when used in the
                       WebSubmit Admin file management interface.
 
                       This value will be used to retrieve where to
                       read the current state of the interface and
                       store uploaded files
    @type sbm_access: string
 
    @param sbm_curdir: the submission curdir parameter. Must be
                       specified in the context of WebSubmit
                       function Create_Upload_File_Interface.
 
                       This value will be used to retrieve where to
                       read the current state of the interface and
                       store uploaded files.
    @type sbm_curdir: string
 
    @param uid: the user id
    @type uid: int
 
    @return Tuple (errorcode, html)

Adding jQuery UI tabs to Drupal 7 [SOLVED]

I recently wanted to add some jQuery UI tabs to nodes. Drupal 7 has jQuery 1.4 included in core, so we’ll take advantage of that.

This is how you do it:

First, edit template.php and create / make some changes to hook _preprocess_html.

function THEMENAME_preprocess_html(&$variables){
   // This function looks for node 1 and only adds the javascript for this.
   // However it can be extended in different ways if required
    drupal_add_library('system', 'ui.tabs');
    drupal_add_js('jQuery(document).ready(function(){
                jQuery("#tabs").tabs({event: "mouseover"});
                jQuery("#tabs").tabs().addClass("ui-tabs-vertical ui-helper-clearfix");
                jQuery("#tabs li").removeClass("ui-corner-top").addClass("ui-corner-left");
            });',
        'inline');
}

*Note that you can remove ui-tabs-vertical if you want horizontal tabs. You can also change the mouseover event to the event you prefer.

This would be the markup:

<!-- TITULOS PESTAÑAS -->
<div id="tabs">
<div id="tab-list">
  <ul>
  <li><a href="#tabs-1">Titulo 1</a></li>
  <li><a href="#tabs-2">Titulo 2</a></li>
  <li><a href="#tabs-3">Titulo 3</a></li>
  <li><a href="#tabs-4">Titulo 4</a></li>
  <li><a href="#tabs-5">Titulo 5</a></li>
  <li><a href="#tabs-6">Titulo 6</a></li>
  <li><a href="#tabs-7">Titulo 7</a></li>
  <li><a href="#tabs-8">Titulo 8</a></li>
  <li><a href="#tabs-9">Titulo 9</a></li>
  <li><a href="#tabs-10">Titulo 10</a></li>
  </ul>
</div>
 
 
<!-- CONTENIDO PESTAÑAS -->
<div id="tab-content">    
  <div id="tabs-1">
    <p>Texto de la TABS-1</p>
  </div>
  <div id="tabs-2">
    <p>Texto de la TABS-2</p>
  </div>
  <div id="tabs-3">
    <p>Texto de la TABS-3</p>
  </div>
  <div id="tabs-4">
    <p>Texto de la TABS-4</p>
  </div>
  <div id="tabs-5">
    <p>Texto de la TABS-5</p>
  </div>
  <div id="tabs-6">
   <p>Texto de la TABS-6</p>
  </div>
  <div id="tabs-7">
    <p>Texto de la TABS-7</p>
  </div>
  <div id="tabs-8">
    <p>Texto de la TABS-8</p>
  </div>
  <div id="tabs-9">
    <p>Texto de la TABS-9</p>
  </div>
  <div id="tabs-10">
    <p>Texto de la TABS-10</p>
  </div>
</div>
</div>

And a sample output:
UI-Tabs-Drupal

Cómo ordenar una lista de diccionarios en python [RESUELTO]

Se tiene una lista de diccionarios Python, se quiere ordenar según un criterio ordenado de valores que puede tomar un determinada llave de un diccionario. Veámoslo con un ejemplo

Se tiene la siguiente lista de diccionarios:

[{'foo': FOO1}, {'foo': FOO2}, {'foo': FOO10}]

Y se tiene la siguiente lista de criterio de ordenación:

[FOO10, FOO2, FOO1]

Se espera que la lista resultante esté ordenada de la siguiente manera:

[{'foo': FOO10}, {'foo': FOO2}, {'foo': FOO1}]

Veamos cómo hacerlo

>>> to_sort = [{'foo': FOO1}, {'foo': FOO2}, {'foo': FOO10}]
>>> criteria = [FOO10, FOO2, FOO1]
>>> to_sort.sort(key=lambda x: criteria.index(x['foo']))
>>> to_sort
[{'foo': FOO10}, {'foo': FOO2}, {'foo': FOO1}]

Drupal 7: quick-edit link for nodes for authorized users [SOLVED]

Showing a “edit this node” link for users who have authorization to edit that node is a useful feature.

The link will show only to logged users who have the editing privilege.

In Drupal7 this can be done by editing the node template and adding these lines to your node.tpl.php (or node–contenttypename-tpl.php)

  <!-- quick edit link -->
  <?php if(user_access('administer nodes')): 
      echo l(t('Edit this node'), 'node/' . $node->nid . '/edit');
   endif; ?>
  <!-- /quick edit link -->

Or:

<?php
if (node_access('update',$node)){
   print l(t('Edit'),'node/'.$node->nid.'/edit' );
}
?>

Add Masonry container template to WordPress RYU THEME [SOLVED]

Some days ago I wrote a post about adding a masonry container to Ryu theme.

Today I would like to explain how to add a masonry container template to your Ryu Theme.

My template will ouput images related to categories (I used the Tejus Category Image plugin to link images to categories) displayed in a masonry wrapper.

First, we’ll have to make the template archive (which you will put in /wp-content/themes/ryu/template-art-lfa.php)

<?php
// File Security Check
if ( ! empty( $_SERVER['SCRIPT_FILENAME'] ) && basename( __FILE__ ) == basename( $_SERVER['SCRIPT_FILENAME'] ) ) :
	die ( 'You do not have sufficient permissions to access this page!' );
endif;
 
/* Template Name: art-lfa */
 
get_header(); ?>
 
<div id="boxes"> <!-- masonry wrapper -->
 
	<?php
	$categorias = get_categories('child_of=2'); // I am getting the subcategories of category with ID=2
	foreach ($categorias as $categoria){
		?>
 
        <div id="categoria-<?php echo $categoria->cat_ID; ?>" class="box">
               <a href="<?php echo get_category_link($categoria->cat_ID); ?> ">
		          <div class="rel">
			        	<img src="<?php echo tejus_dj_getcatimg($categoria->cat_ID); ?>" 
					     	class="attachment-summary-image wp-post-image" 
					     	style="width: 350px; "
					     	alt="<?php echo $categoria->cat_name ?>" />
 
			         	<div class="texts" style="height:100%">
				          	<div class="abs">
								<?php echo $categoria->cat_name; ?>
						</div>
			         	</div>
		           </div>
               </a>
	</div>
	<?php
	} // foreach 
    ?>	  				
</div><!-- del masonry-wrapper -->
<div class="clear"></div>
 
<?php get_footer(); ?>

We will also need some CSS. So, edit /wp-content/themes/ryu/style.css and add these lines at the end of the file:

/* miguel nuevo layout masonry (#boxes) */
#boxes { margin-top: 40px; margin-left: auto; margin-right: auto; }
.box { width: 350px; margin-bottom: 15px; color: #636363; /* para alto fijo: quitar si masonry...  float:left;*/}
.box .rel { position: relative; }
.box .rel p { margin: 0; }
.box .texts { /*position: absolute; top: -20px; left: -20px; width: 450px; color: #fff; z-index: 200;*/color: #FFFFFF;left: 0;position: absolute; top: 0px; width: 460px; z-index: 200; opacity: 0; filter: alpha(opacity=0); }
.box .texts .categories a, .box .texts a, .box .texts .posted, .box .texts .posted a { color: #fff; }
.box .texts .transparent img { opacity: 0.7; filter: alpha(opacity=10); }
.box .texts .abs { position: absolute; top: 50%; width: 100%; text-align: center;}
.box .categories { padding-bottom: 10px; }
.box .categories a, .box .posted a { color: #a1a1a1; }
.box h1 { margin: 0; padding-bottom: 10px; font-size: 16px; }
.box h1 a { color: #333; }
.box .posted { padding-top: 10px; color: #a1a1a1; }
.box img { display: block;
margin-left: auto;
margin-right: auto; }
.box img:hover {opacity: '0.7' filter: 'alpha(opacity=70)'}

Then you will need to use ImagesLoaded (http://imagesloaded.desandro.com/) to avoid some issues with Chrome and Safari. If you do not add this JS file, masonry will be triggering BEFORE images have been fully loaded and will fail in Chrome.

So, first of all you should download imagesloaded.pkgd.min.js and put it into /wp-content/themes/ryu/js/imagesloaded.pkgd.min.js.

Ok, now we have to tell Ryu to use ImagesLoaded. So we’ll need to edit /wp-content/themes/ryu/functions.php to register this new script (pay attention to core_mods function)
Here is my functions.php after doing so:

<?php
/**
 * Ryu functions and definitions
 *
 * @package Ryu
 */
 
 
 /* previa: para archivos cargo cosas del tema gridly */
 // Load jQuery
	if ( !function_exists('core_mods') ) {
		function core_mods() {
			if ( !is_admin() ) {
				wp_deregister_script('jquery');
				wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"));
				wp_register_script('jquery.masonry', (get_template_directory_uri()."/js/jquery.masonry.min.js"),'jquery',false,true);
 
                // nuevo 20140112 para evitar problemas imagenes en chrome... https://github.com/desandro/masonry/issues/35
				wp_register_script('imagesloaded.pkgd.min.js', (get_template_directory_uri()."/js/functions.js"), 'imagesloaded.pkgd', false,true);
				// ------------------------
 
				wp_register_script('gridly.functions', (get_template_directory_uri()."/js/functions.js"),'jquery.masonry',false,true);
 
				wp_enqueue_script('jquery');
				wp_enqueue_script('jquery.masonry');
 
				// nuevo 20140112 para evitar problemas imgs chrome...
				wp_enqueue_script('imagesloaded.pkgd');
				// ---------------------------------
 
 
				wp_enqueue_script('gridly.functions');
			}
		}
		core_mods();
	}
 
 
	// Gridly post thumbnails
	add_theme_support( 'post-thumbnails' );
	add_image_size('summary-image', 310, 9999);
	add_image_size('detail-image', 770, 9999);
 
 
    // hide blank excerpts 
	function custom_excerpt_length( $length ) {
	return 0;
	}
	add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
 
	function new_excerpt_more($more) {
       global $post;
	return '';
	}
	add_filter('excerpt_more', 'new_excerpt_more');
 
 
 
 /* EMPIEZA FUNCTIONS DEL TEMA RYU.... */
 
/**
 * Set the content width based on the theme's design and stylesheet.
 */
if ( ! isset( $content_width ) )
	$content_width = 696; /* pixels */
 
if ( ! function_exists( 'ryu_setup' ) ) :
/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which runs
 * before the init hook. The init hook is too late for some features, such as indicating
 * support post thumbnails.
 */
function ryu_setup() {
	/**
	 * Make theme available for translation
	 * Translations can be filed in the /languages/ directory
	 * If you're building a theme based on ryu, use a find and replace
	 * to change 'ryu' to the name of your theme in all the template files
	 */
	load_theme_textdomain( 'ryu', get_template_directory() . '/languages' );
 
	/**
	 * Add default posts and comments RSS feed links to head
	 */
	add_theme_support( 'automatic-feed-links' );
 
	/**
	 * Enable support for Post Thumbnails
	 */
	add_theme_support( 'post-thumbnails' );
 
	/**
	 * Adding several sizes for Post Thumbnails
	 */
	add_image_size( 'ryu-featured-thumbnail', 1272, 0 );
 
	/**
	 * This theme uses wp_nav_menu() in one location.
	 */
	register_nav_menus( array(
		'primary' => __( 'Primary Menu', 'ryu' ),
	) );
 
	/**
	 * Enable support for Post Formats
	 */
	add_theme_support( 'post-formats', array( 'aside', 'image', 'video', 'quote', 'link', 'gallery' ) );
 
	/**
	 * Enable support for the Tonesque library
	 */
	add_theme_support( 'tonesque' );
}
endif; // ryu_setup
add_action( 'after_setup_theme', 'ryu_setup' );
 
/**
 * Setup the WordPress core custom background feature.
 *
 * Hooks into the after_setup_theme action.
 */
function ryu_register_custom_background() {
	add_theme_support( 'custom-background', apply_filters( 'ryu_custom_background_args', array(
		'default-color' => 'fff',
		'default-image' => '',
	) ) );
}
add_action( 'after_setup_theme', 'ryu_register_custom_background' );
 
/**
 * Register widgetized area and update sidebar with default widgets
 */
function ryu_widgets_init() {
	register_sidebar( array(
		'name'          => __( 'Top Widget Area One', 'ryu' ),
		'id'            => 'sidebar-1',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h1 class="widget-title">',
		'after_title'   => '</h1>',
	) );
 
	register_sidebar( array(
		'name'          => __( 'Top Widget Area Two', 'ryu' ),
		'id'            => 'sidebar-2',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h1 class="widget-title">',
		'after_title'   => '</h1>',
	) );
 
	register_sidebar( array(
		'name'          => __( 'Top Widget Area Three', 'ryu' ),
		'id'            => 'sidebar-3',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h1 class="widget-title">',
		'after_title'   => '</h1>',
	) );
 
	register_sidebar( array(
		'name'          => __( 'Top Widget Area Four', 'ryu' ),
		'id'            => 'sidebar-4',
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h1 class="widget-title">',
		'after_title'   => '</h1>',
	) );
}
add_action( 'widgets_init', 'ryu_widgets_init' );
 
/**
 * Register Google fonts for Ryu
 */
function ryu_fonts() {
	/* translators: If there are characters in your language that are not supported
	   by Lato, translate this to 'off'. Do not translate into your own language. */
	if ( 'off' !== _x( 'on', 'Lato font: on or off', 'ryu' ) ) {
 
		$protocol = is_ssl() ? 'https' : 'http';
 
		wp_register_style( 'ryu-lato', "$protocol://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic", array(), null );
	}
 
	/* translators: If there are characters in your language that are not supported
	   by Playfair Display, translate this to 'off'. Do not translate into your own language. */
	if ( 'off' !== _x( 'on', 'Playfair Display font: on or off', 'ryu' ) ) {
		$subsets = 'latin,latin-ext';
 
		/* translators: To add an additional Playfair Display character subset specific to your language, translate this to 'cyrillic'. Do not translate into your own language. */
		$subset = _x( 'no-subset', 'Playfair Display font: add new subset (cyrillic)', 'ryu' );
 
		if ( 'cyrillic' == $subset )
			$subsets .= ',cyrillic';
 
		$protocol = is_ssl() ? 'https' : 'http';
		$query_args = array(
			'family' => 'Playfair+Display:400,700,900,400italic,700italic,900italic',
			'subset' => $subsets,
		);
		wp_register_style( 'ryu-playfair-display', add_query_arg( $query_args, "$protocol://fonts.googleapis.com/css" ), array(), null );
	}
}
add_action( 'init', 'ryu_fonts' );
 
/**
 * Enqueue scripts and styles
 */
function ryu_scripts() {
	wp_enqueue_style( 'ryu-style', get_stylesheet_uri() );
 
	wp_enqueue_style( 'ryu-lato' );
 
	wp_enqueue_style( 'ryu-playfair-display' );
 
	if ( has_nav_menu( 'primary' ) )
		wp_enqueue_script( 'ryu-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20120206', true );
 
	wp_enqueue_script( 'ryu-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20130115', true );
 
	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) )
		wp_enqueue_script( 'comment-reply' );
 
	if ( is_singular() && wp_attachment_is_image() )
		wp_enqueue_script( 'ryu-keyboard-image-navigation', get_template_directory_uri() . '/js/keyboard-image-navigation.js', array( 'jquery' ), '20120202' );
 
	wp_enqueue_script( 'ryu-theme', get_template_directory_uri() . '/js/ryu.js', array( 'jquery' ), '20130319', true );
}
add_action( 'wp_enqueue_scripts', 'ryu_scripts' );
 
/**
 * Enqueue Google fonts style to admin screen for custom header display.
 */
function ryu_admin_fonts( $hook_suffix ) {
	if ( 'appearance_page_custom-header' != $hook_suffix )
		return;
 
	wp_enqueue_style( 'ryu-lato' );
 
	wp_enqueue_style( 'ryu-playfair-display' );
}
add_action( 'admin_enqueue_scripts', 'ryu_admin_fonts' );
 
/**
 * Count the number of footer sidebars to enable dynamic classes for the footer
 */
function ryu_top_sidebar_class() {
 
	$count = 0;
 
	if ( is_active_sidebar( 'sidebar-1' ) )
		$count++;
 
	if ( is_active_sidebar( 'sidebar-2' ) )
		$count++;
 
	if ( is_active_sidebar( 'sidebar-3' ) )
		$count++;
 
	if ( is_active_sidebar( 'sidebar-4' ) )
		$count++;
 
	$class = '';
 
	switch ( $count ) {
		case '1':
			$class = 'one';
			break;
		case '2':
			$class = 'two';
			break;
		case '3':
			$class = 'three';
			break;
		case '4':
			$class = 'four';
			break;
	}
 
	if ( $class )
		echo 'class="wrap clear ' . $class . '"';
}
 
/**
 * Implement Tonesque if need be
 */
function ryu_load_bundled_tonesque() {
	if ( ! class_exists( 'Tonesque' ) ) {
		require( get_template_directory() . '/inc/tonesque.php' );
	}
}
 
 
/* 20131226 Miguel para añadir la parte de contributors... */
function contributors() {
	global $wpdb;
 
	$authors = $wpdb->get_results("SELECT ID, user_nicename from $wpdb->users ORDER BY display_name");
 
	foreach($authors as $author) {
		echo '<li><div class="authorinfo" style="width: 100%;"">';
		/*echo "<a href=\"".get_bloginfo('url')."/?author=";
		echo $author->ID;
		echo "\">";*/
		//echo get_avatar($author->ID);
 
		echo '<div class="authorphoto">';
		if (function_exists('userphoto')){
			echo userphoto($author->ID); // requiere plugin User Photo para WP
		}
		else{
			echo get_avatar($author->ID);
		}
		echo '</div>';
		echo '<div class="authorbio"><h4>';
		the_author_meta('display_name', $author->ID);
		echo "</h4>";
		echo '<p>';
		the_author_meta('user_description', $author->ID);
		echo '</p>';
		echo "</div>";
		echo "</div></li>";
	}
 
    /* example output */
    /*echo '
    		<div class="authorinfo" style="width: 100%;"">
    			<div class="authorphoto" style="float: left; width: 25%; max-width: 200px; margin-right: 5%; position: relative;">
 
    			</div>
    			<div class="authorbio" style="float: left; width: 70%; max-width: 740px; position: relative">
    				<h4>Nombre</h4>
    				<p style="font-size:0.7em">Esta es la descripcion del autor en funcion contributors() de functinons.php...</p>
    			</div>
    		</div>
    	  ';*/
 
}
/* fin contributors */
 
 
 
 
add_action( 'wp_loaded', 'ryu_load_bundled_tonesque' );
 
/**
 * Implement the Custom Header feature
 */
require get_template_directory() . '/inc/custom-header.php';
 
/**
 * Custom template tags for this theme.
 */
require get_template_directory() . '/inc/template-tags.php';
 
/**
 * Custom functions that act independently of the theme templates
 */
require get_template_directory() . '/inc/extras.php';
 
/**
 * Customizer additions
 */
require get_template_directory() . '/inc/customizer.php';
 
/*
 * Load Jetpack compatibility file.
 */
require get_template_directory() . '/inc/jetpack.php';
 
 
// updater for WordPress.com themes
if ( is_admin() )
	include dirname( __FILE__ ) . '/inc/updater.php';

Next we need to tell Ryu to render the masonry wrapper when all images in our container are fully loaded. ImagesLoaded triggers an event when this happens. So we will just edit /wp-content/themes/ryu/js/functions.js and add these to the end of the file…

// initialize Masonry after all images have loaded  .. EVITAR PROBLEMAS CHROME!!!
// ver mas aqui https://github.com/desandro/masonry/issues/35
 
var $container = $('#boxes');
$container.imagesLoaded( function() {
 
// grid
	$('#boxes').masonry({
		itemSelector: '.box',
		columnWidth: 350,
		isFitWidth: true, 
		gutterWidth: 20	
	});
 
	$('#related').masonry({
		itemSelector: '.box',
		columnWidth: 350,
		isFitWidth: true, 
		gutterWidth: 20	
	});
 
	$('.texts').live({
		'mouseenter': function() {
			//if ($(this).height() < $(this).find('.abs').height()) {
			//	$(this).height($(this).find('.abs').height());
			//}
 
			$(this).stop(true, true).animate({
				'opacity': '0.8',
				'filter': 'alpha(opacity=80)'
			}, 0);
		},
		'mouseleave': function() {
			$(this).stop(true, true).animate({
				'opacity': '0',
				'filter': 'alpha(opacity=0)'
			}, 0);
		}
	});
});

The last step is easy: create a new page (Pages>New Page) and tell it to use the template-art-lfa template we just made.

You can download my ryu-completo-masonry-ok-20140112.

Enjoy!

CDS Invenio: format templates box in advanced search and search results screen [SOLVED]

Invenio 0.99x offers the option to control which output formats are enabled in searches and collections. For instance, if we take a look at the advanced search screen inside of the particular collections of my Invenio instance (more precisely, ‘Trabajos Académicos’), you’ll see this:

invenio_websearch

Why are these output formats being showed, and why in that order? Because in Websearch module, I made those formats (and just those) available in my ‘Trabajos Académicos’ collection and ordered them in that way:

invenio_websearch_webcoll

To this point, everything works as expected.

But let’s go further and perform a search using that advanced search screen in the ‘Trabajos Académicos’ collection. Let’s search for any term. For demonstration purposes, I’ll search ‘water’. This is the screen I get. Note the output formats available now…

invenio_search_engine

Every format available is being shown! Not just the output formats we defined at Websearch…. Why’s that?

If you take a look at the code, you’ll notice that first output (advanced search within a particular collection) is being produced by create_formatoptions function defined at websearch_webcoll.py. This create_formatoptions function is called from create_searchfor_advanced (also defined at websearch_webcoll.py). This is the snippet of code that produces that output (first image in this post):

569     def create_formatoptions(self, ln=CFG_SITE_LANG):
570         "Produces 'Output format options' portal box."
571 
572         # load the right message language
573         _ = gettext_set_language(ln)
574 
575         box = ""
576         values = []
577         query = """SELECT f.code,f.name FROM format AS f, collection_format AS cf
578                    WHERE cf.id_collection=%d AND cf.id_format=f.id AND f.visibility='1'
579                    ORDER BY cf.score DESC, f.name ASC"""  % self.id
580         res = run_sql(query)
581         if res:
582             for row in res:
583                 values.append({'value' : row[0], 'text': row[1]})
584         else:
585             values.append({'value' : 'hb', 'text' : "HTML %s" % _("brief")})
586         box = websearch_templates.tmpl_select(
587                    fieldname = 'of',
588                    css_class = 'address',
589                    values = values
590                   )
591         return box

The second output, the one corresponding to search results, is produced by create_search_box at search_engine.py. This function is called from function tmpl_search_box (defined at websearch_templates.py). Here is the snippet of code from search_engine.py that produces that output (third image in this post) along with the corresponding lines at search_engine.py:

 742 def create_search_box(cc, colls, p, f, rg, sf, so, sp, rm, of, ot, as,
 743                       ln, p1, f1, m1, op1, p2, f2, m2, op2, p3, f3,
 744                       m3, sc, pl, d1y, d1m, d1d, d2y, d2m, d2d, dt, jrec, ec,
 745                       action=""):
 746 
 747     """Create search box for 'search again in the results page' functionality."""
 748 
 
...
 
 806     formats = []
 807     query = """SELECT code,name FROM format WHERE visibility='1' ORDER BY name ASC"""
 808     res = run_sql(query)
 809     if res:
 810         # propose found formats:
 811         for code, name in res:
 812             formats.append({ 'value' : code,
 813                              'text' : name
 814                            })
 815     else:
 816         formats.append({'value' : 'hb',
 817                         'text' : _("HTML brief")
 818                        })

So now we know why the outputs differ.

Every output format is stored at ‘format’ table in your database:

mysql> SELECT code,name FROM format WHERE visibility='1' ORDER BY name ASC;
+--------+------------------------------------+
| code   | name                               |
+--------+------------------------------------+
| hx     | BibTeX                             | 
| xd     | Dublin Core                        | 
| xe     | EndNote                            | 
| hb     | HTML brief                         | 
| hbgeol | HTML Brief Geol                    | 
| hcs    | HTML citesummary                   | 
| hd     | HTML detailed                      | 
| hlight | HTML Light (invocaciones externas) | 
| hm     | MARC                               | 
| xm     | MARCXML                            | 
| mets   | METS                               | 
| xn     | NLM                                | 
| hc     | photo captions ONLY                | 
| hp     | portfolio                          | 
| premis | PREMIS                             | 
| xw     | RefWorks                           | 
| untld  | Untitled                           | 
| untld2 | Untitled                           | 
+--------+------------------------------------+
18 ROWS IN SET (0.00 sec)

This table is quite simple. There is this interesting parameter called ‘visibility’:

mysql> DESC format;
+--------------+-----------------------+------+-----+---------+----------------+
| FIELD        | TYPE                  | NULL | KEY | DEFAULT | Extra          |
+--------------+-----------------------+------+-----+---------+----------------+
| id           | mediumint(9) UNSIGNED | NO   | PRI | NULL    | AUTO_INCREMENT | 
| name         | VARCHAR(255)          | NO   |     | NULL    |                | 
| code         | VARCHAR(6)            | NO   | UNI | NULL    |                | 
| description  | VARCHAR(255)          | YES  |     |         |                | 
| content_type | VARCHAR(255)          | YES  |     |         |                | 
| visibility   | tinyint(4)            | NO   |     | 1       |                | 
+--------------+-----------------------+------+-----+---------+----------------+
6 ROWS IN SET (0.01 sec)

If you set a format’s visibility to ‘0’ then that format won’t be outputed. I’ll be setting to ‘0’ some values to exlude those formats from visualization, just for demonstration purposes:

mysql> SELECT * FROM format WHERE visibility = 0;
+----+--------------------+--------+--------------------------------------------------------------------------+----------------------+------------+
| id | name               | code   | description                                                              | content_type         | visibility |
+----+--------------------+--------+--------------------------------------------------------------------------+----------------------+------------+
| 11 | Excel              | excel  | Excel csv output                                                         | application/ms-excel |          0 | 
| 12 | HTML similarity    | hs     | Very short HTML output FOR similarity box (<i>people also viewed..</i>). | text/html            |          0 | 
| 13 | RSS                | xr     | RSS.                                                                     | text/xml             |          0 | 
| 14 | OAI DC             | xoaidc | OAI DC.                                                                  | text/xml             |          0 | 
| 15 | File mini-panel    | hdfile | Used TO SHOW fulltext files IN mini-panel OF detailed record pages.      | text/html            |          0 | 
| 16 | Actions mini-panel | hdact  | Used TO display actions IN mini-panel OF detailed record pages.          | text/html            |          0 | 
| 17 | REFERENCES tab     | hdref  | Display record REFERENCES IN REFERENCES tab.                             | text/html            |          0 | 
+----+--------------------+--------+--------------------------------------------------------------------------+----------------------+------------+
7 ROWS IN SET (0.01 sec)
 
mysql> UPDATE format SET visibility=0 WHERE id='hbgeol';
Query OK, 0 ROWS affected (0.00 sec)
ROWS matched: 0  Changed: 0  Warnings: 0

After setting some of the output format visibility to 0, these are the ones who have visibility=1:

mysql> SELECT * FROM format WHERE visibility=1 ORDER BY name;
+----+------------------+--------+--------------------------------------------------------------+--------------+------------+
| id | name             | code   | description                                                  | content_type | visibility |
+----+------------------+--------+--------------------------------------------------------------+--------------+------------+
|  8 | BibTeX           | hx     | BibTeX.                                                      | text/html    |          1 | 
|  4 | Dublin Core      | xd     | XML Dublin Core.                                             | text/xml     |          1 | 
|  9 | EndNote          | xe     | XML EndNote.                                                 | text/xml     |          1 | 
|  1 | HTML brief       | hb     | HTML brief output format, used FOR SEARCH results pages.     | text/html    |          1 | 
| 18 | HTML citesummary | hcs    | HTML cite summary format, used FOR SEARCH results pages.     | text/html    |          1 | 
|  2 | HTML detailed    | hd     | HTML detailed output format, used FOR Detailed record pages. | text/html    |          1 | 
|  3 | MARC             | hm     | HTML MARC.                                                   | text/html    |          1 | 
|  5 | MARCXML          | xm     | XML MARC.                                                    | text/xml     |          1 | 
| 22 | METS             | mets   | Formato METS.                                                | text/xml     |          1 | 
| 10 | NLM              | xn     | XML NLM.                                                     | text/xml     |          1 | 
| 24 | PREMIS           | premis | PREMIS                                                       | text/xml     |          1 | 
| 19 | RefWorks         | xw     | RefWorks.                                                    | text/xml     |          1 | 
+----+------------------+--------+--------------------------------------------------------------+--------------+------------+
12 ROWS IN SET (0.00 sec)

And the corresponding output for search results (as a result of performing a search):
CDS Invenio output formats at search results

So, what to do if you want to have ALWAYS just the output formats defined for some collection, no matter if it is the “advanced search screen” or the “search results screen”. Just edit search_engine.py from this:

query = """SELECT code,name FROM format WHERE visibility='1' ORDER BY name ASC"""
    res = run_sql(query)
    if res:
        # propose found formats:
        for code, name in res:
            formats.append({ 'value' : code,
                             'text' : name
                           })
    else:
        formats.append({'value' : 'hb',
                        'text' : _("HTML brief")
                       })

To this:

#query que saca solo los output formats propios de la coleccion... (miguel)
    query = """SELECT f.code,f.name FROM format AS f, collection_format AS cf 
                WHERE cf.id_collection=%d AND cf.id_format=f.id AND f.visibility='1'
                ORDER BY cf.score DESC, f.name ASC""" % cc_colID
    #query que saca todos los formatos de salida, sean o no de la coleccion (original de invenio)
    #query = """SELECT code,name FROM format WHERE visibility='1' ORDER BY name ASC"""
    res = run_sql(query)
    if res:
        # propose found formats:
        for code, name in res:
            formats.append({ 'value' : code,
                             'text' : name
                           })
    else:
        formats.append({'value' : 'hb',
                        'text' : _("HTML brief")
                       })

And remember to run inveniocfg –update-all and then restart your Apache server:

[root@zaguan invenio]# sudo -u apache inveniocfg --update-all; /etc/init.d/httpd restart

And lets see the changes produced at the search results screen…
invenio output format list at search results screen

Hope this was useful!!

Rename multiple files using sequence number in OSX from command line [SOLVED]

With this command you will rename all the jpg files in the current directory to PREFIX_0000.jpg to PREFIX_9999.jpg

find . -name '*.jpg' \
| awk 'BEGIN{ a=0 }{ printf "mv %s PREFIX_%04d.jpg\n", $0, a++ }' \
| bash

If you just need two numbers (PREFIX_00.jpg to PREFIX_99.jpg) you can do it by:

find . -name '*.jpg' \
| awk 'BEGIN{ a=0 }{ printf "mv %s PREFIX_%02d.jpg\n", $0, a++ }' \
| bash

Drupal7: list allowed values from a field type list [SOLVED]

In Drupal 7, how do you list all the allowed values in a certain field of some content type?

You can use the list_allowed_values function.

Lets see it with an example.

I will define a new Content Type called “Actividad” (machine name=’actividad‘), which will have a title, a body and a List(text) field type called ‘tipo_actividad‘ (machine name=’field_tipo_actividad‘):
list_allowed_values drupal 7

And then I will define the allowed values for this field_tipo_actividad field:
drupal 7 list_allowed_values for field

Now, how do I programmatically list the allowed values for that field? Using list_allowed_values function:

$field = field_info_field('field_tipo_actividad'); /* field_tipo_actividad=machine name of the field */
$allowed_values = list_allowed_values($field);     /* what are the values allowed for that field? */
return var_dump($allowed_values);

drupal7 list allowed values

If you want a prettier output, you can change the code to:

$field = field_info_field('field_tipo_actividad');
$allowed_values = list_allowed_values($field);
$salida = "";
foreach ($allowed_values as $key=>$value){
    $salida = $salida."Key: ".$key." Value: ".$value."<br />";
}
return $salida;

And you’ll get something like:
drupal list_allowed_values tutorial example

WordPress: adding masonry grid layout to Ryu theme [SOLVED]

I just love Ryu theme for WordPress. It is a modern, white, minimal yet elegant theme.

The one thing I am not fond of about Ryu is the archive page. I would prefer if it had a grid-based layout (using masonry, for instance). For instance, something like the Gridly theme.

So I will be teaching you how make this posible. If you don’t need so many explanations and are only interested in CSS+markup, you can just read this.

Include masonry and jQuery (if not included) in /wp-content/themes/ryu-wpcom (you can also link to them in http://ajax.googleapis.com/ajax/libs/jquery site)

Then edit /wp-content/themes/ryu-wpcom/functions.php file and add these lines after the <?php tag.

The most important function is the first one. The necessary javascript files are included (jquery.min.js will be linked to google’s website and jquery.masonry.min.js will be loaded from the js folder in the theme, /wp-content/themes/ryu-wpcom/js/). Note that there is also this /js/functions.js file which contents will be defined later.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* functions.php, just after php code starts */
 // Load jQuery
	if ( !function_exists('core_mods') ) {
		function core_mods() {
			if ( !is_admin() ) {
				wp_deregister_script('jquery');
				wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"));
				wp_register_script('jquery.masonry', (get_template_directory_uri()."/js/jquery.masonry.min.js"),'jquery',false,true);
				wp_register_script('gridly.functions', (get_template_directory_uri()."/js/functions.js"),'jquery.masonry',false,true);
 
				wp_enqueue_script('jquery');
				wp_enqueue_script('jquery.masonry');
				wp_enqueue_script('gridly.functions');
			}
		}
		core_mods();
	}
 
	// Gridly post thumbnails
	add_theme_support( 'post-thumbnails' );
	add_image_size('summary-image', 310, 9999);
	add_image_size('detail-image', 770, 9999);
 
 
    // hide blank excerpts 
	function custom_excerpt_length( $length ) {
	return 0;
	}
	add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
 
	function new_excerpt_more($more) {
          global $post;
	  return '';
	}
	add_filter('excerpt_more', 'new_excerpt_more');

Now lets create the referenced /js/functions.js file with this contents (first lines are the ones you can find in gridly theme, so just pay attention to last part, lines 57-61, which is the code we just included):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// this is /js/functions.js (should be placed in your theme's folder, as in /wp-content/themes/ryu-wpcom/js/functions.js)
// masonry code 
$(document).ready(function() {
  $('#post-area').masonry({
    // options
    itemSelector : '.post',
    // options...
  isAnimated: true,
  animationOptions: {
    duration: 400,
    easing: 'linear',
    queue: false
  }
 
  });
});
 
// hover code for index  templates
$(document).ready(function() {
 
		$('#post-area .image').hover(
			function() {
				$(this).stop().fadeTo(300, 0.8);
			},
			function() {
				$(this).fadeTo(300, 1.0);
			}
		);	
 
 
});
 
// comment form values
$(document).ready(function(){
	$("#comment-form input").focus(function () {
		var origval = $(this).val();	
		$(this).val("");	
		//console.log(origval);
		$("#comment-form input").blur(function () {
			if($(this).val().length === 0 ) {
				$(this).val(origval);	
				origval = null;
			}else{
				origval = null;
			};	
		});
	});
});
 
// clear text area
$('textarea.comment-input').focus(function() {
   $(this).val('');
});
 
 
// mi llamada "a mano" a masonry
$(document).ready(function() {
	$('#masonry-wrapper').masonry({ 
	singleMode: true, 
  });
});

Now, two options:

1) If we want all kind of post archives (no matter which category) to be displayed with the grid layout: modify archive.php (/wp-content/themes/ryu-wpcom/archive.php)

2) If we want only some kind of post archives (specific category) to be displayed with the grid layout, and every other kind of post archive displayed with the theme native’s archive.php, then create a category-.php file…

(read this for further help)

I am using the second option. Archive from posts asigned to category ID=3 (named “producto“) will be displayed using masonry-grid-layout and every other archive will be displayed using theme’s native archive layout. So I create a new category-3.php file containing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
/**
 * The template for displaying Archive pages of posts asigned to category ID=3.
 *
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 * http://www.leccionespracticas.com/informatica-web/wordpress/wordpress-custom-archive-specific-category-solved/
 *
 * @package Ryu
 */
 
get_header(); ?>
 
	<section id="primary" class="content-area">
		<div id="content" class="site-content" role="main">
 
		<?php if ( have_posts() ) : ?>
 
			<header class="page-header"  style="display:none;>
				<div class="wrap">
					<h1 class="page-title"">
						<?php
							if ( is_category() ) :
								printf( __( 'Category Archives: %s', 'ryu' ), '<span>' . single_cat_title( '', false ) . '</span>' );
 
							elseif ( is_tag() ) :
								printf( __( 'Tag Archives: %s', 'ryu' ), '<span>' . single_tag_title( '', false ) . '</span>' );
 
							elseif ( is_author() ) :
								the_post();
								printf( __( 'Author Archives: %s', 'ryu' ), '<span class="vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '" title="' . esc_attr( get_the_author() ) . '" rel="me">' . get_the_author() . '</a></span>' );
								rewind_posts();
 
							elseif ( is_day() ) :
								printf( __( 'Daily Archives: %s', 'ryu' ), '<span>' . get_the_date() . '</span>' );
 
							elseif ( is_month() ) :
								printf( __( 'Monthly Archives: %s', 'ryu' ), '<span>' . get_the_date( 'F Y' ) . '</span>' );
 
							elseif ( is_year() ) :
								printf( __( 'Yearly Archives: %s', 'ryu' ), '<span>' . get_the_date( 'Y' ) . '</span>' );
 
							elseif ( is_tax( 'post_format', 'post-format-aside' ) ) :
								_e( 'Asides', 'ryu' );
 
							elseif ( is_tax( 'post_format', 'post-format-image' ) ) :
								_e( 'Images', 'ryu');
 
							elseif ( is_tax( 'post_format', 'post-format-video' ) ) :
								_e( 'Videos', 'ryu' );
 
							elseif ( is_tax( 'post_format', 'post-format-quote' ) ) :
								_e( 'Quotes', 'ryu' );
 
							elseif ( is_tax( 'post_format', 'post-format-link' ) ) :
								_e( 'Links', 'ryu' );
 
							else :
								_e( 'Archives', 'ryu' );
 
							endif;
						?>
					</h1>
					<?php
						// Show an optional term description.
						$term_description = term_description();
						if ( ! empty( $term_description ) ) :
							printf( '<div class="taxonomy-description">%s</div>', $term_description );
						endif;
					?>
				</div>
			</header><!-- .page-header -->
 
			<?php /* Start the Loop */ ?>
            <div id="masonry-wrapper">
			  <?php while ( have_posts() ) : the_post(); ?>
				<?php
					/* Include the Post-Format-specific template for the content.
					 * If you want to overload this in a child theme then include a file
					 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
					 */
					get_template_part( 'content', 'producto' );
				?>
			  <?php endwhile; ?>
            </div><!-- del masonry-wrapper -->
            <div class="clear"></div>
 
 
			<?php ryu_content_nav( 'nav-below' ); ?>
 
		<?php else : ?>
 
			<?php get_template_part( 'no-results', 'archive' ); ?>
 
		<?php endif; ?>
 
		</div><!-- #content -->
	</section><!-- #primary -->
 
<?php get_footer(); ?>

Pay attention to lines 73-84 and specially to line 81, in which we call get_template_part(). This call makes the need for creating a new content-producto.php file, containing:

<?php
/**
 * @package Ryu
 * this is content-producto.php
 */
?>
 
<div id="post-<?php the_ID(); ?>" class="boxy">
		 <?php if ( has_post_thumbnail() ) { ?>
         <div class="gridly-image"><a href="<?php the_permalink() ?>"><?php the_post_thumbnail( 'summary-image' );  ?></a></div>
 
		  <?php } ?>
       			<div class="gridly-copy"><h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
         <?php the_excerpt(); ?> 
 
         </div>
</div>

And then just edit the style.css file to add some CSS rules (in my case, 4 column masonry-grid):

/* el contenedor de masonry ocupará el 95% del área y dejará un margen del 2.5% */
#masonry-wrapper {
    margin-bottom: 2.5%;
    margin-left: 2.5%;
    margin-top: 2.5%;
    width: 95%;
}
 
/* en una "línea" del contenedor habrá 4 posts, cada uno ocupando el 24.8% y un margen por la derecha de 0.1% */
#masonry-wrapper .boxy{
	  width: 24.8%;
      margin-right: 0.1%;
      margin-bottom: 0.1%;
}

You can also download a full example of the theme (not depurated, just a project I am currently doing) here Ryu-theme-with-Grid-Layout