summaryrefslogtreecommitdiffstats
path: root/includes/google_data_visualization.views.inc
blob: 7e66b173e417f344f890b7690326cdc25a25a9d6 (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
388
389
390
<?php

/**
 * @file
 * Views integration for google_data_visualization module . 
 */

/**
 * Implements hook_views_plugins(). 
 */
function google_data_visualization_views_plugins() {
  $plugins['style']['google_data_visualization'] = array(
    'title' => t('google_data_visualization'),
    'help' => t('Display rows in a chart via google_data_visualization . '),
    'handler' => 'google_data_visualization_style_plugin',
    'path' => drupal_get_path('module', 'google_data_visualization')  .  '/includes',
    'theme' => 'google_data_visualization_view',
    'theme path' => drupal_get_path('module', 'google_data_visualization')  .  '/includes',
    'uses row plugin' => TRUE,
    'uses options' => TRUE,
    'uses grouping' => FALSE,
    'type' => 'normal',
  );
  return $plugins;
}

/**
 * Menu callback; Handle AJAX Views requests for charts . 
 */
function google_data_visualization_views_ajax() {
  if (isset($_REQUEST['view_name']) && isset($_REQUEST['view_display_id'])) {
    $name = $_REQUEST['view_name'];
    $display_id = $_REQUEST['view_display_id'];
    $args = isset($_REQUEST['view_args']) && $_REQUEST['view_args'] !== '' ? explode('/', $_REQUEST['view_args']) : array();
    $path = isset($_REQUEST['view_path']) ? $_REQUEST['view_path'] : NULL;
    $dom_id = isset($_REQUEST['google_data_visualization_dom_id']) ? intval($_REQUEST['google_data_visualization_dom_id']) : NULL;
    $first = isset($_REQUEST['first']) ? intval($_REQUEST['first']) : NULL;
    $last = isset($_REQUEST['last']) ? intval($_REQUEST['last']) : NULL;
    views_include('ajax');
    $object = new stdClass();

    $object->status = FALSE;
    $object->display = '';

    $arg = explode('/', $_REQUEST['view_path']);

    // Load the view.
    if ($view = views_get_view($name)) {
      $view->set_display($display_id);

      if ($view->access($display_id)) {

        // Fix 'q' for paging.
        if (!empty($path)) {
          $_GET['q'] = $path;
        }

        // Disable the pager, render between the start and end values.
        // Views 2:
        if (isset($view->pager)) {
          $view->pager['use_pager'] = FALSE;
          $view->pager['offset'] = $first;
          $view->pager['items_per_page'] = $last - $first;
          $view->display[$display_id]->handler->set_option('use_pager', 0);
          $view->display[$display_id]->handler->set_option('offset', $first);
          $view->display[$display_id]->handler->set_option('items_per_page', $last - $first);
        }
        // Views 3:
        else {
          $view->set_items_per_page($last - $first);
          $view->set_offset($first);

          // Redundant but apparently needed.
          $view->items_per_page = $last - $first;
          $view->offset = $first;
        }

        // Reuse the same DOM id so it matches that in Drupal settings.
        $view->google_data_visualization_dom_id = $dom_id;

        $errors = $view->validate();
        if ($errors === TRUE) {
          $object->status = TRUE;
          $object->title = $view->get_title();
          $object->display  . = $view->preview($display_id, $args);
        }
        else {
          foreach ($errors as $error) {
            drupal_set_message($error, 'error');
          }
        }
      }
    }
    $messages = theme('status_messages');
    $object->messages = $messages ? '<div class="views-messages">'  .  $messages  .  '</div>' : '';

    drupal_json_output($object);
  }
}

/**
 * Adds necessary CSS and JS for Views-based charts.
 */
function google_data_visualization_views_add($view, $display_id = NULL) {
  static $dom_counter = 0;

  if (!isset($display_id)) {
    $display_id = empty($view->current_display) ? 'default' : $view->current_display;
  }

  // Save the settings for the chart, these will be used by the JavaScript.
  $options = array();

  // Keep track of each settings addition and give a unique ID .  This can be
  // useful when displaying the same view multiple times with different
  // arguments (i . e .  such as in a panel).
  $options['view_options'] = array(
    'view_args' => check_plain(implode('/', $view->args)),
    'view_path' => check_plain($_GET['q']),
    'view_base_path' => $view->get_path(),
    'view_display_id' => $display_id,
    'view_name' => $view->name,
    'google_data_visualization_dom_id' => isset($view->google_data_visualization_dom_id) ? $view->google_data_visualization_dom_id : ++$dom_counter,
  );

  foreach ($view->style_plugin->options as $key => $option) {
    if ($option) {
      $options[$key] = is_numeric($option) ? (int) $option : $option;
    }
  }

  // By default limit the scrolling to the same number of items as are visible
  // to avoid display glitches.
  if (empty($options['scroll']) && !empty($options['visible'])) {
    $options['scroll'] = $options['visible'];
  }

  // By default limit the scrolling to the same number of items as are visible
  // to avoid display glitches.
  if (empty($options['scroll']) && !empty($options['visible'])) {
    $options['scroll'] = $options['visible'];
  }

  // Get the total number of items in this view.
  $count_query = $view->build_info['count_query']->countQuery();
  $count = $count_query->execute()->fetchField();

  // Views may already populate total_rows later, but since we've already
  // generated this value, we might as well make it available.
  $view->total_rows = $count;

  // If there is just one item disable the auto-scroll and rotation.
  if ($count == 1) {
    $options['graph_type'] = NULL;
    $options['auto'] = 0;
  }

  // Determine AJAX functionality in a backwards-compatible way . Versions prior
  // to google_data_visualization 2 . 6 used the view-level "Use AJAX"
  // option instead of a style
  // setting .  We check $view->style_options here intentionally instead of
  // $view->style_plugin->options.
  $use_ajax = isset($view->style_options['ajax']) ? $view->style_options['ajax'] : $view->use_ajax;

  // If using AJAX, adjust the view's positioning based on the current page.
  if ($use_ajax) {
    $options['ajax'] = TRUE;
    $options['size'] = $count;

    // Views 2:
    if (isset($view->pager)) {
      // Enable and adjust the pager to get the correct page.
      $use_pager = $view->pager['use_pager'];
      $view->pager['use_pager'] = TRUE;
      $view->build($display_id);
      $view->pager['use_pager'] = $use_pager;

      // Create generic variable names.
      $pager_current_page = $view->pager['current_page'];
      $pager_items_per_page = $view->pager['items_per_page'];
      $pager_offset = $view->pager['offset'];
    }
    // Views 3:
    else {
      // Adjusting the query is not necessary.
      $view->build($display_id);

      // Create generic variable names.
      $pager_current_page = $view->current_page;
      $pager_items_per_page = $view->items_per_page;
      $pager_offset = $view->offset;
    }

    // If starting in the middle of a view, initialize the chart at that
    // position .  Strangely the chart must pre-load empty LI items all the way
    // up until the active item, making this inefficient for large lists.
    if ($pager_current_page) {
      // TODO: Pagers and charts do not work well together.
      // google_data_visualization should
      // give items the class "google_data_visualization-item-[offset]",
      // but instead it always
      // starts with "1", making it impossible to define a prepopulated list
      // as the middle of an AJAX view.
      $options['start'] = ($pager_current_page * $pager_items_per_page) + ($pager_offset + 1);
      $options['offset'] = ($pager_current_page * $pager_items_per_page) + ($pager_offset + 1);
    }
    elseif ($pager_offset) {
      $options['start'] = $pager_offset + 1;
      $options['offset'] = $pager_offset + 1;
    }
  }

  $identifier = drupal_clean_css_identifier('google_data_visualization_dom_'  .  $options['view_options']['google_data_visualization_dom_id']);
  return google_data_visualization_add($identifier, $options);
}

/**
 * Preprocess function for google_data_visualization-view . tpl . php . 
 */
function template_preprocess_google_data_visualization_view(&$variables) {

  $view = $variables['view'];
  $display_id = empty($view->current_display) ? 'default' : $view->current_display;

  // Add necessary JavaScript and CSS.
  $attachments = google_data_visualization_views_add($view, $display_id);

  // Find the JavaScript settings in the returned array.
  foreach ($attachments['js'] as $data) {
    if (isset($data['type']) && $data['type'] == 'setting') {
      $settings = reset($data['data']['google_data_visualization']['charts']);
    }
  }

  // Build the list of classes for the chart.
  $options = $view->style_plugin->options;
  $variables['google_data_visualization_classes_array'] = array(
    'google_data_visualization',
    drupal_clean_css_identifier('google_data_visualization-view--' . $view->name . '--' . $display_id),
   // drupal_clean_css_identifier('google_data_visualization-dom-'.
   // $settings['view_options']['google_data_visualization_dom_id']),
  );
  if (empty($options['graph_type'])) {
    $variables['google_data_visualization_classes_array'][] = 'google_data_visualization-skin-' . $options['graph_type'];
  }
  if (empty($options['graph_width'])) {
    $options['graph_width'] = 500;
  }
  if (empty($options['graph_height'])) {
    $options['graph_height'] = 400;
  }
  if (empty($options['fontfamily'])) {
    $options['fontfamily'] = "thahoma";
  }
  if (empty($options['fontsize'])) {
    $options['fontsize'] = 12;
  }
  $variables['google_data_visualization_classes'] = implode(' ', $variables['google_data_visualization_classes_array']);
  // Views 2/3 compatibility.
  $pager_offset = isset($view->pager['offset']) ? $view->pager['offset'] : $view->offset;

  // Give each item a class to identify where in the chart it belongs.
  foreach ($variables['rows'] as $id => $row) {
    $number = $id + 1 + $pager_offset;
    $zebra = ($number % 2 == 0) ? 'even' : 'odd';
    $variables['row_classes'][$id] = 'google_data_visualization-item-'  .  $number  .  ' '  .  $zebra;
  }
  for ($i = 0; $i < count($variables['rows']); $i++) {
    if ($variables['rows'][$i] == NULL) {
      $variables['rows'][$i] = 0;
    }
  }
  $records = $view->display[$view->current_display]->handler->get_option('fields');
  $header = NULL;
  $field_value = NULL;
  $set = array();
  $result = $variables['result'] = $variables['rows'];
  $vars['rows'] = array();
  $vars['field_classes'] = array();
  $vars['header'] = array();
  foreach ($records as $key => $val) {
    if (!$val['exclude']) {
      $set[] = $key;
      $header .= "'" . $val['label'] . "',";
    }
  }
  $header = substr($header , 0 , strlen($header) - 1 );
  $dat_array = '[[' . $header . '],';
  $view_re = $variables['view'];
  $rowfields = $rowfields_scatter = '';
  $j = 0;
  foreach ($view_re->result as $key => $val) {
    $pre = '[';
    $rowfields = $rowfields . $pre;
    $rowfields_scatter = $rowfields_scatter . $pre;
    $i = 0;	
    foreach ($view->field as $id => $field) {
      // render this even if set to exclude so it can be used elsewhere.
      $field_output = $view->style_plugin->get_field($j, $id);
      if (empty($field->options['exclude'])) {
	if (!is_numeric($field_output)) { 
	  $field_output = 0;
	}
	if (empty($field_output)) { 
	  $field_output = 0; 
	}
	if ($i) { 
	  $rowfields .= $field_output . ","; 
	}
	if (!$i) { 
	  $rowfields .= "'" . $field_output . "',"; 
	}
	$rowfields_scatter .= $field_output . ",";
	$empty = $field->is_value_empty($field_output , $field->options['empty_zero']);
	$object = new stdClass();
	$object->handler = &$view->field[$id];
	$object->inline = !empty($vars['options']['inline'][$id]);
	$i++;
      }
    }
    $rowfields_scatter = substr($rowfields_scatter , 0 , strlen($rowfields_scatter) - 1 );
    $rowfields_scatter =$rowfields_scatter . '],';
    $rowfields = substr($rowfields , 0 , strlen($rowfields) - 1 );
    $rowfields = $rowfields . '],';
    $j++;
  }
  $rowfields = substr($rowfields,0, strlen($rowfields) - 1 );
  $rowfields_scatter = substr($rowfields_scatter,0,strlen($rowfields_scatter) - 1);
  $dat_array_scatter = $dat_array . $rowfields_scatter . ']';
  $dat_array = $dat_array . $rowfields . ']';
  $dat_array = substr($dat_array,0, strlen($dat_array) - 1 );
  $dat_array = $dat_array . ']';
  $variables['datasvals'] = $dat_array;
  $variables['records'] = $records;
  $variables['graph_options'] = array();
  $variables['graph_chart'] = array();
  $variables['graph_data'] = array();
  $variables['graph_header'] = array();
  $variables['graph_id'] = array();
  $variables['setonloadcallback'] = 'google . setOnLoadCallback(' . $view->name . '_' . $view->current_display . '_drawChart);';
  $variables['callbackfunction'] = $view->name . '_' . $view->current_display . '_drawChart()';
  $rowfields = '';
  // Data Array.
  $data_var = $dat_array;
  $data_var_scatter = $dat_array_scatter;
  foreach($options['graph_type'] as $key => $val) {
	    switch($val) {
			
	      case 'ScatterChart':	      
		$variables['graph_data'][$val] = 'var ' . $view->name . '_' . $view->current_display . '_' . $val . "= google . visualization . arrayToDataTable(" . $data_var_scatter . ");";
		$variables['graph_header'][$val] = 'var ' . $view->name . '_' . $view->current_display . '_' . $val . ' = new google . visualization . DataTable();';
		$variables['graph_id'][$val] = $view->name . '_' . $view->current_display . '_' . $val;
		$variables['graph_options'][$val] = 'var ' . $view->name . '_' . $view->current_display . '_' . $val . '_options = {
						  title: "' . $options["graph_title"] . '",
						  width: ' . $options["graph_width"] . ' , 
						  height:' . $options["graph_height"] . ' , 
						  hAxis: {title: "' . $options['hAxis'] . '"},
						  hAxis: {color:"red"},
						  vAxis: {color:"red"},
						  vAxis: {title: "' . $options['vAxis'] . '"},
						  fontSize: ' . $options["fontsize"] . ',
						  fontName: "' . $options["fontfamily"] . '",
					  titleTextStyle: {color: "#FF0000"}
						};'; 
                $variables['graph_chart'][$val] = 'var chart = new google . visualization . ' . $val . '(document . getElementById("' . $view->name . '_' . $view->current_display . '_' . $val . '")); 
            chart . draw(' . $view->name . '_' . $view->current_display . '_' . $val . ',' . $view->name . '_' . $view->current_display . '_' . $val . '_options);';
		break;			
	      default:		  
		$variables['graph_data'][$val] = 'var ' . $view->name . '_' . $view->current_display . '_' . $val . "= google . visualization . arrayToDataTable(" . $data_var . ");";
		$variables['graph_header'][$val] = 'var ' . $view->name . '_' . $view->current_display . '_' . $val . ' = new google . visualization . DataTable();';
		$variables['graph_id'][$val] = $view->name . '_' . $view->current_display . '_' . $val;
		$variables['graph_options'][$val] = 'var ' . $view->name . '_' . $view->current_display . '_' . $val . '_options = {
						  title: "' . $options["graph_title"] . '",
						  width: ' . $options["graph_width"] . ' , 
						  height:' . $options["graph_height"] . ' , 
						  hAxis: {title: "' . $options["hAxis"] . '"},
						  hAxis: {color:"red"},
						  vAxis: {color:"red"},
						  vAxis: {title: "' . $options["vAxis"] . '"},
						  fontSize: ' . $options["fontsize"] . ',
						  fontName: "' . $options["fontfamily"] . '",
					  titleTextStyle: {color: "#FF0000"}
						};';
                $variables['graph_chart'][$val] = 'var chart = new google . visualization . ' . $val . '(document . getElementById("' . $view->name . '_' . $view->current_display . '_' . $val . '")); 
        chart . draw(' . $view->name . '_' . $view->current_display . '_' . $val . ',' . $view->name . '_' . $view->current_display . '_' . $val . '_options);';
                break;
     }
  }

}