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

WordPress custom archive for specific category [SOLVED]

This days i’ve been designing a website in which there is a need for different archive views for each category of posts.

For this example, we will asume that we have three post categories defined:
1) uncategorized
2) blog
3) product

First thing is to find the category ID’s. You can do this by going to Posts > Categories and hovering your mouse over the ‘Edit’ link next to each category and pay attention to which URL it points to. In my example, for ‘product’ category I get this link:
http://www.mysite.com/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=3&post_type=post.

This means that product category has id number 3.

Knowing this, how do we make a wordpress archive for specific category of posts?

– Clone the (general purpose) archive.php in your theme folder. Name it category-.php, with being the category you want to customize it for. For instance, category-3.php
– Edit category-3.php and add the custom code.

You can read more about WordPress template hierarchy here.

WordPress and qTranslate: translate menu items

If you have installed qTranslate for the first time in your blog, and you already had a navigation menu with some items, what is the best way to translate those navigation items?

I have found that the easiest way to achieve this is by using some SQL (or phpMyAdmin) to directly modify the values in the database.

Follow this steps:

– open your phpMyAdmin to manage the DB
– go to table wp_posts and click on the Search link
– make a backup :), then
– filter by post_type=nav_menu_item
– look for the non translated records (field post_title)
– modify the field, ie: ‘My menu label in italian’ becomes ‘My menu label in italianMy menu label in english

An example:
qtranslate menu items translation