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