title: Node Update Problem on hook Cron

text:
# Question
Title: Node Update Problem on hook Cron
I am trying to update a node in a `hook_cron()` function. I am using Drupal 6.

Here is my code:

```
function offers_cron() {
  $query= db_query("SELECT * FROM {node} WHERE type = 'product'");
  while($allnodes = db_fetch_object($query)){
    $node_id=$allnodes->nid;
    $node=node_load($node_id);

    $node = new stdClass();
    $node->nid = $node_id;

    $node->type = 'product';
    $node->language = 'en';
    $node->uid=1;
    $node->status = 1;
    $node->created = time();
    $node->changed = $node->created;
    $node->comment=0;
    $node->promote = 0;
    $node->sticky = 0;
    $node->format = 2;
    $node->title='test';
    $node->field_price[0]['value']='120';

    if ($node = node_submit($node)) {
      node_save($node);
      drupal_set_message(t("Node ".$node->title." added correctly"));
    } else {
      drupal_set_message(t("Node ".$node->title." added incorrectly"), "error");
    }
  }
}

```

Now it shows it has updated all nodes. Here is screen shot for this :

Now when I click any node the update does not show.

Please take a look:

Does anybody have any ideas about this?

I have even tried clearing the cache.

Thanks

# Answer
> 0 votes
I got the solution: If the node doesn't change, don't create a new revision.

---
Tags: nodes, hooks, cron
---


# Question
Title: Payments and user balances/virtual coins
I would like to implement some premium options within my website. But most modules I have looked at, focus on providing payment-interactions (buying items, adding node etc.).

In contrast, I am looking for keeping a seperate account per user and their purchases. My expected workflow would be that the user establishes a certain balance eg. 100 USD and then uses this balance to purchase many small items/subscriptions/etc. The payments should be handled via automated payment gateways (Paypal or some credit card processor) or through manual payments added by admin.

Can you suggest any modules - ideally for D6, but feel free to post D7 solutions too - that would faciliate managing a user-based account in Drupal?

Btw, I am aware that the complete solution is not availible out of the box and that custom modules will be necessary. I am also open to suggestions relying on external services or alternative ideas like the userpoints module.

# Answer
Yes, Userpoints should work for this, with one major exception: It doesn't support decimal values. There are patches available for both D6 and D7 but you're pretty much on your own when using them.

There is integration with Ubercart available for D6 and Commerce for D7 (http://drupal.org/project/commerce\_userpoints) which allows you to buy points with money. There are also modules available in the Userpoints Contrib project for requiring points to create nodes, which you can combine with Userpoints Nodes and Comments to remove points when a node is created, resulting in the ability to sell creation of nodes. And, there is Userpoints Node access, http://drupal.org/project/Userpoints\_nodeaccess, which allows to buy access to nodes (only the D7 version works).

In general, the D6 versions of the modules aren't well maintained, especially the modules in Userpoints Contrib are very unstable (while those ported to D7 should work pretty fine).

Disclaimer: I am the Userpoints D7 maintainer and might be biased.
> 1 votes

---
Tags: users, 6, userpoints, payment-gateways
---


# Question
Title: Why do I get pathauto errors when using node_save?
When I'm programatically creating nodes using the code found here I keep getting the following errors:

> Warning: Illegal offset type in isset or empty in pathauto\_cleanstring() (line 180 of .../sites/all/modules/pathauto/pathauto.inc).
>
> Warning: Illegal offset type in pathauto\_cleanstring() (line 223 of .../sites/all/modules/pathauto/pathauto.inc).

I have tried providing a default $node-\>path value, not including a value, setting the value myself using pathauto\_cleanstring(), but nothing seems to work. I find it odd that I'm getting the error twice too :s

The solution to this question didn't help either unfortunately :(

Any help on this would be greatly appreciated!

## UPDATE:

So, the problem had to do with the data that I was using to create the path. I'm loading an XML file using simplexml\_load\_file. The value I was using for the node title was a SimpleXMLElement

```
SimpleXMLElement Object
(
    [0] => Node Title
)

```

Which needed to be cast as a string before saving it as the nodes title. Thank you all for your help!

# Answer
> 2 votes
Try this:

```
      $path = 'your value for the path';
  $node->path = array('alias' => $path);

```

---
Tags: 7, path-aliases, nodes
---


# Question
Title: How to change Date format without diving to core?
I want to convert dates to Jalali format. The problem is I have to change some of the core files in `/includes` and `/modules`. Is it possible to do this without jumping right into the core?

# Answer
> 1 votes
I think your best bet is Calendar\_Systems module that will not do the core changes but everything else needed on the frontend.

# Answer
> 0 votes
You could set the default timezone for your site at

/admin/config/regional/settings

This will change the output of all dates on your site. You shouldn't have to edit any core files to set your sites timezone.

---
Tags: 7, datetime
---


# Question
Title: block->subject set when using one theme, but not when using identical copy of the theme?
I have a theme (based on zen). I made a copy of the theme, replacing all the references to the theme's name in the files. I switched to the new theme and copied all theme settings in drupal (drupal 6).

As far as I can tell everything looks just the same, **except** that on some blocks (notably the footer menu) the name ("Footer Menu") appears. From the theme files i see this is because $block-\>subject suddenly is set.

What's up with this - if the themes are identical and the configuration is the same, why does one have a block-\>subject set and not the other?

# Answer
Looks to be a known issue. I see blocks display emptry string for $block-\>subject. in this thread someone mentions that they had to modify system.module for this to work. you can check it out in this thread here. Looks like a patch is out there for it.
> 1 votes

---
Tags: blocks, theming
---


# Question
Title: Dealing with absolute paths while on localhost
I have a long-term path problem while developing modules.

For instance I have the following project path http://localhost:8888/mylocalproject, which (on the production server) would be http://www.project.com.

Now each time I use global $base\_url or other absolute paths it only returns me the http://localhost:8888/ not http://localhost:8888/mylocalproject. For instance if I want to handcraft a logout link will give me http://localhost:8888/user/logout which is wrong, since mylocalproject is excluded.

I have all the time to hack solutions like this

```
global $base_url;
$needle = "localhost";
if (strpos($_SERVER['REQUEST_URI'], $needle)) {
  path = $base_url."/mylocalproject";
}
else {
  path = $base_url;
}

```

Is there a Drupal standard solution for that?

# Answer
> 5 votes
You should just set the `$base_url` in your settings file while you're working on localhost, then you can just change it when you put the site live.

The settings file is at "sites/default/settings.php" and you should add:

```
$base_url = 'http://localhost:8888/mylocalproject';

```

Obviously when the site goes live you want to change/remove that line to match your new environment.

# Answer
> 2 votes
You should really use url() and l() as much as humanly possible. If you look at the source, you will see the use of base\_path to tack on the proper prefix for where you have Drupal installed. This does assume you have `$basepath` set properly, which should include the sub-directory (as needed) and not just the hostname/portnumber. A bonus with this is that it takes aliases into account, do you don't need to do gloabl search/replace in code when you change the URL for something.

EDIT TO ADDRESS COMMENT:

```
$link = l("Add Content", "node/add", array("attributes" => array("class" => "shlinks")));
$shortcut_set['my_list'][] = array("#markup" => "<li>" . $link . "</li>");

```

---
Tags: 7, uri
---


# Question
Title: How to render a page with arrays and text
I'm writing a module, which gets called from a MENU\_LOCAL\_TASK hook.

```
function load_statistics(){
    $page = display_yes_no(10,40);
    return $page;
}

```

the $page is an array used for rendering with Charts API, the problem is that if I do

```
$page .= 'hello';

```

for example, it's displaying "Arrayhello" instead of the graph and hello. How can I render the page the in drupal, to display both text, both charts?

# Answer
You can do

```
$page['text'] = array('#markup' => 'hello');

```

Or

```
$page = render($page) . 'hello';

```
> 5 votes

---
Tags: 7
---


title: Drush returns error page

text:
# Question
Title: Drush returns error page
When I enter

```
drush -d -v status

```

I get

```
dev@drupal-staging:/var/www/$ drush -d -v satus
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.03 sec, 2.36 MB]                                       [bootstrap]
Initialized Drupal 6.22 root directory at /var/www/ [0.04 sec, 3 MB]                                           [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.05 sec, 3.06 MB]                                       [bootstrap]
Initialized Drupal site default at sites/default [0.09 sec, 3.5 MB]                                                 [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.11 sec, 3.84 MB]                              [bootstrap]
Undefined index:  SERVER_PROTOCOL bootstrap.inc:903 [0.17 sec, 6.69 MB]                                             [notice]
Cannot modify header information - headers already sent by (output started at /opt/drush/includes/drush.inc:820) [warning]
bootstrap.inc:903 [0.17 sec, 6.69 MB]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="misc/favicon.ico" type="image/x-icon" />
<title>Site off-line | DEV </title>
<link type="text/css" rel="stylesheet" media="all" href="modules/system/defaults.css?0" />
<link type="text/css" rel="stylesheet" media="all" href="modules/system/system.css?0" />
<link type="text/css" rel="stylesheet" media="all" href="modules/system/system-menus.css?0" />
<link type="text/css" rel="stylesheet" media="all" href="modules/system/maintenance.css?0" />
<link type="text/css" rel="stylesheet" media="all" href="themes/garland/style.css?0" />
<link type="text/css" rel="stylesheet" media="all" href="themes/garland/minnelli/minnelli.css?0" />
<link type="text/css" rel="stylesheet" media="print" href="themes/garland/print.css?0" />
<!--[if lt IE 7]>
<link type="text/css" rel="stylesheet" media="all" href="themes/garland/fix-ie.css />    <![endif]-->
</head>
<body>

<!-- Layout -->
<div id="header-region" class="clear-block"></div>

<div id="wrapper">
<div id="container" class="clear-block">

<div id="header">
<div id="logo-floater">
<h1><a href="" title="DEV "><img src="themes/garland/minnelli/logo.png" alt="DEV " id="logo" /><span>DEV </span></a></h1>        </div>

</div> <!-- /header -->

<div id="center"><div id="squeeze"><div class="right-corner"><div class="left-corner">
<h2>Site off-line</h2>                              <div class="clear-block">
<p>The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.</p><hr /><p><small>If you are the maintainer of this site, please check your database settings in the <code>settings.php</code> file and ensure that your hosting provider's database server is running. For more help, see the <a href="http://drupal.org/node/258">handbook</a>, or contact your hosting provider.</small></p><p><small>The <em>mysqli</em> error was: <em>Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)</em>.</small></p>          </div>
<div id="footer"></div>
</div></div></div></div> <!-- /.left-corner, /.right-corner, /#squeeze, /#center -->

</div> <!-- /container -->
</div>
<!-- /layout -->

</body>
</html>
Drush command could not be completed. [0.17 sec, 6.71 MB]                                                        [error]
dev@drupal-staging:/var/www/$

```

Since drush was working on this machine, I must have broken it somehow. Any ideas?

# Answer
> 0 votes
The problem is, that I'm working on a multi site installation with a non working default configuration. Setting the host parameter for drush solved the problem.

# Answer
> 5 votes
You are using php-cgi to run Drush. Use php-cli.

---
Tags: 6, drush
---


title: Solution for user account activation?

text:
# Question
Title: Solution for user account activation?
By some chance would a module exist for this registration / user activation workflow?

I'm looking for a module the following functionality:

1. Each user when registering has a dropdown to select their sales representative
2. The sales rep will then get an email regarding this user's registration
3. Since this sales rep knows that they're a user they'll approve this user quicker than a single administrator

Essentially, the user has the ability then to delegate who approves their account improving account approval efficiency (the goal).

Also, could this functionality be accomplished with rules somehow?

# Answer
> 1 votes
The solution for this is three modules.

http://drupal.org/project/token\_profile

and enabling the core module profile.

Add any custom fields for a sales rep. Then enable rules. Rules will take any tokenized field based on certain events.

---
Tags: 6, users
---


# Question
Title: Question about D7 Organic Groups, Memberships, and Views
I have been using OG and Views on Drupal 7. I think it's great but am having one problem. Here's the situation: I am creating views of content, and am wanting to show which group each piece of content is a "member" of. To do this, I bring in a "group membership" relationship and then another group relationship, which then lets me show the GID, title, etc., from the Organic Group.

But here's the problem: as soon as I introduce the "OG membership" relationship into the mix, it begins to show each piece of content twice (or 3 or 4 times) if that content is posted into 2, 3, or 4 groups. I think this is because in the og\_memberships table, each membership has its own ID.

What I'd like to do is show each piece of content once, but have a "multiple" type setting on the OG field area, the same way I can show multiple imagefields or Taxonomy terms that are all related to one node.

Anyone got experience with this?

# Answer
> 1 votes
That sounds more like an issue with the SQL query, called a Cartesian join. It's where you join every row of one table to every row in another table, or to itself, resulting in lots of duplicated rows. Dump the SQL that the View is creating and run it by itself in the database client to see if that's the source of the problem.

---
Tags: 7, views, organic-groups
---


# Question
Title: Is there any problem with downloading and overwriting modules?
Theoretically for the most part is it usually a non-issue to overwrite modules ?

Typically i would disable a module then upgrade a module. Is disabling a module superfluous?

Obviously, I'll take the steps to backup my database before doing so.

# Answer
You don't need to disable a module. That is often not even possible e.g. when there are many other modules relying on it and disabling them would break your site.

You might want to take your site to maintenance mode while running updates though, as your site might completely break between replacing the files and running update.php.

What however is recommended is to remove the old files first and then add the new directory. The reason for this is that you otherwise end up with stale files if files have been moved or deleted.

If you have shell access, I can strongly recommend using drush dl/up for this task as this will handle this for you automatically.
> 15 votes

---
Tags: 7
---


# Question
Title: Token are not working in my content type fields (they show as they are)
I need to have display on all pages a specific token. I have my own content types and I would like fill them with my tokens as well.
I noticed the tokens shows up as they are not as their values.

How can I make tokens display correctly?

# Answer
> 1 votes
You can try using the Token Filter module.

I'm not sure if it will do exactly what you want, but it is a way to have Tokens rendered in your node, if at least in the body text of the node.

---
Tags: tokens
---


# Question
Title: Generating links from words using an input filter
Does anyone know of a D6 module that can do this easily? Really I just want to find certain words in forum posts and link them to other nodes.

# Answer
> 0 votes
I think you can do this with Glossary.

---
Tags: 6, navigation
---


# Question
Title: Use mobile phone number as account ID so users dont have to register?
Im making a mobile first site. Is there a way of using a user's mobile phone number so they dont have to register for an account?

Or, if a user creates an account the normal way on a desktop and enters their phone number, is it possible to detect when the visit the site with a phone from that number and log them in?

Thanks

# Answer
You don't have access to the visitor's phone number when they visit your website from their phone. O2 recently got into a bit of trouble for sending the user's mobile number in the request headers.

According to the article:

> Rival 3G networks are not appending visitors' phone numbers to the HTTP headers.

So I'm afraid there's no way to do this automatically.

You might want to look into building an app for the various platforms if that's an option, I believe in that context you do have access to the user's phone number.
> 0 votes

# Answer
If I get you right you want detect that a user is recuring user? Generaly this can be done with a cookie.

Tecnicaly there is no reason to use a phone number. As far as I know there's no possibility for a web application to get the phonenumber automatically. A solution could be an app as frontend which delegates to the website.
> 1 votes

---
Tags: users, theming
---


title: Wysiwyg display

text:
# Question
Title: Wysiwyg display
Please, any one can help, Why the Wysiwyg editor is displaying for some templates and is hiding (disabling) for some others one. I tried to use it with Kanji 7.x-2.0 and Bartik 7.10 and seven 7.10, it works very well but with other template like business connection template n

# Answer
> 1 votes
This sounds like a bug/shortcomming of the theme. Think about posting an issue to its queue.

---
Tags: 7, theming, wysiwyg
---


title: Make a module out of the mobilize

text:
# Question
Title: Make a module out of the mobilize
I tried using mobilize and made my drupal site mobile ready very fast i.e. added the java script code directly in the theme `page.tpl.php` file. I wanted to make this a module and made a new module and added code like below and enabled the module, But mobile version of website doesn't work. Any thing wrong i ma doing? mobilize is the module name

```
<?php
function mobilize_init() {
 $path = drupal_get_path('module', 'mobilize');
 drupal_add_js($path . '/site.js', 'file');
drupal_add_js('http://cdn.mobilizejs.com/releases/0.1/js/mobilize.core.min.js','external');
}
?>

```

# Answer
Your hook seems to be named as if it was a mobilize one, where it should be named by your module's. something like "my\_module\_init".
> 1 votes

---
Tags: 7
---


# Question
Title: Replace tables with divs in pages generated by views
How can I replace the page layout generated by views with the grid format into something tableless? I need those columns displayed in css stylished divs.

# Answer
> 2 votes
The short answer is to edit the View and change the Style Settings from table to unformatted.

# Answer
> 0 votes
True, especially if you use Views 3, where a lot of options are available via the UI. Almost everything can be done there short of pure CSS stuff.

---
Tags: views, theming
---


# Question
Title: Manual ajax callback on saved dropdown value
Normally the `#ajax` property of a form item launches a ajax callback. So when you select an item of a drop-down menu it will be triggered.

In this case I use `variable_get()` to see if the drop-down menu value has already been saved on that admin page. If it is I use it as the default value. But in that case what does not happen is the ajax call that is associated with that value.

So this is what I would like to have:

```
if(isset(variable_get('dropdown_value'))) {
  // Manually call ajax callback function, just like the one in $form[item][#ajax][callback].
}

```

Does anybody know how to do this? I would prefer to use php instead of JavaScript.

# Answer
> 1 votes
If I understand correctly, anything that can query a URL would do, for example Curl.

# Answer
> 0 votes
I'm assuming that you want the behaviour caused by the AJAX callback to take effect on the form even if the AJAX request hasn't been made?

The best way to do this would be to move the logic out of the AJAX callback function and make all necessary form changes in the form function itself. Then in your AJAX callback you just need to return the element you're interested in. For example your code might look like this:

```
// Simple form presenting a dropdown which changes the value in a textfield.
function mymodule_dropdown_form($form, &$form_state) {
  // If the dropdown value is set in $form_state (which happens when the form
  // is re-built for an AJAX request), use that value.
  if (isset($form_state['values']['dropdown1'])) {
    $dropdown1_value = $form_state['values']['dropdown1'];
  }
  // Otherwise if the variable has already been set, use that value
  else if ($variable_value = variable_get('dropdown_value', FALSE)) {
    $dropdown1_value = $variable_value;
  }
  // Otherwise choose your default value
  else {
    $dropdown1_value = 1;
  }

  $form['dropdown1'] = array(
    '#type' => 'select',
    '#title' => 'Dropdown 1',
    '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5)),
    '#default_value' => $dropdown1_value,
    '#ajax' => array(
      'callback' => 'mymodule_dropdown_form_callback',
      'wrapper' => 'textfield-wrapper'
    )
  );

  // Now decide on the value for the textfield.
  if ($dropdown1_value == 1) {
    $textfield_value = 'Value 1';
  }
  else if ($dropdown1_value == 2) {
    $textfield_value = 'Value 2';
  }
  // etc...

  // Now we have a definitive value for the textfield regardless of context.
  $form['textbox'] = array(
    '#type' => 'textfield',
    '#title' => 'Text Field',
    '#default_value' => $textfield_value,
    '#prefix' => '<div id="textfield-wrapper">',
    '#suffix' => '</div>'
  );

  return $form;
}

function mymodule_dropdown_form_callback(&$form, &$form_state) {
  // The element is already build correctly at this point so just return it.
  return $form['textbox'];
}

```

That's a very rudimentary example and will need a bit of massaging before it does anything useful but it should give you a place to start.

---
Tags: ajax
---


# Question
Title: How to set up APC on Drupal 7 with httpd + fastcgi?
Can you recommend how to set up APC for a site running Drupal 7 on apache2 with fastcgi ?

I got to the point where apc.php shows only one file cached that is apc.php itself. I cannot see if APC cache is used at all when accessing Drupal nodes.

PHPinfo shows:

```
Server API  CGI/FastCGI

```

**apc**

```
APC Support enabled
Version 3.1.9
APC Debugging   Disabled
MMAP Support    Enabled
MMAP File Mask  /dev/zero
Locking type    pthread mutex Locks
Serialization Support   php

Directive   Local Value Master Value
apc.cache_by_default    On  On
apc.canonicalize    On  On
apc.coredump_unmap  Off Off
apc.enable_cli  On  On
apc.enabled On  On
apc.file_md5    Off Off
apc.file_update_protection  2   2
apc.filters no value    no value
apc.gc_ttl  3600    3600
apc.include_once_override   On  On
apc.lazy_classes    Off Off
apc.lazy_functions  Off Off
apc.max_file_size   1M  1M
apc.mmap_file_mask  /dev/zero   /dev/zero
apc.num_files_hint  1024    1024
apc.preload_path    no value    no value
apc.report_autofilter   Off Off
apc.rfc1867 On  On
apc.rfc1867_freq    0   0
apc.rfc1867_name    APC_UPLOAD_PROGRESS APC_UPLOAD_PROGRESS
apc.rfc1867_prefix  upload_ upload_
apc.rfc1867_ttl 3600    3600
apc.serializer  default default
apc.shm_segments    1   1
apc.shm_size    30M 30M
apc.slam_defense    On  On
apc.stat    On  On
apc.stat_ctime  Off Off
apc.ttl 7200    7200
apc.use_request_time    On  On
apc.user_entries_hint   4096    4096
apc.user_ttl    7200    7200
apc.write_lock  On  On

```

**cgi-fcgi**

```
Directive   Local Value Master Value
cgi.check_shebang_line  1   1
cgi.fix_pathinfo    1   1
cgi.force_redirect  1   1
cgi.nph 0   0
cgi.redirect_status_env  no value   no value
cgi.rfc2616_headers 0   0
fastcgi.logging 1   1

```

I would like to use boost + memcache + apc eventually but currently I have a problem enabling apc on httpd with fastcgi.

# Answer
> 2 votes
We finally managed to set this up properly.

Apc works fine for multiple processes with apache/2 + php 5.3.x + php-fpm + fcgi in FPM/FastCGI mode.

PHP 5.3.x is configured with following options --enable-force-cgi-redirect --enable-fastcgi --enable-fpm

# Answer
> 1 votes
I wrote a blog post about this a a few weeks ago, might be useful to some as it goes into a bit more detail. It uses shared memory for APC rather than anonymous mmapped memory (When apc.mmap\_file\_mask = /dev/zero). This *may* be better for performance but I was unable to find a conclusive answer.

Also I think that anonymously mmapped memory ***might*** not be shared amongst the FPM children, but it may have just been something else I did wrong / came across when doing this setup. Before I used shared memory, I would usually be served by the same PHP process when accessing the APC status page, but if I left it a while and tried again, the APC status page would show a different value for apc.mmap\_file\_mask, which would mean there was more than one APC cache being used overall since I had not restarted PHP-FPM in this time. Though again, I'm not certain about this.

Anyway, how I setup Apache MPM Worker, PHP-FPM, FastCGI and APC.

---
Tags: 7, caching, performance
---


title: Get all the fields attached to an term

text:
# Question
Title: Get all the fields attached to an term
How can I get a list of all the fields that have been attached to a taxonomy vocabulary?

I have created 2 new fields using admin/structure/taxonomy/\[machinename\]/fields now I need to get all the fields and use them on a settings form. I have the vocabulary machine name, but how do I retrieve all fields created?

# Answer
> 2 votes
You can use `field_info_instances()` which:

> Retrieves information about field instances.

In the case of taxonomy terms the code would look like this:

```
$instances = field_info_instances('taxonomy_term', $vocab_machine_name);

```

The `$instances` array will contain (amongst other things) the machine names of all the fields attached to the term, if you want further information about any or all of those fields you can run the names through `field_info_field()`.

I think the file that function lives in is included by default but if not just add this before you call it:

```
module_load_include('inc', 'field', 'field.info');

```

---
Tags: 7, entities
---


# Question
Title: Using existing term reference field vs. creating new ones
I have 3 content types (blogs, photos, videos) that all reference the same "topic" vocabulary.

When I add the term reference field to each content type I can either create a new field "field\_blog\_topic", "field\_photo\_topic" and "field\_video\_topic" for each of the types.

Or I could create a "field\_topic" field for blogs and then use that existing field for the photo and video content types.

Would it make any practical difference?

# Answer
> 5 votes
Yes it would make sense to have only one field that you attach to multiple content types.

If you're using a MySQL backend then a table is created for every field you create in the UI (it's probably similar for other storage backends). If you create a single field and attach it to several different entity/bundle types then only a single table is created with the values for all entities. Fewer tables is definitely more desirable.

Also if you wanted to query the database for all nodes that are within a certain vocabulary (using `EntityFieldQuery` or even Views) then the query generated would have two less `JOIN`s to make which is just much better for performance on the whole.

I think it was the intention of the developers that fields be used in this way, there's a complicated mechanism in place for managing different instances of fields and I don't think that logic would need to exist if they weren't supposed to be used like this.

# Answer
> 1 votes
I don't know if it's better or not, but I like to have 1 vocabulary per content type. That way, I can create 3 different term reference fields. I find it more logical, especially when it comes to creating taxonomy menus and using terms in views for each of my content types.

However, I don't know the effects on performance.

---
Tags: 7, taxonomy-terms
---


# Question
Title: Drupal 7: customise archive view to show only blogs from one user
How can I customise the archive view in views 3 so that each user blog page has an archive relating to that page. The default view is for the whole site.

# Answer
> 1 votes
Add a "User" relationship, then just add the corresponding contextual filter. If absolutely necessary, you can set the contextual filter to always use the default value, and set it to be a raw value from the url, and set the number to wherever the username is in the url path.

Example:
url = http://mysite.com/user/USERNAME/blog/archive
raw value from path number = 2 (/user/USERNAME -- it's the second part of the path)

---
Tags: 7, views, nodes
---


# Question
Title: How to print how many nodes of a specific type a user has created?
I'm making a block to be displayed on a node page that I want to display some information about the author of the node. I need to be able to show the number nodes of different types that the author has created. Any suggestions? I found this which gets me halfway there, but I need to be able to filter it by only the node authors content.

# Answer
> 2 votes
The simplest way would be to extend the query from the other question you linked to and add the user id as an extra parameter:

```
function yourtheme_get_node_count($content_type) {
  $query = "
    SELECT COUNT(*)
    FROM {node} n
    WHERE n.type = :type
    AND n.uid = :uid";

  // Get the node object for the current page.
  $node = menu_get_object();

  $params = array(':type' => $content_type, ':uid' => $node->uid);
  $amount = db_query($query, $params)->fetchField();

  return $amount;
}

```

Be sure to only call this on a node page as `menu_get_object()` will only return a node object when you're on such a page.

---
Tags: 7, nodes, blocks, database
---


# Question
Title: Run module after 'Order status gets updated' Action runs
I need to load the order object and run the init function when the order status is updated in Ubercart instead of using `hook_menu()`. How do I hook into the "Order status gets updated" action? The order state should be "Payment Received."

Does it have something to do with the following code:

```
function uc_order_rules_event_info() {
  $events['uc_order_status_update'] = array(
    'label' => t('Order status gets updated'),
    'group' => t('Order'),
    'variables' => array(
        'order' => array(
            'type' => 'uc_order',
            'label' => t('Original order'),
        ),
        'updated_order' => array(
            'type' => 'uc_order',
            'label' => t('Updated order'),
        ),
    ),
);

function hemo_menu() {
  $items['add_listing'] = array(
    'page callback' => 'init',
  );

  return $items;
}

function init() {
  foreach ($order->products as $product) {
    $array = data_array($product->data['attributes']);

    foreach ($array as $property => $value) {
      $product->$property = $value;
    }

    $product->primary_email = $order->primary_email;
    create_directory_listing($product);
  }
}

function data_array($arr) {
  $array = array();

  foreach ($arr as $key => $value) {
    foreach ($value as $key2 => $value2) {
      $chars = array(" ", ",", "'", "(", ")", "__");
      $key = str_replace($chars, "_", strtolower($key));
      $value2 = ucwords($value2);
      $array += array("$key" => $value2);
    }
  }
  return $array;
}

function create_directory_listing($product) {
  $node = new stdClass();
  $node->type = 'directory_listing';
  node_object_prepare($node);
  $node->language = LANGUAGE_NONE;
  $node->uid = $product->order_uid;
  $node->field_order_product_id[$node->language][0]['value'] = $product->order_product_id;
  $node->field_order_id[$node->language][0]['value'] = $product->order_id;

  if (isset($product->attendee_name)) {
    $node->title = $product->attendee_name;
  }
  if (isset($product->institution)) {
    $node->field_institution[$node->language][0]['value'] = $product->institution;
  }
  if (isset($product->lab_group)) {
    $node->field_lab_group[$node->language][0]['value'] = $product->lab_group;
  }
  if (isset($product->address)) {
    $node->field_address1[$node->language][0]['value'] = $product->address;
  }
  if (isset($product->address2)) {
    $node->field_address2[$node->language][0]['value'] = $product->address2;
  }
  if (isset($product->city)) {
    $node->city[$node->language][0]['value'] = $product->city;
  }
  if (isset($product->state_or_region)) {
    $node->field_zone[$node->language][0]['value'] = $product->state_or_region;
  }
  if (isset($product->country)) {
    $node->field_country[$node->language][0]['value'] = $product->country;
  }
  if (isset($product->phone)) {
    $node->field_phone[$node->language][0]['value'] = $product->phone;
  }
  if (isset($product->primary_email)) {
    $node->field_email[$node->language][0]['value'] = $product->primary_email;
  }
  if (isset($product->zip_or_postal_code)) {
    $node->field_postal[$node->language][0]['value'] = $product->zip_or_postal_code;
  }
}

```

# Answer
I believe you're looking for `hook_uc_order()` which runs for several operations, including the `update` operation which is:

> Called when an order's status is changed.

Assuming your module is called "hemo" you code might look something like this:

```
function hemo_uc_order($op, $order, $arg2) {
  if ($op == 'update') {
    if ($order->order_status == 'payment_received') {
      // Do something with the $order object.
    }
  }
}

```

Remember to clear Drupal's cache once you've implemented the new hook or it might not get registered.
> 2 votes

---
Tags: ubercart, actions
---


# Question
Title: Should I use Drupal or a Mediawiki to create a site like Wikihow?
I have some basic experience in using Drupal 7 and I am currently starting a new project where I want to create a wiki site with the same functionalities of Wikihow.com. I have done some research and most wiki sites seem to be built on a wiki open source software such as Mediawiki.

Because I have some experience in Drupal and really like it, I would like some advice on whether to build a Wiki in Drupal (perhaps using the Drupal Commons Distribution), or use a wiki platform instead?

# Answer
You have the source code for Drupal, as well as for Mediawiki (that's the nature of scripting languages such as PHP). This means, both platforms allow endless customization and you can implement your requirements using any of those systems. A decision between Drupal and Mediawiki is therefore not a technical decision, but a business decision: which platform will get the job done with lower costs?

If your are working on your own, you have to weigh "getting it done using something you know" against "risk using a new system but allowing you to become proficient in it". There are also other factors that come into play, like time constraints and the pricing scheme.

A correct answer to your question cannot favor one or the other platform. It can only give you suggestions on what factors to take into account so that you can decide for yourself. My list is not exhaustive.
> 3 votes

---
Tags: 7
---


# Question
Title: Disable page compression only on specific pages
I am running drupal 6 and have page compression enabled. When page compression is enabled, drupal caches all the pages. But I do not want certain pages to be cached. How do I force drupal not to cache certain pages?

# Answer
> 2 votes
You're probably looking for the CacheExclude module.

> \[…\] provides a simple way to exclude certain pages from being cached. Sometimes you want all pages to be cached for anonymous users except for one or two pages that have dynamic or random or rotating content. If those pages are cached, the dynamic parts cease to be dynamic. This module allows an administrator to selectively exclude certain paths from being cached so that dynamic content is actually dynamic.

---
Tags: 6, caching
---


title: How to build a menu hook module

text:
# Question
Title: How to build a menu hook module
I am trying to get into module building with Drupal 7.

Why is `$tryk = "test"` not being taken for the title, but literal strings such as "testmenu" are working?

```
$tryk = "test";
function menufun_menu() {
    global $tryk;
    $items['menufun'] = array(
        'title' => $tryk,
        'page callback' => 'menufun_greeting',
        'file' => 'menufun_greeting.inc',
        'page arguments' => array('Jane', 'Doe'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
);
return $items;
}

```

# Answer
If you want to use a variable for the page title, it is better to use a title callback.

```
function menufun_menu() {
    $items['menufun'] = array(
        'title callback' => 'menufun_title',
        'page callback' => 'menufun_greeting',
        'file' => 'menufun_greeting.inc',
        'page arguments' => array('Jane', 'Doe'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}
function menufun_title(){
    $tryk = 'test'; // dynamic title set here.
    return $tryk;
}

```
> 4 votes

---
Tags: hooks
---


# Question
Title: Profile Completion e-mail to user in Drupal
Hi in drupal(6) how to send reminder e-mail to the user whoever did not complete the profile information?

Is there any module available to do this? i think we can do using rules/trigger. but not exactly. I need similar to that what cron job do in php. Help me out.

# Answer
Use Rules, I actually have the below working for an Intranet site I manage.

**ON** \- Choose your event, maybe "User has logged in"
**IF** \- "Content Profile's field 'field\_NAME' has value"
**DO** \- "Send a mail to the user"

Replace the field\_NAME with the field you would like to check, In the IF I just check for a NULL value on a required field.

```
return array( 0 => array('value' => ''), );

```
> 1 votes

---
Tags: 6, users
---


# Question
Title: Use theme function to change the search form input type
I use the default search block provided by Drupal.
I want to change the type of this search text box from "text" to "search." How do I do this using a theme function?

# Answer
> 1 votes
There is no way to change the type of the search box form item with a theme function, but here's a theme friendly answer :-)

By default the *Search* input type isn't supported in Drupal 7, so you can't use any kind of `hook_form_alter` to change it out of the box. You can do the following though to give you the ability to do what you want though:

* Download and enable the Elements module from the awesome Dave Reid.
* Add the following to your template.php file (you can omit the size - I just put it there to make the box a bit shorter):

```
function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form'] = array(
      '#type' => 'searchfield',
      '#size' => '20'
    );
  }
}

```

This could also me done easily in a custom module, but I know you asked about theming specifically.

---
Tags: 7, search
---


title: Integrate Mathjax and generate PDF

text:
# Question
Title: Integrate Mathjax and generate PDF
Am working on the site with Mathematical content(Drupal 6.18). Have success fully integrated Mathjax for representing mathematical equations. But have an problem to generate PDF of same content.

The issue is that Mathjax Processes the Equations after page is loaded and am using the Print,pdf module. While PDF generation, content is pull from the database which is not mathjax Processed. Hence scrambled data!!!

Is there anyway I can preprocess the content so that the PDF is generated exactly as shown on the web.

I know there are tools to convert HTML to PDF like wkhtmltopdf but any help doing this with Drupal core will be greatly appreciated.

# Answer
After finding out all the possible options for implementing mathematical equations, and considering the requirement to create PDF, I got to the conclusion that the only way to do this is using a CKeditor plugin.

There is the fmath plugin, and I found a useful link: Configuration steps.

As JavaScript is loaded after page load, it was very difficult to generate PDF on the fly.
> 1 votes

---
Tags: 6, theming, files
---


# Question
Title: A disabled module has a schema version of -1, how can I enable the module and then run DB updates using hook_update_N?
The problem is, it seems when I enable a disabled module, the module's schema version in the system table is automatically updated to the latest version supplied by hook\_update\_N.

So my current module with the schema version -1 is modified to 7106 when I enable the module, and no hook\_update\_N functions are run.

So when I come to the next step of running database updates, no hook\_update\_N functions are run because the module thinks it's already the correct version.

The only method I can see is to manually set the module version in hook\_enable, however I'll then need to update the module code to remove the hook\_enable to make sure it doesn't run if the module is ever re-enabled in the future, so obviously this approach is a bit dirty.

I'm hoping there's a better solution?

# Answer
> 5 votes
Disabling a module should *not* set the schema\_version to -1. -1 means SCHEMA\_UNINSTALLED. As the constant says, it means this module has never been installed.

A module that has not been installed before is not supposed to run updates. `hook_schema()` is supposed to contain the current state of a module's schema. So this behavior is correct, and you should not mess around with the schema version manually.

If disabling (not uninstalling) a module really does set the schema\_version to -1, then that's where things go wrong. But Drupal core isn't doing this, see module\_disable().

Also, note that Drupal executes updates for all installed modules, no matter if they're enabled or not.

# Answer
> 0 votes
Uninstall the module (drush pm-uninstall) and then enable it again.

# Answer
> 0 votes
Ok looks like the only way I can think of would be to manually set the schema\_version to 0 for the disabled module, as this seems to prevent it from inheriting a more advanced version number.

Still feels a little dirty, but at least I can handle this with SQL used in a deployment script rather than rely on hooks that could run more than once.

---
Tags: 7, updating
---


# Question
Title: how do I programmatically save nodes with multiple photo uploads?
I have a very straight forward content type created in Drupal - Title, Body, Taxonomy term (drop down select, 1 value only), and Photos (multiple permitted, up to 8, alt and title tags are enabled). I also have the meta

I have a set of CSV files with data for those fields with corresponding photos. I need to iterate over these programatically and use node\_save() to get these in the database as well as upload the related photos.

I followed the direction here, and while it was a good start, I am still confused as to how to handle multiple uploads.

Bulk saving nodes with a file field

Can any suggest a tutorial or provide some sample code that can better illustrate how to do this?

EDIT: Based on the direction below, this is the code I have come up with

```
$images = array();
foreach ($file_data_array as $csv_data) {
    foreach($image_array as $file_data) {
  $file = new stdClass();
  $file->filename = basename($file_data['filepath']);
  $file->filepath = $file_data['filepath'];
  $file->filemime = $file_data['mime'];
  $file->filesize = filesize($file_data['filepath']);
  $file->uid = $uid;
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  $images[] = array(
    'fid' => $file->fid,
    'alt' => $file_data['alt'],
    'title' => $file_data['title']
  );
}
$node = new stdClass;
$node->type = 'baby_clothes';
$node->body = 'body';
$node->title = 'title';
$node->uid = 1;
$node->status = 1;
$node->active = 1;

//the name of my actual field is 'product images'
$node->field_product_images[LANGUAGE_NONE] = $images;

//this is my actual taxonomy field
$node->field_baby_clothes_category[LANGUAGE_NONE][0]['tid'] = 2; //actual ID of the taxonomy for this node

node_save($node);
}

```

Thoughts?

# Answer
You would normally just build up the files in a loop like so:

```
$images = array();

foreach ($file_data_array as $file_data) {
  $file = new stdClass();
  $file->filename = basename($file_data['filepath']);
  $file->filepath = $file_data['filepath'];
  $file->filemime = $file_data['mime'];
  $file->filesize = filesize($file_data['filepath']);

  $file->uid = $uid;
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);

  $images[] = array(
    'fid' => $file->fid,
    'alt' => $file_data['alt'],
    'title' => $file_data['title']
  );
}

$node = new stdClass;
// Build up the rest of the node as normal

$node->field_images[LANGUAGE_NONE] = $images;

node_save($node);

```

This assumes you have your CSV data loaded into an array called `$file_data_array`.

`fid`, `alt`, `title`, `height` and `width` are the only columns available to an image field type so there's no need to build up an array for each field entry containing all the file details (you can ignore that bit in the other answer you linked to as it's unnecessary).

Also note the use of `file_save()` instead of `drupal_write_record()` to commit the file to the database...it's much better to use `file_save()` as it fires the necessary system hooks to let other modules react to your files being added.

Hope that helps
> 4 votes

# Answer
You need to create a dummy node normally and then look at the saved $node array to get an example.

Try the below in a block while you view that page

```
<pre><?php print_r($node) ?></pre>

```

Once you can see the format of the data you can then write the code required to save the picture fields. They will probably be a multi dimensional array with things like the alt and title tags set etc...

Post up the $node array in your question for more advice
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Content pane of users related to node by field using panels, views (D7)
I've created a Content Type of Service Page which is the same as a Basic Page.

I added a new field to Users called service\_type and then added this field to Service Page. I set the service\_type in both Users and Service Pages appropriately. When a Service Page is displayed I would like a list of the Users with the same service\_type to appear below it.

I thought this would be a perfect place for Panels and Views so I made a Content Pane of Users:

Argument Input -\> From context -\> service\_type

Contextual Filter -\> Field: service\_type

I added this Content Pane to my Panels Node and set Field: service\_type to Node being viewed.

Doesn't work though; in fact, nothing appears. If I delete the Contextual Filter I do however get the full list of users, so clearly this is where the problem must be.

Can anyone point me in the right direction?

Views 7.x-3.1, Panels 7.x-3.0

# Answer
The problem was that in the display fields section for my Content Type I had service\_type hidden (because I only wanted to use it to filter Users without having to use a vocabulary), as such it wasn't featuring in the context and wasn't being passed into my View Content Pane.

I had to leave it displayed, then create a custom display for 'Full Content' and hide the field there instead.
> 0 votes

---
Tags: views, users, panels
---


# Question
Title: Node update date changes when saving without changing anything
Why does the timestamp of node\_revisions and changed of node tables are updated when I save a node without making any changes?

All I want to know if anything ever changed in a node (revision). Is there a way to find it?

# Answer
> 2 votes
If you save a node then it *has* changed according to Drupal...regardless of whether or not any specific property/CCK field values have actually been changed.

You can find the evidence for this in the `node_save()` function which contains this line of code which runs for every single call to the function:

```
// The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
$node->changed = $time;

```

Drupal does not do any sort of `diff` against the current and new revisions of a node when saving, so if you've pressed "Save" it makes the assumption that you wanted to add a new revision of the node.

# Answer
> 1 votes
Maybe the Diff module could be helpful for you. It shows the changes between revisions.

> This module adds a tab for sufficiently permissioned users. The tab shows all revisions like standard Drupal but it also allows pretty viewing of all added/changed/deleted words between revisions.

---
Tags: 6, users
---


# Question
Title: Write anything as an author name on an article
I need to make it so the author field when making an article doesn't reference actual users. Is this possible without clunky workarounds? The problem is I often have articles posted that aren't posted by an actual user, but their names still need to be credited.

How do I do this in Drupal 7?

# Answer
> 1 votes
1. Create a field that allows a user to enter text.
2. Implement a preprocess function that changes the values available to node templates (see the source code of template\_preprocess\_node() for a list of available variables).
3. In the preprocess function, change `$variables['submitted']` using the field you defined.

To use the already existing author widget, you would have to implement `hook_form_alter()` such that it removes the validation function from the form.

Now that the validation function is removed from the form, you also need a way to validate the node. For this, you can add your own validation function. This validation function would temporarily set the author field to a valid value and then call the original validation function.

You also need a new column to store the entered value in the database. The original column is not suitable, because it only holds integers. You also have to add an extra submit handler to the form, so that your data actually gets saved.

So yes, it is possible to use the author widget. But I advice against it. You will lose the information who really created the node. You have to manually deal with loading and saving the entry. And you are giving a well established widget a different meaning.

# Answer
> 0 votes
You can just type in a random name in the author field. If it happens to be a username, it will save as a reference, but otherwise it should just save plain text.

---
Tags: 7
---


# Question
Title: Subscribe/Unsubscribe link to a group's content type using Notifications & OG
We're using the Notifications module with Organic Groups (in Drupal 6). We have been writing our own UI module for Notifications so that it is simpler to use and more tailored for our client's needs. One of the remaining tasks is to include a link in the groups that a user can click on to subscribe/unsubscribe to a group's content type.

Does anyone know what structure the subscribe URL needs to be to allow this?

I know for a normal thread it is: `notifications/subscribe/[uid]/thread/nid/[nid]` and `notifications/unsubscribe/[sid]`.

# Answer
> 0 votes
OK, I eventually figured it out:-

```
notifications/subscribe/[uid]/grouptype/group,type/[gid],[type]

```

---
Tags: 6, organic-groups, notifications
---


title: Views page access callback

text:
# Question
Title: Views page access callback
How can I change the access callback for a page view (Views module)? I tried `hook_menu_alter` but realized that views uses the same hook to add the menu items defined by it - as a result of which, I am unable to have access to them.

Any way out?

# Answer
> 9 votes
Views allows you to set the acess within the UI, you can restrict based on roles or permission.

Usually that should be enought but if you need to set a custom access callback you can use hook\_menu\_alter but you will also need to make sure your module is called after the views hook\_menu\_alter, you can change the weight of your module in the database or you can use hook\_module\_implements\_alter to make sure your module is called after the views module for the menu alter hook.

# Answer
> 3 votes
Try the Views Access Callback module.

> Provides callback-based access control for Views.
>
> Available callback functions are defined by modules using `hook_views_access_callbacks()` function (in the same way as in `hook_perm()`), then could be set in the view's "Access restrictions" configuration.

# Answer
> 1 votes
I can't directly answer that question, but you do have two options.

You can make a custom block and embed the view in it, and then hook\_menu it into the system with access control.

The other option is to use a panel page, and add the view to a pane. You can then control access via the panels interface.

---
Tags: views
---


# Question
Title: Views module: How to limit access by user
I'm using the Views module to create a view that only specific users should be able to access. I know that Views includes access control by role or permissions, but I need something more fine-grained: Basically, I want to be able to say only user "x" and user "y" can access a particular view (or else someone with a site administrator role). So this would function very similar to how ACL module acts for individual nodes.

Is the best approach to create a custom views access plugin? I don't have much experience with this.

Also, I'm wondering about using an argument with some validation to accomplish this (so that I don't have to create dozens of separate views). For instance, since this view will be a tab on a specific node path, I'm wondering about setting up a user reference field on that node that specifies who could see the view. I'd just need a way for the view to only validate if the current user equals a user specified in the user reference field.

Any ideas? Or am I making this more complicated than it needs to be?

Thanks, Ben

# Answer
Instead of limiting permissions on the View, you could limit permissions on the menu item that leads to that view (be it a tab on a node or a menu callback). You could create your view with just a "Defaults" display and no Page display (so users can't just figure out the path to it). Then in your `page callback` for the menu item just call `views_embed_view` to display the view. It seems like handling permissions on a menu item might be easier than writing a new plug-in for Views (though a plug-in could be helpful for others).
> 5 votes

# Answer
Try the Views Access Callback module.

> Provides callback-based access control for Views.
>
> Available callback functions are defined by modules using `hook_views_access_callbacks()` function (in the same way as in `hook_perm()`), then could be set in the view's "Access restrictions" configuration.
> 6 votes

# Answer
I must be missing something, but it sounds like you would create a new role and add these Users. Then use the Views' Access: Role feature.

If you do need to tie the Access rights to something in content, I would use a custom Views access, which I found a pain setting up the first time, but appreciate the flexibility once working. If the View is generating the Menu Item, it will not appear if the View does not pass the access function.

If you are only hiding a menu item, it would seem to me that the view would still run and a User could tweak a URI to view the data.

Jerry
> 2 votes

# Answer
How about using the Custom Permissions module to create some new permissions specifically for your purpose, and then using the User Permissions module to assign those new permissions to individual users?

The custom permissions module is very lightweight. I'm not so sure about the User permissions module though, since it essentially creates a new role for each user behind the scenes (these roles are not visible on the main permissions page). If you have a lot of users, this may beef up the size of your roles and user\_roles tables a little.
> 1 votes

# Answer
Right, that makes more sense. I think you could (possibly, not 100% sure) use a View and an argument. Set the argument to be a user id taken from the currently logged in user and make the default argument display nothing. That should be able to do it, although I don't know how secure it would be to be fair. If you give it a try, post back and let me know your progress.
> 0 votes

# Answer
If you're wanting to combine different access plugins in Views, you may want to have a look at the Views access many module.
> 0 votes

---
Tags: views
---


# Question
Title: How do I access the database from a stand-alone PHP script?
I have problems to define the right path to the root and bootstrap data in php.

My structure (Windows) looks like the following.

* C:\xmapp\

+ htdocs\
        - testdrupal\
            * test.php
    + includes\
        - bootstrap.inc
    + sites\
        - default\
            * settings.php

The content of the test.php file is the following.

```
<?php

  chdir('C:\xampp\htdocs\testdrupal\');
  // Bootstrap Drupal up through the database phase.
  include_once('./includes/bootstrap.inc');
  drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
?>

```

When I run it, I get the following error.

> Parse error: syntax error, unexpected '/' in C:\xampp\htdocs\testdrupal\test.php

What am I doing wrong?

# Answer
As reported in the PHP documentation, "\[to\] specify a literal single quote, escape it with a backslash (\\)." In the string you wrote (`'C:\xampp\htdocs\testdrupal\'`) the single quote character is escaped, which means you are saying to PHP "this is not the string delimiter; it is part of the string."

The string that PHP sees is the following one.

```
'C:\xampp\htdocs\testdrupal\');
// Bootstrap Drupal up through the database phase.
include_once('

```

When it parses the rest of the code, it finds the `.` which is the string concatenation operator, and a slash, which doesn't have any meaning for PHP at that point, as it is expecting a literal string, a constant name, a variable name, or a function/method call.

The second error you get about an undefined constant (`DRUPAL_ROOT`) is because Drupal 7 uses that constant, but the code you are using to bootstrap Drupal doesn't define it. See the code in the index.php file to understand where to define that constant and which value to assign it.

```
/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

```

Drupal 7 doesn't rely on the current directory to find the directory where it has been installed, but it uses that constant every time it includes a PHP file. That is what `module_include_file()` does, for example.

```
function module_load_include($type, $module, $name = NULL) {
  if (!isset($name)) {
    $name = $module;
  }

  if (function_exists('drupal_get_path')) {
    $file = DRUPAL_ROOT . '/' . drupal_get_path('module', $module) . "/$name.$type";
    if (is_file($file)) {
      require_once $file;
      return $file;
    }
  }
  return FALSE;
}

```

Your code should be similar to the following one.

```
define('DRUPAL_ROOT', 'C:\xampp\htdocs\testdrupal');

// Bootstrap Drupal up through the database phase.
 require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

```
> 1 votes

# Answer
Check the first line (where you have `..testdrupal\'`);

The `\` before the `'` is escaping the `'` so it's as if it's not there (sorry, it's tricky to explain without my morning coffee).

With the character escaped, the line is being read as follows:

`chdir('C:\xampp\htdocs\testdrupal'./includes/bootstrap.inc');`

Which is where your error is most likely coming from.

Try changing the first line to the following:

```
chdir('C:\xampp\htdocs\testdrupal\\');

```

The extra `\` means that you are escaping the following character so the line will be read the way you want it to be.

There's a quick explanation of escape characters here.
> 2 votes

---
Tags: external-scripts
---


title: Views without paths

text:
# Question
Title: Views without paths
I have a panel with a main content area and a sidebar, path is "news".

Now, I want to create a view to be shown in the main content area, that lists a certain content-type. That's easy enough, but how do you make it so that view doesn't get its own path? I only want the view to be accessible through that panel page.

I am using Drupal 7.

# Answer
> 1 votes
Just create a block, as opposed to a page, and display the block in the panel.

---
Tags: views, panels
---


title: sending query results via email

text:
# Question
Title: sending query results via email
if this is my function:

```
<?php
//dsm($query);

function customstatsB_menu() {
  $items['customstatsB'] = array(
    'title' => 'Maestros Inactivos + email',
    'page callback' => 'customstatsB_all',
    'access arguments' => array('access customstatsB content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}
/**
* Valid permissions for this module
* @return array An array of valid permissions for the customstats module
 * No repetir permisos, este es únicamente un modulo, y cada query NO necesita permisos. PERMISOS A NIVEL MODULE x ROL.
 */

function customstatsB_perm() {
  return array('access customstatsB content');
} // function customstats_perm()

//return array('access customstats content', 'administer customstats');

function customstatsB_all() {

/**
 * MAESTROS INACTIVOS
 */

$query = "
SELECT name, status, rid, mail
FROM users
JOIN users_roles ON users.uid = users_roles.uid
WHERE mail NOT LIKE '%@hotmail.com'
AND users_roles.rid =6
AND users.status =0
";

  // get the links (no range limit here)
  $queryResult =  db_query($query);
  while ($links = db_fetch_object($queryResult)) {
    //$page_content .= l($links->name, 'node/'.$links->mail) . '<br />';
    $page_content .=
    l($links->name, 'mailto:'.$links->mail) . '<br />';
  }

  // check to see if there was any content before
  // returning the page
  if ($page_content == '') {
    // let the user know there is no content to show
    $page_content = "No existe información para mostrar.";
  }

  return $page_content;
}

return array('access customstatsB content', 'administer customstatsB');

/**
 * Email configs
 */

function customstatsB_mail($key, &$message, $params)
  {
     $params = array(
        'subject' => t('SQL Results Tester'),
        'body' => t("Body of the email goes here"),
      );

      drupal_mail("customstatsB", "customstatsB_normal_mail", "my@mail.net", language_default(), $params, "admin@mysite.com");
      drupal_mail("customstatsB", "customstatsB_html_mail", "my@mail.net", language_default(), $params, "admin@mysite.com");
  }
      $language = $message['language'];
      switch ($key)
      {
           case 'customstats_normal_mail':
              $message['subject'] = t($params['subject'], $var, $language->language);
              $message['body'][] = $params['body'];
              break;
          case 'customstats_html_mail':

              $message['subject'] = t($params['subject'], $var, $language->language);

               $body = "<html><body>
                  <h2>HTML Email Sample with Drupal</h2>
                  <hr /><br /><br />
                  {$params['body']}
                  </body></html>";
              $message['body'][] = $body;
              $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
              break;
      }
  }

```

and I am using hook\_mail and drupal\_mail to send an email, how should I insert the query results into the body of the mail?

Also, I have created pagecallbacks customstats1 to customstats15 via hook\_menu and I need to send indivual mails when users visit each page independently. I have read a few tutorials but I haven't been able to do this.

Thanks in advance for your help.

# Answer
> 1 votes
You need to invoke hook\_mail() to specify a 'body' parameter. It is a little confusing since it is two steps but well documented: http://api.drupal.org/api/drupal/includes%21mail.inc/function/drupal\_mail/6

See 'example\_notify()' and 'example\_mail()' from the above link.

In your case yo need to call drupal\_mail outside of your invocation of hook\_mail. See below for an example. You can pass the body as in the $param when you call drupal\_mail or you can edit it when you invoke hook\_mail.

Be advised that this is not the best example since it would fire off an email any time somone visited that page, but I'm not sure where you are trying to call drupal\_mail from:

```
$query = "
SELECT uid
FROM users
JOIN users_roles ON users.uid = users_roles.uid
WHERE mail NOT LIKE '%@mail.com'
AND users_roles.rid =6
AND users.status =0
";

 // get the links (no range limit here)
  $queryResult =  db_query($query);
  while ($links = db_fetch_object($queryResult)) {
    $account = user_load($links->uid);
    $body = t('Message for %name', array('%name' => $links->name));
    $subject = t('New email!');
    $params = array('body' => $body, 'subject' => $subject);
    drupal_mail('customstats', 'html_mail', $account->mail, user_preferred_language($account), $params);
    $page_content .= l($account->name, 'mailto:'.$account->mail) . '<br />';
   }

  if ($page_content == '') {
    $page_content = "No existe información para mostrar.";
  }

  return $page_content;
}

```

---
Tags: 6, database, emails
---


# Question
Title: Merge multiple block views to a single jump menu
I want to implement a jump menu with a list of three different vocabulary terms grouped by each vocabulary name. If I make only a single view all the terms are shown correctly but I would like to be grouped by their vocabulary names. I thought that I could have this result if I could merge three different views with a view for each vocabulary.

Is this possible?

# Answer
Well... It was very simple. I just used a single block view with all the vocabularies and I just used "Group by" the field vocabulary name. This outputs the option values within optgroups for each vocabulary.
> 0 votes

---
Tags: views, taxonomy-terms
---


# Question
Title: how can I have a body with more than 64 Kb of data in it?
I've noticed that when I create a node with too much data in the body field subsequent edits will not save. Or rather, the save goes ahead and I am taken back to viewing the node, but the content hasn't changed.

After extensive trial and error I was able to determine that any save which had a body length of less than 64 Kb saved fine but anything more than that would not save.

What is the cause of this and is there any way to get around it?

# Answer
The reason of the problem is a regular expression that causes PCRE to reach the limit set for pcre.backtrack\_limit or pcre.recursion\_limit.
There was an issue report on drupal.org about truncated body content; the length of the text that is possible to enter before it gets truncated depends from the characters used (English text can be longer than a text containing all Unicode characters), and from the values set for pcre.backtrack\_limit and pcre.recursion\_limit.

The issue report I am speaking of is Document possible preg memory issues. Gerhard Killesreiter's comment is the following one:

> This issue \[the body content being truncated\] is due to the limits of the perl regular expressions that we use to validate that you posted valid UTF8.
>
> If you increase the limits in your settings.php file you will see the text.

```
ini_set('pcre.backtrack_limit', 200000);
ini_set('pcre.recursion_limit', 200000);

```

> You will need to experiment which values work for you.

node\_schema() defines the body field of the node\_revisions table as "big text". This means that with MySQL the maximum length of a node body is 4 GB, and with PostgreSQL there isn't (theoretically) any limit; in both the cases, the limit is not the 64KB you are observing.

The default.settings.php file contains the following comment:

```
/**
 * If you encounter a situation where users post a large amount of text, and
 * the result is stripped out upon viewing but can still be edited, Drupal's
 * output filter may not have sufficient memory to process it.  If you
 * experience this issue, you may wish to uncomment the following two lines
 * and increase the limits of these variables.  For more information, see
 * http://php.net/manual/en/pcre.configuration.php.
 */
# ini_set('pcre.backtrack_limit', 200000);
# ini_set('pcre.recursion_limit', 200000);

```
> 8 votes

# Answer
For sites with Suhosin enabled, this is likely to be the default limit on POST value lenght.

`suhosin.post.max_value_length=65000` is Suhosin's default (and may not be in `/etc/php5/conf.d/suhosin.ini` until you add it).

This setting will be visible in the output of `phpinfo()`.
> 2 votes

# Answer
Some distributions include patches that enforce additional limits on incoming requests in the name of security. I've had problems with webform submissions that contain "too many" parameters which was resolved by increasing the limit enforced by the security patch that Debian includes in PHP.

You might want to look in your PHP and/or HTTP server error logs and see if you can find any mention of requests that are too long, etc.
> 0 votes

---
Tags: 7, nodes
---


# Question
Title: Showing a message (perhaps using a redirect) after a Fileds form is submitted in Drupal 7
I am using Drupal 7 + Rules. I have this form (creates a new node of some content type , dunno the correct jargon here) that users can fill to apply for a job. I want to show them a static message after the form submission. Apparently Rules is the way to go. How to do I achieve this ?

# Answer
> 0 votes
You can setup Rules to display a message when ever a node of the specific type is created. There is an interface for creating Rules you want

Event: Creating a new node
Condition: The node is of the chosen type
Action: Display a message

Alternatively you can use code with `hook_form_alter`, and add a submit handler to the node submit of the specific type, where you use `drupal_set_message` to display the message. This can be done faster (if you know how to create modules for drupal, and it requires less resources (is faster in execution) than the Rules solution.

---
Tags: entities, rules
---


# Question
Title: How do you migrate a site with Drupal 7 Image Styles and make sure the adjusted images migrate?
I am moving a D7 site from local to staging for the first time. I pushed my codebase through deployment, and I did `drush sql-dump` to get the database moved over. Then I copied the `files` directory as-is.

The new server site works perfectly -- except that images that are supposed to be generated by the image styles show up as broken. They're not being dynamically generated like they should, even though the styles themselves are there.

Any thoughts on why this would happen or how to debug it?

# Answer
Turns out I was trying to run deployment with my files directory outside of the Drupal root, and even though I was relatively pointing to the right path, it just didn't like that. So I symlinked sites/default/files to the folder outside of the Drupal root and it works fine now.
> 1 votes

# Answer
In general using the Features module is the best way to push configuration changes like "Image Styles" from dev to production: http://drupal.org/project/features . Yours is a different use case since you are pushing the entire database.

There is no "good" reason why the Image Styles shouldn't work on your new server. I would check to make sure that the file permissions on your production server are setup correctly. See: http://drupal.org/node/244924

Even if "sites/default/files" is given the proper permissions "sites/default/files/styles" might not have the proper permissions. You can check that the Image Style settings for your server are working correctly by visiting "/admin/config/media/image-styles/edit/thumbnail". If a style is not being generated there is an issue with your server setup.

Are you using 'GD2' or 'ImageMagic' and what version of PHP are you using to resize your images? These are PHP libraries that Drupal needs (1 of them has to be installed) to resize images. If you visit 'admin/reports/status' you should be able to see if one or both are installed correctly.
> 0 votes

---
Tags: media
---


# Question
Title: Two Drush bam-backup errors: Command not Found & Could not find a Drupal setting.php file at
I am trying to use Drush to backup a standard 7.12 local installation, but I am getting two error messages when running `drush bam-backup`:

```
The drush command 'bam-backup' could not be found.
Run `drush cache-clear drush` to clear the commandfile cache
if you have installed new extensions.

Could not find a Drupal settings.php file at ./sites/default/settings.php.

```

The bam module is enabled in my system.

Regarding the second issue, I have checked in the corresponding directory and it contains a `default.settings.php` file, but no `settings.php` file.

Is this a configuration issue, or a more fundamental bug? How can use Drush to backup my installation? Thanks.

**P.S.:**

I am on Windows 7 and I have used the Windows installer available here to install Drush. The bam version is 7.x-2.2 and Drush version is 5.0-dev.

# Answer
> 5 votes
Where is the settings.php file for your Drupal installation?

The problem Drush is having is that it cannot figure out where your settings.php file is. By default, Drush only looks in sites/default. There are a few ways that you can select the site you want if it is not in sites/default. One is to cd to the directory that contains the settings.php file, then run your command.

```
cd /path/to/drupal/sites/mysite
drush status

```

The other way is to specify the site you mean via the --uri parameter:

```
drush --root=/path/to/drupal --uri=mysite.com status

```

Once the status command works per the above advice, try calling bam-backup again.

---
Tags: 7, drush, backups
---


# Question
Title: When to add an extra "helper" table rather than running complex query
I'm trying to build a "notification" feature into my site similar to Facebook:

I would show a little graphic with a number indicating the number of new comments to nodes a user created or commented on.

The query will probably look like this, assuming uid=1 (haven't tested yet):

```
SELECT count(node.nid) as new_comments
FROM {node} node
INNER JOIN {node_comment_statistics} ncs ON node.nid = ncs.nid
INNER JOIN {history} h ON h.nid = node.nid
WHERE ( (h.uid = 1) AND (h.timestamp < ncs.last_comment_timestamp)
AND ((node.uid = 1) OR (0 < (SELECT COUNT(*) FROM comment c WHERE c.uid = 1 AND c.nid = node.nid)) )))

```

This query would run with every page request for all logged in users which could impact performance. I could create a "helper" table where I keep a "new\_comments" counter for each uid. For every comment added or updated I would then check which users need their "new\_comments" counter incremented.

**My question:**

Is there a rule of thumb when to use such a "helper" table instead of running complex queries. Or do I need to create say a million records in Devel and test the performance of above query under full load?

# Answer
> 3 votes
As long as all your fields used in JOIN and WHERE are indexed properly, you don't really need a separate table to do this, I probably would rewrite it in a single query, sub queries tend to be slow.

If you want something intermediate (in case you have \> 1.000.000 rows), you have 2 options:

1. Create a temporary table and keep it up to date using cron and/or hooks
2. Use caching in Drupal to remember the result and combine it with hooks

Both solution have pro's and con's:

1. Can be updated by cron, but has a record for every user, no matter if that user visits the site or not.
2. Needs to run the query when there's no cached data, but will be faster on a second page visit.

# Answer
> 1 votes
If you want to do anything complex, that doesn't change often, or you know / can act on when it does change, you should use the "helper" table called cache - or just create your own cache\_module\_name table.

A single query like what you have posted above, is probably not going to be a big deal. But if you plan on have a lot of these kind of statistics, they quickly add up, instead you can cache the rendered output and improve performance a lot.

---
Tags: 7, database
---


# Question
Title: what are the implications of installing APC on a VPS running multiple Drupal sites?
I have a single VPS running a number of independent Drupal sites. What considerations do I need to make (if any) when installing APC?

# Answer
One thing to keep in mind is that APC will require quite a bit of memory if you have multiple sites because each file will be kept in memory, even if it is in fact exactly the same file, just with a different path.

So you need to watch and tune the amount of memory that apc uses/can use. By default, it's 32MB, that's often too less for even a single Drupal site if you have many contrib modules. The problem is that if APC has not enough memory, it will always have to delete files from the cache. If it has *much* to less (e.g. not even enough for all files in a single page request), it will make your site slower than if you hadn't used APC at all.

VPS often don't have a lot of memory, make sure that you have enough for your sites. You could consider merging them into multi-sites to save memory.
> 2 votes

# Answer
The implications are a much faster website! Check out this article, and others, by 2bits.com

http://2bits.com/articles/benchmarking-apc-vs-eaccelerator-using-drupal.html

Here is another that talks specifically about tuning APC for drupal sites

http://2bits.com/articles/high-php-execution-times-drupal-and-tuning-apc-includeonce-performance.html

My company runs several sites on a single VPS with APC configured as suggested in the above articles. That, with memcache, significanly speeds up our sites.

We have not witnessed any server issues or conflicts or had any security concerns, if that's more what you are asking.
> 1 votes

# Answer
APC as a general opcode cache is entirely safe, and will greatly help the performance of your sites. However, there is one potential problem. You can't use Drupal modules like http://drupal.org/project/apc in most shared server APC environments as it's a big security risk. The APC cache is generally shared between all sites running on the server without a lot of thought going into separating them. If you are not a sysadmin, I would steer well clear of these modules.

That said, just installing APC for the opcode cache will generally increase the performance of your sites by quite a bit, so it's definitely worth using. Just be aware of some of the issues with the other functionality provided by APC.
> 1 votes

---
Tags: 7, caching
---


# Question
Title: What is the most sustainable way to obtain aggregate information on fields?
EntityFieldQuery is not intended to be used to run aggregate functions (SUM, AVG, etc.) on field data because it is SQL-agnostic. That said, such operations legitimately need to be run from time to time. According to SQL function with EntityFieldQuery and especially EntityFieldQuery and how to use aggregate functions SUM, ARG and MAX, SQL queries need to be used, and that approach fits my use case the best. I was speaking with @chx yesterday and he recommended using a couple of internal functions to find the field name and column name. I'm just wondering if this is sustainable and if it's appropriate to do in a codebase that I might release to otehrs.

If it's the best way, then it's the best way. I just don't want to do it before I'm absolutely sure because it feels messy.

# Answer
The View field module allows you to expose field tables as base tables to views. This differs from Views default behavior in that the base table is the field table and not an entity to which the field data is then loaded from. For example when selecting node as a base table you can then add fields, but the primary (base table) in the query is still node which depending on your data can screw up the aggregate functions (aka a many-to-one relationship of some fields to the node).

Views field allows you direct access to the field tables which means aggregate functions work properly. Additionally if you need to do "interesting" joins to other field tables you can control them completely using the following.

```
/**
 * Implements hook_views_data_alter().
 */
function mymodule_views_data_alter(&$data) {
  views_field_add_multi_join($data, /* see docs */);
}

```

Which is fairly simple to use and allows you to then perform aggregate functions across multiple field tables at once. You can then manually invoke a view `$view->execute()` and pull the results off the view. There are examples of this in the views documentation.

The benefits of this approach over EntityFieldQuery is that you can manage the process in Views (which almost everyone will already be using) and allow it to perform the physical query building in less direct way which helps elevate possible breakage down the road. In addition many times you will want to display such aggregate data on an admin screen which you can then use the view to provide both a display and access the results in code for additional purposes.
> 2 votes

# Answer
Could this be done in an add-on module to views? It handles queries very well and some results are published with aggregate functions such as in actions when contextual filters fail where it can default to all values and give counts on the available results in each. The functions for the queries should be there but a UI form would be needed for it. Let me know if this makes sense. I am just beginning to dissect views and am speculating.
> 0 votes

---
Tags: 7, entities, database
---


# Question
Title: Setting up drush ini path in my site alias
Unfortunately, i use shared hosting for my dev site to show to clients.

I'd like to specify an ini path in my `example.aliases.drush.php` file.

I couldn't find that particular custom variable in the example file.

Is it possible to set the drush.ini path so i don't get these nagging open basedir errors?

```
<?php
        $aliases['dev'] = array(
        'remote-host' => 'foohost',
        'root' => '/home/xxxxxx/users/.home/domains/xxxxxx/html',
        'php' => '/usr/bin/php',
        'path-aliases' => array(
         '%drush' => '$HOME/bin/drush/',
         '%drush-ini'=>'/home/xxxxxx/etc/drush.ini',
         '%drush-script' => '$HOME/bin/drush/drush/drush.php',
         '%dump' => ' ../db/dev.xxx.sql',
        '%files' => 'sites/all/files',
        ),
    );

```

# Answer
Drush processes drush.ini in the drush bash script prior to calling drush.php. Here is the relevant code it uses:

```
for conf_dir in $(dirname "$SELF_PATH") /etc/drush $HOME/.drush ; do
  if [ -f $conf_dir/php.ini ] ; then
    drush_php_ini=$conf_dir/php.ini
  fi
  if [ -f $conf_dir/drush.ini ] ; then
    drush_php_override=$conf_dir/drush.ini
  fi
done

```

You will need to make sure that your drush.ini file is in one of those location in order for it to be found and processed. Note that the drush bash script never acts on command line parameters; those are parsed in php. There are some environment variables that affect the drush bash script, but there are no environment variables that affect the selection of drush.ini, and there is no facility in site aliases to pass environment variable values to drush on the remote machine.

Sorry.

**Edit:** You could try setting %drush-script in your alias file to point to a script on the remote machine that called `php /path/to/drush/drush.php`. Read the advice in the README.txt for Drush-4 on how to make an alias to drush.php if you do this; you will want to make sure that --php is passed to Drush correctly, etc.
> 4 votes

---
Tags: drush
---


title: Module File Upload

text:
# Question
Title: Module File Upload
I am working on a module and I am trying to add an upload box for an MP3 file. I cannot seem to get it working no matter what I try to do. I have looked at file\_save\_upload and I am not having any luck. Below is my form code. Could someone point me in the right direction for the file upload process?

```
$form['background_audio_file'] = array(
  '#type'=> 'file',
  '#title' => t('Upload File'),
  '#description' => t('Please select your file to be uploaded'),
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Save Changes'),
);

```

The form is working great I just cant seem to find a good example and makes sense for uploading a simple mp3 file. This is D7 btw.

Thanks in advance.

Justin

# Answer
Rather than worry about moving/saving the file yourself you could use the `managed_file` element type and let Drupal do it for you:

```
function mymodule_some_form($form, &$form_state) {
  $form['background_audio_file'] = array(
    '#type' => 'managed_file',
    '#title' => t('Upload File'),
    '#description' => t('Please select your file to be uploaded'),
    '#upload_location' => 'public://audio-files'
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save Changes'),
  );

  return $form;
}

function mymodule_some_form_submit($form, &$form_state) {
  // The file is automatically uploaded and saved in the default
  // validation process so you just need to load the file object at this point,
  // mark that you want to keep it, and save it again.
  // The file ID is contained in the $form_state['values'] array
  $file = file_load($form_state['values']['background_audio_file']);
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
}

```

Uploading files using this method has the added benefit of a reference to them being added to the `file_managed` table so they can be managed with the system at a later date if needs be.

Hope that helps.
> 3 votes

---
Tags: 7
---


# Question
Title: Does request_uri() have to be filtered or escaped?
Mind my ignorance, but I'm trying to understand whether or not calling request\_uri(), and then echoing output from it into a link is safe.

What I'm doing is getting arguments from the URL, for example:

```
$exploded_url = explode('/', request_uri());
echo $exploded_url[3];

```

My questions: is this function's output being escaped/filtered already? Would it be overkill for me to do it again? What would be the way to ensure that it is safe? Is there another/better function I should or could use?

Thanks, any input is appreciated!

# Answer
> 2 votes
The short answer is yes, you need to sanitise the variable yourself.

All `request_uri()` does is pass the raw input from `$_SERVER['REQUEST_URI']` (or from a different source if the server is not Apache). Apache/PHP does nothing by default to sanitise the `$_SERVER` variables on your behalf so they should be considered unsafe.

There's an excellent answer to Which $\_SERVER variables are safe on StackOverflow that goes into a lot more detail, and actually notes that `REQUEST_URI` "may contain tainted data".

---
Tags: 7, navigation
---


# Question
Title: Are there any issues with installing memcache on a VPS running multiple Drupal sites?
I have a VPS running a few independent Drupal sites (not multi-site). What considerations do I need to make (if any) when installing memcache?

# Answer
> 2 votes
Make sure your settings.php file has a unique prefix for each site that has memcache enabled. I got tripped up by this, and everything went berserk. This thread fixed it for me. Basically, this is the only issue you would have as far as conflicts.

http://drupal.org/node/1416102

Like APC, memcache works indepedently of your sites. Make sure you have enough memory for it to function correctly. You can get a rough idea idea by seeing how much disk space all of your drupal databases take up. Not all tables in each database will be cached of course, but so long as you have that much memory to dedicate to memcache, you are good to go.

Said differently, as an example I have 12 sites on my VPS 4 gigs of RAM total with 1 Gig dedicated to memcache. I have never had a problem. Total size of databases on disk is around 400 mb.

# Answer
> 0 votes
Then important thing is that you give each site a different prefix, see http://drupal.org/node/1131468.

Of course, it's the same about memory as with APC. Depending on how much memory you have, you might want to use memcache only for sites which have a high(er) load than others and keep cache of the less used ones in the database or use another cache backend that doesn't sit in memory.

---
Tags: 7, caching
---


# Question
Title: How do I export/import all the relations created by Relation module?
There are standard procedures to export/import relation types, but not for the relations themselves. At least, I couldn't find any. Am I missing something obvious?

# Answer
> 3 votes
Export/Import of entities is something that is not standardized and there are many methods of approaching the problem. This is also something Drupal 8 is attempting to solve.

Currently you want to look at Deploy and UUID Features are your best bet. Neither have stable D7 releases, but I played around with deploy and using the views plugin I was able to export entities.

The primary issues with content (entities vs configuration) is that content many times needs to be merged from one server to another so it ends up being a fairly complicated proposition.

---
Tags: 7, importing-exporting, entities
---


title: Patch tests in issue queues?

text:
# Question
Title: Patch tests in issue queues?
How does one get a patch tested in core and attached to an issue queue (with the pretty red or green styling)?

Is it automatically done when you attach a patch? Or do you have to have an account to the qa.drupal.org server?

# Answer
> 5 votes
Patches uploaded on issues are automatically tested if they meet the right conditions which include:

* not excluded based on name (described in description on upload field)
* project has testing active
* patch is again d6-8 banch

For core, testing is enabled; if you upload a patch against Drupal 7, for example, it will automatically be tested. For other projects, it can be enabled if you are a maintainer by looking at the *Issue* settings tab; there is a checkbox to enable testing.

For more information, see Automated testing.

---
Tags: community-official-site
---


# Question
Title: Drupal logo is displayed with out the dimensions like width and height
My client raised an issue that when viewing the source the logo of my website does not have any attributes, but I saw many themes, and not all have those attributes.

How do I add these to the logo? Is it really required?

# Answer
The width and height is not required when using the `img` tag, but you can add it by overriding the theme template for the page, aka page.tpl.php in the directory containing the theme for your site. Usually sites/.../themes/YOURTHEME
> 2 votes

---
Tags: 7
---


# Question
Title: Should I add a div class to a fields TPL file or just change my CSS file?
I am starting to understand how to edit the CSS of individual views on my site. I use the Views module (release 2). I know Views 3 makes life easier in these things but for now I have to use Views 2.

I have a comment block on my site. I wondering if it is best/easier to add some kind of div class to a fields TPL file or wether I could just change it in my CSS file. I seem to have tried both in my time with various success. I really struggle to find out what part of the div class I need to change in a view when viewing it with Firebug.

This for instance:

> view view-comments-recent view-id-comments\_recent view-display-id-block view-dom-id-5

Would I make the css something like

> .view-comments-recent view-id-comments\_recent view-display-id-block view-dom-id-5 body { font-family:Arial, Helvetica, sans-serif; font-size:12px; line-height:16px; }

to change the text in the comment field?

I feel it might be better to create a `views-view-field--comments-recent--block--comment.tpl.php` file and then do something like this:

```
 <div class="mynewclass"><the print output bit> </div>

```

And then add this:

```
.mynewclass body {
font-family:Arial, Helvetica, sans-serif;
  font-size:12px;
  line-height:16px;
}

```

Or maye that would be like so:

```
.mynewclass p {
font-family:Arial, Helvetica, sans-serif;
  font-size:12px;
  line-height:16px;
}

```

Could anyone help me with what I am trying to do? I feel like I almost have it.

Which way would be best do you think?

# Answer
> 2 votes
You should be able to set a custom css class for each field, but otherwise your technique of drilling down using css classes is fairly common practice.

---
Tags: views, theming
---


title: How to setup a Drush Alias?

text:
# Question
Title: How to setup a Drush Alias?
I want to setup Drush aliases for a Drupal site on WAMP. I tried, however I had no luck.

All my installations for Drupal sites are located in c:\wamp\www

Drush is located in c:\drush

I would not say I have multi site up!!

The URL I use in the browser is `caribbean.localhost`

I'm really not sure, or I have trouble setting up my Drush alias. So I wonder if anyone can advise me or offer direction help to me!

# Answer
> 2 votes
It's difficult to answer your question without some concrete specifics. But i went ahead and provided you some common troubleshooting tips when i was in your shoes a moons ago:

* Visit the latest readme.txt: It's named that for a reason. I've never read a more helpful readme.txt in terms of contributed modules. Of the best. There's a section relating to site aliases as well. What you have to do for it to work etc.
* Review Documentation: First off, please review the Drush documentation which provides great examples of how to create a site aliases.
* Copy an example: Also, the maintainers created some awesome examples for a `example.aliases.drushrc.php` file. In fact, theres a whole folder regarding this that you can copy and paste examples.

**Debugging Drush**

Additionally, here are some cheap tests to confirm that your site alias is working:

* Try running `drush status` a drush status will show which you which alias file is being read in.
* If that's not enough review the drushrc.php file. I would turn on verbose output to figure out how drush is failing.

---
Tags: drush
---


title: Best way to create subsites?

text:
# Question
Title: Best way to create subsites?
What's the best way/module I can use to automatically create *subsites*, like drupalgardens.com.

Is there a module to do it? Can I use *drush* for this?

# Answer
> 2 votes
If you want something like drupalgardens (aka new sites), you can use drush site-install, but you will still need to create the site directory and what not.

If you have a basic template for the new sites you should probably create an install profile or feature module and have it set everything up.

# Answer
> 1 votes
The most straightforward and easiest way is to do it using Aegir. Aegir helps you create subdomains, sites etc under various install profiles and servers. To get a taste of how it works, check this Drupalcon london 2011 video.

# Answer
> 0 votes
Not sure about your exact requirement..suggest you could also try using domain access module. You could use the same database and restrict or share your content across the domains created, restrict users to content of a specific domain, provides options for URL aliasing and redirects, it also has a feature named domain user that lets creation of a domain based on username. And all this does not involve creation of any additional settings.php or sites dirs.

---
Tags: 7, subsites
---


# Question
Title: Replace data from command line: site name
I run in mysql:

```
update variable set value = replace(value,'SiteName','NewName');

```

and then clearing cache:

```
drush cache-clear

```

But I dont know why the site name become blank instead of `NewName`

I've tried this after replace in variable table, but not works:

```
update cache set data = replace(data,'SiteName','NewName');

```

I hope I can change any data from command line.

# Answer
The values are serialized using the built in PHP function serialize() so setting them directly shouldn't work if I understand what you did correctly. You can use drush since it appears you have that available.

Simply use:

```
drush variable-set site_name "Some name here"

```

Otherwise you can always configure from the Drupal admin interface.
> 6 votes

---
Tags: 6, database, drush
---


# Question
Title: Hooks for altering Views block output in Drupal 6
I have a View in which i mention 3 fields then i displayed as a block.

I want to want to change value of these fields.

> Which hook will i use so i can change content to fields on page load ?
>
> I tried hook\_view, hook\_block, they don't help me.

Thanks

# Answer
You could use hook\_views\_pre\_render to alter the results of the View before Views passes the data of for rendering.
> 2 votes

---
Tags: 7, hooks, views
---