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