devel_generate.inc 14.8 KB
Newer Older
1 2 3 4 5 6 7
<?php
// $Id$
// If not in 'safe mode', increase the maximum execution time:
if (!ini_get('safe_mode')) {
  set_time_limit(240);
}

8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/**
 * Generate some random users.
 *
 * @param $num
 *  Number of users to generate.
 * @param $kill
 *  Boolean that indicates if existing users should be removed first.
 */
function devel_create_users($num, $kill) {
  $url = parse_url($GLOBALS['base_url']);
  if ($kill) {
    db_query('DELETE FROM {users} WHERE uid > 1');
    drupal_set_message(t('Users deleted.'));
  }
  for ($i = 0; $i < $num; $i++) {
23
    $length = rand(6, 12);
24 25 26 27
    $name = devel_generate_word($length);
    $pass = md5(user_password());
    $mail = $name .'@'. $url['host'];
    $now = time();
28
    db_query("INSERT INTO {users} (name, pass, mail, status, created, access) VALUES ('%s', '%s', '%s', %d, %d, %d)", $name, $pass, $mail, 1, $now, $now);
29 30 31 32
  }
  drupal_set_message(t('!num_users created.', array('!num_users' => format_plural($num, '1 user', '@count users'))));
}

33
function devel_generate_content($num_nodes, $num_comments, $title_length, $kill, $add_upload = FALSE, $add_terms = FALSE, $add_alias = FALSE, $node_types) {
34
  if ($kill) {
35 36 37 38
    $sql = 'SELECT nid FROM {node} WHERE type IN ('. db_placeholders($node_types, 'text'). ')';
    $result = db_query($sql, $node_types);
    while ($row = db_fetch_object($result)) {
      node_delete($row->nid);
39 40 41 42 43 44
    }
  }

  // Get user id.
  $users = devel_get_users();

45
  // Create $num_nodes pseudo-random nodes and comments (if specified)
46
  devel_create_nodes($num_nodes, $users, $title_length, $add_upload, $add_terms, $num_comments, $add_alias, $node_types);
47
  drupal_set_message(format_plural($num_nodes, '1 node created.', '@count nodes created'));
48
}
49

50
function devel_create_nodes($records, $users, $title_length = 8, $add_upload = FALSE, $add_terms = FALSE, $num_comments = 0, $add_alias = FALSE, $node_types = array()) {
51
  
52
  $users = array_merge($users, array('0'));
53
  // $nids = array();
54

55
  if (count($node_types)) {
56 57
    // Insert new data:
    for ($i = 1; $i <= $records; $i++) {
58
      $node->type = $node_types[array_rand($node_types)];
59 60 61
      require_once './modules/node/node.pages.inc';
      node_object_prepare($node);
      $node->uid = $users[array_rand($users)];
62

63
      $node->title = devel_create_greeking(rand(1, $title_length), TRUE);
64
      $node->body = "node ($node->type) - ". devel_create_content();
65 66
      $node->teaser = node_teaser($node->body);
      $node->filter = variable_get('filter_default_format', 1);
67
      $node->format = FILTER_FORMAT_DEFAULT;
68
      $node->language = '';
69 70 71
      $node->revision = rand(0,1);
      $node->promote = rand(0, 1);
      $node->created = time();
72 73
      
      // Add an url alias
74
      // TODO: the nid is not known yet. move back to post creation.
75 76 77 78 79 80 81 82 83 84 85 86
      // if ($add_alias) {
      //   $node->path = "node-$node->nid-$node->type";
      // }
      
      if ($add_upload) {
        devel_generate_add_upload($node);
      }
      
      if ($add_terms) {
        devel_generate_add_terms($node);
      }
      
87 88 89 90 91
      // Populate any CCK fields in the content type
      if (module_exists("content")) {
        devel_generate_fields($node);
      }
      
92 93
      // Save the node:
      node_save($node);
94 95 96 97
      
      if ($num_comments) {
        devel_generate_add_comments($node, $users, $num_comments, $title_length);
      }
98 99 100 101 102 103

      unset($node);
    }
  }
}

104
function devel_generate_add_comments($node, $users, $num_comments, $title_length = 8) {
105
  // Insert new data:
106 107 108 109 110 111
  for ($i = 1; $i <= $num_comments; $i++) {
    $comment->nid = $node->nid;
    $comment->cid = NULL;
    $comment->format = FILTER_FORMAT_DEFAULT;
    $comment->name = 'devel generate';
    $comment->mail = 'devel_generate@example.com';
112 113 114

    switch ($i % 3) {
      case 1:
115
        $comment->pid = db_result(db_query_range("SELECT cid FROM {comments} WHERE pid = 0 AND nid = %d ORDER BY RAND()", $comment->nid, 0, 1));
116 117
        break;
      case 2:
118
        $comment->pid = db_result(db_query("SELECT cid FROM {comments} WHERE pid > 0 AND nid = %d ORDER BY RAND()", $comment->nid, 0, 1));
119 120 121 122 123
        break;
      default:
        $comment->pid = 0;
    }

124 125
    $comment->subject = devel_create_greeking(rand(1, $title_length), TRUE);
    $comment->comment = devel_create_content();
126 127
    $comment->uid = $users[array_rand($users)];

128 129
    // this is slow but gets the threading right.
    comment_save((array)$comment);
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
function devel_generate_vocabs($records, $maxlength = 12, $types = array('story', 'blog', 'forum', 'page')) {
  $vocs = array();

  // Insert new data:
  for ($i = 1; $i <= $records; $i++) {
    $voc = array();
    $voc['name'] = devel_generate_word(rand(2, $maxlength));
    $voc['description'] = "description of ". $voc['name'];
    $voc['nodes'] = array_flip(array($types[array_rand($types)]));
    foreach ($voc['nodes'] as $key => $value) {
      $voc['nodes'][$key] = $key;
    }
    $voc['multiple'] = 1;
    $voc['required'] = 0;
    $voc['relations'] = 1;
    $voc['hierarchy'] = 1;
    $voc['weight'] = rand(0,10);

    taxonomy_save_vocabulary($voc);
    $vocs[] = $voc['name'];
  }
  return $vocs;
}

function devel_generate_terms($records, $vocs, $maxlength = 12) {
  $terms = array();

  // Insert new data:
  for ($i = 1; $i <= $records; $i++) {
    switch ($i % 2) {
      case 1:
        $term['vid'] = $vocs[array_rand($vocs)];
        // dont set a parent. handled by taxonomy_save_term()
        // $term->parent = 0;
        break;
      case 2:
      default:
        $parent = db_fetch_object(db_query_range("SELECT t.tid, v.vid FROM {term_data} t INNER JOIN {vocabulary} v ON t.vid = v.vid ORDER BY RAND()", 0, 1));
        $term['parent'] = array($parent->tid);
        $term['vid'] = $parent->vid;
        break;
    }

    $term['name'] = devel_generate_word(rand(2, $maxlength));
    $term['description'] = "description of ". $term['name'];
    $term['weight'] = rand(0,10);

    $status = taxonomy_save_term($term);
    $output = NULL;

    if ($status) {
      $terms[] = $term['name'];
    }

    unset($term);
  }
  return $terms;
}

function devel_generate_get_vocabs() {
  $vocs = array();
  $result = db_query("SELECT vid FROM {vocabulary}");
  while($voc = db_fetch_object($result)){
    $vocs[] = $voc->vid;
  }
  return $vocs;
}

function devel_generate_taxonomy_data($num_vocab, $num_terms, $title_length, $kill) {

  if ($kill) {
    db_query("DELETE FROM {term_data}");
    db_query("DELETE FROM {term_node}");
    db_query("DELETE FROM {term_hierarchy}");
    db_query("DELETE FROM {term_relation}");
    db_query("DELETE FROM {term_synonym}");
    db_query("DELETE FROM {vocabulary}");
    db_query("DELETE FROM {vocabulary_node_types}");
    switch ($GLOBALS['db_type']) {
      case 'mysql':
      case 'mysqli':
        db_query("ALTER TABLE {vocabulary} AUTO_INCREMENT = 1");
        db_query("ALTER TABLE {term_data} AUTO_INCREMENT = 1");
        break;
      case 'pgsql':
        db_query("SELECT setval('{vocabulary}_vid_seq', 1, false)");
        db_query("SELECT setval('{term_data}_tid_seq', 1, false)");
        break;
    }
    drupal_set_message(t('Deleted taxonomy.'));
  }

  $new_vocs = devel_generate_vocabs($num_vocab, $title_length);
  if (!empty($new_vocs)) {
    drupal_set_message(t('Created the following new vocabularies: !vocs', array('!vocs' => theme('item_list', $new_vocs))));
  }
  $vocs = devel_generate_get_vocabs();
  $new_terms = devel_generate_terms($num_terms, $vocs, $title_length);
  if (!empty($new_terms)) {
    drupal_set_message(t('Created the following new terms: !terms', array('!terms' => theme('item_list', $new_terms))));
  }
}

function devel_generate_word($length){
  srand((double)microtime()*1000000);

  $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){
    $word .= $cons[rand(0, $num_cons - 1)] . $vowels[rand(0, $num_vowels - 1)];
  }

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

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
function devel_create_content() {
  $nparas = rand(1,12);
  $type = rand(0,3);

  $output = "";
  switch($type % 3) {
    case 1: // html
      for ($i = 1; $i <= $nparas; $i++) {
        $output .= devel_create_para(rand(10,60),1);
      }
      break;

    case 2: // brs only
      for ($i = 1; $i <= $nparas; $i++) {
        $output .= devel_create_para(rand(10,60),2);
      }
      break;

    default: // plain text
      for ($i = 1; $i <= $nparas; $i++) {
        $output .= devel_create_para(rand(10,60)) ."\n\n";
      }
  }

  return $output;
}

function devel_create_para($words, $type = 0) {
  $output = "";
  switch ($type) {
    case 1:
      $output .= "<p>";
      $output .= devel_create_greeking($words);
      $output = trim($output) ."</p>";
      break;

    case 2:
      $output .= devel_create_greeking($words);
      $output = trim($output) ."<br />";
      break;

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

function devel_create_greeking($words, $title = FALSE) {
  $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");

  $greeking = "";

  if (!$title) {
	  while ($words > 0) {
	    $sentence_length = rand(3,10);
340

341 342 343 344
	    $greeking .= ucfirst($dictionary[array_rand($dictionary)]);
	    for ($i = 1; $i < $sentence_length; $i++) {
	      $greeking .= " " . $dictionary[array_rand($dictionary)];
	    }
345

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
	    $greeking .= ". ";
	    $words -= $sentence_length;
	  }
  }
  else {
  	// use different method for titles
  	$title_length = $words;
  	$array = array();
  	for ($i = 0; $i < $words; $i++) {
  		$array[] = $dictionary[array_rand($dictionary)];
  	}
  	$greeking = ucwords(implode(' ', $array));
  }
  return $greeking;
}

362
function devel_generate_add_terms(&$node) {
363 364
  $vocabs = taxonomy_get_vocabularies($node->type);
  foreach ($vocabs as $vocab) {
365
    $sql = "SELECT tid FROM {term_data} WHERE vid = %d ORDER BY RAND()";
366 367 368 369 370 371 372 373 374 375 376
    $result = db_query_range($sql, $vocab->vid, 0, 5);
    while ($row = db_fetch_object($result)) {
      if ($vocab->tags) {
        $node->taxonomy['tags'][] = $row->tid;
      }
      else {
        $node->taxonomy[$row->tid] = $row->tid;
      }
      if (!$vocab->multiple) {
        break;
      }
377 378 379 380 381 382
    }
  }
}

function devel_get_users() {
  $users = array();
383
  $result = db_query_range("SELECT uid FROM {users}", 0, 50);
384 385 386 387 388 389
  while($user = db_fetch_object($result)){
    $users[] = $user->uid;
  }
  return $users;
}

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
function devel_generate_add_upload(&$node) {
  $source = 'misc/blog.png';
  $size = filesize($source);
  
  // $after this call, $source contains the new path.
  file_copy($source);
  $file = new stdClass();
  $file->filename = 'blog.png';
  $file->filepath = $source;
  $file->filemime = 'image/png';
  $file->list = variable_get('upload_list_default', TRUE);
  $file->description = 'b log.png was here';
  $file->filesize = $size;

  // If we made it this far it's safe to record this file in the database.
  db_query("INSERT INTO {files} (uid, filename, filepath, filemime, filesize, status, timestamp) VALUES (%d, '%s', '%s', '%s', %d, %d, %d)", $node->uid, $file->filename, $file->filepath, $file->filemime, $file->filesize, FILE_STATUS_TEMPORARY, time());
  $file->fid = db_last_insert_id('files', 'fid');
  
  $_SESSION['upload_files'][$file->fid] = $file;
  $node->files[$file->fid] = $file;
410 411
}

412 413 414 415 416 417 418 419
/**
 * Enrich the $node that is about to be saved with arbitrary information in each of its CCK fields.
 * Not yet implemented by CCK fields. See http://drupal.org/node/187599 for status.
 *
 * Borrows from _content_field_invoke() but calls fields multiple times if content.module handles multiples.
 * 
 * @return void
 **/
420
function devel_generate_fields(&$node) {
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
  $type_name = $node->type;
  $type = content_types($type_name);
  $field_types = _content_field_types();

  $return = array();
  if (!empty($type['fields'])) {
    foreach ($type['fields'] as $field) {
      // If module handles own multiples, then only call its hook once.
      if (content_callback('field', 'multiple values', $field) != CONTENT_CALLBACK_DEFAULT) {
        $max = 1;
      }
      else {
        switch ($field['multiple']) {
          case 0:
            $max = 0;
            break;
          case 1:
            $max = 2; //just an arbitrary number for 'unlimited'
            break;
          default:
            $max = $field['multiple'];
            break;
        }
      }

      for ($i=0; $i <= $max; $i++) {
         $module = $field_types[$field['type']]['module'];
        $function = $module .'_content_generate';
        if (function_exists($function)) {
          $result = $function($op, $node, $field); // $items, $teaser, $page
          if (is_array($result)) {
            $return = array_merge($return, $result);
          }
          else if (isset($result)) {
            $return[] = $result;
          }
        }
      }

      $node->$field['field_name'] = $return;
    }
  }
463
}