/[drupal]/contributions/modules/devel/devel_generate.inc
ViewVC logotype

Contents of /contributions/modules/devel/devel_generate.inc

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


Revision 1.58 - (show annotations) (download) (as text)
Wed Oct 14 14:44:48 2009 UTC (6 weeks, 4 days ago) by weitzman
Branch: MAIN
Changes since 1.57: +6 -2 lines
File MIME type: text/x-php
When generating users, allow admin to specify their roles.
1 <?php
2 // $Id: devel_generate.inc,v 1.57 2009/10/13 16:26:28 weitzman Exp $
3 // If not in 'safe mode', increase the maximum execution time:
4 if (!ini_get('safe_mode')) {
5 set_time_limit(240);
6 }
7
8 /**
9 * Generate some random users.
10 *
11 * @param $num
12 * Number of users to generate.
13 * @param $kill
14 * Boolean that indicates if existing users should be removed first.
15 * @param $age
16 * The max age of each randomly-generated user, in seconds.
17 * @param $roles
18 * An array of role IDs that the users should receive.
19 */
20 function devel_create_users($num, $kill, $age = 0, $roles = array()) {
21 $url = parse_url($GLOBALS['base_url']);
22 if ($kill) {
23 // TODO: deal with cancel API
24 db_delete('users')->condition('uid', 1, '>')->execute();
25 drupal_set_message(t('Users deleted.'));
26 }
27 // Determine if we should create user pictures.
28 $pic_config = FALSE;
29 module_load_include('inc', 'system', 'image.gd');
30 if (variable_get('user_pictures', 0) && function_exists('image_gd_check_settings') && image_gd_check_settings()) {
31 $pic_config['path'] = variable_get('user_picture_path', 'pictures');
32 list($pic_config['width'], $pic_config['height']) = explode('x', variable_get('user_picture_dimensions', '85x85'));
33 }
34
35 if ($num > 0) {
36 $names = array();
37 while (count($names) < $num) {
38 $name = devel_generate_word(mt_rand(6, 12));
39 $names[$name] = '';
40 }
41 foreach ($names as $name => $value) {
42 $edit = array(
43 'name' => $name,
44 'pass' => user_password(),
45 'mail' => $name . '@' . $url['host'],
46 'status' => 1,
47 'created' => REQUEST_TIME - mt_rand(0, $age),
48 'roles' => drupal_map_assoc($roles),
49 );
50
51 $account = user_save(NULL, $edit);
52
53 if ($pic_config) {
54 // Since the image.module should scale the picture just pick an
55 // arbitrary size that it's too big for our font.
56 $im = imagecreatetruecolor(200, 200);
57
58 // Randomize the foreground using the md5 of the user id, then invert it
59 // for the background color so there's enough contrast to read the text.
60 $parts = array_map('hexdec', str_split(md5($account->uid), 2));
61 $fg = imagecolorallocate($im, $parts[1], $parts[3], $parts[5]);
62 $bg = imagecolorallocate($im, 255 - $parts[0], 255 - $parts[1], 255 - $parts[2]);
63
64 // Fill the background then print their user info.
65 imagefill($im, 0, 0, $bg);
66 imagestring($im, 5, 5, 5, "#" . $account->uid, $fg);
67 imagestring($im, 5, 5, 25, $account->name, $fg);
68
69
70 // Create an empty, managed file where we want the user's picture to
71 // be so we can have GD overwrite it with the image.
72 $picture_directory = variable_get('file_default_scheme', 'public') . '://' . variable_get('user_picture_path', 'pictures');
73 $destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '.png');
74 $file = file_save_data('', $destination);
75
76 // GD doesn't like stream wrapped paths so convert the URI to a normal
77 // file system path.
78 if (isset($file) && $wrapper = file_stream_wrapper_get_instance_by_uri($file->uri)) {
79 imagepng($im, $wrapper->realpath());
80 }
81 imagedestroy($im);
82
83 // Clear the cached filesize, set the owner and MIME-type then re-save
84 // the file.
85 clearstatcache();
86 $file->uid = $account->uid;
87 $file->filemime = 'image/png';
88 $file = file_save($file);
89
90 // Save the user record with the new picture.
91 $edit = (array) $account;
92 $edit['picture'] = $file;
93 user_save($account, $edit);
94 }
95 }
96 }
97 drupal_set_message(t('!num_users created.', array('!num_users' => format_plural($num, '1 user', '@count users'))));
98 }
99
100
101 /**
102 * The main API function for creating content.
103 *
104 * See devel_generate_content_form() for the supported keys in $form_state['values'].
105 * Other modules may participate by form_alter() on that form and then handling their data during hook_nodeapi('pre_save') or in own submit handler for the form.
106 *
107 * @param string $form_state
108 * @return void
109 */
110 function devel_generate_content($form_state) {
111 if (!empty($form_state['values']['kill_content'])) {
112 devel_generate_content_kill($form_state['values']);
113 }
114
115 if (count($form_state['values']['node_types'])) {
116 // Generate nodes.
117 devel_generate_content_pre_node($form_state['values']);
118 for ($i = 1; $i <= $form_state['values']['num_nodes']; $i ++) {
119 devel_generate_content_add_node($form_state['values']);
120 }
121 }
122
123 drupal_set_message(format_plural($form_state['values']['num_nodes'], '1 node created.', '@count nodes created'));
124 }
125
126 function devel_generate_add_comments($node, $users, $num_comments, $title_length = 8) {
127 // Insert new data:
128 for ($i = 1; $i <= $num_comments; $i++) {
129 $comment->nid = $node->nid;
130 $comment->cid = NULL;
131 $comment->comment_format = filter_default_format();
132 $comment->name = 'devel generate';
133 $comment->mail = 'devel_generate@example.com';
134 $comment->timestamp = mt_rand($node->created, REQUEST_TIME);
135
136 switch ($i % 3) {
137 case 1:
138 $comment->pid = db_query_range("SELECT cid FROM {comment} WHERE pid = 0 AND nid = :nid ORDER BY RAND()", 0, 1, array(':nid' => $comment->nid))->fetchField();
139 break;
140 case 2:
141 $comment->pid = db_query_range("SELECT cid FROM {comment} WHERE pid > 0 AND nid = :nid ORDER BY RAND()", 0, 1, array(':nid' => $comment->nid))->fetchField();
142 break;
143 default:
144 $comment->pid = 0;
145 }
146
147 $comment->subject = devel_create_greeking(mt_rand(1, $title_length), TRUE);
148 $comment->comment = devel_create_content();
149 $comment->uid = $users[array_rand($users)];
150 comment_save($comment);
151 }
152 }
153
154 function devel_generate_vocabs($records, $maxlength = 12, $types = array('page', 'article')) {
155 $vocs = array();
156
157 // Insert new data:
158 for ($i = 1; $i <= $records; $i++) {
159 $voc = new stdClass();
160 $voc->name = devel_generate_word(mt_rand(2, $maxlength));
161 $voc->description = "description of ". $voc->name;
162 // TODO: not working
163 $voc->nodes = array_flip(array($types[array_rand($types)]));
164 foreach ($voc->nodes as $key => $value) {
165 $voc->nodes[$key] = $key;
166 }
167
168 $voc->multiple = 1;
169 $voc->required = 0;
170 $voc->relations = 1;
171 $voc->hierarchy = 1;
172 $voc->weight = mt_rand(0,10);
173
174 taxonomy_vocabulary_save($voc);
175 $vocs[] = $voc->name;
176
177 unset($voc);
178 }
179 return $vocs;
180 }
181
182 function devel_generate_terms($records, $vocs, $maxlength = 12) {
183 $terms = array();
184
185 // Insert new data:
186 for ($i = 1; $i <= $records; $i++) {
187 $term = new stdClass();
188 switch ($i % 2) {
189 case 1:
190 $term->vid = $vocs[array_rand($vocs)];
191 // dont set a parent. handled by taxonomy_save_term()
192 // $term->parent = 0;
193 break;
194 case 2:
195 default:
196 $parent = db_query_range("SELECT t.tid, v.vid FROM {taxonomy_term_data} t INNER JOIN {taxonomy_vocabulary} v ON t.vid = v.vid ORDER BY RAND()", 0, 1)->fetchObject();
197 $term->parent = array($parent->tid);
198 $term->vid = $parent->vid;
199 break;
200 }
201
202 $term->name = devel_generate_word(mt_rand(2, $maxlength));
203 $term->description = "description of ". $term->name;
204 $term->weight = mt_rand(0,10);
205 $status = taxonomy_term_save($term);
206 $output = NULL;
207
208 if ($status) {
209 $terms[] = $term->name;
210 }
211
212 unset($term);
213 }
214 return $terms;
215 }
216
217 function devel_generate_get_vocabs() {
218 $vocs = array();
219 return db_query("SELECT vid FROM {taxonomy_vocabulary}")->fetchCol();
220 }
221
222 function devel_generate_taxonomy_data($num_vocab, $num_terms, $title_length, $kill) {
223
224 if ($kill) {
225 foreach (taxonomy_get_vocabularies() as $vid => $vocab) {
226 taxonomy_vocabulary_delete($vid);
227 }
228 drupal_set_message(t('Deleted existing vocabularies and terms.'));
229 }
230
231 $new_vocs = devel_generate_vocabs($num_vocab, $title_length);
232 if (!empty($new_vocs)) {
233 drupal_set_message(t('Created the following new vocabularies: !vocs', array('!vocs' => theme('item_list', $new_vocs))));
234 }
235 $vocs = devel_generate_get_vocabs();
236 $new_terms = devel_generate_terms($num_terms, $vocs, $title_length);
237 if (!empty($new_terms)) {
238 drupal_set_message(t('Created the following new terms: !terms', array('!terms' => theme('item_list', $new_terms))));
239 }
240 }
241
242 function devel_generate_word($length){
243 mt_srand((double)microtime()*1000000);
244
245 $vowels = array("a", "e", "i", "o", "u");
246 $cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr",
247 "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl", "sh");
248
249 $num_vowels = count($vowels);
250 $num_cons = count($cons);
251 $word = '';
252
253 while(strlen($word) < $length){
254 $word .= $cons[mt_rand(0, $num_cons - 1)] . $vowels[mt_rand(0, $num_vowels - 1)];
255 }
256
257 return substr($word, 0, $length);
258 }
259
260 function devel_create_content($type = NULL) {
261 $nparas = mt_rand(1,12);
262 $type = empty($type) ? mt_rand(0,3) : $type;
263
264 $output = "";
265 switch($type % 3) {
266 case 1: // html
267 for ($i = 1; $i <= $nparas; $i++) {
268 $output .= devel_create_para(mt_rand(10,60),1);
269 }
270 break;
271
272 case 2: // brs only
273 for ($i = 1; $i <= $nparas; $i++) {
274 $output .= devel_create_para(mt_rand(10,60),2);
275 }
276 break;
277
278 default: // plain text
279 for ($i = 1; $i <= $nparas; $i++) {
280 $output .= devel_create_para(mt_rand(10,60)) ."\n\n";
281 }
282 }
283
284 return $output;
285 }
286
287 function devel_create_para($words, $type = 0) {
288 $output = "";
289 switch ($type) {
290 case 1:
291 $output .= "<p>";
292 $output .= devel_create_greeking($words);
293 $output = trim($output) ."</p>";
294 break;
295
296 case 2:
297 $output .= devel_create_greeking($words);
298 $output = trim($output) ."<br />";
299 break;
300
301 default:
302 $output .= devel_create_greeking($words);
303 $output = trim($output);
304 }
305 return $output;
306 }
307
308 function devel_create_greeking($words, $title = FALSE) {
309 $dictionary = array("abbas", "abdo", "abico", "abigo", "abluo", "accumsan",
310 "acsi", "ad", "adipiscing", "aliquam", "aliquip", "amet", "antehabeo",
311 "appellatio", "aptent", "at", "augue", "autem", "bene", "blandit",
312 "brevitas", "caecus", "camur", "capto", "causa", "cogo", "comis",
313 "commodo", "commoveo", "consectetuer", "consequat", "conventio", "cui",
314 "damnum", "decet", "defui", "diam", "dignissim", "distineo", "dolor",
315 "dolore", "dolus", "duis", "ea", "eligo", "elit", "enim", "erat",
316 "eros", "esca", "esse", "et", "eu", "euismod", "eum", "ex", "exerci",
317 "exputo", "facilisi", "facilisis", "fere", "feugiat", "gemino",
318 "genitus", "gilvus", "gravis", "haero", "hendrerit", "hos", "huic",
319 "humo", "iaceo", "ibidem", "ideo", "ille", "illum", "immitto",
320 "importunus", "imputo", "in", "incassum", "inhibeo", "interdico",
321 "iriure", "iusto", "iustum", "jugis", "jumentum", "jus", "laoreet",
322 "lenis", "letalis", "lobortis", "loquor", "lucidus", "luctus", "ludus",
323 "luptatum", "macto", "magna", "mauris", "melior", "metuo", "meus",
324 "minim", "modo", "molior", "mos", "natu", "neo", "neque", "nibh",
325 "nimis", "nisl", "nobis", "nostrud", "nulla", "nunc", "nutus", "obruo",
326 "occuro", "odio", "olim", "oppeto", "os", "pagus", "pala", "paratus",
327 "patria", "paulatim", "pecus", "persto", "pertineo", "plaga", "pneum",
328 "populus", "praemitto", "praesent", "premo", "probo", "proprius",
329 "quadrum", "quae", "qui", "quia", "quibus", "quidem", "quidne", "quis",
330 "ratis", "refero", "refoveo", "roto", "rusticus", "saepius",
331 "sagaciter", "saluto", "scisco", "secundum", "sed", "si", "similis",
332 "singularis", "sino", "sit", "sudo", "suscipere", "suscipit", "tamen",
333 "tation", "te", "tego", "tincidunt", "torqueo", "tum", "turpis",
334 "typicus", "ulciscor", "ullamcorper", "usitas", "ut", "utinam",
335 "utrum", "uxor", "valde", "valetudo", "validus", "vel", "velit",
336 "veniam", "venio", "vereor", "vero", "verto", "vicis", "vindico",
337 "virtus", "voco", "volutpat", "vulpes", "vulputate", "wisi", "ymo",
338 "zelus");
339
340 $greeking = "";
341
342 if (!$title) {
343 while ($words > 0) {
344 $sentence_length = mt_rand(3,10);
345
346 $greeking .= ucfirst($dictionary[array_rand($dictionary)]);
347 for ($i = 1; $i < $sentence_length; $i++) {
348 $greeking .= " " . $dictionary[array_rand($dictionary)];
349 }
350
351 $greeking .= ". ";
352 $words -= $sentence_length;
353 }
354 }
355 else {
356 // use different method for titles
357 $title_length = $words;
358 $array = array();
359 for ($i = 0; $i < $words; $i++) {
360 $array[] = $dictionary[array_rand($dictionary)];
361 }
362 $greeking = ucwords(implode(' ', $array));
363 }
364 return $greeking;
365 }
366
367 function devel_generate_add_terms(&$node) {
368 $vocabs = taxonomy_get_vocabularies($node->type);
369 foreach ($vocabs as $vocab) {
370 $sql = "SELECT tid FROM {taxonomy_term_data} WHERE vid = :vid ORDER BY RAND()";
371 $result = db_query_range($sql, 0, 5 , array(':vid' => $vocab->vid));
372 foreach($result as $row) {
373 $node->taxonomy[] = $row->tid;
374 if (!$vocab->multiple) {
375 break;
376 }
377 }
378 }
379 }
380
381 function devel_get_users() {
382 $users = array();
383 $result = db_query_range("SELECT uid FROM {users}", 0, 50);
384 foreach ($result as $record) {
385 $users[] = $record->uid;
386 }
387 return $users;
388 }
389
390 /**
391 * Generate statistics information for a node.
392 *
393 * @param $node
394 * A node object.
395 */
396 function devel_generate_add_statistics($node) {
397 $statistic = array(
398 'nid' => $node->nid,
399 'totalcount' => mt_rand(0, 500),
400 'timestamp' => REQUEST_TIME - mt_rand(0, $node->created),
401 );
402 $statistic['daycount'] = mt_rand(0, $statistic['totalcount']);
403 db_insert('node_counter')->fields($statistic)->execute();
404 }
405
406 function devel_generate_add_upload(&$node) {
407 // Pick a random PNG to attach.
408 $files = file_scan_directory(DRUPAL_ROOT. '/misc', '/^.*\.png$/');
409 $source = $files[array_rand($files)];
410
411 // Setup the file object.
412 $file = new stdClass();
413 $file->uri = file_unmanaged_copy($source->uri);
414 $file->filename = $source->filename;
415 $file->filemime = 'image/png';
416 $file->uid = $node->uid;
417 $file->status = FILE_STATUS_PERMANENT;
418
419 // Data for upload.module.
420 $file->list = variable_get('upload_list_default', TRUE);
421 $file->description = $source->name . ' was here';
422 $file->weight = mt_rand(0,10);
423 $file->new = TRUE;
424
425 $file = file_save($file);
426 $node->files[$file->fid] = $file;
427 }
428
429 /**
430 * Handle the devel_generate_content_form request to kill all of the content.
431 * This is used by both the batch and non-batch branches of the code.
432 *
433 * @param $num
434 * array of options obtained from devel_generate_content_form.
435 */
436 function devel_generate_content_kill($values) {
437 $results = db_select('node', 'n')
438 ->fields('n', array('nid'))
439 ->condition('type', $values['node_types'], 'IN')
440 ->execute();
441 foreach ($results as $result) {
442 $nids[] = $result->nid;
443 }
444
445 if (!empty($nids)) {
446 node_delete_multiple($nids);
447 drupal_set_message(t('Deleted %count nodes.', array('%count' => count($nids))));
448 }
449 }
450
451 /**
452 * Pre-process the devel_generate_content_form request. This is needed so
453 * batch api can get the list of users once. This is used by both the batch
454 * and non-batch branches of the code.
455 *
456 * @param $num
457 * array of options obtained from devel_generate_content_form.
458 */
459 function devel_generate_content_pre_node(&$results) {
460 // Get user id.
461 $users = devel_get_users();
462 $users = array_merge($users, array('0'));
463 $results['users'] = $users;
464 }
465
466 /**
467 * Create one node. This is used by both the batch and non-batch branches of
468 * the code.
469 *
470 * @param $num
471 * array of options obtained from devel_generate_content_form.
472 */
473 function devel_generate_content_add_node(&$results) {
474 global $language;
475 $node = new StdClass();
476
477 // Insert new data:
478 $node->type = array_rand($results['node_types']);
479 module_load_include('inc', 'node', 'node.pages');
480 node_object_prepare($node);
481 $users = $results['users'];
482 $node->uid = $users[array_rand($users)];
483 $type = node_type_get_type($node);
484 $node->title[FIELD_LANGUAGE_NONE][0]['value'] = $type->has_title ? devel_create_greeking(mt_rand(1, $results['title_length']), TRUE) : '';
485
486 $node->filter = variable_get('filter_default_format', 1);
487 $node->node_format = filter_default_format();
488 $node->language = '';
489 $node->revision = mt_rand(0,1);
490 $node->promote = mt_rand(0, 1);
491 // Avoid NOTICE.
492 if (!isset($results['time_range'])) {
493 $results['time_range'] = 0;
494 }
495 $node->created = REQUEST_TIME - mt_rand(0, $results['time_range']);
496
497 // A flag to let hook_nodeapi() implementations know that this is a generated node.
498 $node->devel_generate = $results;
499
500 // Populate all core fields on behalf of field.module
501 module_load_include('inc', 'devel_generate', 'devel_generate.fields');
502 cck_generate_fields($node, $node->type);
503
504 // See devel_generate_nodeapi() for actions that happen before and after this save.
505 node_save($node);
506 }

  ViewVC Help
Powered by ViewVC 1.1.2