devel_generate.inc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. <?php
  2. /**
  3. * Generate some random users.
  4. *
  5. * @param $num
  6. * Number of users to generate.
  7. * @param $kill
  8. * Boolean that indicates if existing users should be removed first.
  9. * @param $age
  10. * The max age of each randomly-generated user, in seconds.
  11. * @param $roles
  12. * An array of role IDs that the users should receive.
  13. * @param $pass
  14. * A string to be used as common password for all generated users.
  15. */
  16. function devel_create_users($num, $kill, $age = 0, $roles = array(), $pass = NULL) {
  17. $url = parse_url($GLOBALS['base_url']);
  18. if ($kill) {
  19. $uids = db_select('users', 'u')
  20. ->fields('u', array('uid'))
  21. ->condition('uid', 1, '>')
  22. ->execute()
  23. ->fetchAllAssoc('uid');
  24. user_delete_multiple(array_keys($uids));
  25. drupal_set_message(format_plural(count($uids), '1 user deleted', '@count 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. if ($num > 0) {
  35. $names = array();
  36. while (count($names) < $num) {
  37. $name = devel_generate_word(mt_rand(6, 12));
  38. $names[$name] = '';
  39. }
  40. if (empty($roles)) {
  41. $roles = array(DRUPAL_AUTHENTICATED_RID);
  42. }
  43. foreach ($names as $name => $value) {
  44. $edit = array(
  45. 'uid' => NULL,
  46. 'name' => $name,
  47. 'pass' => $pass,
  48. 'mail' => $name . '@' . $url['host'].'.invalid',
  49. 'status' => 1,
  50. 'created' => REQUEST_TIME - mt_rand(0, $age),
  51. 'roles' => drupal_map_assoc($roles),
  52. 'devel_generate' => TRUE // A flag to let hook_user_* know that this is a generated user.
  53. );
  54. // Populate all core fields on behalf of field.module
  55. module_load_include('inc', 'devel_generate', 'devel_generate.fields');
  56. $edit = (object) $edit;
  57. $edit->language = LANGUAGE_NONE;
  58. devel_generate_fields($edit, 'user', 'user');
  59. $edit = (array) $edit;
  60. $account = user_save(drupal_anonymous_user(), $edit);
  61. if ($pic_config) {
  62. // Since the image.module should scale the picture just pick an
  63. // arbitrary size that it's too big for our font.
  64. $im = imagecreatetruecolor(200, 200);
  65. // Randomize the foreground using the md5 of the user id, then invert it
  66. // for the background color so there's enough contrast to read the text.
  67. $parts = array_map('hexdec', str_split(md5($account->uid), 2));
  68. $fg = imagecolorallocate($im, $parts[1], $parts[3], $parts[5]);
  69. $bg = imagecolorallocate($im, 255 - $parts[0], 255 - $parts[1], 255 - $parts[2]);
  70. // Fill the background then print their user info.
  71. imagefill($im, 0, 0, $bg);
  72. imagestring($im, 5, 5, 5, "#" . $account->uid, $fg);
  73. imagestring($im, 5, 5, 25, $account->name, $fg);
  74. // Create an empty, managed file where we want the user's picture to
  75. // be so we can have GD overwrite it with the image.
  76. $picture_directory = variable_get('file_default_scheme', 'public') . '://' . variable_get('user_picture_path', 'pictures');
  77. file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
  78. $destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '.png');
  79. $file = file_save_data('', $destination);
  80. // GD doesn't like stream wrapped paths so convert the URI to a normal
  81. // file system path.
  82. if (isset($file) && $wrapper = file_stream_wrapper_get_instance_by_uri($file->uri)) {
  83. imagepng($im, $wrapper->realpath());
  84. }
  85. imagedestroy($im);
  86. // Clear the cached filesize, set the owner and MIME-type then re-save
  87. // the file.
  88. clearstatcache();
  89. $file->uid = $account->uid;
  90. $file->filemime = 'image/png';
  91. $file = file_save($file);
  92. // Save the user record with the new picture.
  93. $edit = (array) $account;
  94. $edit['picture'] = $file;
  95. $edit['pass'] = $pass; // Reassign password as it is replaced with the hashed version in $account
  96. user_save($account, $edit);
  97. }
  98. }
  99. }
  100. drupal_set_message(t('!num_users created.', array('!num_users' => format_plural($num, '1 user', '@count users'))));
  101. }
  102. /**
  103. * The main API function for creating content.
  104. *
  105. * See devel_generate_content_form() for the supported keys in
  106. * $form_state['values'].
  107. * Other modules may participate by form_alter() on that form and then handling
  108. * their data during hook_node_insert() or in their own submit handler for the
  109. * form.
  110. *
  111. * @param string $form_state
  112. * @return void
  113. */
  114. function devel_generate_content($form_state) {
  115. if (!empty($form_state['values']['kill_content'])) {
  116. devel_generate_content_kill($form_state['values']);
  117. }
  118. if (count($form_state['values']['node_types'])) {
  119. // Generate nodes.
  120. devel_generate_content_pre_node($form_state['values']);
  121. $start = time();
  122. for ($i = 1; $i <= $form_state['values']['num_nodes']; $i++) {
  123. devel_generate_content_add_node($form_state['values']);
  124. if (function_exists('drush_log') && $i % drush_get_option('feedback', 1000) == 0) {
  125. $now = time();
  126. 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');
  127. $start = $now;
  128. }
  129. }
  130. }
  131. devel_generate_set_message(format_plural($form_state['values']['num_nodes'], '1 node created.', 'Finished creating @count nodes'));
  132. }
  133. function devel_generate_add_comments($node, $users, $max_comments, $title_length = 8) {
  134. $num_comments = mt_rand(1, $max_comments);
  135. for ($i = 1; $i <= $num_comments; $i++) {
  136. $comment = new stdClass;
  137. $comment->nid = $node->nid;
  138. $comment->cid = NULL;
  139. $comment->name = 'devel generate';
  140. $comment->mail = 'devel_generate@example.com';
  141. $comment->timestamp = mt_rand($node->created, REQUEST_TIME);
  142. switch ($i % 3) {
  143. case 1:
  144. $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();
  145. break;
  146. case 2:
  147. $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();
  148. break;
  149. default:
  150. $comment->pid = 0;
  151. }
  152. // The subject column has a max character length of 64
  153. // See bug: http://drupal.org/node/1024340
  154. $comment->subject = substr(devel_create_greeking(mt_rand(2, $title_length), TRUE), 0, 63);
  155. $comment->uid = $users[array_rand($users)];
  156. $comment->language = LANGUAGE_NONE;
  157. // Populate all core fields on behalf of field.module
  158. module_load_include('inc', 'devel_generate', 'devel_generate.fields');
  159. devel_generate_fields($comment, 'comment', 'comment_node_' . $node->type);
  160. comment_save($comment);
  161. }
  162. }
  163. function devel_generate_vocabs($records, $maxlength = 12, $types = array('page', 'article')) {
  164. $vocs = array();
  165. // Insert new data:
  166. for ($i = 1; $i <= $records; $i++) {
  167. $voc = new stdClass();
  168. $voc->name = devel_generate_word(mt_rand(2, $maxlength));
  169. $voc->machine_name = drupal_strtolower($voc->name);
  170. $voc->description = "description of ". $voc->name;
  171. // TODO: not working
  172. $voc->nodes = array_flip(array($types[array_rand($types)]));
  173. foreach ($voc->nodes as $key => $value) {
  174. $voc->nodes[$key] = $key;
  175. }
  176. $voc->multiple = 1;
  177. $voc->required = 0;
  178. $voc->relations = 1;
  179. $voc->hierarchy = 1;
  180. $voc->weight = mt_rand(0,10);
  181. $voc->language = LANGUAGE_NONE;
  182. taxonomy_vocabulary_save($voc);
  183. $vocs[] = $voc->name;
  184. unset($voc);
  185. }
  186. return $vocs;
  187. }
  188. /**
  189. * Generates taxonomy terms for a list of given vocabularies.
  190. *
  191. * @param $records
  192. * int number of terms to create in total.
  193. * @param $vocabs
  194. * array list of vocabs to populate.
  195. * @param $maxlength
  196. * int maximum length per term.
  197. * @return
  198. * array the list of names of the created terms.
  199. */
  200. function devel_generate_terms($records, $vocabs, $maxlength = 12) {
  201. $terms = array();
  202. // Insert new data:
  203. $max = db_query('SELECT MAX(tid) FROM {taxonomy_term_data}')->fetchField();
  204. $start = time();
  205. for ($i = 1; $i <= $records; $i++) {
  206. $term = new stdClass;
  207. switch ($i % 2) {
  208. case 1:
  209. // Set vid and vocabulary_machine_name properties.
  210. $vocab = $vocabs[array_rand($vocabs)];
  211. $term->vid = $vocab->vid;
  212. $term->vocabulary_machine_name = $vocab->machine_name;
  213. // Don't set a parent. Handled by taxonomy_save_term()
  214. // $term->parent = 0;
  215. break;
  216. default:
  217. while (TRUE) {
  218. // Keep trying to find a random parent.
  219. $candidate = mt_rand(1, $max);
  220. $query = db_select('taxonomy_term_data', 't');
  221. $query->innerJoin('taxonomy_vocabulary', 'v', 't.vid = v.vid');
  222. $parent = $query
  223. ->fields('t', array('tid', 'vid'))
  224. ->fields('v', array('machine_name'))
  225. ->condition('v.vid', array_keys($vocabs), 'IN')
  226. ->condition('t.tid', $candidate, '>=')
  227. ->range(0,1)
  228. ->execute()
  229. ->fetchAssoc();
  230. if ($parent['tid']) {
  231. break;
  232. }
  233. }
  234. $term->parent = $parent['tid'];
  235. // Slight speedup due to this property being set.
  236. $term->vocabulary_machine_name = $parent['machine_name'];
  237. $term->vid = $parent['vid'];
  238. break;
  239. }
  240. $term->name = devel_generate_word(mt_rand(2, $maxlength));
  241. $term->description = "description of ". $term->name;
  242. $term->format = filter_fallback_format();
  243. $term->weight = mt_rand(0, 10);
  244. $term->language = LANGUAGE_NONE;
  245. $term->devel_generate = TRUE;
  246. // Populate all core fields on behalf of field.module
  247. module_load_include('inc', 'devel_generate', 'devel_generate.fields');
  248. devel_generate_fields($term, 'taxonomy_term', $term->vocabulary_machine_name);
  249. if ($status = taxonomy_term_save($term)) {
  250. $max += 1;
  251. if (function_exists('drush_log')) {
  252. $feedback = drush_get_option('feedback', 1000);
  253. if ($i % $feedback == 0) {
  254. $now = time();
  255. drush_log(dt('Completed !feedback terms (!rate terms/min)', array('!feedback' => $feedback, '!rate' => $feedback*60 / ($now-$start) )), 'ok');
  256. $start = $now;
  257. }
  258. }
  259. // Limit memory usage. Only report first 20 created terms.
  260. if ($i < 20) {
  261. $terms[] = $term->name;
  262. }
  263. unset($term);
  264. }
  265. }
  266. return $terms;
  267. }
  268. // TODO: use taxonomy_get_entries once that exists.
  269. function devel_generate_get_terms($vids) {
  270. return db_select('taxonomy_term_data', 'td')
  271. ->fields('td', array('tid'))
  272. ->condition('vid', $vids, 'IN')
  273. ->orderBy('tid', 'ASC')
  274. ->execute()
  275. ->fetchCol('tid');
  276. }
  277. /**
  278. * Deletes all terms of a vocabulary.
  279. *
  280. * @param $vid
  281. * int a vocabulary vid.
  282. */
  283. function devel_generate_delete_vocabulary_terms($vid) {
  284. foreach (taxonomy_get_tree($vid) as $term) {
  285. taxonomy_term_delete($term->tid);
  286. }
  287. }
  288. /**
  289. * Deletes all vocabularies.
  290. */
  291. function devel_generate_delete_vocabularies() {
  292. foreach (taxonomy_vocabulary_load_multiple(FALSE) as $vid => $vocab) {
  293. taxonomy_vocabulary_delete($vid);
  294. }
  295. }
  296. /**
  297. * Deletes custom generated menus
  298. */
  299. function devel_generate_delete_menus() {
  300. if (module_exists('menu')) {
  301. foreach (menu_get_menus(FALSE) as $menu => $menu_title) {
  302. if (strpos($menu, 'devel-') === 0) {
  303. $menu = menu_load($menu);
  304. menu_delete($menu);
  305. }
  306. }
  307. }
  308. // Delete menu links generated by devel.
  309. $result = db_select('menu_links', 'm')
  310. ->fields('m', array('mlid'))
  311. ->condition('m.menu_name', 'devel', '<>')
  312. // Look for the serialized version of 'devel' => TRUE.
  313. ->condition('m.options', '%' . db_like('s:5:"devel";b:1') . '%', 'LIKE')
  314. ->execute();
  315. foreach ($result as $link) {
  316. menu_link_delete($link->mlid);
  317. }
  318. }
  319. /**
  320. * Generates new menus.
  321. */
  322. function devel_generate_menus($num_menus, $title_length = 12) {
  323. $menus = array();
  324. if (!module_exists('menu')) {
  325. $num_menus = 0;
  326. }
  327. for ($i = 1; $i <= $num_menus; $i++) {
  328. $menu = array();
  329. $menu['title'] = devel_generate_word(mt_rand(2, max(2, $title_length)));
  330. $menu['menu_name'] = 'devel-' . drupal_strtolower($menu['title']);
  331. $menu['description'] = t('Description of @name', array('@name' => $menu['title']));
  332. menu_save($menu);
  333. $menus[$menu['menu_name']] = $menu['title'];
  334. }
  335. return $menus;
  336. }
  337. /**
  338. * Generates menu links in a tree structure.
  339. */
  340. function devel_generate_links($num_links, $menus, $title_length, $link_types, $max_depth, $max_width) {
  341. $links = array();
  342. $menus = array_keys(array_filter($menus));
  343. $link_types = array_keys(array_filter($link_types));
  344. $nids = array();
  345. for ($i = 1; $i <= $num_links; $i++) {
  346. // Pick a random menu.
  347. $menu_name = $menus[array_rand($menus)];
  348. // Build up our link.
  349. $link = array(
  350. 'menu_name' => $menu_name,
  351. 'options' => array('devel' => TRUE),
  352. 'weight' => mt_rand(-50, 50),
  353. 'mlid' => 0,
  354. 'link_title' => devel_generate_word(mt_rand(2, max(2, $title_length))),
  355. );
  356. $link['options']['attributes']['title'] = t('Description of @title.', array('@title' => $link['link_title']));
  357. // For the first $max_width items, make first level links.
  358. if ($i <= $max_width) {
  359. $depth = 0;
  360. }
  361. else {
  362. // Otherwise, get a random parent menu depth.
  363. $depth = mt_rand(1, max(1, $max_depth - 1));
  364. }
  365. // Get a random parent link from the proper depth.
  366. do {
  367. $link['plid'] = db_select('menu_links', 'm')
  368. ->fields('m', array('mlid'))
  369. ->condition('m.menu_name', $menus, 'IN')
  370. ->condition('m.depth', $depth)
  371. ->range(0, 1)
  372. ->orderRandom()
  373. ->execute()
  374. ->fetchField();
  375. $depth--;
  376. } while (!$link['plid'] && $depth > 0);
  377. if (!$link['plid']) {
  378. $link['plid'] = 0;
  379. }
  380. $link_type = array_rand($link_types);
  381. switch ($link_types[$link_type]) {
  382. case 'node':
  383. // Grab a random node ID.
  384. $select = db_select('node', 'n')
  385. ->fields('n', array('nid', 'title'))
  386. ->condition('n.status', 1)
  387. ->range(0, 1)
  388. ->orderRandom();
  389. // Don't put a node into the menu twice.
  390. if (!empty($nids[$menu_name])) {
  391. $select->condition('n.nid', $nids[$menu_name], 'NOT IN');
  392. }
  393. $node = $select->execute()->fetchAssoc();
  394. if (isset($node['nid'])) {
  395. $nids[$menu_name][] = $node['nid'];
  396. $link['link_path'] = $link['router_path'] = 'node/' . $node['nid'];
  397. $link['link_title'] = $node['title'];
  398. break;
  399. }
  400. case 'external':
  401. $link['link_path'] = 'http://www.example.com/';
  402. break;
  403. case 'front':
  404. $link['link_path'] = $link['router_path'] = '<front>';
  405. break;
  406. default:
  407. $link['devel_link_type'] = $link_type;
  408. break;
  409. }
  410. menu_link_save($link);
  411. $links[$link['mlid']] = $link['link_title'];
  412. }
  413. return $links;
  414. }
  415. function devel_generate_word($length){
  416. mt_srand((double)microtime()*1000000);
  417. $vowels = array("a", "e", "i", "o", "u");
  418. $cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr",
  419. "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl", "sh");
  420. $num_vowels = count($vowels);
  421. $num_cons = count($cons);
  422. $word = '';
  423. while(strlen($word) < $length){
  424. $word .= $cons[mt_rand(0, $num_cons - 1)] . $vowels[mt_rand(0, $num_vowels - 1)];
  425. }
  426. return substr($word, 0, $length);
  427. }
  428. function devel_create_content() {
  429. $nparas = mt_rand(1, 12);
  430. $output = '';
  431. for ($i = 1; $i <= $nparas; $i++) {
  432. $output .= devel_create_para(mt_rand(10,60)) . "\n\n";
  433. }
  434. return $output;
  435. }
  436. function devel_create_para($words, $type = 0) {
  437. $output = '';
  438. switch ($type) {
  439. case 1:
  440. $output .= "<p>" . devel_create_greeking($words) . "</p>";
  441. break;
  442. case 2:
  443. $output .= devel_create_greeking($words) . "<br />";
  444. break;
  445. default:
  446. $output .= devel_create_greeking($words);
  447. }
  448. return $output;
  449. }
  450. function devel_create_greeking($word_count, $title = FALSE) {
  451. $dictionary = array("abbas", "abdo", "abico", "abigo", "abluo", "accumsan",
  452. "acsi", "ad", "adipiscing", "aliquam", "aliquip", "amet", "antehabeo",
  453. "appellatio", "aptent", "at", "augue", "autem", "bene", "blandit",
  454. "brevitas", "caecus", "camur", "capto", "causa", "cogo", "comis",
  455. "commodo", "commoveo", "consectetuer", "consequat", "conventio", "cui",
  456. "damnum", "decet", "defui", "diam", "dignissim", "distineo", "dolor",
  457. "dolore", "dolus", "duis", "ea", "eligo", "elit", "enim", "erat",
  458. "eros", "esca", "esse", "et", "eu", "euismod", "eum", "ex", "exerci",
  459. "exputo", "facilisi", "facilisis", "fere", "feugiat", "gemino",
  460. "genitus", "gilvus", "gravis", "haero", "hendrerit", "hos", "huic",
  461. "humo", "iaceo", "ibidem", "ideo", "ille", "illum", "immitto",
  462. "importunus", "imputo", "in", "incassum", "inhibeo", "interdico",
  463. "iriure", "iusto", "iustum", "jugis", "jumentum", "jus", "laoreet",
  464. "lenis", "letalis", "lobortis", "loquor", "lucidus", "luctus", "ludus",
  465. "luptatum", "macto", "magna", "mauris", "melior", "metuo", "meus",
  466. "minim", "modo", "molior", "mos", "natu", "neo", "neque", "nibh",
  467. "nimis", "nisl", "nobis", "nostrud", "nulla", "nunc", "nutus", "obruo",
  468. "occuro", "odio", "olim", "oppeto", "os", "pagus", "pala", "paratus",
  469. "patria", "paulatim", "pecus", "persto", "pertineo", "plaga", "pneum",
  470. "populus", "praemitto", "praesent", "premo", "probo", "proprius",
  471. "quadrum", "quae", "qui", "quia", "quibus", "quidem", "quidne", "quis",
  472. "ratis", "refero", "refoveo", "roto", "rusticus", "saepius",
  473. "sagaciter", "saluto", "scisco", "secundum", "sed", "si", "similis",
  474. "singularis", "sino", "sit", "sudo", "suscipere", "suscipit", "tamen",
  475. "tation", "te", "tego", "tincidunt", "torqueo", "tum", "turpis",
  476. "typicus", "ulciscor", "ullamcorper", "usitas", "ut", "utinam",
  477. "utrum", "uxor", "valde", "valetudo", "validus", "vel", "velit",
  478. "veniam", "venio", "vereor", "vero", "verto", "vicis", "vindico",
  479. "virtus", "voco", "volutpat", "vulpes", "vulputate", "wisi", "ymo",
  480. "zelus");
  481. $dictionary_flipped = array_flip($dictionary);
  482. $greeking = '';
  483. if (!$title) {
  484. $words_remaining = $word_count;
  485. while ($words_remaining > 0) {
  486. $sentence_length = mt_rand(3, 10);
  487. $words = array_rand($dictionary_flipped, $sentence_length);
  488. $sentence = implode(' ', $words);
  489. $greeking .= ucfirst($sentence) . '. ';
  490. $words_remaining -= $sentence_length;
  491. }
  492. }
  493. else {
  494. // Use slightly different method for titles.
  495. $words = array_rand($dictionary_flipped, $word_count);
  496. $words = is_array($words) ? implode(' ', $words) : $words;
  497. $greeking = ucwords($words);
  498. }
  499. // Work around possible php garbage collection bug. Without an unset(), this
  500. // function gets very expensive over many calls (php 5.2.11).
  501. unset($dictionary, $dictionary_flipped);
  502. return trim($greeking);
  503. }
  504. function devel_generate_add_terms(&$node) {
  505. $vocabs = taxonomy_get_vocabularies($node->type);
  506. foreach ($vocabs as $vocab) {
  507. $sql = "SELECT tid FROM {taxonomy_term_data} WHERE vid = :vid ORDER BY RAND()";
  508. $result = db_query_range($sql, 0, 5 , array(':vid' => $vocab->vid));
  509. foreach($result as $row) {
  510. $node->taxonomy[] = $row->tid;
  511. if (!$vocab->multiple) {
  512. break;
  513. }
  514. }
  515. }
  516. }
  517. function devel_get_users() {
  518. $users = array();
  519. $result = db_query_range("SELECT uid FROM {users}", 0, 50);
  520. foreach ($result as $record) {
  521. $users[] = $record->uid;
  522. }
  523. return $users;
  524. }
  525. /**
  526. * Generate statistics information for a node.
  527. *
  528. * @param $node
  529. * A node object.
  530. */
  531. function devel_generate_add_statistics($node) {
  532. $statistic = array(
  533. 'nid' => $node->nid,
  534. 'totalcount' => mt_rand(0, 500),
  535. 'timestamp' => REQUEST_TIME - mt_rand(0, $node->created),
  536. );
  537. $statistic['daycount'] = mt_rand(0, $statistic['totalcount']);
  538. db_insert('node_counter')->fields($statistic)->execute();
  539. }
  540. /**
  541. * Handle the devel_generate_content_form request to kill all of the content.
  542. * This is used by both the batch and non-batch branches of the code.
  543. *
  544. * @param $num
  545. * array of options obtained from devel_generate_content_form.
  546. */
  547. function devel_generate_content_kill($values) {
  548. $results = db_select('node', 'n')
  549. ->fields('n', array('nid'))
  550. ->condition('type', $values['node_types'], 'IN')
  551. ->execute();
  552. foreach ($results as $result) {
  553. $nids[] = $result->nid;
  554. }
  555. if (!empty($nids)) {
  556. node_delete_multiple($nids);
  557. drupal_set_message(t('Deleted %count nodes.', array('%count' => count($nids))));
  558. }
  559. }
  560. /**
  561. * Pre-process the devel_generate_content_form request. This is needed so
  562. * batch api can get the list of users once. This is used by both the batch
  563. * and non-batch branches of the code.
  564. *
  565. * @param $num
  566. * array of options obtained from devel_generate_content_form.
  567. */
  568. function devel_generate_content_pre_node(&$results) {
  569. // Get user id.
  570. $users = devel_get_users();
  571. $users = array_merge($users, array('0'));
  572. $results['users'] = $users;
  573. }
  574. /**
  575. * Create one node. Used by both batch and non-batch code branches.
  576. *
  577. * @param $results
  578. * array of options obtained from devel_generate_content_form. If call
  579. * this function directly, $results should contain at the very least:
  580. * node_types => an associative array of node type machine names
  581. * users => an array of UIDs
  582. * title_length => max number of words in titles, for example 4.
  583. */
  584. function devel_generate_content_add_node(&$results) {
  585. $node = new stdClass();
  586. $node->nid = NULL;
  587. // Insert new data:
  588. $node->type = array_rand($results['node_types']);
  589. node_object_prepare($node);
  590. $users = $results['users'];
  591. $node->uid = $users[array_rand($users)];
  592. $type = node_type_get_type($node);
  593. $node->revision = mt_rand(0,1);
  594. $node->promote = mt_rand(0, 1);
  595. if (!$type || $type->has_title) {
  596. // We should not use the random function if the value is not random
  597. if ($results['title_length'] < 2) {
  598. $node->title = devel_create_greeking(1, TRUE);
  599. }
  600. else {
  601. $node->title = devel_create_greeking(mt_rand(1, $results['title_length']), TRUE);
  602. }
  603. }
  604. // Avoid NOTICE.
  605. if (!isset($results['time_range'])) {
  606. $results['time_range'] = 0;
  607. }
  608. devel_generate_set_language($results, $node);
  609. $node->created = REQUEST_TIME - mt_rand(0, $results['time_range']);
  610. // A flag to let hook_node_insert() implementations know that this is a
  611. // generated node.
  612. $node->devel_generate = $results;
  613. // Populate all core fields on behalf of field.module
  614. module_load_include('inc', 'devel_generate', 'devel_generate.fields');
  615. devel_generate_fields($node, 'node', $node->type);
  616. // See devel_generate_node_insert() for actions that happen before and after
  617. // this save.
  618. node_save($node);
  619. }
  620. /*
  621. * Populate $object->language based on $results
  622. */
  623. function devel_generate_set_language($results, $object) {
  624. if (isset($results['add_language'])) {
  625. $languages = $results['add_language'];
  626. $object->language = $languages[array_rand($languages)];
  627. }
  628. else {
  629. $default = language_default('language');
  630. $object->language = $default == 'en' ? LANGUAGE_NONE : $default;
  631. }
  632. }