GenerateData - Make the generated sample data more stable (wrt shuffle+array_rand)
[civicrm-core.git] / CRM / Core / CodeGen / GenerateData.php
CommitLineData
3a2a6e86
TO
1<?php
2
3class CRM_Core_CodeGen_GenerateData {
4
5 /**
6 * Constants
7 */
8
9 // Set ADD_TO_DB = FALSE to do a dry run
10 const ADD_TO_DB = TRUE;
11
12 const DATA_FILENAME = "sample_data.xml";
13 const NUM_DOMAIN = 1;
14 const NUM_CONTACT = 200;
15 const INDIVIDUAL_PERCENT = 80;
16 const HOUSEHOLD_PERCENT = 10;
17 const ORGANIZATION_PERCENT = 10;
18 const NUM_INDIVIDUAL_PER_HOUSEHOLD = 4;
19 const NUM_ACTIVITY = 150;
20
21 // Location types from the table crm_location_type
22 const HOME = 1;
23 const WORK = 2;
24 const MAIN = 3;
25 const OTHER = 4;
26
27 /**
28 * Class constructor
29 */
849e0b97 30 public function __construct($seed = '123456789') {
3a2a6e86 31 // initialize all the vars
849e0b97 32 $this->seed = $seed;
82d32482 33 $this->time = strtotime(date('Y') . '-01-01 02:03:04');
3a2a6e86
TO
34 $this->numIndividual = self::INDIVIDUAL_PERCENT * self::NUM_CONTACT / 100;
35 $this->numHousehold = self::HOUSEHOLD_PERCENT * self::NUM_CONTACT / 100;
36 $this->numOrganization = self::ORGANIZATION_PERCENT * self::NUM_CONTACT / 100;
37 $this->numStrictIndividual = $this->numIndividual - ($this->numHousehold * self::NUM_INDIVIDUAL_PER_HOUSEHOLD);
38
39 // Parse data file
d94d506c 40 foreach ((array) simplexml_load_file(self::getCivicrmDir() . '/sql/' . self::DATA_FILENAME) as $key => $val) {
3a2a6e86
TO
41 $val = (array) $val;
42 $this->sampleData[$key] = (array) $val['item'];
43 }
44 // Init DB
45 $config = CRM_Core_Config::singleton();
46
47 // Relationship types indexed by name_a_b from the table civicrm_relationship_type
48 $this->relTypes = CRM_Utils_Array::index(array('name_a_b'), CRM_Core_PseudoConstant::relationshipType('name'));
49
50 }
51
52 /**
53 * Public wrapper for calling private "add" functions
54 * Provides user feedback
55 * @param $itemName
56 */
57 public function generate($itemName) {
58 echo "Generating $itemName\n";
59 $fn = "add$itemName";
60 $this->$fn();
61 }
62
63 /**
64 * this function creates arrays for the following
65 *
66 * domain id
67 * contact id
68 * contact_location id
69 * contact_contact_location id
70 * contact_email uuid
71 * contact_phone_uuid
72 * contact_instant_message uuid
73 * contact_relationship uuid
74 * contact_task uuid
75 * contact_note uuid
76 */
77 public function initID() {
78 // get the domain and contact id arrays
79 $this->domain = range(1, self::NUM_DOMAIN);
0049e17a 80 $this->domain = $this->shuffle($this->domain);
3a2a6e86
TO
81
82 // Get first contact id
83 $this->startCid = $cid = CRM_Core_DAO::singleValueQuery("SELECT MAX(id) FROM civicrm_contact");
84 $this->contact = range($cid + 1, $cid + self::NUM_CONTACT);
0049e17a 85 $this->contact = $this->shuffle($this->contact);
3a2a6e86
TO
86
87 // get the individual, household and organizaton contacts
88 $offset = 0;
89 $this->Individual = array_slice($this->contact, $offset, $this->numIndividual);
90 $offset += $this->numIndividual;
91 $this->Household = array_slice($this->contact, $offset, $this->numHousehold);
92 $offset += $this->numHousehold;
93 $this->Organization = array_slice($this->contact, $offset, $this->numOrganization);
94
95 // get the strict individual contacts (i.e individual contacts not belonging to any household)
96 $this->strictIndividual = array_slice($this->Individual, 0, $this->numStrictIndividual);
97
98 // get the household to individual mapping array
99 $this->householdIndividual = array_slice($this->Individual, $this->numStrictIndividual);
100 $this->householdIndividual = array_chunk($this->householdIndividual, self::NUM_INDIVIDUAL_PER_HOUSEHOLD);
101 $this->householdIndividual = array_combine($this->Household, $this->householdIndividual);
102 }
103
104 /*
105 * private members
106 *
107 */
108
849e0b97
TO
109 /**
110 * @var int
111 */
112 private $seed;
113
3a2a6e86
TO
114 /**
115 * enum's from database
116 * @var array
117 */
118 private $preferredCommunicationMethod = array('1', '2', '3', '4', '5');
119 private $contactType = array('Individual', 'Household', 'Organization');
120 private $phoneType = array('1', '2', '3', '4');
121
122 /**
123 * customizable enums (foreign keys)
124 * @var array
125 */
126 private $prefix = array(
127 // Female
128 1 => array(
129 1 => 'Mrs.',
130 2 => 'Ms.',
131 4 => 'Dr.',
132 ),
133 // Male
134 2 => array(
135 3 => 'Mr.',
136 4 => 'Dr.',
137 ),
138 );
139 /**
140 * @var array
141 */
142 private $suffix = array(1 => 'Jr.', 2 => 'Sr.', 3 => 'II', 4 => 'III');
143 private $gender = array(1 => 'female', 2 => 'male');
144
145 /**
146 * store domain id's
147 * @var array
148 */
149 private $domain = array();
150
151 /**
152 * store contact id's
153 * @var array
154 */
155 private $contact = array();
156 private $Individual = array();
157 private $Household = array();
158 private $Organization = array();
159
160 // store which contacts have a location entity
161 /**
162 * for automatic management of is_primary field
163 * @var array
164 */
165 private $location = array(
166 'Email' => array(),
167 'Phone' => array(),
168 'Address' => array(),
169 );
170
171 /**
172 * stores the strict individual id and household id to individual id mapping
173 * @var array
174 */
175 private $strictIndividual = array();
176 private $householdIndividual = array();
177 private $householdName = array();
178
179 /**
180 * sample data in xml format
181 * @var array
182 */
183 private $sampleData = array();
184
185 /**
186 * private vars
187 * @var array
188 */
189 private $startCid;
190 private $numIndividual = 0;
191 private $numHousehold = 0;
192 private $numOrganization = 0;
193 private $numStrictIndividual = 0;
194 private $stateMap = array();
195 private $states = array();
196
197 private $groupMembershipStatus = array('Added', 'Removed', 'Pending');
198 private $subscriptionHistoryMethod = array('Admin', 'Email');
199 private $deceasedContactIds = array();
200
201 /*********************************
202 * private methods
203 * *******************************
3a2a6e86
TO
204 */
205
38cdbfc7
TO
206 /**
207 * Random number generator.
208 *
209 * All other random() functions should derive from this.
210 *
849e0b97
TO
211 * This is very weak RNG. The goal is to provide a reproducible sequence of
212 * random-ish values for generating dummy-data.
213 *
38cdbfc7
TO
214 * @param int $min
215 * @param int $max
216 * @return int
217 */
218 private function randomInt($min, $max) {
849e0b97
TO
219 $range = min(1 + $max - $min, mt_getrandmax());
220 $this->seed = md5($this->seed . chr(0) . $min . chr(0) . $max);
221 return $min + (hexdec(substr($this->seed, 20, 8)) % $range);
38cdbfc7
TO
222 }
223
3a2a6e86
TO
224 /**
225 * Get a randomly generated string.
226 *
227 * @param int $size
228 *
229 * @return string
230 */
231 private function randomString($size = 32) {
232 $string = "";
233
234 // get an ascii code for each character
235 for ($i = 0; $i < $size; $i++) {
38cdbfc7 236 $random_int = $this->randomInt(65, 122);
3a2a6e86
TO
237 if (($random_int < 97) && ($random_int > 90)) {
238 // if ascii code between 90 and 97 substitute with space
239 $random_int = 32;
240 }
241 $random_char = chr($random_int);
242 $string .= $random_char;
243 }
244 return $string;
245 }
246
247 /**
248 * @return string
249 */
250 private function randomChar() {
38cdbfc7 251 return chr($this->randomInt(65, 90));
3a2a6e86
TO
252 }
253
254 /**
255 * Get a random item from the sample data or any other array
256 *
257 * @param $items (array or string) - if string, used as key for sample data, if array, used as data source
258 *
259 * @return mixed (element from array)
260 *
261 * @private
262 */
263 private function randomItem($items) {
264 if (!is_array($items)) {
265 $key = $items;
266 $items = $this->sampleData[$key];
267 }
268 if (!$items) {
269 echo "Error: no items found for '$key'\n";
270 return FALSE;
271 }
38cdbfc7 272 return $items[$this->randomInt(0, count($items) - 1)];
3a2a6e86
TO
273 }
274
275 /**
276 * @param $items
277 *
278 * @return mixed
279 */
280 private function randomIndex($items) {
281 return $this->randomItem(array_keys($items));
282 }
283
284 /**
285 * @param $items
286 *
287 * @return array
288 */
289 private function randomKeyValue($items) {
290 $key = $this->randomIndex($items);
291 return array($key, $items[$key]);
292 }
293
0049e17a
TO
294 private function shuffle($array) {
295 for ($i = count($array) - 1; $i >= 1; $i--) {
296 $j = $this->randomInt(0, $i);
297 $tmp = $array[$i];
298 $array[$i] = $array[$j];
299 $array[$j] = $tmp;
300 }
301 return $array;
302 }
303
3a2a6e86
TO
304 /**
305 * @param $chance
306 *
307 * @return int
308 */
309 private function probability($chance) {
38cdbfc7 310 if ($this->randomInt(0, 100) < ($chance * 100)) {
3a2a6e86
TO
311 return 1;
312 }
313 return 0;
314 }
315
316 /**
317 * Generate a random date.
318 *
319 * If both $startDate and $endDate are defined generate
320 * date between them.
321 *
322 * If only startDate is specified then date generated is
323 * between startDate + 1 year.
324 *
325 * if only endDate is specified then date generated is
326 * between endDate - 1 year.
327 *
328 * if none are specified - date is between today - 1year
329 * and today
330 *
331 * @param int $startDate Start Date in Unix timestamp
332 * @param int $endDate End Date in Unix timestamp
333 * @access private
334 *
335 * @return string randomly generated date in the format "Ymd"
336 *
337 */
338 private function randomDate($startDate = 0, $endDate = 0) {
339
340 // number of seconds per year
341 $numSecond = 31536000;
342 $dateFormat = "YmdHis";
82d32482 343 $today = $this->time;
3a2a6e86
TO
344
345 // both are defined
346 if ($startDate && $endDate) {
38cdbfc7 347 return date($dateFormat, $this->randomInt($startDate, $endDate));
3a2a6e86
TO
348 }
349
350 // only startDate is defined
351 if ($startDate) {
38cdbfc7 352 return date($dateFormat, $this->randomInt($startDate, $startDate + $numSecond));
3a2a6e86
TO
353 }
354
355 // only endDate is defined
356 if ($startDate) {
38cdbfc7 357 return date($dateFormat, $this->randomInt($endDate - $numSecond, $endDate));
3a2a6e86
TO
358 }
359
360 // none are defined
38cdbfc7 361 return date($dateFormat, $this->randomInt($today - $numSecond, $today));
3a2a6e86
TO
362 }
363
364 /**
365 * Automatically manage the is_primary field by tracking which contacts have each item
366 * @param $cid
367 * @param $type
368 * @return int
369 */
370 private function isPrimary($cid, $type) {
371 if (empty($this->location[$type][$cid])) {
372 $this->location[$type][$cid] = TRUE;
373 return 1;
374 }
375 return 0;
376 }
377
378 /**
379 * Execute a query unless we are doing a dry run
380 * Note: this wrapper should not be used for SELECT queries
381 * @param $query
382 * @param array $params
383 * @return \CRM_Core_DAO
384 */
385 private function _query($query, $params = array()) {
386 if (self::ADD_TO_DB) {
387 return CRM_Core_DAO::executeQuery($query, $params);
388 }
389 }
390
391 /**
392 * Call dao insert method unless we are doing a dry run
393 * @param $dao
394 */
395 private function _insert(&$dao) {
396 if (self::ADD_TO_DB) {
397 if (!$dao->insert()) {
398 echo "ERROR INSERT: " . mysqli_error($dao->getConnection()->connection) . "\n";
399 print_r($dao);
400 exit(1);
401 }
402 }
403 }
404
405 /**
406 * Call dao update method unless we are doing a dry run
407 * @param $dao
408 */
409 private function _update(&$dao) {
410 if (self::ADD_TO_DB) {
411 if (!$dao->update()) {
412 echo "ERROR UPDATE: " . mysqli_error($dao->getConnection()->connection) . "\n";
413 print_r($dao);
414 exit(1);
415 }
416 }
417 }
418
419 /**
420 * Add core DAO object
421 * @param $type
422 * @param $params
423 */
424 private function _addDAO($type, $params) {
425 $daoName = "CRM_Core_DAO_$type";
426 $obj = new $daoName();
427 foreach ($params as $key => $value) {
428 $obj->$key = $value;
429 }
430 if (isset($this->location[$type])) {
431 $obj->is_primary = $this->isPrimary($params['contact_id'], $type);
432 }
433 $this->_insert($obj);
434 }
435
436 /**
437 * Fetch contact type based on stored mapping
438 * @param $id
439 * @return string $type
440 */
441 private function getContactType($id) {
442 foreach (array('Individual', 'Household', 'Organization') as $type) {
443 if (in_array($id, $this->$type)) {
444 return $type;
445 }
446 }
447 }
448
449 /**
450 * This method adds NUM_DOMAIN domains and then adds NUM_REVISION
451 * revisions for each domain with the latest revision being the last one..
452 */
453 private function addDomain() {
454
455 /* Add a location for domain 1 */
456
457 $domain = new CRM_Core_DAO_Domain();
458 for ($id = 2; $id <= self::NUM_DOMAIN; $id++) {
459 // domain name is pretty simple. it is "Domain $id"
460 $domain->name = "Domain $id";
461 $domain->description = "Description $id";
462 $domain->contact_name = $this->randomName();
463
464 // insert domain
465 $this->_insert($domain);
466 }
467 }
468
469 /**
470 * @return string
471 */
472 public function randomName() {
473 $first_name = $this->randomItem(($this->probability(.5) ? 'fe' : '') . 'male_name');
474 $middle_name = ucfirst($this->randomChar());
475 $last_name = $this->randomItem('last_name');
476 return "$first_name $middle_name. $last_name";
477 }
478
479 /**
480 * This method adds data to the contact table
481 *
482 * id - from $contact
483 * contact_type 'Individual' 'Household' 'Organization'
484 * preferred_communication (random 1 to 3)
485 */
486 private function addContact() {
487 $contact = new CRM_Contact_DAO_Contact();
488 $cid = $this->startCid;
489
490 for ($id = $cid + 1; $id <= $cid + self::NUM_CONTACT; $id++) {
491 $contact->contact_type = $this->getContactType($id);
492 $contact->do_not_phone = $this->probability(.2);
493 $contact->do_not_email = $this->probability(.2);
494 $contact->do_not_post = $this->probability(.2);
495 $contact->do_not_trade = $this->probability(.2);
496 $contact->preferred_communication_method = NULL;
497 if ($this->probability(.5)) {
498 $contact->preferred_communication_method = CRM_Core_DAO::VALUE_SEPARATOR . $this->randomItem($this->preferredCommunicationMethod) . CRM_Core_DAO::VALUE_SEPARATOR;
499 }
500 $contact->source = 'Sample Data';
501 $this->_insert($contact);
502 }
503 }
504
505 /**
506 * addIndividual()
507 *
508 * This method adds individual's data to the contact table
509 *
510 * The following fields are generated and added.
511 *
512 * contact_uuid - individual
513 * contact_rid - latest one
514 * first_name 'First Name $contact_uuid'
515 * middle_name 'Middle Name $contact_uuid'
516 * last_name 'Last Name $contact_uuid'
517 * job_title 'Job Title $contact_uuid'
518 *
519 */
520 private function addIndividual() {
521
522 $contact = new CRM_Contact_DAO_Contact();
523 $year = 60 * 60 * 24 * 365.25;
82d32482 524 $now = $this->time;
3a2a6e86
TO
525
526 foreach ($this->Individual as $cid) {
527 $contact->is_deceased = $contact->gender_id = $contact->birth_date = $contact->deceased_date = $email = NULL;
528 list($gender_id, $gender) = $this->randomKeyValue($this->gender);
38cdbfc7 529 $birth_date = $this->randomInt($now - 90 * $year, $now - 10 * $year);
3a2a6e86
TO
530
531 $contact->last_name = $this->randomItem('last_name');
532
533 // Manage household names
534 if (!in_array($contact->id, $this->strictIndividual)) {
535 // Find position in household
536 foreach ($this->householdIndividual as $householdId => $house) {
537 foreach ($house as $position => $memberId) {
538 if ($memberId == $cid) {
539 break 2;
540 }
541 }
542 }
543 // Head of household: set name
544 if (empty($this->householdName[$householdId])) {
545 $this->householdName[$householdId] = $contact->last_name;
546 }
547 // Kids get household name, spouse might get it
548 if ($position > 1 || $this->probability(.5)) {
549 $contact->last_name = $this->householdName[$householdId];
550 }
551 elseif ($this->householdName[$householdId] != $contact->last_name) {
552 // Spouse might hyphenate name
553 if ($this->probability(.5)) {
554 $contact->last_name .= '-' . $this->householdName[$householdId];
555 }
556 // Kids might hyphenate name
557 else {
558 $this->householdName[$householdId] .= '-' . $contact->last_name;
559 }
560 }
561 // Sensible ages and genders
38cdbfc7 562 $offset = $this->randomInt($now - 40 * $year, $now);
3a2a6e86
TO
563 // Parents
564 if ($position < 2) {
38cdbfc7 565 $birth_date = $this->randomInt($offset - 35 * $year, $offset - 20 * $year);
3a2a6e86
TO
566 if ($this->probability(.8)) {
567 $gender_id = 2 - $position;
568 $gender = $this->gender[$gender_id];
569 }
570 }
571 // Kids
572 else {
38cdbfc7 573 $birth_date = $this->randomInt($offset - 10 * $year, $offset);
3a2a6e86
TO
574 }
575 }
576 // Non household people
577 else {
578 if ($this->probability(.6)) {
579 $this->_addAddress($cid);
580 }
581 }
582
583 $contact->first_name = $this->randomItem($gender . '_name');
584 $contact->middle_name = $this->probability(.5) ? '' : ucfirst($this->randomChar());
585 $age = intval(($now - $birth_date) / $year);
586
587 // Prefix and suffix by gender and age
588 $contact->prefix_id = $contact->suffix_id = $prefix = $suffix = NULL;
589 if ($this->probability(.5) && $age > 20) {
590 list($contact->prefix_id, $prefix) = $this->randomKeyValue($this->prefix[$gender_id]);
591 $prefix .= ' ';
592 }
593 if ($gender == 'male' && $this->probability(.50)) {
594 list($contact->suffix_id, $suffix) = $this->randomKeyValue($this->suffix);
595 $suffix = ' ' . $suffix;
596 }
597 if ($this->probability(.7)) {
598 $contact->gender_id = $gender_id;
599 }
600 if ($this->probability(.7)) {
601 $contact->birth_date = date("Ymd", $birth_date);
602 }
603
604 // Deceased probability based on age
605 if ($contact->gender_id && $contact->gender_id == 2) {
606 $checkAge = 64;
607 }
608 else {
609 $checkAge = 68;
610 }
611 if ($age > $checkAge && count($this->deceasedContactIds) < 4) {
612 $contact->is_deceased = $this->probability(($age - 30) / 100);
613 if ($contact->is_deceased && $this->probability(.7)) {
614 $contact->deceased_date = $this->randomDate();
615 }
616 }
617
618 // Add 0, 1 or 2 email address
38cdbfc7 619 $count = $this->randomInt(0, 2);
3a2a6e86
TO
620 for ($i = 0; $i < $count; ++$i) {
621 $email = $this->_individualEmail($contact);
622 $this->_addEmail($cid, $email, self::HOME);
623 }
624
625 // Add 0, 1 or 2 phones
38cdbfc7 626 $count = $this->randomInt(0, 2);
3a2a6e86
TO
627 for ($i = 0; $i < $count; ++$i) {
628 $this->_addPhone($cid);
629 }
630
631 // Occasionally you get contacts with just an email in the db
632 if ($this->probability(.2) && $email) {
633 $contact->first_name = $contact->last_name = $contact->middle_name = NULL;
634 $contact->is_deceased = $contact->gender_id = $contact->birth_date = $contact->deceased_date = NULL;
635 $contact->display_name = $contact->sort_name = $email;
636 $contact->postal_greeting_display = $contact->email_greeting_display = "Dear $email";
637 }
638 else {
639 $contact->display_name = $prefix . $contact->first_name . ' ' . $contact->last_name . $suffix;
640 $contact->sort_name = $contact->last_name . ', ' . $contact->first_name;
641 $contact->postal_greeting_display = $contact->email_greeting_display = 'Dear ' . $contact->first_name;
642 }
643 $contact->addressee_id = $contact->postal_greeting_id = $contact->email_greeting_id = 1;
644 $contact->addressee_display = $contact->display_name;
645 $contact->hash = crc32($contact->sort_name);
646 $contact->id = $cid;
647 $this->_update($contact);
648 if ($contact->is_deceased) {
649 $this->deceasedContactIds[] = $cid;
650 }
651 }
652 }
653
654 /**
655 * This method adds household's data to the contact table
656 *
657 * The following fields are generated and added.
658 *
659 * contact_uuid - household_individual
660 * contact_rid - latest one
661 * household_name 'household $contact_uuid primary contact $primary_contact_uuid'
662 * nick_name 'nick $contact_uuid'
663 * primary_contact_uuid = $household_individual[$contact_uuid][0];
664 *
665 */
666 private function addHousehold() {
667
668 $contact = new CRM_Contact_DAO_Contact();
669 foreach ($this->Household as $cid) {
670 // Add address
671 $this->_addAddress($cid);
672
673 $contact->id = $cid;
674 $contact->household_name = $this->householdName[$cid] . " family";
675 // need to update the sort name for the main contact table
676 $contact->display_name = $contact->sort_name = $contact->household_name;
677 $contact->postal_greeting_id = $contact->email_greeting_id = 5;
678 $contact->postal_greeting_display = $contact->email_greeting_display = 'Dear ' . $contact->household_name;
679 $contact->addressee_id = 2;
680 $contact->addressee_display = $contact->display_name;
681 $contact->hash = crc32($contact->sort_name);
682 $this->_update($contact);
683 }
684 }
685
686 /**
687 * This method adds organization data to the contact table
688 *
689 * The following fields are generated and added.
690 *
691 * contact_uuid - organization
692 * contact_rid - latest one
693 * organization_name 'organization $contact_uuid'
694 * legal_name 'legal $contact_uuid'
695 * nick_name 'nick $contact_uuid'
696 * sic_code 'sic $contact_uuid'
697 * primary_contact_id - random individual contact uuid
698 *
699 */
700 private function addOrganization() {
701
702 $org = new CRM_Contact_DAO_Contact();
703 $employees = $this->Individual;
0049e17a 704 $employees = $this->shuffle($employees);
3a2a6e86
TO
705
706 foreach ($this->Organization as $key => $id) {
707 $org->primary_contact_id = $website = $email = NULL;
708 $org->id = $id;
709 $address = $this->_addAddress($id);
710
711 $namePre = $this->randomItem('organization_prefix');
712 $nameMid = $this->randomItem('organization_name');
713 $namePost = $this->randomItem('organization_suffix');
714
715 // Some orgs are named after their location
716 if ($this->probability(.7)) {
717 $place = $this->randomItem(array('city', 'street_name', 'state'));
718 $namePre = $address[$place];
719 }
720 $org->organization_name = "$namePre $nameMid $namePost";
721
722 // Most orgs have a website and email
723 if ($this->probability(.8)) {
724 $website = $this->_addWebsite($id, $org->organization_name);
725 $url = str_replace('http://', '', $website['url']);
726 $email = $this->randomItem('email_address') . '@' . $url;
727 $this->_addEmail($id, $email, self::MAIN);
728 }
729
730 // current employee
731 if ($this->probability(.8)) {
732 $indiv = new CRM_Contact_DAO_Contact();
733 $org->primary_contact_id = $indiv->id = $employees[$key];
734 $indiv->organization_name = $org->organization_name;
735 $indiv->employer_id = $id;
736 $this->_update($indiv);
737 // Share address with employee
738 if ($this->probability(.8)) {
739 $this->_addAddress($indiv->id, $id);
740 }
741 // Add work email for employee
742 if ($website) {
743 $indiv->find(TRUE);
744 $email = $this->_individualEmail($indiv, $url);
745 $this->_addEmail($indiv->id, $email, self::WORK);
746 }
747 }
748
749 // need to update the sort name for the main contact table
750 $org->display_name = $org->sort_name = $org->organization_name;
751 $org->addressee_id = 3;
752 $org->addressee_display = $org->display_name;
753 $org->hash = crc32($org->sort_name);
754 $this->_update($org);
755 }
756 }
757
758 /**
759 * This method adds data to the contact_relationship table
760 */
761 private function addRelationship() {
762
763 $relationship = new CRM_Contact_DAO_Relationship();
764
765 // Household relationships
766 foreach ($this->householdIndividual as $household_id => $household_member) {
767 // Default active
768 $relationship->is_active = 1;
769
770 // add child_of relationship for each child
771 $relationship->relationship_type_id = $this->relTypes['Child of']['id'];
772 foreach (array(0, 1) as $parent) {
773 foreach (array(2, 3) as $child) {
774 $relationship->contact_id_a = $household_member[$child];
775 $relationship->contact_id_b = $household_member[$parent];
776 $this->_insert($relationship);
777 }
778 }
779
780 // add sibling_of relationship
781 $relationship->relationship_type_id = $this->relTypes['Sibling of']['id'];
782 $relationship->contact_id_a = $household_member[3];
783 $relationship->contact_id_b = $household_member[2];
784 $this->_insert($relationship);
785
786 // add member_of_household relationships and shared address
787 $relationship->relationship_type_id = $this->relTypes['Household Member of']['id'];
788 $relationship->contact_id_b = $household_id;
789 for ($i = 1; $i < 4; ++$i) {
790 $relationship->contact_id_a = $household_member[$i];
791 $this->_insert($relationship);
792 $this->_addAddress($household_member[$i], $household_id);
793 }
794
795 // Divorced/separated couples - end relationship and different address
796 if ($this->probability(.4)) {
797 $relationship->is_active = 0;
798 $this->_addAddress($household_member[0]);
799 }
800 else {
801 $this->_addAddress($household_member[0], $household_id);
802 }
803
804 // add head_of_household relationship 1 for head of house
805 $relationship->relationship_type_id = $this->relTypes['Head of Household for']['id'];
806 $relationship->contact_id_a = $household_member[0];
807 $relationship->contact_id_b = $household_id;
808 $this->_insert($relationship);
809
810 // add spouse_of relationship 1 for both the spouses
811 $relationship->relationship_type_id = $this->relTypes['Spouse of']['id'];
812 $relationship->contact_id_a = $household_member[1];
813 $relationship->contact_id_b = $household_member[0];
814 $this->_insert($relationship);
815 }
816
817 // Add current employer relationships
818 $this->_query("INSERT INTO civicrm_relationship
819 (contact_id_a, contact_id_b, relationship_type_id, is_active)
820 (SELECT id, employer_id, " . $this->relTypes['Employee of']['id'] . ", 1 FROM civicrm_contact WHERE employer_id IN (" . implode(',', $this->Organization) . "))"
821 );
822 }
823
824 /**
825 * Create an address for a contact
826 *
827 * @param $cid int: contact id
828 * @param $masterContactId int: set if this is a shared address
829 *
830 * @return array
831 */
832 private function _addAddress($cid, $masterContactId = NULL) {
833
834 // Share existing address
835 if ($masterContactId) {
836 $dao = new CRM_Core_DAO_Address();
837 $dao->is_primary = 1;
838 $dao->contact_id = $masterContactId;
839 $dao->find(TRUE);
840 $dao->master_id = $dao->id;
841 $dao->id = NULL;
842 $dao->contact_id = $cid;
843 $dao->is_primary = $this->isPrimary($cid, 'Address');
844 $dao->location_type_id = $this->getContactType($masterContactId) == 'Organization' ? self::WORK : self::HOME;
845 $this->_insert($dao);
846 }
847
848 // Generate new address
849 else {
850 $params = array(
851 'contact_id' => $cid,
852 'location_type_id' => $this->getContactType($cid) == 'Organization' ? self::MAIN : self::HOME,
38cdbfc7 853 'street_number' => $this->randomInt(1, 1000),
3a2a6e86
TO
854 'street_number_suffix' => ucfirst($this->randomChar()),
855 'street_name' => $this->randomItem('street_name'),
856 'street_type' => $this->randomItem('street_type'),
857 'street_number_postdirectional' => $this->randomItem('address_direction'),
858 'county_id' => 1,
859 );
860
861 $params['street_address'] = $params['street_number'] . $params['street_number_suffix'] . " " . $params['street_name'] . " " . $params['street_type'] . " " . $params['street_number_postdirectional'];
862
863 if ($params['location_type_id'] == self::MAIN) {
864 $params['supplemental_address_1'] = $this->randomItem('supplemental_addresses_1');
865 }
866
867 // Hack to add lat/long (limited to USA based addresses)
868 list(
869 $params['country_id'],
870 $params['state_province_id'],
871 $params['city'],
872 $params['postal_code'],
873 $params['geo_code_1'],
874 $params['geo_code_2'],
875 ) = $this->getZipCodeInfo();
876
877 $this->_addDAO('Address', $params);
878 $params['state'] = $this->states[$params['state_province_id']];
879 return $params;
880 }
881 }
882
883 /**
884 * Add a phone number for a contact
885 *
886 * @param $cid int: contact id
887 *
888 * @return array
889 */
890 private function _addPhone($cid) {
38cdbfc7
TO
891 $area = $this->probability(.5) ? '' : $this->randomInt(201, 899);
892 $pre = $this->randomInt(201, 899);
893 $post = $this->randomInt(1000, 9999);
3a2a6e86
TO
894 $params = array(
895 'location_type_id' => $this->getContactType($cid) == 'Organization' ? self::MAIN : self::HOME,
896 'contact_id' => $cid,
897 'phone' => ($area ? "($area) " : '') . "$pre-$post",
898 'phone_numeric' => $area . $pre . $post,
38cdbfc7 899 'phone_type_id' => $this->randomInt(1, 2),
3a2a6e86
TO
900 );
901 $this->_addDAO('Phone', $params);
902 return $params;
903 }
904
905 /**
906 * Add an email for a contact
907 *
908 * @param $cid int: contact id
909 * @param $email
910 * @param $locationType
911 *
912 * @return array
913 */
914 private function _addEmail($cid, $email, $locationType) {
915 $params = array(
916 'location_type_id' => $locationType,
917 'contact_id' => $cid,
918 'email' => $email,
919 );
920 $this->_addDAO('Email', $params);
921 return $params;
922 }
923
924 /**
925 * Add a website based on organization name
926 * Using common naming patterns
927 *
928 * @param $cid int: contact id
929 * @param $name str: contact name
930 *
931 * @return array
932 */
933 private function _addWebsite($cid, $name) {
934 $part = array_pad(explode(' ', strtolower($name)), 3, '');
935 if (count($part) > 3) {
936 // Abbreviate the place name if it's two words
937 $domain = $part[0][0] . $part[1][0] . $part[2] . $part[3];
938 }
939 else {
940 // Common naming patterns
38cdbfc7 941 switch ($this->randomInt(1, 3)) {
3a2a6e86
TO
942 case 1:
943 $domain = $part[0] . $part[1] . $part[2];
944 break;
945
946 case 2:
947 $domain = $part[0] . $part[1];
948 break;
949
950 case 3:
951 $domain = $part[0] . $part[2];
952 break;
953 }
954 }
955 $params = array(
956 'website_type_id' => 1,
957 'location_type_id' => self::MAIN,
958 'contact_id' => $cid,
959 'url' => "http://$domain.org",
960 );
961 $this->_addDAO('Website', $params);
962 return $params;
963 }
964
965 /**
966 * Create an email address based on a person's name
967 * Using common naming patterns
968 *
969 * @param $contact obj: individual contact record
970 * @param $domain str: supply a domain (i.e. for a work address)
971 *
972 * @return string
973 */
974 private function _individualEmail($contact, $domain = NULL) {
975 $first = $contact->first_name;
976 $last = $contact->last_name;
977 $f = $first[0];
978 $l = $last[0];
979 $m = $contact->middle_name ? $contact->middle_name[0] . '.' : '';
980 // Common naming patterns
38cdbfc7 981 switch ($this->randomInt(1, 6)) {
3a2a6e86
TO
982 case 1:
983 $email = $first . $last;
984 break;
985
986 case 2:
987 $email = "$last.$first";
988 break;
989
990 case 3:
991 $email = $last . $f;
992 break;
993
994 case 4:
995 $email = $first . $l;
996 break;
997
998 case 5:
999 $email = "$last.$m$first";
1000 break;
1001
1002 case 6:
1003 $email = "$f$m$last";
1004 break;
1005 }
1006 //to ensure we dont insert
1007 //invalid characters in email
1008 $email = preg_replace("([^a-zA-Z0-9_\.-]*)", "", $email);
1009
1010 // Some people have numbers in their address
1011 if ($this->probability(.4)) {
38cdbfc7 1012 $email .= $this->randomInt(1, 99);
3a2a6e86
TO
1013 }
1014 // Generate random domain if not specified
1015 if (!$domain) {
1016 $domain = $this->randomItem('email_domain') . '.' . $this->randomItem('email_tld');
1017 }
1018 return strtolower($email) . '@' . $domain;
1019 }
1020
1021 /**
1022 * This method populates the civicrm_entity_tag table
1023 */
1024 private function addEntityTag() {
1025
1026 $entity_tag = new CRM_Core_DAO_EntityTag();
1027
1028 // add categories 1,2,3 for Organizations.
1029 for ($i = 0; $i < $this->numOrganization; $i += 2) {
1030 $org_id = $this->Organization[$i];
1031 // echo "org_id = $org_id\n";
1032 $entity_tag->entity_id = $this->Organization[$i];
1033 $entity_tag->entity_table = 'civicrm_contact';
38cdbfc7 1034 $entity_tag->tag_id = $this->randomInt(1, 3);
3a2a6e86
TO
1035 $this->_insert($entity_tag);
1036 }
1037
1038 // add categories 4,5 for Individuals.
1039 for ($i = 0; $i < $this->numIndividual; $i += 2) {
1040 $entity_tag->entity_table = 'civicrm_contact';
1041 $entity_tag->entity_id = $this->Individual[$i];
1042 if (($entity_tag->entity_id) % 3) {
38cdbfc7 1043 $entity_tag->tag_id = $this->randomInt(4, 5);
3a2a6e86
TO
1044 $this->_insert($entity_tag);
1045 }
1046 else {
1047 // some of the individuals are in both categories (4 and 5).
1048 $entity_tag->tag_id = 4;
1049 $this->_insert($entity_tag);
1050 $entity_tag->tag_id = 5;
1051 $this->_insert($entity_tag);
1052 }
1053 }
1054 }
1055
1056 /**
1057 * This method populates the civicrm_group_contact table
1058 */
1059 private function addGroup() {
1060 // add the 3 groups first
1061 foreach ($this->sampleData['group'] as $groupName) {
1062 $group = new CRM_Contact_BAO_Group();
1063 $group->name = $group->title = $groupName;
1064 $group->group_type = "\ 11\ 12\ 1";
1065 $group->visibility = 'Public Pages';
1066 $group->is_active = 1;
1067 $group->save();
1068 }
1069
1070 // 60 are for newsletter
1071 for ($i = 0; $i < 60; $i++) {
1072 $groupContact = new CRM_Contact_DAO_GroupContact();
1073 // newsletter subscribers
1074 $groupContact->group_id = 2;
1075 $groupContact->contact_id = $this->Individual[$i];
1076 // always add members
1077 $groupContact->status = 'Added';
1078
1079 $subscriptionHistory = new CRM_Contact_DAO_SubscriptionHistory();
1080 $subscriptionHistory->contact_id = $groupContact->contact_id;
1081
1082 $subscriptionHistory->group_id = $groupContact->group_id;
1083 $subscriptionHistory->status = $groupContact->status;
1084 // method
1085 $subscriptionHistory->method = $this->randomItem($this->subscriptionHistoryMethod);
1086 $subscriptionHistory->date = $this->randomDate();
1087 if ($groupContact->status != 'Pending') {
1088 $this->_insert($groupContact);
1089 }
1090 $this->_insert($subscriptionHistory);
1091 }
1092
1093 // 15 volunteers
1094 for ($i = 0; $i < 15; $i++) {
1095 $groupContact = new CRM_Contact_DAO_GroupContact();
1096 // Volunteers
1097 $groupContact->group_id = 3;
1098 $groupContact->contact_id = $this->Individual[$i + 60];
1099 // membership status
1100 $groupContact->status = 'Added';
1101
1102 $subscriptionHistory = new CRM_Contact_DAO_SubscriptionHistory();
1103 $subscriptionHistory->contact_id = $groupContact->contact_id;
1104 $subscriptionHistory->group_id = $groupContact->group_id;
1105 $subscriptionHistory->status = $groupContact->status;
1106 // method
1107 $subscriptionHistory->method = $this->randomItem($this->subscriptionHistoryMethod);
1108 $subscriptionHistory->date = $this->randomDate();
1109
1110 if ($groupContact->status != 'Pending') {
1111 $this->_insert($groupContact);
1112 }
1113 $this->_insert($subscriptionHistory);
1114 }
1115
1116 // 8 advisory board group
1117 for ($i = 0; $i < 8; $i++) {
1118 $groupContact = new CRM_Contact_DAO_GroupContact();
1119 // advisory board group
1120 $groupContact->group_id = 4;
1121 $groupContact->contact_id = $this->Individual[$i * 7];
1122 // membership status
1123 $groupContact->status = 'Added';
1124
1125 $subscriptionHistory = new CRM_Contact_DAO_SubscriptionHistory();
1126 $subscriptionHistory->contact_id = $groupContact->contact_id;
1127 $subscriptionHistory->group_id = $groupContact->group_id;
1128 $subscriptionHistory->status = $groupContact->status;
1129 // method
1130 $subscriptionHistory->method = $this->randomItem($this->subscriptionHistoryMethod);
1131 $subscriptionHistory->date = $this->randomDate();
1132
1133 if ($groupContact->status != 'Pending') {
1134 $this->_insert($groupContact);
1135 }
1136 $this->_insert($subscriptionHistory);
1137 }
1138
1139 //In this function when we add groups that time we are cache the contact fields
1140 //But at the end of setup we are appending sample custom data, so for consistency
1141 //reset the cache.
1142 Civi::cache('fields')->flush();
1143 CRM_Core_BAO_Cache::resetCaches();
1144 }
1145
1146 /**
1147 * This method populates the civicrm_note table
1148 */
1149 private function addNote() {
1150 $params = array(
1151 'entity_table' => 'civicrm_contact',
1152 'contact_id' => 1,
1153 'privacy' => 0,
1154 );
1155 for ($i = 0; $i < self::NUM_CONTACT; $i += 10) {
1156 $params['entity_id'] = $this->randomItem($this->contact);
1157 $params['note'] = $this->randomItem('note');
1158 $params['modified_date'] = $this->randomDate();
1159 $this->_addDAO('Note', $params);
1160 }
1161 }
1162
1163 /**
1164 * This method populates the civicrm_activity_history table
1165 */
1166 private function addActivity() {
1167 $contactDAO = new CRM_Contact_DAO_Contact();
1168 $contactDAO->contact_type = 'Individual';
1169 $contactDAO->selectAdd();
1170 $contactDAO->selectAdd('id');
1171 $contactDAO->orderBy('sort_name');
1172 $contactDAO->find();
1173
1174 $count = 0;
1175 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1176 while ($contactDAO->fetch()) {
1177 if ($count++ > 2) {
1178 break;
1179 }
1180 for ($i = 0; $i < self::NUM_ACTIVITY; $i++) {
1181 $activityDAO = new CRM_Activity_DAO_Activity();
1182 $activityId = CRM_Core_OptionGroup::values('activity_type', NULL, NULL, NULL, ' AND v.name IN ("Tell A Friend", "Pledge Acknowledgment")');
0049e17a 1183 $activityTypeID = $this->randomIndex($activityId);
3a2a6e86
TO
1184 $activity = CRM_Core_PseudoConstant::activityType();
1185 $activityDAO->activity_type_id = $activityTypeID;
1186 $activityDAO->subject = "Subject for $activity[$activityTypeID]";
1187 $activityDAO->activity_date_time = $this->randomDate();
1188 $activityDAO->status_id = 2;
1189 $this->_insert($activityDAO);
1190
1191 $activityContactDAO = new CRM_Activity_DAO_ActivityContact();
1192 $activityContactDAO->activity_id = $activityDAO->id;
1193 $activityContactDAO->contact_id = $contactDAO->id;
1194 $activityContactDAO->record_type_id = CRM_Utils_Array::key('Activity Source', $activityContacts);
1195 $this->_insert($activityContactDAO);
1196
1197 if ($activityTypeID == 9) {
1198 $activityContactDAO = new CRM_Activity_DAO_ActivityContact();
1199 $activityContactDAO->activity_id = $activityDAO->id;
38cdbfc7 1200 $activityContactDAO->contact_id = $this->randomInt(1, 101);
3a2a6e86
TO
1201 $activityContactDAO->record_type_id = CRM_Utils_Array::key('Activity Targets', $activityContacts);
1202 $this->_insert($activityContactDAO);
1203 }
1204 }
1205 }
1206 }
1207
1208 /**
1209 * @return array
1210 */
1211 public function getZipCodeInfo() {
1212
1213 if (!$this->stateMap) {
1214 $query = 'SELECT id, name, abbreviation from civicrm_state_province where country_id = 1228';
1215 $dao = new CRM_Core_DAO();
1216 $dao->query($query);
1217 $this->stateMap = array();
1218 while ($dao->fetch()) {
1219 $this->stateMap[$dao->abbreviation] = $dao->id;
1220 $this->states[$dao->id] = $dao->name;
1221 }
1222 }
1223
1224 static $zipCodes = NULL;
1225 if ($zipCodes === NULL) {
d94d506c 1226 $zipCodes = json_decode(file_get_contents(self::getCivicrmDir() . '/sql/zipcodes.json'));
3a2a6e86
TO
1227 }
1228
38cdbfc7 1229 $zipCode = $zipCodes[$this->randomInt(0, count($zipCodes))];
3a2a6e86
TO
1230
1231 if ($this->stateMap[$zipCode->state]) {
1232 $stateID = $this->stateMap[$zipCode->state];
1233 }
1234 else {
1235 $stateID = 1004;
1236 }
1237
1238 $zip = str_pad($zipCode->zip, 5, '0', STR_PAD_LEFT);
1239 return array(1228, $stateID, $zipCode->city, $zip, $zipCode->latitude, $zipCode->longitude);
1240 }
1241
1242 /**
1243 * @param $zipCode
1244 *
1245 * @return array
1246 */
1247 public static function getLatLong($zipCode) {
1248 $query = "http://maps.google.com/maps?q=$zipCode&output=js";
1249 $userAgent = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0";
1250
1251 $ch = curl_init();
1252 curl_setopt($ch, CURLOPT_URL, $query);
1253 curl_setopt($ch, CURLOPT_HEADER, FALSE);
1254 curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
1255 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1256
1257 // grab URL and pass it to the browser
1258 $outstr = curl_exec($ch);
1259
1260 // close CURL resource, and free up system resources
1261 curl_close($ch);
1262
1263 $preg = "/'(<\?xml.+?)',/s";
1264 preg_match($preg, $outstr, $matches);
1265 if ($matches[1]) {
1266 $xml = simplexml_load_string($matches[1]);
1267 $attributes = $xml->center->attributes();
1268 if (!empty($attributes)) {
1269 return array((float ) $attributes['lat'], (float ) $attributes['lng']);
1270 }
1271 }
1272 return array(NULL, NULL);
1273 }
1274
1275 private function addMembershipType() {
1276 $organizationDAO = new CRM_Contact_DAO_Contact();
1277 $organizationDAO->id = 5;
1278 $organizationDAO->find(TRUE);
1279 $contact_id = $organizationDAO->contact_id;
1280
1281 $membershipType = "INSERT INTO civicrm_membership_type
1282 (name, description, member_of_contact_id, financial_type_id, minimum_fee, duration_unit, duration_interval, period_type, fixed_period_start_day, fixed_period_rollover_day, relationship_type_id, relationship_direction, visibility, weight, is_active)
1283 VALUES
1284 ('General', 'Regular annual membership.', " . $contact_id . ", 2, 100, 'year', 1, 'rolling',null, null, 7, 'b_a', 'Public', 1, 1),
1285 ('Student', 'Discount membership for full-time students.', " . $contact_id . ", 2, 50, 'year', 1, 'rolling', null, null, 7, 'b_a', 'Public', 2, 1),
1286 ('Lifetime', 'Lifetime membership.', " . $contact_id . ", 2, 1200, 'lifetime', 1, 'rolling', null, null, 7, 'b_a', 'Admin', 3, 1);
1287 ";
1288 $this->_query($membershipType);
1289 }
1290
1291 private function addMembership() {
1292 $contact = new CRM_Contact_DAO_Contact();
1293 $contact->query("SELECT id FROM civicrm_contact where contact_type = 'Individual'");
1294 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1295 while ($contact->fetch()) {
1296 $contacts[] = $contact->id;
1297 }
0049e17a 1298 $contacts = $this->shuffle($contacts);
3a2a6e86
TO
1299
1300 $randomContacts = array_slice($contacts, 20, 30);
1301
1302 $sources = array('Payment', 'Donation', 'Check');
1303 $membershipTypes = array(1, 2);
1304 $membershipTypeNames = array('General', 'Student');
1305 $statuses = array(3, 4);
1306
1307 $membership = "
1308INSERT INTO civicrm_membership
1309 (contact_id, membership_type_id, join_date, start_date, end_date, source, status_id)
1310VALUES
1311";
1312
1313 $activity = "
1314INSERT INTO civicrm_activity
1315 (source_record_id, activity_type_id, subject, activity_date_time, duration, location, phone_id, phone_number, details, priority_id,parent_id, is_test, status_id)
1316VALUES
1317";
1318
1319 $activityContact = "
1320INSERT INTO civicrm_activity_contact
1321 (activity_id, contact_id, record_type_id)
1322VALUES
1323";
1324
1325 $currentActivityID = CRM_Core_DAO::singleValueQuery("SELECT MAX(id) FROM civicrm_activity");
1326 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1327 foreach ($randomContacts as $count => $dontCare) {
1328 $source = $this->randomItem($sources);
1329 $activitySourceId = $count + 1;
1330 $currentActivityID++;
1331 $activityContact .= "( $currentActivityID, {$randomContacts[$count]}, {$sourceID} )";
1332 if ((($count + 1) % 11 == 0)) {
1333 // lifetime membership, status can be anything
1334 $startDate = date('Y-m-d', mktime(0, 0, 0, date('m'), (date('d') - $count), date('Y')));
1335 $membership .= "( {$randomContacts[$count]}, 3, '{$startDate}', '{$startDate}', null, '{$source}', 1)";
1336 $activity .= "( {$activitySourceId}, 7, 'Lifetime', '{$startDate} 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 )";
1337 }
1338 elseif (($count + 1) % 5 == 0) {
1339 // Grace or expired, memberhsip type is random of 1 & 2
0049e17a 1340 $randIndex = $this->randomIndex($membershipTypes);
3a2a6e86
TO
1341 $membershipTypeId = $membershipTypes[$randIndex];
1342 $membershipStatusId = $statuses[$randIndex];
1343 $membershipTypeName = $membershipTypeNames[$randIndex];
1344 $YearFactor = $membershipTypeId * 2;
1345 //reverse the type and consider as year factor.
1346 if ($YearFactor != 2) {
1347 $YearFactor = 1;
1348 }
1349 $dateFactor = ($count * ($YearFactor) * ($YearFactor) * ($YearFactor));
1350 $startDate = date('Y-m-d', mktime(0, 0, 0,
1351 date('m'),
1352 (date('d') - ($dateFactor)),
1353 (date('Y') - ($YearFactor))
1354 ));
1355 $partOfDate = explode('-', $startDate);
1356 $endDate = date('Y-m-d', mktime(0, 0, 0,
1357 $partOfDate[1],
1358 ($partOfDate[2] - 1),
1359 ($partOfDate[0] + ($YearFactor))
1360 ));
1361
1362 $membership .= "( {$randomContacts[$count]}, {$membershipTypeId}, '{$startDate}', '{$startDate}', '{$endDate}', '{$source}', {$membershipStatusId})";
1363 $activity .= "( {$activitySourceId}, 7, '{$membershipTypeName}', '{$startDate} 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 )";
1364 }
1365 elseif (($count + 1) % 2 == 0) {
1366 // membership type 2
1367 $startDate = date('Y-m-d', mktime(0, 0, 0, date('m'), (date('d') - $count), date('Y')));
1368 $endDate = date('Y-m-d', mktime(0, 0, 0, date('m'), (date('d') - ($count + 1)), (date('Y') + 1)));
1369 $membership .= "( {$randomContacts[$count]}, 2, '{$startDate}', '{$startDate}', '{$endDate}', '{$source}', 1)";
1370 $activity .= "( {$activitySourceId}, 7, 'Student', '{$startDate} 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 )";
1371 }
1372 else {
1373 // membership type 1
1374 $startDate = date('Y-m-d', mktime(0, 0, 0, date('m'), (date('d') - $count), date('Y')));
1375 $endDate = date('Y-m-d', mktime(0, 0, 0, date('m'), (date('d') - ($count + 1)), (date('Y') + 2)));
1376 $membership .= "( {$randomContacts[$count]}, 1, '{$startDate}', '{$startDate}', '{$endDate}', '{$source}', 1)";
1377 $activity .= "( {$activitySourceId}, 7, 'General', '{$startDate} 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 )";
1378 }
1379
1380 if ($count != 29) {
1381 $membership .= ",";
1382 $activity .= ",";
1383 $activityContact .= ",";
1384 }
1385 }
1386
1387 $this->_query($membership);
1388 $this->_query($activity);
1389 $this->_query($activityContact);
1390 }
1391
1392 /**
1393 * @param $date
1394 *
1395 * @return string
1396 */
1397 public static function repairDate($date) {
1398 $dropArray = array('-' => '', ':' => '', ' ' => '');
1399 return strtr($date, $dropArray);
1400 }
1401
1402 private function addMembershipLog() {
1403 $membership = new CRM_Member_DAO_Membership();
1404 $membership->query("SELECT id FROM civicrm_membership");
1405 while ($membership->fetch()) {
1406 $ids[] = $membership->id;
1407 }
1408 foreach ($ids as $id) {
1409 $membership = new CRM_Member_DAO_Membership();
1410 $membership->id = $id;
1411 $membershipLog = new CRM_Member_DAO_MembershipLog();
1412 if ($membership->find(TRUE)) {
1413 $membershipLog->membership_id = $membership->id;
1414 $membershipLog->status_id = $membership->status_id;
1415 $membershipLog->start_date = self::repairDate($membership->start_date);
1416 $membershipLog->end_date = self::repairDate($membership->end_date);
1417 $membershipLog->modified_id = $membership->contact_id;
1418 $membershipLog->modified_date = date("Ymd");
1419 $membershipLog->membership_type_id = $membership->membership_type_id;
1420 $membershipLog->save();
1421 }
1422 $membershipLog = NULL;
1423 }
1424 }
1425
1426 private function addEvent() {
1427 $event = "INSERT INTO civicrm_address ( contact_id, location_type_id, is_primary, is_billing, street_address, street_number, street_number_suffix, street_number_predirectional, street_name, street_type, street_number_postdirectional, street_unit, supplemental_address_1, supplemental_address_2, supplemental_address_3, city, county_id, state_province_id, postal_code_suffix, postal_code, usps_adc, country_id, geo_code_1, geo_code_2, timezone)
1428 VALUES
1429 ( NULL, 1, 1, 1, '14S El Camino Way E', 14, 'S', NULL, 'El Camino', 'Way', NULL, NULL, NULL, NULL, NULL, 'Collinsville', NULL, 1006, NULL, '6022', NULL, 1228, 41.8328, -72.9253, NULL),
1430 ( NULL, 1, 1, 1, '11B Woodbridge Path SW', 11, 'B', NULL, 'Woodbridge', 'Path', NULL, NULL, NULL, NULL, NULL, 'Dayton', NULL, 1034, NULL, '45417', NULL, 1228, 39.7531, -84.2471, NULL),
1431 ( NULL, 1, 1, 1, '581O Lincoln Dr SW', 581, 'O', NULL, 'Lincoln', 'Dr', NULL, NULL, NULL, NULL, NULL, 'Santa Fe', NULL, 1030, NULL, '87594', NULL, 1228, 35.5212, -105.982, NULL)
1432 ";
1433 $this->_query($event);
1434
1435 $sql = "SELECT id from civicrm_address where street_address = '14S El Camino Way E'";
1436 $eventAdd1 = CRM_Core_DAO::singleValueQuery($sql);
1437 $sql = "SELECT id from civicrm_address where street_address = '11B Woodbridge Path SW'";
1438 $eventAdd2 = CRM_Core_DAO::singleValueQuery($sql);
1439 $sql = "SELECT id from civicrm_address where street_address = '581O Lincoln Dr SW'";
1440 $eventAdd3 = CRM_Core_DAO::singleValueQuery($sql);
1441
1442 $event = "INSERT INTO civicrm_email (contact_id, location_type_id, email, is_primary, is_billing, on_hold, hold_date, reset_date)
1443 VALUES
1444 (NULL, 1, 'development@example.org', 0, 0, 0, NULL, NULL),
1445 (NULL, 1, 'tournaments@example.org', 0, 0, 0, NULL, NULL),
1446 (NULL, 1, 'celebration@example.org', 0, 0, 0, NULL, NULL)
1447 ";
1448 $this->_query($event);
1449
1450 $sql = "SELECT id from civicrm_email where email = 'development@example.org'";
1451 $eventEmail1 = CRM_Core_DAO::singleValueQuery($sql);
1452 $sql = "SELECT id from civicrm_email where email = 'tournaments@example.org'";
1453 $eventEmail2 = CRM_Core_DAO::singleValueQuery($sql);
1454 $sql = "SELECT id from civicrm_email where email = 'celebration@example.org'";
1455 $eventEmail3 = CRM_Core_DAO::singleValueQuery($sql);
1456
1457 $event = "INSERT INTO civicrm_phone (contact_id, location_type_id, is_primary, is_billing, mobile_provider_id, phone, phone_numeric, phone_type_id)
1458 VALUES
1459 (NULL, 1, 0, 0, NULL, '204 222-1000', '2042221000', '1'),
1460 (NULL, 1, 0, 0, NULL, '204 223-1000', '2042231000', '1'),
1461 (NULL, 1, 0, 0, NULL, '303 323-1000', '3033231000', '1')
1462 ";
1463 $this->_query($event);
1464
1465 $sql = "SELECT id from civicrm_phone where phone = '204 222-1000'";
1466 $eventPhone1 = CRM_Core_DAO::singleValueQuery($sql);
1467 $sql = "SELECT id from civicrm_phone where phone = '204 223-1000'";
1468 $eventPhone2 = CRM_Core_DAO::singleValueQuery($sql);
1469 $sql = "SELECT id from civicrm_phone where phone = '303 323-1000'";
1470 $eventPhone3 = CRM_Core_DAO::singleValueQuery($sql);
1471
1472 $event = "INSERT INTO civicrm_loc_block ( address_id, email_id, phone_id, address_2_id, email_2_id, phone_2_id)
1473 VALUES
1474 ( $eventAdd1, $eventEmail1, $eventPhone1, NULL,NULL,NULL),
1475 ( $eventAdd2, $eventEmail2, $eventPhone2, NULL,NULL,NULL),
1476 ( $eventAdd3, $eventEmail3, $eventPhone3, NULL,NULL,NULL)
1477 ";
1478
1479 $this->_query($event);
1480
1481 $sql = "SELECT id from civicrm_loc_block where phone_id = $eventPhone1 AND email_id = $eventEmail1 AND address_id = $eventAdd1";
1482 $eventLok1 = CRM_Core_DAO::singleValueQuery($sql);
1483 $sql = "SELECT id from civicrm_loc_block where phone_id = $eventPhone2 AND email_id = $eventEmail2 AND address_id = $eventAdd2";
1484 $eventLok2 = CRM_Core_DAO::singleValueQuery($sql);
1485 $sql = "SELECT id from civicrm_loc_block where phone_id = $eventPhone3 AND email_id = $eventEmail3 AND address_id = $eventAdd3";
1486 $eventLok3 = CRM_Core_DAO::singleValueQuery($sql);
1487
1488 $event = "INSERT INTO civicrm_event
1489 ( title, summary, description, event_type_id, participant_listing_id, is_public, start_date, end_date, is_online_registration, registration_link_text, max_participants, event_full_text, is_monetary, financial_type_id, is_map, is_active, fee_label, is_show_location, loc_block_id,intro_text, footer_text, confirm_title, confirm_text, confirm_footer_text, is_email_confirm, confirm_email_text, confirm_from_name, confirm_from_email, cc_confirm, bcc_confirm, default_fee_id, thankyou_title, thankyou_text, thankyou_footer_text, is_pay_later, pay_later_text, pay_later_receipt, is_multiple_registrations, allow_same_participant_emails, currency )
1490 VALUES
82d32482
TO
1491 ( 'Fall Fundraiser Dinner', 'Kick up your heels at our Fall Fundraiser Dinner/Dance at Glen Echo Park! Come by yourself or bring a partner, friend or the entire family!', 'This event benefits our teen programs. Admission includes a full 3 course meal and wine or soft drinks. Grab your dancing shoes, bring the kids and come join the party!', 3, 1, 1, '" . date('Y-m-d 17:00:00', strtotime("+6 months", $this->time)) . "', '" . date('Y-m-d 17:00:00', strtotime("+6 months +2 days", $this->time)) . "', 1, 'Register Now', 100, 'Sorry! The Fall Fundraiser Dinner is full. Please call Jane at 204 222-1000 ext 33 if you want to be added to the waiting list.', 1, 4, 1, 1, 'Dinner Contribution', 1 ,$eventLok1,'Fill in the information below to join as at this wonderful dinner event.', NULL, 'Confirm Your Registration Information', 'Review the information below carefully.', NULL, 1, 'Contact the Development Department if you need to make any changes to your registration.', 'Fundraising Dept.', 'development@example.org', NULL, NULL, NULL, 'Thanks for Registering!', '<p>Thank you for your support. Your contribution will help us build even better tools.</p><p>Please tell your friends and colleagues about this wonderful event.</p>', '<p><a href=https://civicrm.org>Back to CiviCRM Home Page</a></p>', 1, 'I will send payment by check', 'Send a check payable to Our Organization within 3 business days to hold your reservation. Checks should be sent to: 100 Main St., Suite 3, San Francisco CA 94110', 1, 0, 'USD' ),
1492 ( 'Summer Solstice Festival Day Concert', 'Festival Day is coming! Join us and help support your parks.', 'We will gather at noon, learn a song all together, and then join in a joyous procession to the pavilion. We will be one of many groups performing at this wonderful concert which benefits our city parks.', 5, 1, 1, '" . date('Y-m-d 12:00:00', strtotime("-1 day", $this->time)) . "', '" . date('Y-m-d 17:00:00', strtotime("-1 day", $this->time)) . "', 1, 'Register Now', 50, 'We have all the singers we can handle. Come to the pavilion anyway and join in from the audience.', 1, 2, NULL, 1, 'Festival Fee', 1, $eventLok2, 'Complete the form below and click Continue to register online for the festival. Or you can register by calling us at 204 222-1000 ext 22.', '', 'Confirm Your Registration Information', '', '', 1, 'This email confirms your registration. If you have questions or need to change your registration - please do not hesitate to call us.', 'Event Dept.', 'events@example.org', '', NULL, NULL, 'Thanks for Your Joining In!', '<p>Thank you for your support. Your participation will help build new parks.</p><p>Please tell your friends and colleagues about the concert.</p>', '<p><a href=https://civicrm.org>Back to CiviCRM Home Page</a></p>', 0, NULL, NULL, 1, 0, 'USD' ),
1493 ( 'Rain-forest Cup Youth Soccer Tournament', 'Sign up your team to participate in this fun tournament which benefits several Rain-forest protection groups in the Amazon basin.', 'This is a FYSA Sanctioned Tournament, which is open to all USSF/FIFA affiliated organizations for boys and girls in age groups: U9-U10 (6v6), U11-U12 (8v8), and U13-U17 (Full Sided).', 3, 1, 1, '" . date('Y-m-d 07:00:00', strtotime("+7 months", $this->time)) . "', '" . date('Y-m-d 17:00:00', strtotime("+7 months +3 days", $this->time)) . "', 1, 'Register Now', 500, 'Sorry! All available team slots for this tournament have been filled. Contact Jill Futbol for information about the waiting list and next years event.', 1, 4, NULL, 1, 'Tournament Fees',1, $eventLok3, 'Complete the form below to register your team for this year''s tournament.', '<em>A Soccer Youth Event</em>', 'Review and Confirm Your Registration Information', '', '<em>A Soccer Youth Event</em>', 1, 'Contact our Tournament Director for eligibility details.', 'Tournament Director', 'tournament@example.org', '', NULL, NULL, 'Thanks for Your Support!', '<p>Thank you for your support. Your participation will help save thousands of acres of rainforest.</p>', '<p><a href=https://civicrm.org>Back to CiviCRM Home Page</a></p>', 0, NULL, NULL, 0, 0, 'USD' )
3a2a6e86
TO
1494 ";
1495 $this->_query($event);
1496
1497 //CRM-4464
1498 $eventTemplates = "INSERT INTO civicrm_event
1499 ( is_template, template_title, event_type_id, default_role_id, participant_listing_id, is_public, is_monetary, is_online_registration, is_multiple_registrations, allow_same_participant_emails, is_email_confirm, financial_type_id, fee_label, confirm_title, thankyou_title, confirm_from_name, confirm_from_email, is_active, currency )
1500 VALUES
1501 ( 1, 'Free Meeting without Online Registration', 4, 1, 1, 1, 0, 0, null, null, null, null, null, null, null, null, null, 1, 'USD' ),
1502 ( 1, 'Free Meeting with Online Registration', 4, 1, 1, 1, 0, 1, 1, 1, 0, null, null, 'Confirm Your Registration Information', 'Thanks for Registering!', null, null, 1, 'USD' ),
1503 ( 1, 'Paid Conference with Online Registration', 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 'Conference Fee', 'Confirm Your Registration Information', 'Thanks for Registering!', 'Event Template Dept.', 'event_templates@example.org', 1, 'USD' )";
1504
1505 $this->_query($eventTemplates);
1506
1507 $ufJoinValues = $tellFriendValues = array();
1508 $profileID = CRM_Core_DAO::singleValueQuery("Select id from civicrm_uf_group where name ='event_registration'");
1509
1510 // grab id's for all events and event templates
1511 $query = "
1512SELECT id
1513 FROM civicrm_event";
1514
1515 $template = CRM_Core_DAO::executeQuery($query);
1516 while ($template->fetch()) {
1517 if ($profileID) {
1518 $ufJoinValues[] = "( 1, 'CiviEvent', 'civicrm_event', {$template->id}, 1, {$profileID} )";
1519 }
1520 $tellFriendValues[] = "( 'civicrm_event', {$template->id}, 'Tell A Friend', '<p>Help us spread the word about this event. Use the space below to personalize your email message - let your friends know why you''re attending. Then fill in the name(s) and email address(es) and click ''Send Your Message''.</p>', 'Thought you might be interested in checking out this event. I''m planning on attending.', NULL, 'Thanks for Spreading the Word', '<p>Thanks for spreading the word about this event to your friends.</p>', 1)";
1521 }
1522
1523 //insert values in civicrm_uf_join for the required event_registration profile - CRM-9587
1524 if (!empty($ufJoinValues)) {
1525 $includeProfile = "INSERT INTO civicrm_uf_join
1526 (is_active, module, entity_table, entity_id, weight, uf_group_id )
1527 VALUES " . implode(',', $ufJoinValues);
1528 $this->_query($includeProfile);
1529 }
1530
1531 //insert values in civicrm_tell_friend
1532 if (!empty($tellFriendValues)) {
1533 $tellFriend = "INSERT INTO civicrm_tell_friend
1534 (entity_table, entity_id, title, intro, suggested_message,
1535 general_link, thankyou_title, thankyou_text, is_active)
1536 VALUES " . implode(',', $tellFriendValues);
1537 $this->_query($tellFriend);
1538 }
1539 }
1540
1541 private function addParticipant() {
1542 $contact = new CRM_Contact_DAO_Contact();
1543 $contact->query("SELECT id FROM civicrm_contact");
1544 while ($contact->fetch()) {
1545 $contacts[] = $contact->id;
1546 }
0049e17a 1547 $contacts = $this->shuffle($contacts);
3a2a6e86
TO
1548 $randomContacts = array_slice($contacts, 20, 50);
1549
1550 $participant = "
1551INSERT INTO civicrm_participant
1552 (contact_id, event_id, status_id, role_id, register_date, source, fee_level, is_test, fee_amount, fee_currency)
1553VALUES
1554 ( " . $randomContacts[0] . ", 1, 1, 1, '2009-01-21', 'Check', 'Single', 0, 50, 'USD'),
1555 ( " . $randomContacts[1] . ", 2, 2, 2, '2008-05-07', 'Credit Card', 'Soprano', 0, 50, 'USD'),
1556 ( " . $randomContacts[2] . ", 3, 3, 3, '2008-05-05', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD') ,
1557 ( " . $randomContacts[3] . ", 1, 4, 4, '2008-10-21', 'Direct Transfer', 'Single', 0, 50, 'USD'),
1558 ( " . $randomContacts[4] . ", 2, 1, 1, '2008-01-10', 'Check', 'Soprano', 0, 50, 'USD'),
1559 ( " . $randomContacts[5] . ", 3, 2, 2, '2008-03-05', 'Direct Transfer', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1560 ( " . $randomContacts[6] . ", 1, 3, 3, '2009-07-21', 'Direct Transfer', 'Single', 0, 50, 'USD'),
1561 ( " . $randomContacts[7] . ", 2, 4, 4, '2009-03-07', 'Credit Card', 'Soprano', 0, 50, 'USD'),
1562 ( " . $randomContacts[8] . ", 3, 1, 1, '2008-02-05', 'Direct Transfer', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1563 ( " . $randomContacts[9] . ", 1, 2, 2, '2008-02-01', 'Check', 'Single', 0, 50, 'USD'),
1564 ( " . $randomContacts[10] . ", 2, 3, 3, '2009-01-10', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),
1565 ( " . $randomContacts[11] . ", 3, 4, 4, '2009-03-06', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1566 ( " . $randomContacts[12] . ", 1, 1, 2, '2008-06-04', 'Credit Card', 'Single', 0, 50, 'USD'),
1567 ( " . $randomContacts[13] . ", 2, 2, 3, '2008-01-10', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),
1568 ( " . $randomContacts[14] . ", 3, 4, 1, '2008-07-04', 'Check', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1569 ( " . $randomContacts[15] . ", 1, 4, 2, '2009-01-21', 'Credit Card', 'Single', 0, 50, 'USD'),
1570 ( " . $randomContacts[16] . ", 2, 2, 3, '2008-01-10', 'Credit Card', 'Soprano', 0, 50, 'USD'),
1571 ( " . $randomContacts[17] . ", 3, 3, 1, '2009-03-05', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1572 ( " . $randomContacts[18] . ", 1, 2, 1, '2008-10-21', 'Direct Transfer', 'Single', 0, 50, 'USD'),
1573 ( " . $randomContacts[19] . ", 2, 4, 1, '2009-01-10', 'Credit Card', 'Soprano', 0, 50, 'USD'),
1574 ( " . $randomContacts[20] . ", 3, 1, 4, '2008-03-25', 'Check', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1575 ( " . $randomContacts[21] . ", 1, 2, 3, '2009-10-21', 'Direct Transfer', 'Single', 0, 50, 'USD'),
1576 ( " . $randomContacts[22] . ", 2, 4, 1, '2008-01-10', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),
1577 ( " . $randomContacts[23] . ", 3, 3, 1, '2008-03-11', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1578 ( " . $randomContacts[24] . ", 3, 2, 2, '2008-04-05', 'Direct Transfer', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1579 ( " . $randomContacts[25] . ", 1, 1, 1, '2009-01-21', 'Check', 'Single', 0, 50, 'USD'),
1580 ( " . $randomContacts[26] . ", 2, 2, 2, '2008-05-07', 'Credit Card', 'Soprano', 0, 50, 'USD'),
1581 ( " . $randomContacts[27] . ", 3, 3, 3, '2009-12-12', 'Direct Transfer', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1582 ( " . $randomContacts[28] . ", 1, 4, 4, '2009-12-13', 'Credit Card', 'Single', 0, 50, 'USD'),
1583 ( " . $randomContacts[29] . ", 2, 1, 1, '2009-12-14', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),
1584 ( " . $randomContacts[30] . ", 3, 2, 2, '2009-12-15', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1585 ( " . $randomContacts[31] . ", 1, 3, 3, '2009-07-21', 'Check', 'Single', 0, 50, 'USD'),
1586 ( " . $randomContacts[32] . ", 2, 4, 4, '2009-03-07', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),
1587 ( " . $randomContacts[33] . ", 3, 1, 1, '2009-12-15', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1588 ( " . $randomContacts[34] . ", 1, 2, 2, '2009-12-13', 'Direct Transfer', 'Single', 0, 50, 'USD'),
1589 ( " . $randomContacts[35] . ", 2, 3, 3, '2009-01-10', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),
1590 ( " . $randomContacts[36] . ", 3, 4, 4, '2009-03-06', 'Check', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1591 ( " . $randomContacts[37] . ", 1, 1, 2, '2009-12-13', 'Direct Transfer', 'Single', 0, 50, 'USD'),
1592 ( " . $randomContacts[38] . ", 2, 2, 3, '2008-01-10', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),
1593 ( " . $randomContacts[39] . ", 3, 4, 1, '2009-12-14', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1594 ( " . $randomContacts[40] . ", 1, 4, 2, '2009-01-21', 'Credit Card', 'Single', 0, 50, 'USD'),
1595 ( " . $randomContacts[41] . ", 2, 2, 3, '2009-12-15', 'Credit Card', 'Soprano', 0, 50, 'USD'),
1596 ( " . $randomContacts[42] . ", 3, 3, 1, '2009-03-05', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1597 ( " . $randomContacts[43] . ", 1, 2, 1, '2009-12-13', 'Direct Transfer', 'Single', 0, 50, 'USD'),
1598 ( " . $randomContacts[44] . ", 2, 4, 1, '2009-01-10', 'Direct Transfer', 'Soprano', 0, 50, 'USD'),
1599 ( " . $randomContacts[45] . ", 3, 1, 4, '2009-12-13', 'Check', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1600 ( " . $randomContacts[46] . ", 1, 2, 3, '2009-10-21', 'Credit Card', 'Single', 0, 50, 'USD'),
1601 ( " . $randomContacts[47] . ", 2, 4, 1, '2009-12-10', 'Credit Card', 'Soprano', 0, 50, 'USD'),
1602 ( " . $randomContacts[48] . ", 3, 3, 1, '2009-03-11', 'Credit Card', 'Tiny-tots (ages 5-8)', 0, 800, 'USD'),
1603 ( " . $randomContacts[49] . ", 3, 2, 2, '2009-04-05', 'Check', 'Tiny-tots (ages 5-8)', 0, 800, 'USD');
1604";
1605 $this->_query($participant);
1606
1607 $query = "
1608INSERT INTO civicrm_activity
1609 (source_record_id, activity_type_id, subject, activity_date_time, duration, location, phone_id, phone_number, details, priority_id,parent_id, is_test, status_id)
1610VALUES
1611 (01, 5, 'NULL', '2009-01-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1612 (02, 5, 'NULL', '2008-05-07 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1613 (03, 5, 'NULL', '2008-05-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1614 (04, 5, 'NULL', '2008-10-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1615 (05, 5, 'NULL', '2008-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1616 (06, 5, 'NULL', '2008-03-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1617 (07, 5, 'NULL', '2009-07-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1618 (08, 5, 'NULL', '2009-03-07 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1619 (09, 5, 'NULL', '2008-02-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1620 (10, 5, 'NULL', '2008-02-01 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1621 (11, 5, 'NULL', '2009-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1622 (12, 5, 'NULL', '2009-03-06 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1623 (13, 5, 'NULL', '2008-06-04 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1624 (14, 5, 'NULL', '2008-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1625 (15, 5, 'NULL', '2008-07-04 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1626 (16, 5, 'NULL', '2009-01-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1627 (17, 5, 'NULL', '2008-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1628 (18, 5, 'NULL', '2009-03-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1629 (19, 5, 'NULL', '2008-10-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1630 (20, 5, 'NULL', '2009-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1631 (21, 5, 'NULL', '2008-03-25 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1632 (22, 5, 'NULL', '2009-10-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1633 (23, 5, 'NULL', '2008-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1634 (24, 5, 'NULL', '2008-03-11 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1635 (25, 5, 'NULL', '2008-04-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1636 (26, 5, 'NULL', '2009-01-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1637 (27, 5, 'NULL', '2008-05-07 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1638 (28, 5, 'NULL', '2009-12-12 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1639 (29, 5, 'NULL', '2009-12-13 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1640 (30, 5, 'NULL', '2009-12-14 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1641 (31, 5, 'NULL', '2009-12-15 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1642 (32, 5, 'NULL', '2009-07-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1643 (33, 5, 'NULL', '2009-03-07 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1644 (34, 5, 'NULL', '2009-12-15 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1645 (35, 5, 'NULL', '2009-12-13 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1646 (36, 5, 'NULL', '2009-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1647 (37, 5, 'NULL', '2009-03-06 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1648 (38, 5, 'NULL', '2009-12-13 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1649 (39, 5, 'NULL', '2008-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1650 (40, 5, 'NULL', '2009-12-14 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1651 (41, 5, 'NULL', '2009-01-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1652 (42, 5, 'NULL', '2009-12-15 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1653 (43, 5, 'NULL', '2009-03-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1654 (44, 5, 'NULL', '2009-12-13 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1655 (45, 5, 'NULL', '2009-01-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1656 (46, 5, 'NULL', '2009-12-13 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1657 (47, 5, 'NULL', '2009-10-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1658 (48, 5, 'NULL', '2009-12-10 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1659 (49, 5, 'NULL', '2009-03-11 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1660 (50, 5, 'NULL', '2009-04-05 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 )
1661 ";
1662 $this->_query($query);
1663
1664 $activityContact = "
1665INSERT INTO civicrm_activity_contact
1666 (contact_id, activity_id, record_type_id)
1667VALUES
1668";
1669 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
1670 $currentActivityID = CRM_Core_DAO::singleValueQuery("SELECT MAX(id) FROM civicrm_activity");
1671 $currentActivityID -= 50;
1672 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
1673 for ($i = 0; $i < 50; $i++) {
1674 $currentActivityID++;
1675 $activityContact .= "({$randomContacts[$i]}, $currentActivityID, $sourceID)";
1676 if ($i != 49) {
1677 $activityContact .= ", ";
1678 }
1679 }
1680 $this->_query($activityContact);
1681 }
1682
1683 private function addPCP() {
1684 $query = "
1685INSERT INTO `civicrm_pcp`
1686 (contact_id, status_id, title, intro_text, page_text, donate_link_text, page_id, page_type, is_thermometer, is_honor_roll, goal_amount, currency, is_active, pcp_block_id, is_notify)
1687VALUES
1688 ({$this->Individual[3]}, 2, 'My Personal Civi Fundraiser', 'I''m on a mission to get all my friends and family to help support my favorite open-source civic sector CRM.', '<p>Friends and family - please help build much needed infrastructure for the civic sector by supporting my personal campaign!</p>\r\n<p><a href=\"https://civicrm.org\">You can learn more about CiviCRM here</a>.</p>\r\n<p>Then click the <strong>Contribute Now</strong> button to go to our easy-to-use online contribution form.</p>', 'Contribute Now', 1, 'contribute', 1, 1, 5000.00, 'USD', 1, 1, 1);
1689";
1690 $this->_query($query);
1691 }
1692
1693 private function addContribution() {
1694 $query = "
1695INSERT INTO civicrm_contribution
1696 (contact_id, financial_type_id, payment_instrument_id, receive_date, non_deductible_amount, total_amount, trxn_id, check_number, currency, cancel_date, cancel_reason, receipt_date, thankyou_date, source )
1697VALUES
1698 (2, 1, 4, '2010-04-11 00:00:00', 0.00, 125.00, NULL, '1041', 'USD', NULL, NULL, NULL, NULL, 'Apr 2007 Mailer 1' ),
1699 (4, 1, 1, '2010-03-21 00:00:00', 0.00, 50.00, 'P20901X1', NULL, 'USD', NULL, NULL, NULL, NULL, 'Online: Save the Penguins' ),
1700 (6, 1, 4, '2010-04-29 00:00:00', 0.00, 25.00, NULL, '2095', 'USD', NULL, NULL, NULL, NULL, 'Apr 2007 Mailer 1' ),
1701 (8, 1, 4, '2010-04-11 00:00:00', 0.00, 50.00, NULL, '10552', 'USD', NULL, NULL, NULL, NULL, 'Apr 2007 Mailer 1' ),
1702 (16, 1, 4, '2010-04-15 00:00:00', 0.00, 500.00, NULL, '509', 'USD', NULL, NULL, NULL, NULL, 'Apr 2007 Mailer 1' ),
1703 (19, 1, 4, '2010-04-11 00:00:00', 0.00, 175.00, NULL, '102', 'USD', NULL, NULL, NULL, NULL, 'Apr 2007 Mailer 1' ),
1704 (82, 1, 1, '2010-03-27 00:00:00', 0.00, 50.00, 'P20193L2', NULL, 'USD', NULL, NULL, NULL, NULL, 'Online: Save the Penguins' ),
1705 (92, 1, 1, '2010-03-08 00:00:00', 0.00, 10.00, 'P40232Y3', NULL, 'USD', NULL, NULL, NULL, NULL, 'Online: Help CiviCRM' ),
1706 (34, 1, 1, '2010-04-22 00:00:00', 0.00, 250.00, 'P20193L6', NULL, 'USD', NULL, NULL, NULL, NULL, 'Online: Help CiviCRM' ),
1707 (71, 1, 1, '2009-07-01 11:53:50', 0.00, 500.00, 'PL71', NULL, 'USD', NULL, NULL, NULL, NULL, NULL ),
1708 (43, 1, 1, '2009-07-01 12:55:41', 0.00, 200.00, 'PL43II', NULL, 'USD', NULL, NULL, NULL, NULL, NULL ),
1709 (32, 1, 1, '2009-10-01 11:53:50', 0.00, 200.00, 'PL32I', NULL, 'USD', NULL, NULL, NULL, NULL, NULL ),
1710 (32, 1, 1, '2009-12-01 12:55:41', 0.00, 200.00, 'PL32II', NULL, 'USD', NULL, NULL, NULL, NULL, NULL );
1711";
1712 $this->_query($query);
1713
1714 $currentActivityID = CRM_Core_DAO::singleValueQuery("SELECT MAX(id) FROM civicrm_activity");
1715 $query = "
1716INSERT INTO civicrm_activity
1717 (source_record_id, activity_type_id, subject, activity_date_time, duration, location, phone_id, phone_number, details, priority_id,parent_id, is_test, status_id)
1718VALUES
1719 (1, 6, '$ 125.00-Apr 2007 Mailer 1', '2010-04-11 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1720 (2, 6, '$ 50.00-Online: Save the Penguins', '2010-03-21 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1721 (3, 6, '$ 25.00-Apr 2007 Mailer 1', '2010-04-29 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1722 (4, 6, '$ 50.00-Apr 2007 Mailer 1', '2010-04-11 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1723 (5, 6, '$ 500.00-Apr 2007 Mailer 1', '2010-04-15 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1724 (6, 6, '$ 175.00-Apr 2007 Mailer 1', '2010-04-11 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1725 (7, 6, '$ 50.00-Online: Save the Penguins', '2010-03-27 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1726 (8, 6, '$ 10.00-Online: Save the Penguins', '2010-03-08 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1727 (9, 6, '$ 250.00-Online: Save the Penguins', '2010-04-22 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1728 (10, 6, NULL, '2009-07-01 11:53:50', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1729 (11, 6, NULL, '2009-07-01 12:55:41', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1730 (12, 6, NULL, '2009-10-01 11:53:50', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 ),
1731 (13, 6, NULL, '2009-12-01 12:55:41', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 );
1732 ";
1733 $this->_query($query);
1734
1735 $activityContact = "
1736INSERT INTO civicrm_activity_contact
1737 (contact_id, activity_id, record_type_id)
1738VALUES
1739";
1740
1741 $arbitraryNumbers = array(2, 4, 6, 8, 16, 19, 82, 92, 34, 71, 43, 32, 32);
1742 for ($i = 0; $i < count($arbitraryNumbers); $i++) {
1743 $currentActivityID++;
1744 $activityContact .= "({$arbitraryNumbers[$i]}, $currentActivityID, 2)";
1745 if ($i != count($arbitraryNumbers) - 1) {
1746 $activityContact .= ", ";
1747 }
1748 }
1749 $this->_query($activityContact);
1750 }
1751
1752 private function addSoftContribution() {
1753
1754 $sql = "SELECT id from civicrm_contribution where contact_id = 92";
1755 $contriId1 = CRM_Core_DAO::singleValueQuery($sql);
1756
1757 $sql = "SELECT id from civicrm_contribution where contact_id = 34";
1758 $contriId2 = CRM_Core_DAO::singleValueQuery($sql);
1759
1760 $sql = "SELECT cov.value FROM civicrm_option_value cov LEFT JOIN civicrm_option_group cog ON cog.id = cov.option_group_id WHERE cov.name = 'pcp' AND cog.name = 'soft_credit_type'";
1761
1762 $pcpId = CRM_Core_DAO::singleValueQuery($sql);
1763
1764 $query = "
1765INSERT INTO `civicrm_contribution_soft`
1766 ( contribution_id, contact_id ,amount , currency, pcp_id , pcp_display_in_roll ,pcp_roll_nickname,pcp_personal_note, soft_credit_type_id )
1767VALUES
1768 ( $contriId1, {$this->Individual[3]}, 10.00, 'USD', 1, 1, 'Jones Family', 'Helping Hands', $pcpId),
1769 ( $contriId2, {$this->Individual[3]}, 250.00, 'USD', 1, 1, 'Annie and the kids', 'Annie Helps', $pcpId);
1770 ";
1771
1772 $this->_query($query);
1773 }
1774
1775 private function addPledge() {
1776 $pledge = "INSERT INTO civicrm_pledge
1777 (contact_id, financial_type_id, contribution_page_id, amount, original_installment_amount, currency,frequency_unit, frequency_interval, frequency_day, installments, start_date, create_date, acknowledge_date, modified_date, cancel_date, end_date, status_id, is_test)
1778 VALUES
1779 (71, 1, 1, 500.00, '500', 'USD', 'month', 1, 1, 1, '2009-07-01 00:00:00', '2009-06-26 00:00:00', NULL, NULL, NULL,'2009-07-01 00:00:00', 1, 0),
1780 (43, 1, 1, 800.00, '200', 'USD', 'month', 3, 1, 4, '2009-07-01 00:00:00', '2009-06-23 00:00:00', '2009-06-23 00:00:00', NULL, NULL, '2009-04-01 10:11:40', 5, 0),
1781 (32, 1, 1, 600.00, '200', 'USD', 'month', 1, 1, 3, '2009-10-01 00:00:00', '2009-09-14 00:00:00', '2009-09-14 00:00:00', NULL, NULL, '2009-12-01 00:00:00', 5, 0);
1782";
1783 $this->_query($pledge);
1784 }
1785
1786 private function addPledgePayment() {
1787 $pledgePayment = "INSERT INTO civicrm_pledge_payment
1788 ( pledge_id, contribution_id, scheduled_amount, actual_amount, currency, scheduled_date, reminder_date, reminder_count, status_id)
1789 VALUES
1790 (1, 10, 500.00, 500.00, 'USD','2009-07-01 00:00:00', null, 0, 1 ),
1791 (2, 11, 200.00, 200.00, 'USD','2009-07-01 00:00:00', null, 0, 1 ),
1792 (2, null, 200.00, null, 'USD', '2009-10-01 00:00:00', null, 0, 2 ),
1793 (2, null, 200.00, null, 'USD', '2009-01-01 00:00:00', null, 0, 2 ),
1794 (2, null, 200.00, null, 'USD', '2009-04-01 00:00:00', null, 0, 2 ),
1795
1796 (3, 12, 200.00, 200.00, 'USD', '2009-10-01 00:00:00', null, 0, 1 ),
1797 (3, 13, 200.00, 200.00, 'USD', '2009-11-01 00:0:00', '2009-10-28 00:00:00', 1, 1),
1798 (3, null, 200.00, null, 'USD', '2009-12-01 00:00:00', null, 0, 2 );
1799 ";
1800 $this->_query($pledgePayment);
1801 }
1802
1803 private function addContributionLineItem() {
1804 $query = " INSERT INTO civicrm_line_item (`entity_table`, `entity_id`, contribution_id, `price_field_id`, `label`, `qty`, `unit_price`, `line_total`, `participant_count`, `price_field_value_id`, `financial_type_id`)
1805SELECT 'civicrm_contribution', cc.id, cc.id contribution_id, cpf.id as price_field, cpfv.label, 1, cc.total_amount, cc.total_amount line_total, 0, cpfv.id as price_field_value, cpfv.financial_type_id
1806FROM civicrm_contribution cc
1807LEFT JOIN civicrm_price_set cps ON cps.name = 'default_contribution_amount'
1808LEFT JOIN civicrm_price_field cpf ON cpf.price_set_id = cps.id
1809LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = cpf.id
1810order by cc.id; ";
1811 $this->_query($query);
1812 }
1813
1814 private function addAccountingEntries() {
1815 $components = array('contribution', 'membership', 'participant');
1816 $select = 'SELECT contribution.id contribution_id, cli.id as line_item_id, contribution.contact_id, contribution.receive_date, contribution.total_amount, contribution.currency, cli.label,
1817 cli.financial_type_id, cefa.financial_account_id, contribution.payment_instrument_id, contribution.check_number, contribution.trxn_id';
1818 $where = 'WHERE cefa.account_relationship = 1';
1819 $financialAccountId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount(4);
1820 foreach ($components as $component) {
1821 if ($component == 'contribution') {
1822 $from = 'FROM `civicrm_contribution` contribution';
1823 }
1824 else {
1825 $from = " FROM `civicrm_{$component}` {$component}
1826 INNER JOIN civicrm_{$component}_payment cpp ON cpp.{$component}_id = {$component}.id
1827 INNER JOIN civicrm_contribution contribution on contribution.id = cpp.contribution_id";
1828 }
1829 $from .= " INNER JOIN civicrm_line_item cli ON cli.entity_id = {$component}.id and cli.entity_table = 'civicrm_{$component}'
1830 INNER JOIN civicrm_entity_financial_account cefa ON cefa.entity_id = cli.financial_type_id ";
1831 $sql = " {$select} {$from} {$where} ";
1832 $result = CRM_Core_DAO::executeQuery($sql);
1833 $this->addFinancialItem($result, $financialAccountId);
1834 }
1835 }
1836
1837 /**
1838 * @param $result
1839 * @param null $financialAccountId
1840 */
1841 private function addFinancialItem($result, $financialAccountId) {
1842 $defaultFinancialAccount = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1 AND financial_account_type_id = 1");
1843 while ($result->fetch()) {
1844 $trxnParams = array(
1845 'trxn_date' => CRM_Utils_Date::processDate($result->receive_date),
1846 'total_amount' => $result->total_amount,
1847 'currency' => $result->currency,
1848 'status_id' => 1,
1849 'trxn_id' => $result->trxn_id,
1850 'contribution_id' => $result->contribution_id,
1851 'to_financial_account_id' => empty($financialAccountId[$result->payment_instrument_id]) ? $defaultFinancialAccount : $financialAccountId[$result->payment_instrument_id],
1852 'payment_instrument_id' => $result->payment_instrument_id,
1853 'check_number' => $result->check_number,
1854 'is_payment' => 1,
1855 );
1856 $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
1857 $financialItem = array(
1858 'transaction_date' => CRM_Utils_Date::processDate($result->receive_date),
1859 'amount' => $result->total_amount,
1860 'currency' => $result->currency,
1861 'status_id' => 1,
1862 'entity_id' => $result->line_item_id,
1863 'contact_id' => $result->contact_id,
1864 'entity_table' => 'civicrm_line_item',
1865 'description' => $result->label,
1866 'financial_account_id' => $result->financial_account_id,
1867 );
1868 $trxnId['id'] = $trxn->id;
1869 CRM_Financial_BAO_FinancialItem::create($financialItem, NULL, $trxnId);
1870 }
1871 }
1872
1873 private function addLineItemParticipants() {
1874 $participant = new CRM_Event_DAO_Participant();
1875 $participant->query("INSERT INTO civicrm_line_item (`entity_table`, `entity_id`, contribution_id, `price_field_id`, `label`, `qty`, `unit_price`, `line_total`, `participant_count`, `price_field_value_id`, `financial_type_id`)
1876SELECT 'civicrm_participant', cp.id, cpp.contribution_id, cpfv.price_field_id, cpfv.label, 1, cpfv.amount, cpfv.amount as line_total, 0, cpfv.id, cpfv.financial_type_id FROM civicrm_participant cp LEFT JOIN civicrm_participant_payment cpp ON cpp.participant_id = cp.id
1877LEFT JOIN civicrm_price_set_entity cpe ON cpe.entity_id = cp.event_id LEFT JOIN civicrm_price_field cpf ON cpf.price_set_id = cpe.price_set_id LEFT JOIN civicrm_price_field_value cpfv ON cpfv.price_field_id = cpf.id WHERE cpfv.label = cp.fee_level");
1878 }
1879
1880 private function addMembershipPayment() {
1881 $maxContribution = CRM_Core_DAO::singleValueQuery("select max(id) from civicrm_contribution");
1882 $financialTypeID = CRM_Core_DAO::singleValueQuery("select id from civicrm_financial_type where name = 'Member Dues'");
1883 $paymentInstrumentID = CRM_Core_DAO::singleValueQuery("select value from civicrm_option_value where name = 'Credit Card' AND option_group_id = (SELECT id from civicrm_option_group where name = 'payment_instrument')");
1884 $sql = "INSERT INTO civicrm_contribution (contact_id,financial_type_id,payment_instrument_id, receive_date, total_amount, currency, source, contribution_status_id)
1885SELECT cm.contact_id, $financialTypeID, $paymentInstrumentID, now(), cmt.minimum_fee, 'USD', CONCAT(cmt.name, ' Membership: Offline signup'), 1 FROM `civicrm_membership` cm
1886LEFT JOIN civicrm_membership_type cmt ON cmt.id = cm.membership_type_id;";
1887
1888 $this->_query($sql);
1889
1890 $sql = "INSERT INTO civicrm_membership_payment (contribution_id,membership_id)
1891SELECT cc.id, cm.id FROM civicrm_contribution cc
1892LEFT JOIN civicrm_membership cm ON cm.contact_id = cc.contact_id
1893WHERE cc.id > $maxContribution;";
1894
1895 $this->_query($sql);
1896
1897 $sql = "INSERT INTO civicrm_line_item (entity_table, entity_id, contribution_id, price_field_value_id, price_field_id, label, qty, unit_price, line_total, financial_type_id)
1898SELECT 'civicrm_membership', cm.id, cmp.contribution_id, cpfv.id, cpfv.price_field_id, cpfv.label, 1, cpfv.amount, cpfv.amount as unit_price, cpfv.financial_type_id FROM `civicrm_membership` cm
1899LEFT JOIN civicrm_membership_payment cmp ON cmp.membership_id = cm.id
1900LEFT JOIN civicrm_price_field_value cpfv ON cpfv.membership_type_id = cm.membership_type_id
1901LEFT JOIN civicrm_price_field cpf ON cpf.id = cpfv.price_field_id
1902LEFT JOIN civicrm_price_set cps ON cps.id = cpf.price_set_id
1903WHERE cps.name = 'default_membership_type_amount'";
1904 $this->_query($sql);
1905
1906 $sql = "INSERT INTO civicrm_activity(source_record_id, activity_type_id, subject, activity_date_time, status_id, details)
1907SELECT id, 6, CONCAT('$ ', total_amount, ' - ', source), now(), 2, 'Membership Payment' FROM civicrm_contribution WHERE id > $maxContribution";
1908 $this->_query($sql);
1909
1910 $sql = "INSERT INTO civicrm_activity_contact(contact_id, activity_id, record_type_id)
1911SELECT c.contact_id, a.id, 2
1912FROM civicrm_contribution c, civicrm_activity a
1913WHERE c.id > $maxContribution
1914AND a.source_record_id = c.id
1915AND a.details = 'Membership Payment'
1916";
1917 $this->_query($sql);
1918 }
1919
1920 private function addParticipantPayment() {
1921 $maxContribution = CRM_Core_DAO::singleValueQuery("select max(id) from civicrm_contribution");
1922 $financialTypeID = CRM_Core_DAO::singleValueQuery("select id from civicrm_financial_type where name = 'Event Fee'");
1923 $paymentInstrumentID = CRM_Core_DAO::singleValueQuery("select value from civicrm_option_value where name = 'Credit Card' AND option_group_id = (SELECT id from civicrm_option_group where name = 'payment_instrument')");
1924 $sql = "INSERT INTO civicrm_contribution (contact_id, financial_type_id, payment_instrument_id, receive_date, total_amount, currency, receipt_date, source, contribution_status_id)
1925SELECT `contact_id`, $financialTypeID, $paymentInstrumentID, now(), `fee_amount`, 'USD', now(), CONCAT(ce.title, ' : Offline registration'), 1 FROM `civicrm_participant` cp
1926LEFT JOIN civicrm_event ce ON ce.id = cp.event_id
1927group by `contact_id`, `fee_amount`, `title`;";
1928
1929 $this->_query($sql);
1930
1931 $sql = "INSERT INTO civicrm_participant_payment (contribution_id,participant_id)
1932SELECT cc.id, cp.id FROM civicrm_contribution cc
1933LEFT JOIN civicrm_participant cp ON cp.contact_id = cc.contact_id
1934WHERE cc.id > $maxContribution";
1935
1936 $this->_query($sql);
1937
1938 $sql = "INSERT INTO civicrm_activity(source_record_id, activity_type_id, subject, activity_date_time, status_id, details)
1939SELECT id, 6, CONCAT('$ ', total_amount, ' - ', source), now(), 2, 'Participant' FROM `civicrm_contribution` WHERE id > $maxContribution";
1940 $this->_query($sql);
1941
1942 $sql = "INSERT INTO civicrm_activity_contact(contact_id, activity_id, record_type_id)
1943SELECT c.contact_id, a.id, 2
1944FROM civicrm_contribution c, civicrm_activity a
1945WHERE c.id > $maxContribution
1946AND a.source_record_id = c.id
1947AND a.details = 'Participant Payment'
1948";
1949 $this->_query($sql);
1950 }
1951
d94d506c
TO
1952 /**
1953 * @return string
1954 */
1955 protected static function getCivicrmDir():string {
1956 return dirname(dirname(dirname(__DIR__)));
1957 }
1958
3a2a6e86 1959}