devel_generate.inc 23.6 KB
Newer Older
1
2
<?php

3
4
5
6
7
8
9
/**
 * Generate some random users.
 *
 * @param $num
 *  Number of users to generate.
 * @param $kill
 *  Boolean that indicates if existing users should be removed first.
10
11
 * @param $age
 *  The max age of each randomly-generated user, in seconds.
12
13
 * @param $roles
 *  An array of role IDs that the users should receive.
14
15
 * @param $pass
 *  A string to be used as common password for all generated users.
16
 */
17
function devel_create_users($num, $kill, $age = 0, $roles = array(), $pass = NULL) {
18
19
  $url = parse_url($GLOBALS['base_url']);
  if ($kill) {
20
21
22
23
24
25
26
    $uids = db_select('users', 'u')
            ->fields('u', array('uid'))
            ->condition('uid', 1, '>')
            ->execute()
            ->fetchAllAssoc('uid');
    user_delete_multiple(array_keys($uids));
    drupal_set_message(format_plural(count($uids), '1 user deleted', '@count users deleted.'));
27
  }
28
29
30
  // Determine if we should create user pictures.
  $pic_config = FALSE;
  module_load_include('inc', 'system', 'image.gd');
31
  if (variable_get('user_pictures', 0) && function_exists('image_gd_check_settings') && image_gd_check_settings()) {
32
33
34
35
    $pic_config['path'] = variable_get('user_picture_path', 'pictures');
    list($pic_config['width'], $pic_config['height']) = explode('x', variable_get('user_picture_dimensions', '85x85'));
  }

36
37
38
39
40
41
  if ($num > 0) {
    $names = array();
    while (count($names) < $num) {
      $name = devel_generate_word(mt_rand(6, 12));
      $names[$name] = '';
    }
moshe weitzman's avatar
moshe weitzman committed
42
43
44
45

    if (empty($roles)) {
      $roles = array(DRUPAL_AUTHENTICATED_RID);
    }
46
47
    foreach ($names as $name => $value) {
      $edit = array(
48
        'uid'     => NULL,
49
        'name'    => $name,
50
        'pass'    => $pass,
51
        'mail'    => $name . '@' . $url['host'].'.invalid',
52
53
        'status'  => 1,
        'created' => REQUEST_TIME - mt_rand(0, $age),
54
        'roles' => drupal_map_assoc($roles),
55
        'devel_generate' => TRUE // A flag to let hook_user_* know that this is a generated user.
56
      );
57

58
59
60
      // Populate all core fields on behalf of field.module
      module_load_include('inc', 'devel_generate', 'devel_generate.fields');
      $edit = (object) $edit;
61
      $edit->language = LANGUAGE_NONE;
62
63
64
      devel_generate_fields($edit, 'user', 'user');
      $edit = (array) $edit;

65
      $account = user_save(drupal_anonymous_user(), $edit);
66
67

      if ($pic_config) {
68
69
70
        // Since the image.module should scale the picture just pick an
        // arbitrary size that it's too big for our font.
        $im = imagecreatetruecolor(200, 200);
71
72
73
74
75
76
77
78
79
80
81
82

        // Randomize the foreground using the md5 of the user id, then invert it
        // for the background color so there's enough contrast to read the text.
        $parts = array_map('hexdec', str_split(md5($account->uid), 2));
        $fg = imagecolorallocate($im, $parts[1], $parts[3], $parts[5]);
        $bg = imagecolorallocate($im, 255 - $parts[0], 255 - $parts[1], 255 - $parts[2]);

        // Fill the background then print their user info.
        imagefill($im, 0, 0, $bg);
        imagestring($im, 5, 5, 5, "#" . $account->uid, $fg);
        imagestring($im, 5, 5, 25, $account->name, $fg);

83
84
85
86

        // Create an empty, managed file where we want the user's picture to
        // be so we can have GD overwrite it with the image.
        $picture_directory =  variable_get('file_default_scheme', 'public') . '://' . variable_get('user_picture_path', 'pictures');
87
        file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
88
89
90
91
92
        $destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '.png');
        $file = file_save_data('', $destination);

        // GD doesn't like stream wrapped paths so convert the URI to a normal
        // file system path.
drewish's avatar
drewish committed
93
        if (isset($file) && $wrapper = file_stream_wrapper_get_instance_by_uri($file->uri)) {
94
95
          imagepng($im, $wrapper->realpath());
        }
96
97
        imagedestroy($im);

98
99
        // Clear the cached filesize, set the owner and MIME-type then re-save
        // the file.
100
101
        clearstatcache();
        $file->uid = $account->uid;
102
        $file->filemime = 'image/png';
103
104
105
106
107
        $file = file_save($file);

        // Save the user record with the new picture.
        $edit = (array) $account;
        $edit['picture'] = $file;
108
        $edit['pass'] = $pass; // Reassign password as it is replaced with the hashed version in $account
109
110
        user_save($account, $edit);
      }
111
    }
112
113
114
115
  }
  drupal_set_message(t('!num_users created.', array('!num_users' => format_plural($num, '1 user', '@count users'))));
}

116

117
/**
118
119
 * The main API function for creating content.
 *
120
121
122
123
124
 * See devel_generate_content_form() for the supported keys in
 * $form_state['values'].
 * Other modules may participate by form_alter() on that form and then handling
 * their data during hook_node_insert() or in their own submit handler for the
 * form.
125
 *
126
 * @param string $form_state
127
128
129
 * @return void
 */
function devel_generate_content($form_state) {
130
  if (!empty($form_state['values']['kill_content'])) {
131
    devel_generate_content_kill($form_state['values']);
132
133
  }

134
  if (count($form_state['values']['node_types'])) {
135
    // Generate nodes.
136
    devel_generate_content_pre_node($form_state['values']);
137
138
    $start = time();
    for ($i = 1; $i <= $form_state['values']['num_nodes']; $i++) {
139
      devel_generate_content_add_node($form_state['values']);
140
141
      if (function_exists('drush_log') && $i % drush_get_option('feedback', 1000) == 0) {
        $now = time();
142
        drush_log(dt('Completed !feedback nodes (!rate nodes/min)', array('!feedback' => drush_get_option('feedback', 1000), '!rate' => (drush_get_option('feedback', 1000)*60)/($now-$start))), 'ok');
143
144
        $start = $now;
      }
145
146
    }
  }
147

148
  devel_generate_set_message(format_plural($form_state['values']['num_nodes'], '1 node created.', 'Finished creating @count nodes'));
149
150
}

151
152
function devel_generate_add_comments($node, $users, $max_comments, $title_length = 8) {
  $num_comments = mt_rand(1, $max_comments);
153
  for ($i = 1; $i <= $num_comments; $i++) {
154
    $comment = new stdClass;
155
156
157
158
    $comment->nid = $node->nid;
    $comment->cid = NULL;
    $comment->name = 'devel generate';
    $comment->mail = 'devel_generate@example.com';
159
    $comment->timestamp = mt_rand($node->created, REQUEST_TIME);
160
161
162

    switch ($i % 3) {
      case 1:
drewish's avatar
drewish committed
163
        $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();
164
165
        break;
      case 2:
drewish's avatar
drewish committed
166
        $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();
167
168
169
170
        break;
      default:
        $comment->pid = 0;
    }
171

172
173
174
    // The subject column has a max character length of 64
    // See bug: http://drupal.org/node/1024340
    $comment->subject = substr(devel_create_greeking(mt_rand(2, $title_length), TRUE), 0, 63);
175
    $comment->uid = $users[array_rand($users)];
176
    $comment->language = LANGUAGE_NONE;
177
178
    // Populate all core fields on behalf of field.module
    module_load_include('inc', 'devel_generate', 'devel_generate.fields');
179
    devel_generate_fields($comment, 'comment', 'comment_node_' . $node->type);
180
    comment_save($comment);
181
182
183
  }
}

184
function devel_generate_vocabs($records, $maxlength = 12, $types = array('page', 'article')) {
185
186
187
188
  $vocs = array();

  // Insert new data:
  for ($i = 1; $i <= $records; $i++) {
189
    $voc = new stdClass();
190
    $voc->name = devel_generate_word(mt_rand(2, $maxlength));
191
    $voc->machine_name = drupal_strtolower($voc->name);
192
    $voc->description = "description of ". $voc->name;
193
    // TODO: not working
194
195
196
    $voc->nodes = array_flip(array($types[array_rand($types)]));
    foreach ($voc->nodes as $key => $value) {
      $voc->nodes[$key] = $key;
197
    }
198

199
200
201
202
    $voc->multiple = 1;
    $voc->required = 0;
    $voc->relations = 1;
    $voc->hierarchy = 1;
203
    $voc->weight = mt_rand(0,10);
204
    $voc->language = LANGUAGE_NONE;
205
206
207
208
209

    taxonomy_vocabulary_save($voc);
    $vocs[] = $voc->name;

    unset($voc);
210
211
212
213
  }
  return $vocs;
}

214
215
216
217
218
219
220
221
222
223
224
225
/**
 * Generates taxonomy terms for a list of given vocabularies.
 *
 * @param $records
 *   int number of terms to create in total.
 * @param $vocabs
 *   array list of vocabs to populate.
 * @param $maxlength
 *   int maximum length per term.
 * @return
 *   array the list of names of the created terms.
 */
226
function devel_generate_terms($records, $vocabs, $maxlength = 12) {
227
228
229
  $terms = array();

  // Insert new data:
230
  $max = db_query('SELECT MAX(tid) FROM {taxonomy_term_data}')->fetchField();
231
  $start = time();
232
  for ($i = 1; $i <= $records; $i++) {
233
    $term = new stdClass;
234
235
    switch ($i % 2) {
      case 1:
236
        // Set vid and vocabulary_machine_name properties.
237
238
239
240
        $vocab = $vocabs[array_rand($vocabs)];
        $term->vid = $vocab->vid;
        $term->vocabulary_machine_name = $vocab->machine_name;
        // Don't set a parent. Handled by taxonomy_save_term()
241
242
243
        // $term->parent = 0;
        break;
      default:
244
        while (TRUE) {
245
          // Keep trying to find a random parent.
246
247
248
249
250
251
          $candidate = mt_rand(1, $max);
          $query = db_select('taxonomy_term_data', 't');
          $query->innerJoin('taxonomy_vocabulary', 'v', 't.vid = v.vid');
          $parent = $query
                    ->fields('t', array('tid', 'vid'))
                    ->fields('v', array('machine_name'))
252
                    ->condition('v.vid', array_keys($vocabs), 'IN')
253
254
255
256
257
258
259
260
261
262
263
264
                    ->condition('t.tid', $candidate, '>=')
                    ->range(0,1)
                    ->execute()
                    ->fetchAssoc();
          if ($parent['tid']) {
            break;
          }
        }
        $term->parent = $parent['tid'];
        // Slight speedup due to this property being set.
        $term->vocabulary_machine_name = $parent['machine_name'];
        $term->vid = $parent['vid'];
265
266
267
        break;
    }

268
    $term->name = devel_generate_word(mt_rand(2, $maxlength));
269
    $term->description = "description of ". $term->name;
270
    $term->format = filter_fallback_format();
271
    $term->weight = mt_rand(0, 10);
272
    $term->language = LANGUAGE_NONE;
273
    $term->devel_generate = TRUE;
274
275
276

    // Populate all core fields on behalf of field.module
    module_load_include('inc', 'devel_generate', 'devel_generate.fields');
277
    devel_generate_fields($term, 'taxonomy_term', $term->vocabulary_machine_name);
278

279
280
    if ($status = taxonomy_term_save($term)) {
      $max += 1;
281
282
283
284
285
286
287
      if (function_exists('drush_log')) {
        $feedback = drush_get_option('feedback', 1000);
        if ($i % $feedback == 0) {
          $now = time();
          drush_log(dt('Completed !feedback terms (!rate terms/min)', array('!feedback' => $feedback, '!rate' => $feedback*60 / ($now-$start) )), 'ok');
          $start = $now;
        }
288
      }
289

290
      // Limit memory usage. Only report first 20 created terms.
291
292
293
      if ($i < 20) {
        $terms[] = $term->name;
      }
294

295
296
      unset($term);
    }
297
298
299
300
  }
  return $terms;
}

301
302
303
304
305
306
307
308
// TODO: use taxonomy_get_entries once that exists.
function devel_generate_get_terms($vids) {
  return db_select('taxonomy_term_data', 'td')
           ->fields('td', array('tid'))
           ->condition('vid', $vids, 'IN')
           ->orderBy('tid', 'ASC')
           ->execute()
           ->fetchCol('tid');
309
310
}

311
312
313
314
315
316
317
318
319
/**
 * Deletes all terms of a vocabulary.
 *
 * @param $vid
 *   int a vocabulary vid.
 */
function devel_generate_delete_vocabulary_terms($vid) {
  foreach (taxonomy_get_tree($vid) as $term) {
    taxonomy_term_delete($term->tid);
320
321
322
  }
}

323
324
325
326
327
328
/**
 * Deletes all vocabularies.
 */
function devel_generate_delete_vocabularies() {
  foreach (taxonomy_vocabulary_load_multiple(FALSE) as $vid => $vocab) {
    taxonomy_vocabulary_delete($vid);
329
330
331
  }
}

332
333
334
335
336
337
338
339
340
/**
 * Deletes custom generated menus
 */
function devel_generate_delete_menus() {
  if (module_exists('menu')) {
    foreach (menu_get_menus(FALSE) as $menu => $menu_title) {
      if (strpos($menu, 'devel-') === 0) {
        $menu = menu_load($menu);
        menu_delete($menu);
341
342
343
      }
    }
  }
344
345
346
347
348
349
350
351
352
  // Delete menu links generated by devel.
  $result = db_select('menu_links', 'm')
    ->fields('m', array('mlid'))
    ->condition('m.menu_name', 'devel', '<>')
    // Look for the serialized version of 'devel' => TRUE.
    ->condition('m.options', '%' . db_like('s:5:"devel";b:1') . '%', 'LIKE')
    ->execute();
  foreach ($result as $link) {
    menu_link_delete($link->mlid);
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
  }
}

/**
 * Generates new menus.
 */
function devel_generate_menus($num_menus, $title_length = 12) {
  $menus = array();

  if (!module_exists('menu')) {
    $num_menus = 0;
  }

  for ($i = 1; $i <= $num_menus; $i++) {
    $menu = array();
368
    $menu['title'] = devel_generate_word(mt_rand(2, max(2, $title_length)));
369
    $menu['menu_name'] = 'devel-' . drupal_strtolower($menu['title']);
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
    $menu['description'] = t('Description of @name', array('@name' => $menu['title']));
    menu_save($menu);
    $menus[$menu['menu_name']] = $menu['title'];
  }

  return $menus;
}

/**
 * Generates menu links in a tree structure.
 */
function devel_generate_links($num_links, $menus, $title_length, $link_types, $max_depth, $max_width) {
  $links = array();
  $menus = array_keys(array_filter($menus));
  $link_types = array_keys(array_filter($link_types));

  $nids = array();
  for ($i = 1; $i <= $num_links; $i++) {
    // Pick a random menu.
    $menu_name = $menus[array_rand($menus)];
    // Build up our link.
    $link = array(
      'menu_name'   => $menu_name,
      'options'     => array('devel' => TRUE),
      'weight'      => mt_rand(-50, 50),
      'mlid'        => 0,
396
      'link_title'  => devel_generate_word(mt_rand(2, max(2, $title_length))),
397
398
399
400
401
402
403
404
405
    );
    $link['options']['attributes']['title'] = t('Description of @title.', array('@title' => $link['link_title']));

    // For the first $max_width items, make first level links.
    if ($i <= $max_width) {
      $depth = 0;
    }
    else {
      // Otherwise, get a random parent menu depth.
406
      $depth = mt_rand(1, max(1, $max_depth - 1));
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
    }
    // Get a random parent link from the proper depth.
    do {
      $link['plid'] = db_select('menu_links', 'm')
        ->fields('m', array('mlid'))
        ->condition('m.menu_name', $menus, 'IN')
        ->condition('m.depth', $depth)
        ->range(0, 1)
        ->orderRandom()
        ->execute()
        ->fetchField();
      $depth--;
    } while (!$link['plid'] && $depth > 0);
    if (!$link['plid']) {
      $link['plid'] = 0;
    }

    $link_type = array_rand($link_types);
    switch ($link_types[$link_type]) {
      case 'node':
        // Grab a random node ID.
        $select = db_select('node', 'n')
          ->fields('n', array('nid', 'title'))
          ->condition('n.status', 1)
          ->range(0, 1)
          ->orderRandom();
        // Don't put a node into the menu twice.
        if (!empty($nids[$menu_name])) {
          $select->condition('n.nid', $nids[$menu_name], 'NOT IN');
        }
        $node = $select->execute()->fetchAssoc();
        if (isset($node['nid'])) {
          $nids[$menu_name][] = $node['nid'];
          $link['link_path'] = $link['router_path'] = 'node/' . $node['nid'];
          $link['link_title'] = $node['title'];
          break;
        }
      case 'external':
        $link['link_path'] = 'http://www.example.com/';
        break;
      case 'front':
        $link['link_path'] = $link['router_path'] = '<front>';
        break;
      default:
        $link['devel_link_type'] = $link_type;
        break;
    }

    menu_link_save($link);

    $links[$link['mlid']] = $link['link_title'];
  }

  return $links;
}

463
function devel_generate_word($length){
464
  mt_srand((double)microtime()*1000000);
465
466
467
468
469
470
471
472
473
474

  $vowels = array("a", "e", "i", "o", "u");
  $cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr",
  "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl", "sh");

  $num_vowels = count($vowels);
  $num_cons = count($cons);
  $word = '';

  while(strlen($word) < $length){
475
    $word .= $cons[mt_rand(0, $num_cons - 1)] . $vowels[mt_rand(0, $num_vowels - 1)];
476
477
478
479
480
  }

  return substr($word, 0, $length);
}

481
482
483
484
485
function devel_create_content() {
  $nparas = mt_rand(1, 12);
  $output = '';
  for ($i = 1; $i <= $nparas; $i++) {
    $output .= devel_create_para(mt_rand(10,60)) . "\n\n";
486
487
488
489
490
491
  }

  return $output;
}

function devel_create_para($words, $type = 0) {
492
  $output = '';
493
494
  switch ($type) {
    case 1:
495
      $output .= "<p>" . devel_create_greeking($words)  . "</p>";
496
497
498
      break;

    case 2:
499
      $output .= devel_create_greeking($words) . "<br />";
500
501
502
503
504
505
506
507
      break;

    default:
      $output .= devel_create_greeking($words);
  }
  return $output;
}

508
function devel_create_greeking($word_count, $title = FALSE) {
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
  $dictionary = array("abbas", "abdo", "abico", "abigo", "abluo", "accumsan",
    "acsi", "ad", "adipiscing", "aliquam", "aliquip", "amet", "antehabeo",
    "appellatio", "aptent", "at", "augue", "autem", "bene", "blandit",
    "brevitas", "caecus", "camur", "capto", "causa", "cogo", "comis",
    "commodo", "commoveo", "consectetuer", "consequat", "conventio", "cui",
    "damnum", "decet", "defui", "diam", "dignissim", "distineo", "dolor",
    "dolore", "dolus", "duis", "ea", "eligo", "elit", "enim", "erat",
    "eros", "esca", "esse", "et", "eu", "euismod", "eum", "ex", "exerci",
    "exputo", "facilisi", "facilisis", "fere", "feugiat", "gemino",
    "genitus", "gilvus", "gravis", "haero", "hendrerit", "hos", "huic",
    "humo", "iaceo", "ibidem", "ideo", "ille", "illum", "immitto",
    "importunus", "imputo", "in", "incassum", "inhibeo", "interdico",
    "iriure", "iusto", "iustum", "jugis", "jumentum", "jus", "laoreet",
    "lenis", "letalis", "lobortis", "loquor", "lucidus", "luctus", "ludus",
    "luptatum", "macto", "magna", "mauris", "melior", "metuo", "meus",
    "minim", "modo", "molior", "mos", "natu", "neo", "neque", "nibh",
    "nimis", "nisl", "nobis", "nostrud", "nulla", "nunc", "nutus", "obruo",
    "occuro", "odio", "olim", "oppeto", "os", "pagus", "pala", "paratus",
    "patria", "paulatim", "pecus", "persto", "pertineo", "plaga", "pneum",
    "populus", "praemitto", "praesent", "premo", "probo", "proprius",
    "quadrum", "quae", "qui", "quia", "quibus", "quidem", "quidne", "quis",
    "ratis", "refero", "refoveo", "roto", "rusticus", "saepius",
    "sagaciter", "saluto", "scisco", "secundum", "sed", "si", "similis",
    "singularis", "sino", "sit", "sudo", "suscipere", "suscipit", "tamen",
    "tation", "te", "tego", "tincidunt", "torqueo", "tum", "turpis",
    "typicus", "ulciscor", "ullamcorper", "usitas", "ut", "utinam",
    "utrum", "uxor", "valde", "valetudo", "validus", "vel", "velit",
    "veniam", "venio", "vereor", "vero", "verto", "vicis", "vindico",
    "virtus", "voco", "volutpat", "vulpes", "vulputate", "wisi", "ymo",
    "zelus");
539
  $dictionary_flipped = array_flip($dictionary);
540

541
  $greeking = '';
542
543

  if (!$title) {
544
545
546
547
548
    $words_remaining = $word_count;
    while ($words_remaining > 0) {
      $sentence_length = mt_rand(3, 10);
      $words = array_rand($dictionary_flipped, $sentence_length);
      $sentence = implode(' ', $words);
549
      $greeking .= ucfirst($sentence) . '. ';
550
      $words_remaining -= $sentence_length;
551
    }
552
553
  }
  else {
554
555
    // Use slightly different method for titles.
    $words = array_rand($dictionary_flipped, $word_count);
556
557
    $words = is_array($words) ? implode(' ', $words) : $words;
    $greeking = ucwords($words);
558
  }
559
560
561

  // Work around possible php garbage collection bug. Without an unset(), this
  // function gets very expensive over many calls (php 5.2.11).
562
563
  unset($dictionary, $dictionary_flipped);
  return trim($greeking);
564
565
}

566
function devel_generate_add_terms(&$node) {
567
568
  $vocabs = taxonomy_get_vocabularies($node->type);
  foreach ($vocabs as $vocab) {
569
    $sql = "SELECT tid FROM {taxonomy_term_data} WHERE vid = :vid ORDER BY RAND()";
570
571
    $result = db_query_range($sql, 0, 5 , array(':vid' => $vocab->vid));
    foreach($result as $row) {
572
      $node->taxonomy[] = $row->tid;
573
574
575
      if (!$vocab->multiple) {
        break;
      }
576
577
578
579
580
581
    }
  }
}

function devel_get_users() {
  $users = array();
582
  $result = db_query_range("SELECT uid FROM {users}", 0, 50);
drewish's avatar
drewish committed
583
584
  foreach ($result as $record) {
    $users[] = $record->uid;
585
586
587
588
  }
  return $users;
}

589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
/**
 * Generate statistics information for a node.
 *
 * @param $node
 *   A node object.
 */
function devel_generate_add_statistics($node) {
  $statistic = array(
    'nid' => $node->nid,
    'totalcount' => mt_rand(0, 500),
    'timestamp' => REQUEST_TIME - mt_rand(0, $node->created),
  );
  $statistic['daycount'] = mt_rand(0, $statistic['totalcount']);
  db_insert('node_counter')->fields($statistic)->execute();
}

605
606
607
608
609
610
611
/**
 * Handle the devel_generate_content_form request to kill all of the content.
 * This is used by both the batch and non-batch branches of the code.
 *
 * @param $num
 *   array of options obtained from devel_generate_content_form.
 */
612
613
614
615
616
617
618
function devel_generate_content_kill($values) {
  $results = db_select('node', 'n')
              ->fields('n', array('nid'))
              ->condition('type', $values['node_types'], 'IN')
              ->execute();
  foreach ($results as $result) {
    $nids[] = $result->nid;
619
  }
620

621
622
623
  if (!empty($nids)) {
    node_delete_multiple($nids);
    drupal_set_message(t('Deleted %count nodes.', array('%count' => count($nids))));
624
  }
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
}

/**
 * Pre-process the devel_generate_content_form request.  This is needed so
 * batch api can get the list of users once.  This is used by both the batch
 * and non-batch branches of the code.
 *
 * @param $num
 *   array of options obtained from devel_generate_content_form.
 */
function devel_generate_content_pre_node(&$results) {
  // Get user id.
  $users = devel_get_users();
  $users = array_merge($users, array('0'));
  $results['users'] = $users;
}

/**
moshe weitzman's avatar
moshe weitzman committed
643
 * Create one node. Used by both batch and non-batch code branches.
644
 *
645
646
647
648
649
650
 * @param $results
 *   array of options obtained from devel_generate_content_form. If call
 *   this function directly, $results should contain at the very least:
 *     node_types => an associative array of node type machine names
 *     users => an array of UIDs
 *     title_length => max number of words in titles, for example 4.
651
652
 */
function devel_generate_content_add_node(&$results) {
653
654
  $node = new stdClass();
  $node->nid = NULL;
drewish's avatar
drewish committed
655

656
657
  // Insert new data:
  $node->type = array_rand($results['node_types']);
658
  node_object_prepare($node);
659
660
  $users = $results['users'];
  $node->uid = $users[array_rand($users)];
661
  $type = node_type_get_type($node);
662
663
  $node->revision = mt_rand(0,1);
  $node->promote = mt_rand(0, 1);
664

665
  if (!$type || $type->has_title) {
666
667
668
669
670
671
672
673
674
    // We should not use the random function if the value is not random
    if ($results['title_length'] < 2) {
      $node->title = devel_create_greeking(1, TRUE);
    }
    else {
      $node->title = devel_create_greeking(mt_rand(1, $results['title_length']), TRUE);
    }
  }

675
676
677
678
  // Avoid NOTICE.
  if (!isset($results['time_range'])) {
    $results['time_range'] = 0;
  }
679
680
681

  devel_generate_set_language($results, $node);

682
  $node->created = REQUEST_TIME - mt_rand(0, $results['time_range']);
683

684
685
  // A flag to let hook_node_insert() implementations know that this is a
  // generated node.
686
  $node->devel_generate = $results;
drewish's avatar
drewish committed
687

688
689
  // Populate all core fields on behalf of field.module
  module_load_include('inc', 'devel_generate', 'devel_generate.fields');
690
  devel_generate_fields($node, 'node', $node->type);
691

692
693
  // See devel_generate_node_insert() for actions that happen before and after
  // this save.
694
  node_save($node);
695
}
696
697
698
699
700
701

/*
 * Populate $object->language based on $results
 */
function devel_generate_set_language($results, $object) {
  if (isset($results['add_language'])) {
702
    $languages = $results['add_language'];
703
704
705
    $object->language = $languages[array_rand($languages)];
  }
  else {
706
    $default = language_default('language');
707
708
709
    $object->language =  $default == 'en' ? LANGUAGE_NONE : $default;
  }
}