/[drupal]/contributions/modules/votingapi/votingapi.module
ViewVC logotype

Contents of /contributions/modules/votingapi/votingapi.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.46 - (show annotations) (download) (as text)
Wed Aug 1 04:34:25 2007 UTC (2 years, 3 months ago) by eaton
Branch: MAIN
CVS Tags: HEAD
Branch point for: DRUPAL-6--2, DRUPAL-6--1
Changes since 1.45: +100 -56 lines
File MIME type: text/x-php
Many, many bugs fixed. 2.0 API still in flux.
1 <?php
2 /* $Id: votingapi.module,v 1.45 2007/07/17 05:54:17 eaton Exp $ */
3
4 /**
5 * VotingAPI 2.0
6 *
7 * A generalized voting API for Drupal. Modules can cast votes with
8 * arbitrary properties and VotingAPI will total them automatically.
9 * Support for basic anonymous voting by IP address, multi-criteria
10 * voting, arbitrary aggregation functions, etc.
11 */
12
13 /**
14 * Implementation of hook_menu. Adds the url path for the votingapi
15 * settings page.
16 */
17 function votingapi_menu() {
18 $items = array();
19 $items['admin/settings/votingapi'] = array(
20 'title' => 'Voting API',
21 'description' => 'Global settings for the Voting API.',
22 'page callback' => 'drupal_get_form',
23 'page arguments' => array('votingapi_settings_form'),
24 'access callback' => 'user_access',
25 'access arguments' => array('administer voting api'),
26 'type' => MENU_NORMAL_ITEM
27 );
28 return $items;
29 }
30
31 /**
32 * Implementation of hook_init. Loads the Views integration code.
33 */
34 function votingapi_init() {
35 if (module_exists('views')) {
36 require_once(drupal_get_path('module', 'votingapi') .'/votingapi_views.inc');
37 }
38 }
39
40 /**
41 * Implementation of hook_perm
42 */
43 function votingapi_perm() {
44 return array('administer voting api');
45 }
46
47 /**
48 * Implementation of hook_cron. Allows db-intensive recalculations
49 * to put off until cron-time.
50 */
51 function votingapi_cron() {
52 if (variable_get('votingapi_calculation_schedule', 'immediate') == 'cron') {
53 $time = time();
54 $last_cron = variable_get('votingapi_last_cron', 0);
55 $result = db_query('SELECT DISTINCT content_type, content_id FROM {votingapi_vote} WHERE timestamp > %d', $last_cron);
56
57 while ($content = db_fetch_object($result)) {
58 votingapi_recalculate_results($content->content_type, $content->content_id, TRUE);
59 }
60
61 variable_set('votingapi_last_cron', $time);
62 }
63 }
64
65
66 function votingapi_settings_form($form_state) {
67 $period = array(0 => t('Never'));
68 $period += drupal_map_assoc(array(600, 3600, 10800, 21600, 32400, 43200, 86400), 'format_interval');
69
70 $form['votingapi_anonymous_window'] = array(
71 '#type' => 'select',
72 '#title' => t('Anonymous vote rollover'),
73 '#description' => t('The amount of time that must pass before two anonymous votes from the same computer are considered unique. Setting this to \'never\' will eliminate most double-voting, but will make it impossible for multiple anonymous on the same computer (like internet cafe customers) from casting votes.'),
74 '#default_value' => variable_get('votingapi_anonymous_window', 3600),
75 '#options' => $period
76 );
77
78 $form['votingapi_calculation_schedule'] = array(
79 '#type' => 'radios',
80 '#title' => t('Vote tallying'),
81 '#description' => t('On high-traffic sites, administrators can use this setting to postpone the calculation of vote results.'),
82 '#default_value' => variable_get('votingapi_calculation_schedule', 'immediate'),
83 '#options' => array(
84 'immediate' => t('Tally results whenever a vote is cast'),
85 'cron' => t('Tally results at cron-time'),
86 'manual' => t('Do not tally results automatically: I am using a module that manages its own vote results.')
87 ),
88 );
89
90 return system_settings_form($form);
91 }
92
93
94
95 /**
96 * Cast a vote on a particular piece of content. If a vote already
97 * exists, its value is changed. In most cases, this is the function
98 * that should be used by external modules.
99 *
100 * @param $votes
101 * A single vote object, or an array of vote objects, with the following
102 * properties:
103 * $vote->content_type (Optional, defaults to 'node')
104 * $vote->content_id (Required)
105 * $vote->value_type (Optional, defaults to 'percent')
106 * $vote->value (Required)
107 * $vote->tag (Optional, defaults to 'vote')
108 * $vote->uid (Optional, defaults to current user)
109 * $vote->vote_source (Optional, defaults to current IP)
110 * $vote->timestamp (Optional, defaults to time())
111 * @param $criteria
112 * A keyed array used to determine what votes will be deleted
113 * when the current vote is cast. If no value is specified, all
114 * votes for the current content by the current user will be reset.
115 * If an empty array is passed in, no votes will be reset and all
116 * incoming votes will be saved IN ADDITION to existing ones.
117 * $criteria['vote_id'] (If this is set, all other keyes are skipped)
118 * $criteria['content_type']
119 * $criteria['content_type']
120 * $criteria['value_type']
121 * $criteria['tag']
122 * $criteria['uid']
123 * $criteria['vote_source']
124 * $criteria['timestamp'] (If this is set, records with timestamps
125 * GREATER THAN the set value will be selected.)
126 * @return
127 * An array of vote result records affected by the vote. The values
128 * are contained in a nested array keyed thusly:
129 * $value = $results[$content_type][$content_id][$tag][$value_type][$function]
130 * If $silent is TRUE, this array will be empty.
131 */
132 function votingapi_set_vote($votes = array(), $criteria = NULL) {
133 if (is_object($votes)) {
134 $votes = array($votes);
135 }
136 $touched = array();
137
138 foreach($votes as $key => $vote) {
139 // First nuke existing votes by this user.
140 $vote = _votingapi_prep_vote($vote);
141 if (!isset($criteria)) {
142 $criteria = votingapi_current_user_identifier();
143 $criteria += (array)$vote;
144 }
145 if (!empty($criteria)) {
146 votingapi_delete_votes(votingapi_select_votes($criteria));
147 }
148
149
150 $votes[$key] = votingapi_add_votes($vote);
151 $touched[$vote->content_type][$vote->content_id] = TRUE;
152 }
153
154 if (variable_get('votingapi_calculation_schedule', 'immediate') != 'cron') {
155 foreach($touched as $type => $ids) {
156 foreach ($ids as $id => $bool) {
157 $touched[$type][$id] = votingapi_recalculate_results($type, $id);
158 }
159 }
160 }
161 return $touched;
162 }
163
164 /**
165 * Generate a proper identifier for the current user: if they have
166 * an account, return their UID. Otherwise, return their IP address.
167 */
168 function votingapi_current_user_identifier() {
169 global $user;
170 $criteria = array();
171 if ($user->uid) {
172 $criteria['uid'] = $user->uid;
173 }
174 else {
175 $criteria['vote_source'] = ip_address();
176 }
177 return $criteria;
178 }
179
180 /**
181 * Save a single vote to the database.
182 *
183 * @param $vobj
184 * An array of vote objects with the following properties:
185 * $vote->content_type (Optional, defaults to 'node')
186 * $vote->content_id (Required)
187 * $vote->value_type (Optional, defaults to 'percent')
188 * $vote->value (Required)
189 * $vote->tag (Optional, defaults to 'vote')
190 * $vote->uid (Optional, defaults to current user)
191 * $vote->vote_source (Optional, defaults to current IP)
192 * $vote->timestamp (Optional, defaults to time())
193 * @return
194 * The same vote objects, with vote_ids property populated.
195 */
196 function votingapi_add_votes($votes = array()) {
197 if (is_object($votes)) {
198 $votes = array($votes);
199 }
200
201 foreach ($votes as $vobj) {
202 $vobj = _votingapi_prep_vote($vobj);
203 db_query("INSERT INTO {votingapi_vote} (content_type, content_id, value, value_type, tag, uid, timestamp, vote_source) VALUES ('%s', %d, %f, '%s', '%s', %d, %d, '%s')",
204 $vobj->content_type, $vobj->content_id, $vobj->value, $vobj->value_type, $vobj->tag, $vobj->uid, $vobj->timestamp, $vobj->vote_source);
205 $vobj->vote_id = db_last_insert_id('votingapi_vote', 'vote_id');
206 }
207 module_invoke_all('votingapi_insert', $votes);
208 return $votes;
209 }
210
211 /**
212 * Save a single vote result to the database.
213 *
214 * @param robj
215 * An array of vote result objects with the following properties:
216 * $robj->content_type
217 * $robj->content_id
218 * $robj->value_type
219 * $robj->value
220 * $robj->tag
221 * $robj->function
222 * $robj->timestamp (Optional, defaults to time())
223 */
224 function votingapi_add_results($vote_results = array()) {
225 if (is_object($vote_results)) {
226 $vote_results = array($vote_results);
227 }
228
229 foreach ($vote_results as $robj) {
230 $robj->timestamp = time();
231 db_query("INSERT INTO {votingapi_cache} (content_type, content_id, value, value_type, tag, function, timestamp) VALUES ('%s', %d, %f, '%s', '%s', '%s', %d)",
232 $robj->content_type, $robj->content_id, $robj->value, $robj->value_type, $robj->tag, $robj->function, $robj->timestamp);
233 }
234 }
235
236 /**
237 * Delete votes from the database.
238 *
239 * @param $votes
240 * An array of vote objects to delete. Minimally, each object must
241 * have the vote_id property set.
242 */
243 function votingapi_delete_votes($votes = array()) {
244 if (!empty($votes)) {
245 module_invoke_all('votingapi_delete', $votes);
246 $vids = array();
247 foreach ($votes as $vote) {
248 $vids[] = $vote->vote_id;
249 }
250 db_query("DELETE FROM {votingapi_vote} WHERE vote_id IN (". implode(',', array_fill(0, count($vids), '%d')) .")", $vids);
251 }
252 }
253
254 /**
255 * Delete cached vote results from the database.
256 *
257 * @param $vote_results
258 * An array of vote result objects to delete. Minimally, each object
259 * must have the vote_cache_id property set.
260 */
261 function votingapi_delete_results($vote_results = array()) {
262 if (!empty($vote_results)) {
263 $vids = array();
264 foreach ($vote_results as $vote) {
265 $vids[] = $vote->vote_cache_id;
266 }
267 db_query("DELETE FROM {votingapi_cache} WHERE vote_cache_id IN (". implode(',', array_fill(0, count($vids), '%d')) .")", $vids);
268 }
269 }
270
271 /**
272 * Select individual votes from the database.
273 *
274 * @param $criteria
275 * A keyed array used to build the select query. Keys can contain
276 * a single value or an array of values to be matched.
277 * $criteria['vote_id'] (If this is set, all other keyes are skipped)
278 * $criteria['content_id']
279 * $criteria['content_type']
280 * $criteria['value_type']
281 * $criteria['tag']
282 * $criteria['uid']
283 * $criteria['vote_source']
284 * $criteria['timestamp'] (If this is set, records with timestamps
285 * GREATER THAN the set value will be selected.)
286 * @return
287 * An array of vote objects matching the criteria.
288 */
289 function votingapi_select_votes($criteria = array()) {
290 if (!empty($criteria['vote_source'])) {
291 $criteria['timestamp'] = time() - variable_get('votingapi_anonymous_window', 3600);
292 }
293 $votes = array();
294 $result = _votingapi_query('vote', $criteria);
295 while ($vote = db_fetch_object($result)) {
296 $votes[] = $vote;
297 }
298 return $votes;
299 }
300
301
302 /**
303 * Select cached vote results from the database.
304 *
305 * @param $criteria
306 * A keyed array used to build the select query. Keys can contain
307 * a single value or an array of values to be matched.
308 * $criteria['vote_cache_id'] (If this is set, all other keyes are skipped)
309 * $criteria['content_type']
310 * $criteria['content_type']
311 * $criteria['value_type']
312 * $criteria['tag']
313 * $criteria['uid']
314 * $criteria['vote_source']
315 * $criteria['timestamp'] (If this is set, records with timestamps
316 * GREATER THAN the set value will be selected.)
317 * @return
318 * An array of vote result objects matching the criteria.
319 */
320 function votingapi_select_results($criteria = array()) {
321 $cached = array();
322 $result = _votingapi_query('cache', $criteria);
323 while ($cache = db_fetch_object($result)) {
324 $cached[] = $cache;
325 }
326 return $cached;
327 }
328
329 /**
330 * Loads all votes for a given piece of content, then calculates and
331 * caches the aggregate vote results. This is only intended for modules
332 * that have assumed responsibility for the full voting cycle: the
333 * votingapi_set_vote() function recalculates automatically.
334 *
335 * @param $content_type
336 * A string identifying the type of content being rated. Node, comment,
337 * aggregator item, etc.
338 * @param $content_id
339 * The key ID of the content being rated.
340 * @return
341 * An array of the resulting votingapi_cache records, structured thusly:
342 * $value = $results[$ag][$value_type][$function]
343 */
344 function votingapi_recalculate_results($content_type, $content_id, $force_calculation = FALSE) {
345 // if we're operating in cron mode, and the 'force recalculation' flag is NOT set,
346 // bail out. The cron run will pick up the results.
347
348 if (variable_get('votingapi_calculation_schedule', 'immediate') != 'cron' || $force_calculation == TRUE) {
349 // blow away the existing cache records.
350 $criteria = array('content_type' => $content_type, 'content_id' => $content_id);
351 $old_cache = votingapi_select_results($criteria);
352 votingapi_delete_results($old_cache);
353 $votes = votingapi_select_votes($criteria);
354 $cache = array();
355
356 // Loop through, calculate per-type and per-tag totals, etc.
357 foreach ($votes as $vote) {
358 switch ($vote->value_type) {
359 case 'percent':
360 $cache[$vote->tag][$vote->value_type]['count'] += 1;
361 $cache[$vote->tag][$vote->value_type]['sum'] += $vote->value;
362 break;
363
364 case 'points':
365 $cache[$vote->tag][$vote->value_type]['count'] += 1;
366 $cache[$vote->tag][$vote->value_type]['sum'] += $vote->value;
367 break;
368
369 case 'option':
370 $cache[$vote->tag][$vote->value_type][$vote->value] += 1;
371 break;
372 }
373 }
374
375 // Do a quick loop through to calculate averages.
376 // This is also a good example of how external modules can do their own processing.
377 foreach ($cache as $tag => $types) {
378 foreach ($types as $type => $functions) {
379 if ($type == 'percent' || $type == 'points') {
380 $cache[$tag][$type]['average'] = $functions['sum'] / $functions['count'];
381 }
382 if ($type == 'percent') {
383 // we don't actually need the sum for this. discard it to avoid cluttering the db.
384 unset($cache[$tag][$type]['sum']);
385 }
386 }
387 }
388
389 // Give other modules a chance to alter the collection of votes.
390 drupal_alter('votingapi_results', $cache, $votes, $content_type, $content_id);
391
392 // Now, do the caching. Woo.
393 foreach ($cache as $tag => $types) {
394 foreach ($types as $type => $functions) {
395 foreach ($functions as $function => $value) {
396 $cached[] = (object) array(
397 'content_type' => $content_type,
398 'content_id' => $content_id,
399 'value_type' => $type,
400 'value' => $value,
401 'tag' => $tag,
402 'function' => $function,
403 );
404 }
405 }
406 }
407 votingapi_add_results($cached);
408
409 // Give other modules a chance to act on the results of the vote totaling.
410 module_invoke_all('votingapi_results', $cached, $votes, $content_type, $content_id);
411
412 return $cached;
413 }
414 }
415
416
417 /**
418 * Simple wrapper function for votingapi_select_votes. Returns the
419 * value of the first vote matching the criteria passed in.
420 */
421 function votingapi_select_single_vote_value($criteria = array()) {
422 if ($votes = votingapi_select_votes($criteria) && !empty($votes)) {
423 return $votes[0]->value;
424 }
425 }
426
427 /**
428 * Simple wrapper function for votingapi_select_results. Returns the
429 * value of the first result matching the criteria passed in.
430 */
431 function votingapi_select_single_result_value($criteria = array()) {
432 return db_result(_votingapi_query('cache', $criteria, 1));
433 }
434
435 /**
436 * Populate the value of any unset vote properties.
437 *
438 * @param $vobj
439 * A single vote object.
440 * @return
441 * A vote object with all required properties filled in with
442 * their default values.
443 */
444 function _votingapi_prep_vote($vobj) {
445 global $user;
446 if (empty($vobj->prepped)) {
447 $varray = (array)$vobj;
448 $vote = array();
449 $vote['content_type'] = 'node';
450 $vote['value_type'] = 'percent';
451 $vote['tag'] = 'vote';
452 $vote['uid'] = $user->uid;
453 $vote['timestamp'] = time();
454 $vote['vote_source'] = ip_address();
455 $vote['prepped'] = TRUE;
456
457 $varray += $vote;
458 return (object)$varray;
459 }
460 return $vobj;
461 }
462
463 function _votingapi_query($table = 'vote', $criteria = array(), $limit = 0) {
464 $criteria += array(
465 'vote_id' => NULL,
466 'vote_cache_id' => NULL,
467 'content_id' => NULL,
468 'content_type' => NULL,
469 'value_type' => NULL,
470 'value' => NULL,
471 'tag' => NULL,
472 'uid' => NULL,
473 'timestamp' => NULL,
474 'vote_source' => NULL,
475 'function' => NULL,
476 );
477
478 $query = "SELECT * FROM {votingapi_". $table ."} v WHERE 1 = 1";
479 $args = array();
480 if (!empty($criteria['vote_id'])) {
481 _votingapi_query_builder('vote_id', $criteria['vote_id'], $query, $args);
482 } elseif (!empty($criteria['vote_cache_id'])) {
483 _votingapi_query_builder('vote_cache_id', $criteria['vote_cache_id'], $query, $args);
484 } else {
485 _votingapi_query_builder('content_type', $criteria['content_type'], $query, $args, TRUE);
486 _votingapi_query_builder('content_id', $criteria['content_id'], $query, $args);
487 _votingapi_query_builder('value_type', $criteria['value_type'], $query, $args, TRUE);
488 _votingapi_query_builder('tag', $criteria['tag'], $query, $args, TRUE);
489 _votingapi_query_builder('function', $criteria['function'], $query, $args);
490 _votingapi_query_builder('uid', $criteria['uid'], $query, $args);
491 _votingapi_query_builder('vote_source', $criteria['vote_source'], $query, $args, TRUE);
492 _votingapi_query_builder('timestamp', $criteria['timestamp'], $query, $args);
493 }
494 return $limit ? db_query_range($query, $args, 0, $limit) : db_query($query, $args);
495 }
496
497 function _votingapi_query_builder($name, $value, &$query, &$args, $col_is_string = FALSE) {
498 if (!isset($value)) {
499 // Do nothing
500 }
501 elseif ($name === 'timestamp') {
502 $query .= " AND v.timestamp >= %d";
503 $args[] = $value;
504 }
505 else {
506 if (is_array($value)) {
507 if ($col_is_string) {
508 $query .= " AND v.". $name ." IN ('". array_fill(1, count($value), "'%s'") ."')";
509 $args += $value;
510 }
511 else {
512 $query .= " AND v.". $name ." IN (". array_fill(1, count($value), "%d") .")";
513 $args += $value;
514 }
515 } else {
516 if ($col_is_string) {
517 $query .= " AND v.". $name ." = '%s'";
518 $args[] = $value;
519 }
520 else {
521 $query .= " AND v.". $name ." = %d";
522 $args[] = $value;
523 }
524 }
525 }
526 }

  ViewVC Help
Powered by ViewVC 1.1.2