/[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.59 - (show annotations) (download) (as text)
Fri Nov 6 01:56:28 2009 UTC (2 weeks, 6 days ago) by weitzman
Branch: MAIN
Changes since 1.58: +2 -1 lines
File MIME type: text/x-php
Hard code ->language=en for now
1 <?php
2 // $Id: devel_generate.inc,v 1.58 2009/10/14 14:44:48 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->language = 'en'; // $node->language not usable since it is '' but comment requires en
151 comment_save($comment);
152 }
153 }
154
155 function devel_generate_vocabs($records, $maxlength = 12, $types = array('page', 'article')) {
156 $vocs = array();
157
158 // Insert new data:
159 for ($i = 1; $i <= $records; $i++) {
160 $voc = new stdClass();
161 $voc->name = devel_generate_word(mt_rand(2, $maxlength));
162 $voc->description = "description of ". $voc->name;
163 // TODO: not working
164 $voc->nodes = array_flip(array($types[array_rand($types)]));
165 foreach ($voc->nodes as $key => $value) {
166 $voc->nodes[$key] = $key;
167 }
168
169 $voc->multiple = 1;
170 $voc->required = 0;
171 $voc->relations = 1;
172 $voc->hierarchy = 1;
173 $voc->weight = mt_rand(0,10);
174
175 taxonomy_vocabulary_save($voc);
176 $vocs[] = $voc->name;
177
178 unset($voc);
179 }
180 return $vocs;
181 }
182
183 function devel_generate_terms($records, $vocs, $maxlength = 12) {
184 $terms = array();
185
186 // Insert new data:
187 for ($i = 1; $i <= $records; $i++) {
188 $term = new stdClass();
189 switch ($i % 2) {
190 case 1:
191 $term->vid = $vocs[array_rand($vocs)];
192 // dont set a parent. handled by taxonomy_save_term()
193 // $term->parent = 0;
194 break;
195 case 2:
196 default:
197 $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();
198 $term->parent = array($parent->tid);
199 $term->vid = $parent->vid;
200 break;
201 }
202
203 $term->name = devel_generate_word(mt_rand(2, $maxlength));
204 $term->description = "description of ". $term->name;
205 $term->weight = mt_rand(0,10);
206 $status = taxonomy_term_save($term);
207 $output = NULL;
208
209 if ($status) {
210 $terms[] = $term->name;
211 }
212
213 unset($term);
214 }
215 return $terms;
216 }
217
218 function devel_generate_get_vocabs() {
219 $vocs = array();
220 return db_query("SELECT vid FROM {taxonomy_vocabulary}")->fetchCol();
221 }
222
223 function devel_generate_taxonomy_data($num_vocab, $num_terms, $title_length, $kill) {
224
225 if ($kill) {
226 foreach (taxonomy_get_vocabularies() as $vid => $vocab) {
227 taxonomy_vocabulary_delete($vid);
228 }
229 drupal_set_message(t('Deleted existing vocabularies and terms.'));
230 }
231
232 $new_vocs = devel_generate_vocabs($num_vocab, $title_length);
233 if (!empty($new_vocs)) {
234 drupal_set_message(t('Created the following new vocabularies: !vocs', array('!vocs' => theme('item_list', $new_vocs))));
235 }
236 $vocs = devel_generate_get_vocabs();
237 $new_terms = devel_generate_terms($num_terms, $vocs, $title_length);
238 if (!empty($new_terms)) {
239 drupal_set_message(t('Created the following new terms: !terms', array('!terms' => theme('item_list', $new_terms))));
240 }
241 }
242
243 function devel_generate_word($length){
244 mt_srand((double)microtime()*1000000);
245
246 $vowels = array("a", "e", "i", "o", "u");
247 $cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr",
248 "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl", "sh");
249
250 $num_vowels = count($vowels);
251 $num_cons = count($cons);
252 $word = '';
253
254 while(strlen($word) < $length){
255 $word .= $cons[mt_rand(0, $num_cons - 1)] . $vowels[mt_rand(0, $num_vowels - 1)];
256 }
257
258 return substr($word, 0, $length);
259 }
260
261 function devel_create_content($type = NULL) {
262 $nparas = mt_rand(1,12);
263 $type = empty($type) ? mt_rand(0,3) : $type;
264
265 $output = "";
266 switch($type % 3) {
267 case 1: // html
268 for ($i = 1; $i <= $nparas; $i++) {
269 $output .= devel_create_para(mt_rand(10,60),1);
270 }
271 break;
272
273 case 2: // brs only
274 for ($i = 1; $i <= $nparas; $i++) {
275 $output .= devel_create_para(mt_rand(10,60),2);
276 }
277 break;
278
279 default: // plain text
280 for ($i = 1; $i <= $nparas; $i++) {
281 $output .= devel_create_para(mt_rand(10,60)) ."\n\n";
282 }
283 }
284
285 return $output;
286 }
287
288 function devel_create_para($words, $type = 0) {
289 $output = "";
290 switch ($type) {
291 case 1:
292 $output .= "<p>";
293 $output .= devel_create_greeking($words);
294 $output = trim($output) ."</p>";
295 break;
296
297 case 2:
298 $output .= devel_create_greeking($words);
299 $output = trim($output) ."<br />";
300 break;
301
302 default:
303 $output .= devel_create_greeking($words);
304 $output = trim($output);
305 }
306 return $output;
307 }
308
309 function devel_create_greeking($words, $title = FALSE) {
310 $dictionary = array("abbas", "abdo", "abico", "abigo", "abluo", "accumsan",
311 "acsi", "ad", "adipiscing", "aliquam", "aliquip", "amet", "antehabeo",
312 "appellatio", "aptent", "at", "augue", "autem", "bene", "blandit",
313 "brevitas", "caecus", "camur", "capto", "causa", "cogo", "comis",
314 "commodo", "commoveo", "consectetuer", "consequat", "conventio", "cui",
315 "damnum", "decet", "defui", "diam", "dignissim", "distineo", "dolor",
316 "dolore", "dolus", "duis", "ea", "eligo", "elit", "enim", "erat",
317 "eros", "esca", "esse", "et", "eu", "euismod", "eum", "ex", "exerci",
318 "exputo", "facilisi", "facilisis", "fere", "feugiat", "gemino",
319 "genitus", "gilvus", "gravis", "haero", "hendrerit", "hos", "huic",
320 "humo", "iaceo", "ibidem", "ideo", "ille", "illum", "immitto",
321 "importunus", "imputo", "in", "incassum", "inhibeo", "interdico",
322 "iriure", "iusto", "iustum", "jugis", "jumentum", "jus", "laoreet",
323 "lenis", "letalis", "lobortis", "loquor", "lucidus", "luctus", "ludus",
324 "luptatum", "macto", "magna", "mauris", "melior", "metuo", "meus",
325 "minim", "modo", "molior", "mos", "natu", "neo", "neque", "nibh",
326 "nimis", "nisl", "nobis", "nostrud", "nulla", "nunc", "nutus", "obruo",
327 "occuro", "odio", "olim", "oppeto", "os", "pagus", "pala", "paratus",
328 "patria", "paulatim", "pecus", "persto", "pertineo", "plaga", "pneum",
329 "populus", "praemitto", "praesent", "premo", "probo", "proprius",
330 "quadrum", "quae", "qui", "quia", "quibus", "quidem", "quidne", "quis",
331 "ratis", "refero", "refoveo", "roto", "rusticus", "saepius",
332 "sagaciter", "saluto", "scisco", "secundum", "sed", "si", "similis",
333 "singularis", "sino", "sit", "sudo", "suscipere", "suscipit", "tamen",
334 "tation", "te", "tego", "tincidunt", "torqueo", "tum", "turpis",
335 "typicus", "ulciscor", "ullamcorper", "usitas", "ut", "utinam",
336 "utrum", "uxor", "valde", "valetudo", "validus", "vel", "velit",
337 "veniam", "venio", "vereor", "vero", "verto", "vicis", "vindico",
338 "virtus", "voco", "volutpat", "vulpes", "vulputate", "wisi", "ymo",
339 "zelus");
340
341 $greeking = "";
342
343 if (!$title) {
344 while ($words > 0) {
345 $sentence_length = mt_rand(3,10);
346
347 $greeking .= ucfirst($dictionary[array_rand($dictionary)]);
348 for ($i = 1; $i < $sentence_length; $i++) {
349 $greeking .= " " . $dictionary[array_rand($dictionary)];
350 }
351
352 $greeking .= ". ";
353 $words -= $sentence_length;
354 }
355 }
356 else {
357 // use different method for titles
358 $title_length = $words;
359 $array = array();
360 for ($i = 0; $i < $words; $i++) {
361 $array[] = $dictionary[array_rand($dictionary)];
362 }
363 $greeking = ucwords(implode(' ', $array));
364 }
365 return $greeking;
366 }
367
368 function devel_generate_add_terms(&$node) {
369 $vocabs = taxonomy_get_vocabularies($node->type);
370 foreach ($vocabs as $vocab) {
371 $sql = "SELECT tid FROM {taxonomy_term_data} WHERE vid = :vid ORDER BY RAND()";
372 $result = db_query_range($sql, 0, 5 , array(':vid' => $vocab->vid));
373 foreach($result as $row) {
374 $node->taxonomy[] = $row->tid;
375 if (!$vocab->multiple) {
376 break;
377 }
378 }
379 }
380 }
381
382 function devel_get_users() {
383 $users = array();
384 $result = db_query_range("SELECT uid FROM {users}", 0, 50);
385 foreach ($result as $record) {
386 $users[] = $record->uid;
387 }
388 return $users;
389 }
390
391 /**
392 * Generate statistics information for a node.
393 *
394 * @param $node
395 * A node object.
396 */
397 function devel_generate_add_statistics($node) {
398 $statistic = array(
399 'nid' => $node->nid,
400 'totalcount' => mt_rand(0, 500),
401 'timestamp' => REQUEST_TIME - mt_rand(0, $node->created),
402 );
403 $statistic['daycount'] = mt_rand(0, $statistic['totalcount']);
404 db_insert('node_counter')->fields($statistic)->execute();
405 }
406
407 function devel_generate_add_upload(&$node) {
408 // Pick a random PNG to attach.
409 $files = file_scan_directory(DRUPAL_ROOT. '/misc', '/^.*\.png$/');
410 $source = $files[array_rand($files)];
411
412 // Setup the file object.
413 $file = new stdClass();
414 $file->uri = file_unmanaged_copy($source->uri);
415 $file->filename = $source->filename;
416 $file->filemime = 'image/png';
417 $file->uid = $node->uid;
418 $file->status = FILE_STATUS_PERMANENT;
419
420 // Data for upload.module.
421 $file->list = variable_get('upload_list_default', TRUE);
422 $file->description = $source->name . ' was here';
423 $file->weight = mt_rand(0,10);
424 $file->new = TRUE;
425
426 $file = file_save($file);
427 $node->files[$file->fid] = $file;
428 }
429
430 /**
431 * Handle the devel_generate_content_form request to kill all of the content.
432 * This is used by both the batch and non-batch branches of the code.
433 *
434 * @param $num
435 * array of options obtained from devel_generate_content_form.
436 */
437 function devel_generate_content_kill($values) {
438 $results = db_select('node', 'n')
439 ->fields('n', array('nid'))
440 ->condition('type', $values['node_types'], 'IN')
441 ->execute();
442 foreach ($results as $result) {
443 $nids[] = $result->nid;
444 }
445
446 if (!empty($nids)) {
447 node_delete_multiple($nids);
448 drupal_set_message(t('Deleted %count nodes.', array('%count' => count($nids))));
449 }
450 }
451
452 /**
453 * Pre-process the devel_generate_content_form request. This is needed so
454 * batch api can get the list of users once. This is used by both the batch
455 * and non-batch branches of the code.
456 *
457 * @param $num
458 * array of options obtained from devel_generate_content_form.
459 */
460 function devel_generate_content_pre_node(&$results) {
461 // Get user id.
462 $users = devel_get_users();
463 $users = array_merge($users, array('0'));
464 $results['users'] = $users;
465 }
466
467 /**
468 * Create one node. This is used by both the batch and non-batch branches of
469 * the code.
470 *
471 * @param $num
472 * array of options obtained from devel_generate_content_form.
473 */
474 function devel_generate_content_add_node(&$results) {
475 global $language;
476 $node = new StdClass();
477
478 // Insert new data:
479 $node->type = array_rand($results['node_types']);
480 module_load_include('inc', 'node', 'node.pages');
481 node_object_prepare($node);
482 $users = $results['users'];
483 $node->uid = $users[array_rand($users)];
484 $type = node_type_get_type($node);
485 $node->title[FIELD_LANGUAGE_NONE][0]['value'] = $type->has_title ? devel_create_greeking(mt_rand(1, $results['title_length']), TRUE) : '';
486
487 $node->filter = variable_get('filter_default_format', 1);
488 $node->node_format = filter_default_format();
489 $node->language = '';
490 $node->revision = mt_rand(0,1);
491 $node->promote = mt_rand(0, 1);
492 // Avoid NOTICE.
493 if (!isset($results['time_range'])) {
494 $results['time_range'] = 0;
495 }
496 $node->created = REQUEST_TIME - mt_rand(0, $results['time_range']);
497
498 // A flag to let hook_nodeapi() implementations know that this is a generated node.
499 $node->devel_generate = $results;
500
501 // Populate all core fields on behalf of field.module
502 module_load_include('inc', 'devel_generate', 'devel_generate.fields');
503 cck_generate_fields($node, $node->type);
504
505 // See devel_generate_nodeapi() for actions that happen before and after this save.
506 node_save($node);
507 }

  ViewVC Help
Powered by ViewVC 1.1.2