summaryrefslogtreecommitdiffstats
path: root/modules/block.module
blob: 50db977c8ecb8a5601e52763487e91f1ce750f7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
<?php
// $Id$

function block_help($section = "admin/help#block") {
  $output = "";

  switch ($section) {
    case 'admin/help#block':
      $output = t("
<p>Blocks are the boxes visible in the sidebar(s) of your web site. These are usually generated automatically by modules (e.g. recent forum topics), but you can also create your own blocks using either static HTML or dynamic PHP content.</p>
<p>The sidebar each block appears in depends on both which theme you're using (some are left-only, some right, some both), and on the settings in block management.</p><p>Whether a block is visible in the first place depends on four things:</p><ul><li>It must have its \"enabled\" box checked in block management.</li><li>If it has its \"custom\" box checked in block management, the user must have chosen to display it in their user preferences.</li><li>If the \"path\" field in block management is set, the visitor must be on a page that matches the path specification (more on this later).</li><li>If the block has its throttle box checked, the user will only see the block if the site throttle level is low.</li></ul>
<p>The block management screen also lets you specify the vertical sort-order of the blocks within a sidebar. You do this by assigning a <strong>weight</strong> to each block. Lighter blocks (smaller weight) \"float up\" towards the top of the sidebar. Heavier ones \"sink down\" towards the bottom of it. Once you've positioned things just so, you can preview what the layout will look like in different types of themes by clicking the preview placement link in the menu to the left.</p>
<p>The path setting lets you define the pages on which a specific block is visible. If you leave the path blank it will appear on all pages. The path uses a regular expression syntax so remember to escape special characters! The path expression is matched against the relative URL of a Drupal page, e.g. <code>book</code>, <code>node/view/12</code>, <code>admin</code>.</p>
<p>In case you do not know what a regular expression is, you should read about them in the PHP manual. The chapter to look at is the one on <a href=\"%pcre\">Perl-Compatible Regular Expressions (PCRE)</a>.</p>
<p>However, for basic tasks it is sufficient to look at the following examples:</p>
<p>If the block should only show up on blog pages, use &lt;^blog&gt;.  To display on all node views use &lt;^node/view&gt;.  The angular brackets are used as delimiters of the regular expression.  To show up on either forum or book pages use &lt;^(forum|book)&gt;.  The round brackets form a group of expressions, divided by the | character. It matches if any of the expressions in it match.  A more complicated example is &lt;^node/add/(story|blog|image)&gt;. Blocks which have their paths set to this expression will show up on story, block, or image composition pages.  If you want to show a block an all pages, but not the search page, use &lt;^(?!search)&gt;.</p>
<h3>Administrator Defined Blocks</h3>
<p>An administrator defined block contains HTML, text or PHP content supplied by you (as opposed to being generated automatically by a module). Each admin-defined block consists of a title, a description, and a body containing text, HTML, or PHP code which can be as long as you wish. The Drupal engine will 'render' the content of the block.</p>
<h4>PHP in admin-defined blocks</h4>
<p>If you know how to script in PHP, Drupal gives you the power to embed any script you like inside a block. It will be executed when the page is viewed and dynamically embedded into the page. This gives you amazing flexibility and power, but of course with that comes danger and insecurity if you don't write good code. If you are not familiar with PHP, SQL or with the site engine, avoid experimenting with PHP blocks because you can corrupt your database or render your site insecure or even unusable! If you don't plan to do fancy stuff with your blocks then you're probably better off with straight HTML.</p>
<p>Remember that the code within each PHP block must be valid PHP code - including things like correctly terminating statements with a semicolon so that the parser won't die. It is highly recommended that you develop your blocks separately using a simple test script on top of a test database before migrating to your production environment.</p>
<p>Notes:</p><ul><li>You can use global variables, such as configuration parameters, within the scope of a PHP box but remember that variables which have been given values in a PHP box will retain these values in the engine or module afterwards.</li><li>register_globals is now set to <strong>off</strong> by default. If you need form information you need to get it from the \"superglobals\" \$_POST, \$_GET, etc.</li><li>You should use the <code>return</code> statement to return the actual content for your block.</li></ul>
<p>A basic example:</p>
<blockquote><p>You want to have a box with the title \"Welcome\" that you use to greet your visitors. The content for this box could be created by going:</p>
<pre>
  return t(\"Welcome visitor, ... welcome message goes here ...\");
</pre>
<p>If we are however dealing with a registered user, we can customize the message by using:</p>
<pre>
  if (\$user->uid) {
    return t(\"Welcome \$user->name, ... welcome message goes here ...\");
  }
  else {
    return t(\"Welcome visitor, ... welcome message goes here ...\");
  }
</pre></blockquote>
<p>For more in-depth examples, we recommend that you check the existing boxes and use them as a starting point.</p>", array("%pcre" => "http://php.net/pcre/"));
      break;
    case 'admin/system/modules#description':
      $output = t("Controls the boxes that are displayed around the main content.");
      break;
    case 'admin/system/block':
      $output = t("Blocks are the boxes in the left- and right- side bars of the web site, depending on the choosen theme.  They are created by <strong>active</strong> Drupal modules. The 'enabled' checkbox sets the default status of the block. Only enabled blocks are shown. When the 'custom' checkbox is checked, your users can show or hide the block using their account settings. In that case, the 'enabled' checkbox signifies the block's default status. You can assign the block's placement by giving it a region and a weight. The region specifies which side of the page the block is on, and the weight sorts blocks within a region. Lighter (smaller weight value) blocks \"float up\" towards the top of the page. The path setting lets you define which pages you want a block to be shown on. You can also create your own blocks, where you specify the content of the block rather than its being generated by a module (you can even use PHP in these). You can create one of these by clicking the <a href=\"%createblock\">new block</a> link in the menu to the left. Edit and delete links will become active below for these admin-defined blocks.  Blocks can automatically be temporarily disabled to reduce server load when your site becomes extremely busy by checking throttle.  The auto-throttle functionality must be enabled on the <a href=\"%throttle\">throttle configuration page</a> after having enabled the throttle module.", array("%createblock" => url("admin/system/block/add"), "%throttle" => url("admin/system/modules/throttle")));
      break;
    case 'admin/system/block/add':
      $output = t("Here you can create a new block. Once you have created this block you must make it active, and give it a place on the page using <a href=\"%overview\">blocks</a>. The title is used when displaying the block. The description is used in the \"block\" column on the <a href=\"%overview\">blocks</a> page. If you are going to place PHP code in the block, and you have <strong>create php content</strong> permission (see the <a href=\"%permission\">permissions</a> page) you <strong>must</strong> change the type to PHP to make your code active.", array("%overview" => url("admin/system/block"), "%permission" => url("admin/user/permission")));
      break;
    case 'admin/system/block/preview':
      $output = t("This page show you the placement of your blocks in different themes types. The numbers are the weight of each block, which is used to sort them within the sidebars.");
      break;
  }

  return $output;
}

function block_help_page() {
  print theme("page", block_help());
}

function block_perm() {
  return array("administer blocks");
}

function block_link($type) {
  if ($type == "system" && user_access("administer blocks")) {

    menu("admin/system/block", t("blocks"), "block_admin", 3);
    menu("admin/system/block/add", t("new block"), "block_admin", 2);
    menu("admin/system/block/preview", t("preview placement"), "block_admin", 3);
    menu("admin/system/block/help", t("help"), "block_help_page", 9);
  }
}

function block_block($op = "list", $delta = 0) {
  if ($op == "list") {
    $result = db_query("SELECT bid, title, info FROM {boxes} ORDER BY title");
    while ($block = db_fetch_object($result)) {
      $blocks[$block->bid]["info"] = $block->info;
    }
    return $blocks;
  }
  else {
    $block = db_fetch_object(db_query("SELECT * FROM {boxes} WHERE bid = %d", $delta));
    $data["subject"] = $block->title;
    $data["content"] = ($block->type == 1) ? eval($block->body) : $block->body;
    return $data;
  }
}

function block_admin_save($edit) {
  foreach ($edit as $module => $blocks) {
    foreach ($blocks as $delta => $block) {
      db_query("UPDATE {blocks} SET region = %d, status = %d, custom = %d, path = '%s', weight = %d, throttle = %d WHERE module = '%s' AND delta = '%s'",
                $block["region"], $block["status"], $block["custom"], $block["path"], $block["weight"], $block["throttle"], $module, $delta);
    }
  }

  return t("the block settings have been updated.");
}

/**
 * update blocks db table with blocks currently exported by modules
 *
 * @param $order_by php <a
 *   href="http://www.php.net/manual/en/function.array-multisort.php">array_multisort()</a>
 *   style sort ordering, eg. "weight", SORT_ASC, SORT_STRING.
 *
 * @return blocks currently exported by modules, sorted by $order_by
 */
function _block_rehash($order_by = array("weight")) {
  $result = db_query("SELECT * FROM {blocks} ");
  while ($old_block = db_fetch_object($result)) {
    $old_blocks[$old_block->module][$old_block->delta] = $old_block;
  }

  db_query("DELETE FROM {blocks} ");

  foreach (module_list() as $module) {
    $module_blocks = module_invoke($module, "block", "list");
    if ($module_blocks) {
      foreach ($module_blocks as $delta => $block) {
        $block["module"] = $module;
        $block["delta"]  = $delta;
        if ($old_blocks[$module][$delta]) {
          $block["status"] = $old_blocks[$module][$delta]->status;
          $block["weight"] = $old_blocks[$module][$delta]->weight;
          $block["region"] = $old_blocks[$module][$delta]->region;
          $block["path"]   = $old_blocks[$module][$delta]->path;
          $block["custom"] = $old_blocks[$module][$delta]->custom;
          $block["throttle"] = $old_blocks[$module][$delta]->throttle;
        }
        else {
          $block["status"] = $block["weight"] = $block["region"] = $block["custom"] = 0;
          $block["path"]   = "";
        }

        // reinsert blocks into table
        db_query("INSERT INTO {blocks} (module, delta, status, weight, region, path, custom, throttle) VALUES ('%s', '%s', %d, %d, %d, '%s', %d, %d)",
                  $block["module"], $block["delta"], $block["status"], $block["weight"], $block["region"], $block["path"], $block["custom"], $block["throttle"]);

        $blocks[] = $block;

        // build array to sort on
        $order[$order_by[0]][] = $block[$order_by[0]];
      }
    }
  }

  // sort
  array_multisort($order[$order_by[0]], $order_by[1] ? $order_by[1] : SORT_ASC, $order_by[2] ? $order_by[2] : SORT_REGULAR, $blocks);

  return $blocks;
}

function block_admin_display() {

  $blocks = _block_rehash();

  $header = array(t("block"), t("enabled"), t("custom"), t("throttle"), t("weight"), t("region"), t("path"), array("data" => t("operations"), "colspan" => 2));

  foreach ($blocks as $block) {
    if ($block["module"] == "block") {
      $edit = l(t("edit"), "admin/system/block/edit/". $block["delta"]);
      $delete = l(t("delete"), "admin/system/block/delete/". $block["delta"]);
    }
    else {
      $edit = "";
      $delete = "";
    }

    $rows[] = array($block["info"], array("data" => form_checkbox(NULL, $block["module"] ."][". $block["delta"] ."][status", 1, $block["status"]), "align" => "center"), array("data" => form_checkbox(NULL, $block["module"] ."][". $block["delta"] ."][custom", 1, $block["custom"]), "align" => "center"), array("data" => form_checkbox(NULL, $block["module"] ."][". $block["delta"] ."][throttle", 1, $block["throttle"], NULL, module_exist('throttle') ? NULL : array("disabled" => "disabled")), "align" => "center"), form_weight(NULL, $block["module"] ."][". $block["delta"] ."][weight", $block["weight"]), form_radios(NULL, $block["module"] ."][". $block["delta"] ."][region", $block["region"], array(t("left"), t("right"))), form_textfield(NULL, $block["module"] ."][". $block["delta"] ."][path", $block["path"], 10, 255),
    $edit, $delete);
  }

  $output = theme("table", $header, $rows);
  $output .= form_submit(t("Save blocks"));

  return form($output);
}

function block_admin_preview() {

  $result = db_query("SELECT * FROM {blocks} WHERE status > 0 AND region = 0 ORDER BY weight");
  $lblocks .= "<table border=\"0\" cellpadding=\"2\" cellspacing=\"2\">\n";
  while ($block = db_fetch_object($result)) {
    $block_data = module_invoke($block->module, "block", "list");
    $name = $block_data[$block->delta]["info"];
    $lblocks .= " <tr><td>". ($block->status == 2 ? "<strong>$name</strong>" : $name) ."</td><td>$block->weight</td></tr>\n";
  }
  $lblocks .= "</table>\n";

  $result = db_query("SELECT * FROM {blocks} WHERE status > 0 AND region = 1 ORDER BY weight");
  $rblocks .= "<table border=\"0\" cellpadding=\"2\" cellspacing=\"2\">\n";
  while ($block = db_fetch_object($result)) {
    $block_data = module_invoke($block->module, "block", "list");
    $name = $block_data[$block->delta]["info"];
    $rblocks .= " <tr><td>". ($block->status == 2 ? "<strong>$name</strong>" : $name) ."</td><td>$block->weight</td></tr>\n";
  }
  $rblocks .= "</table>\n";

  $output .= "<h3>". t("Themes with both left and right sidebars") .":</h3>\n";
  $output .= "<table border=\"1\" cellpadding=\"2\" cellspacing=\"2\">\n";
  $output .= " <tr><td colspan=\"3\" style=\"text-align: center;\">". t("header") ."</td></tr>\n";
  $output .= " <tr><td>\n". ($lblocks ? $lblocks : "&nbsp;") ."</td><td style=\"width: 300px;\">&nbsp;</td><td>\n". ($rblocks ? $rblocks : "&nbsp;") ."</td></tr>\n";
  $output .= " <tr><td colspan=\"3\" style=\"text-align: center;\">". t("footer") ."</td></tr>\n";
  $output .= "</table>\n";

  $result = db_query("SELECT * FROM {blocks} WHERE status > 0 ORDER BY weight");
  $blocks .= "<table border=\"0\" cellpadding=\"2\" cellspacing=\"2\">\n";
  while ($block = db_fetch_object($result)) {
    $block_data = module_invoke($block->module, "block", "list");
    $name = $block_data[$block->delta]["info"];
    $blocks .= " <tr><td>". ($block->status == 2 ? "<strong>$name</strong>" : $name) ."</td><td>$block->weight</td></tr>\n";
  }
  $blocks .= "</table>\n";

  $output .= "<h3>". t("Themes with right-sidebar only") .":</h3>\n";
  $output .= "<table border=\"1\" cellpadding=\"2\" cellspacing=\"2\">\n";
  $output .= " <tr><td colspan=\"2\" style=\"text-align: center;\">". t("header") ."</td></tr>\n";
  $output .= " <tr><td style=\"width: 400px;\">&nbsp;</td><td>\n". ($blocks ? $blocks : "&nbsp;") ."</td></tr>\n";
  $output .= " <tr><td colspan=\"2\" style=\"text-align: center;\">". t("footer") ."</td></tr>\n";
  $output .= "</table>\n";

  $output .= "<h3>". t("Themes with left-sidebar only") .":</h3>\n";
  $output .= "<table border=\"1\" cellpadding=\"2\" cellspacing=\"2\">\n";
  $output .= " <tr><td colspan=\"2\" style=\"text-align: center;\">". t("header") ."</td></tr>\n";
  $output .= " <tr><td>\n". ($blocks ? $blocks : "&nbsp;") ."</td><td style=\"width: 400px;\">&nbsp;</td></tr>\n";
  $output .= " <tr><td colspan=\"2\" style=\"text-align: center;\">". t("footer") ."</td></tr>\n";
  $output .= "</table>\n";

  return $output;
}

function block_box_get($bid) {
  return db_fetch_array(db_query("SELECT * FROM {boxes} WHERE bid = %d", $bid));
}

function block_box_form($edit = array()) {
  $type = array(0 => "HTML", 1 => "PHP");

  $form = form_textfield(t("Title"), "title", $edit["title"], 50, 64);
  $form .= form_textfield(t("Description"), "info", $edit["info"], 50, 64);
  $form .= form_textarea(t("Body"), "body", $edit["body"], 70, 10);
  if (user_access("create php content")) {
    $form .= form_select(t("Type"), "type", $edit["type"], $type);
  }

  if ($edit["bid"]) {
    $form .= form_hidden("bid", $edit["bid"]);
  }

  $form .= form_submit(t("Save block"));

  return form($form);
}

function block_box_save($edit) {
  if (!user_access("create php content")) {
    $edit["type"] = 0;
  }

  if ($edit["bid"]) {
    db_query("UPDATE {boxes} SET title = '%s', body = '%s', info = '%s', type = %d WHERE bid = %d", $edit["title"], $edit["body"], $edit["info"], $edit["type"], $edit["bid"]);
    return t("the block has been updated.");
  }
  else {
    db_query("INSERT INTO {boxes} (title, body, info, type) VALUES  ('%s', '%s', '%s', %d)", $edit["title"], $edit["body"], $edit["info"], $edit["type"]);
    return t("the new block has been added.");
  }
}

function block_box_delete($bid) {
  if ($bid) {
    db_query("DELETE FROM {boxes} WHERE bid = %d", $bid);
    return t("the block has been deleted.");
  }
}

function block_admin() {
  $op = $_POST["op"];
  $edit = $_POST["edit"];

  if (empty($op)) {
    $op = arg(3);
  }

  switch ($op) {
    case "preview":
      $output = block_admin_preview();
      break;
    case "add":
      $output = block_box_form();
      break;
    case "edit":
      $output = block_box_form(block_box_get(arg(4)));
      break;
    case "delete":
      drupal_set_message(block_box_delete(arg(4)));
      cache_clear_all();
      $output .= block_admin_display();
      break;
    case t("Save block"):
      drupal_set_message(block_box_save($edit));
      cache_clear_all();
      $output .= block_admin_display();
      break;
    case t("Save blocks"):
      drupal_set_message(block_admin_save($edit));
      cache_clear_all();
      // fall through
    default:
      $output .= block_admin_display();
  }

  print theme("page", $output);
}

function block_user($type, $edit, &$user) {
  switch ($type) {
    case "edit_form":
      $result = db_query("SELECT * FROM {blocks} WHERE custom = %d ORDER BY module, delta", 1);

      while ($block = db_fetch_object($result)) {
        $data = module_invoke($block->module, "block", "list");
        if ($data[$block->delta]["info"]) {
          $form .= form_checkbox($data[$block->delta]['info'], "block][$block->module][$block->delta", 1, isset($user->block[$block->module][$block->delta]) ? $user->block[$block->module][$block->delta] : $block->status);
        }
      }

      if (isset($form)) {
        return array(t('Block configuration') => $form);
      }

      break;
    case "edit_validate":
      if (!$edit["block"]) {
        $edit["block"] = array();
      }
      return $edit;
  }
}

/**
 * Return blocks available for current $user at $region.
 *
 * @param $region main|left|right
 *
 * @return array of block objects, indexed with <i>module</i>_<i>delta</i>
 *
 * @see <a href="http://drupal.org/node/view/1042" target="_top">[feature]
 *   Generic template design difficult w/o block region "look-ahead"</a>
 * @todo add a proper primary key (bid) to the blocks table so we don't have
 *   to mess around with this <i>module</i>_<i>delta</i> construct. currently,
 *   "blocks" has no primary key defined (bad)!
 */
function block_list($region) {
  global $user;
  static $blocks = array();

  if (!isset($blocks[$region])) {
    $blocks[$region] = array();
    $result = db_query("SELECT * FROM {blocks} WHERE (status = '1' OR custom = '1') ". ($region != "all" ? "AND region = %d " : "") ."ORDER BY weight, module", $region == "left" ? 0 : 1);

    while ($result && ($block = db_fetch_array($result))) {
      // When the user's account setting is empty, we use the block's regular 'status' (which is the default)
      if ($block['custom'] && $user->uid && !isset($user->block[$block['module']][$block['delta']])) {
        $user->block[$block['module']][$block['delta']] = $block['status'];
      }
      if ((($block['status'] && (!$user->uid || !$block['custom'])) || ($block['custom'] && $user->block[$block['module']][$block['delta']])) && (!$block['path'] || preg_match($block['path'], ereg_replace('^/(\?q=)?', '', request_uri())))) {

        /*
        ** Check the current throttle status and see if block should be displayed
        ** based on server load.
        */
        if (!($block['throttle'] && (module_invoke("throttle", "status") > 4))) {
          $block = array_merge($block, module_invoke($block['module'], 'block', 'view', $block['delta']));
        }
        if (isset($block['content']) && $block['content']) {
          $blocks[$region]["$block[module]_$block[delta]"] = (object) $block;
        }
      }
    }
  }
  return $blocks[$region];
}

?>