Merge pull request #2391 from colemanw/arrayEmpty
[civicrm-core.git] / tests / phpunit / CiviTest / CiviSeleniumTestCase.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 require_once 'PHPUnit/Extensions/SeleniumTestCase.php';
29
30 /**
31 * Include configuration
32 */
33 define('CIVICRM_SETTINGS_PATH', __DIR__ . '/civicrm.settings.dist.php');
34 define('CIVICRM_SETTINGS_LOCAL_PATH', __DIR__ . '/civicrm.settings.local.php');
35
36 if (file_exists(CIVICRM_SETTINGS_LOCAL_PATH)) {
37 require_once CIVICRM_SETTINGS_LOCAL_PATH;
38 }
39 require_once CIVICRM_SETTINGS_PATH;
40
41 /**
42 * Base class for CiviCRM Selenium tests
43 *
44 * Common functions for unit tests
45 * @package CiviCRM
46 */
47 class CiviSeleniumTestCase extends PHPUnit_Extensions_SeleniumTestCase {
48
49 // Current logged-in user
50 protected $loggedInAs = NULL;
51
52 /**
53 * Constructor
54 *
55 * Because we are overriding the parent class constructor, we
56 * need to show the same arguments as exist in the constructor of
57 * PHPUnit_Framework_TestCase, since
58 * PHPUnit_Framework_TestSuite::createTest() creates a
59 * ReflectionClass of the Test class and checks the constructor
60 * of that class to decide how to set up the test.
61 *
62 * @param string $name
63 * @param array $data
64 * @param string $dataName
65 */
66 function __construct($name = NULL, array$data = array(), $dataName = '', array$browser = array()) {
67 parent::__construct($name, $data, $dataName, $browser);
68 $this->loggedInAs = NULL;
69
70 require_once 'CiviSeleniumSettings.php';
71 $this->settings = new CiviSeleniumSettings();
72 if (property_exists($this->settings, 'serverStartupTimeOut') && $this->settings->serverStartupTimeOut) {
73 global $CiviSeleniumTestCase_polled;
74 if (!$CiviSeleniumTestCase_polled) {
75 $CiviSeleniumTestCase_polled = TRUE;
76 CRM_Utils_Network::waitForServiceStartup(
77 $this->drivers[0]->getHost(),
78 $this->drivers[0]->getPort(),
79 $this->settings->serverStartupTimeOut
80 );
81 }
82 }
83
84 // autoload
85 require_once 'CRM/Core/ClassLoader.php';
86 CRM_Core_ClassLoader::singleton()->register();
87
88 // also initialize a connection to the db
89 // FIXME: not necessary for most tests, consider moving into functions that need this
90 $config = CRM_Core_Config::singleton();
91 }
92
93 protected function setUp() {
94 $this->setBrowser($this->settings->browser);
95 // Make sure that below strings have path separator at the end
96 $this->setBrowserUrl($this->settings->sandboxURL);
97 $this->sboxPath = $this->settings->sandboxPATH;
98 if (property_exists($this->settings, 'rcHost') && $this->settings->rcHost) {
99 $this->setHost($this->settings->rcHost);
100 }
101 if (property_exists($this->settings, 'rcPort') && $this->settings->rcPort) {
102 $this->setPort($this->settings->rcPort);
103 }
104 }
105
106 protected function tearDown() {
107 }
108
109 /**
110 * Authenticate as drupal user
111 * @param $user: (str) the key 'user' or 'admin', or a literal username
112 * @param $pass: (str) if $user is a literal username and not 'user' or 'admin', supply the password
113 */
114 function webtestLogin($user = 'user', $pass = NULL) {
115 // If already logged in as correct user, do nothing
116 if ($this->loggedInAs === $user) {
117 return;
118 }
119 // If we are logged in as a different user, log out first
120 if ($this->loggedInAs) {
121 $this->webtestLogout();
122 }
123 $this->open("{$this->sboxPath}user");
124 // Lookup username & password if not supplied
125 $username = $user;
126 if ($pass === NULL) {
127 $pass = $user == 'admin' ? $this->settings->adminPassword : $this->settings->password;
128 $username = $user == 'admin' ? $this->settings->adminUsername : $this->settings->username;
129 }
130 // Make sure login form is available
131 $this->waitForElementPresent('edit-submit');
132 $this->type('edit-name', $username);
133 $this->type('edit-pass', $pass);
134 $this->click('edit-submit');
135 $this->waitForPageToLoad($this->getTimeoutMsec());
136 $this->loggedInAs = $user;
137 }
138
139 function webtestLogout() {
140 if ($this->loggedInAs) {
141 $this->open($this->sboxPath . "user/logout");
142 $this->waitForPageToLoad($this->getTimeoutMsec());
143 }
144 $this->loggedInAs = NULL;
145 }
146
147 /**
148 * Open an internal path beginning with 'civicrm/'
149 *
150 * @param $url (str) omit the 'civicrm/' it will be added for you
151 * @param $args (str|array) optional url arguments
152 * @param $waitFor - page element to wait for - using this is recommended to ensure the document is fully loaded
153 *
154 * Although it doesn't seem to do much now, using this function is recommended for
155 * opening all civi pages, and using the $args param is also strongly encouraged
156 * This will make it much easier to run webtests in other CMSs in the future
157 */
158 function openCiviPage($url, $args = NULL, $waitFor = 'civicrm-footer') {
159 // Construct full url with args
160 // This could be extended in future to work with other CMS style urls
161 if ($args) {
162 if (is_array($args)) {
163 $sep = '?';
164 foreach ($args as $key => $val) {
165 $url .= $sep . $key . '=' . $val;
166 $sep = '&';
167 }
168 }
169 else {
170 $url .= "?$args";
171 }
172 }
173 $this->open("{$this->sboxPath}civicrm/$url");
174 $this->waitForPageToLoad($this->getTimeoutMsec());
175 if ($waitFor) {
176 $this->waitForElementPresent($waitFor);
177 }
178 }
179
180 /**
181 * Click on a link or button
182 * Wait for the page to load
183 * Wait for an element to be present
184 */
185 function clickLink($element, $waitFor = 'civicrm-footer', $waitForPageLoad = TRUE) {
186 $this->click($element);
187 // conditional wait for page load e.g for ajax form save
188 if ($waitForPageLoad) {
189 $this->waitForPageToLoad($this->getTimeoutMsec());
190 }
191 if ($waitFor) {
192 $this->waitForElementPresent($waitFor);
193 }
194 }
195
196 /**
197 * Call the API on the local server
198 * (kind of defeats the point of a webtest - see CRM-11889)
199 */
200 function webtest_civicrm_api($entity, $action, $params) {
201 if (!isset($params['version'])) {
202 $params['version'] = 3;
203 }
204
205 $result = civicrm_api($entity, $action, $params);
206 $this->assertTrue(!civicrm_error($result), 'Civicrm api error.');
207 return $result;
208 }
209
210 /**
211 * Call the API on the remote server
212 * Experimental - currently only works if permissions on remote site allow anon user to access ajax api
213 * @see CRM-11889
214 */
215 function rest_civicrm_api($entity, $action, $params = array()) {
216 $params += array(
217 'version' => 3,
218 );
219 $url = "{$this->settings->sandboxURL}/{$this->sboxPath}civicrm/ajax/rest?entity=$entity&action=$action&json=" . json_encode($params);
220 $request = array(
221 'http' => array(
222 'method' => 'POST',
223 // Naughty sidestep of civi's security checks
224 'header' => "X-Requested-With: XMLHttpRequest",
225 ),
226 );
227 $ctx = stream_context_create($request);
228 $result = file_get_contents($url, FALSE, $ctx);
229 return json_decode($result, TRUE);
230 }
231
232 function webtestGetFirstValueForOptionGroup($option_group_name) {
233 $result = $this->webtest_civicrm_api("OptionValue", "getvalue", array(
234 'option_group_name' => $option_group_name,
235 'option.limit' => 1,
236 'return' => 'value'
237 ));
238 return $result;
239 }
240
241 function webtestGetValidCountryID() {
242 static $_country_id;
243 if (is_null($_country_id)) {
244 $config_backend = $this->webtestGetConfig('countryLimit');
245 $_country_id = current($config_backend);
246 }
247 return $_country_id;
248 }
249
250 function webtestGetValidEntityID($entity) {
251 // michaelmcandrew: would like to use getvalue but there is a bug
252 // for e.g. group where option.limit not working at the moment CRM-9110
253 $result = $this->webtest_civicrm_api($entity, "get", array('option.limit' => 1, 'return' => 'id'));
254 if (!empty($result['values'])) {
255 return current(array_keys($result['values']));
256 }
257 return NULL;
258 }
259
260 function webtestGetConfig($field) {
261 static $_config_backend;
262 if (is_null($_config_backend)) {
263 $result = $this->webtest_civicrm_api("Domain", "getvalue", array(
264 'current_domain' => 1,
265 'option.limit' => 1,
266 'return' => 'config_backend'
267 ));
268 $_config_backend = unserialize($result);
269 }
270 return $_config_backend[$field];
271 }
272
273 /**
274 * Ensures the required CiviCRM components are enabled
275 */
276 function enableComponents($components) {
277 $this->openCiviPage("admin/setting/component", "reset=1", "_qf_Component_next-bottom");
278 $enabledComponents = $this->getSelectOptions("enableComponents-t");
279 $added = FALSE;
280 foreach ((array) $components as $comp) {
281 if (!in_array($comp, $enabledComponents)) {
282 $this->addSelection("enableComponents-f", "label=$comp");
283 $this->click("//option[@value='$comp']");
284 $this->click("add");
285 $added = TRUE;
286 }
287 }
288 if ($added) {
289 $this->click("_qf_Component_next-bottom");
290 $this->waitForPageToLoad($this->getTimeoutMsec());
291 $this->waitForText('crm-notification-container', "Saved");
292 }
293 }
294
295 /**
296 * Add a contact with the given first and last names and either a given email
297 * (when specified), a random email (when true) or no email (when unspecified or null).
298 *
299 * @param string $fname contact’s first name
300 * @param string $lname contact’s last name
301 * @param mixed $email contact’s email (when string) or random email (when true) or no email (when null)
302 *
303 * @return mixed either a string with the (either generated or provided) email or null (if no email)
304 */
305 function webtestAddContact($fname = 'Anthony', $lname = 'Anderson', $email = NULL, $contactSubtype = NULL) {
306 $url = $this->sboxPath . 'civicrm/contact/add?reset=1&ct=Individual';
307 if ($contactSubtype) {
308 $url = $url . "&cst={$contactSubtype}";
309 }
310 $this->open($url);
311 $this->waitForElementPresent('_qf_Contact_upload_view-bottom');
312 $this->type('first_name', $fname);
313 $this->type('last_name', $lname);
314 if ($email === TRUE) {
315 $email = substr(sha1(rand()), 0, 7) . '@example.org';
316 }
317 if ($email) {
318 $this->type('email_1_email', $email);
319 }
320 $this->waitForElementPresent('_qf_Contact_upload_view-bottom');
321 $this->click('_qf_Contact_upload_view-bottom');
322 $this->waitForPageToLoad($this->getTimeoutMsec());
323 return $email;
324 }
325
326 function webtestAddHousehold($householdName = "Smith's Home", $email = NULL) {
327
328 $this->openCiviPage("contact/add", "reset=1&ct=Household");
329 $this->click('household_name');
330 $this->type('household_name', $householdName);
331
332 if ($email === TRUE) {
333 $email = substr(sha1(rand()), 0, 7) . '@example.org';
334 }
335 if ($email) {
336 $this->type('email_1_email', $email);
337 }
338
339 $this->click('_qf_Contact_upload_view');
340 $this->waitForPageToLoad($this->getTimeoutMsec());
341 return $email;
342 }
343
344 function webtestAddOrganization($organizationName = "Organization XYZ", $email = NULL, $contactSubtype = NULL) {
345
346 $url = $this->sboxPath . 'civicrm/contact/add?reset=1&ct=Organization';
347 if ($contactSubtype) {
348 $url = $url . "&cst={$contactSubtype}";
349 }
350 $this->open($url);
351 $this->click('organization_name');
352 $this->type('organization_name', $organizationName);
353
354 if ($email === TRUE) {
355 $email = substr(sha1(rand()), 0, 7) . '@example.org';
356 }
357 if ($email) {
358 $this->type('email_1_email', $email);
359 }
360 $this->click('_qf_Contact_upload_view');
361 $this->waitForPageToLoad($this->getTimeoutMsec());
362 return $email;
363 }
364
365 /**
366 */
367 function webtestFillAutocomplete($sortName, $fieldName = 'contact_1') {
368 $this->click($fieldName);
369 $this->type($fieldName, $sortName);
370 $this->typeKeys($fieldName, $sortName);
371 $this->waitForElementPresent("css=div.ac_results-inner li");
372 $this->click("css=div.ac_results-inner li");
373 $this->assertContains($sortName, $this->getValue($fieldName), "autocomplete expected $sortName but didn’t find it in " . $this->getValue($fieldName));
374 }
375
376 /**
377 */
378 function webtestOrganisationAutocomplete($sortName) {
379 $this->type('contact_name', $sortName);
380 $this->click('contact_name');
381 $this->waitForElementPresent("css=div.ac_results-inner li");
382 $this->click("css=div.ac_results-inner li");
383 //$this->assertContains($sortName, $this->getValue('contact_1'), "autocomplete expected $sortName but didn’t find it in " . $this->getValue('contact_1'));
384 }
385
386 /*
387 * 1. By default, when no strtotime arg is specified, sets date to "now + 1 month"
388 * 2. Does not set time. For setting both date and time use webtestFillDateTime() method.
389 * 3. Examples of $strToTime arguments -
390 * webtestFillDate('start_date',"now")
391 * webtestFillDate('start_date',"10 September 2000")
392 * webtestFillDate('start_date',"+1 day")
393 * webtestFillDate('start_date',"+1 week")
394 * webtestFillDate('start_date',"+1 week 2 days 4 hours 2 seconds")
395 * webtestFillDate('start_date',"next Thursday")
396 * webtestFillDate('start_date',"last Monday")
397 */
398 function webtestFillDate($dateElement, $strToTimeArgs = NULL) {
399 $timeStamp = strtotime($strToTimeArgs ? $strToTimeArgs : '+1 month');
400
401 $year = date('Y', $timeStamp);
402 // -1 ensures month number is inline with calender widget's month
403 $mon = date('n', $timeStamp) - 1;
404 $day = date('j', $timeStamp);
405
406 $this->click("{$dateElement}_display");
407 $this->waitForElementPresent("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month");
408 $this->select("css=div#ui-datepicker-div.ui-datepicker div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-month", "value=$mon");
409 $this->select("css=div#ui-datepicker-div div.ui-datepicker-header div.ui-datepicker-title select.ui-datepicker-year", "value=$year");
410 $this->click("link=$day");
411 }
412
413 // 1. set both date and time.
414 function webtestFillDateTime($dateElement, $strToTimeArgs = NULL) {
415 $this->webtestFillDate($dateElement, $strToTimeArgs);
416
417 $timeStamp = strtotime($strToTimeArgs ? $strToTimeArgs : '+1 month');
418 $hour = date('h', $timeStamp);
419 $min = date('i', $timeStamp);
420 $meri = date('A', $timeStamp);
421
422 $this->type("{$dateElement}_time", "{$hour}:{$min}{$meri}");
423 }
424
425 /**
426 * Verify that given label/value pairs are in *sibling* td cells somewhere on the page.
427 *
428 * @param array $expected Array of key/value pairs (like Status/Registered) to be checked
429 * @param string $xpathPrefix Pass in an xpath locator to "get to" the desired table or tables. Will be prefixed to xpath
430 * table path. Include leading forward slashes (e.g. "//div[@id='activity-content']").
431 * @param string $tableId Pass in the id attribute of a table to be verified if you want to only check a specific table
432 * on the web page.
433 */
434 function webtestVerifyTabularData($expected, $xpathPrefix = NULL, $tableId = NULL) {
435 $tableLocator = "";
436 if ($tableId) {
437 $tableLocator = "[@id='$tableId']";
438 }
439 foreach ($expected as $label => $value) {
440 if ($xpathPrefix) {
441 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td{$xpathPrefix}[text()='{$label}']/../following-sibling::td", preg_quote($value), 'In line ' . __LINE__);
442 }
443 else {
444 $this->verifyText("xpath=//table{$tableLocator}/tbody/tr/td[text()='{$label}']/following-sibling::td", preg_quote($value), 'In line ' . __LINE__);
445 }
446 }
447 }
448
449 /**
450 * Types text into a ckEditor rich text field in a form
451 *
452 * @param string $fieldName form field name (as assigned by PHP buildForm class)
453 * @param string $text text to type into the field
454 * @param string $editor which text editor (valid values are 'CKEditor', 'TinyMCE')
455 *
456 * @return void
457 */
458 function fillRichTextField($fieldName, $text = 'Typing this text into editor.', $editor = 'CKEditor') {
459 // make sure cursor focuses on the field
460 $this->fireEvent($fieldName, 'focus');
461 if ($editor == 'CKEditor') {
462 $this->waitForElementPresent("xpath=//div[@id='cke_{$fieldName}']//iframe");
463 $this->runScript("CKEDITOR.instances['{$fieldName}'].setData('<p>{$text}</p>');");
464 }
465 elseif ($editor == 'TinyMCE') {
466 $this->waitForElementPresent("xpath=//iframe[@id='{$fieldName}_ifr']");
467 $this->runScript("tinyMCE.activeEditor.setContent('<p>{$text}</p>');");
468 }
469 else {
470 $this->fail("Unknown editor value: $editor, failing (in CiviSeleniumTestCase::fillRichTextField ...");
471 }
472 $this->selectFrame('relative=top');
473 }
474
475 /**
476 * Types option label and name into a table of multiple choice options
477 * (for price set fields of type select, radio, or checkbox)
478 * TODO: extend for custom field multiple choice table input
479 *
480 * @param array $options form field name (as assigned by PHP buildForm class)
481 * @param array $validateStrings appends label and name strings to this array so they can be validated later
482 *
483 * @return void
484 */
485 function addMultipleChoiceOptions($options, &$validateStrings) {
486 foreach ($options as $oIndex => $oValue) {
487 $validateStrings[] = $oValue['label'];
488 $validateStrings[] = $oValue['amount'];
489 if (!empty($oValue['membership_type_id'])) {
490 $this->select("membership_type_id_{$oIndex}", "value={$oValue['membership_type_id']}");
491 }
492 if (!empty($oValue['financial_type_id'])) {
493 $this->select("option_financial_type_id_{$oIndex}", "label={$oValue['financial_type_id']}");
494 }
495 $this->type("option_label_{$oIndex}", $oValue['label']);
496 $this->type("option_amount_{$oIndex}", $oValue['amount']);
497 $this->click('link=another choice');
498 }
499 }
500
501 /**
502 */
503 function webtestNewDialogContact($fname = 'Anthony', $lname = 'Anderson', $email = 'anthony@anderson.biz',
504 $type = 4, $selectId = 'profiles_1', $row = 1, $prefix = '') {
505 // 4 - Individual profile
506 // 5 - Organization profile
507 // 6 - Household profile
508 $this->select($selectId, "value={$type}");
509
510 // create new contact using dialog
511 if (!$prefix) {
512 $this->waitForElementPresent("css=div#contact-dialog-{$row}");
513 }
514 else {
515 $this->waitForElementPresent("css=div#contact-dialog-{$prefix}_{$row}");
516 }
517 $this->waitForElementPresent('_qf_Edit_next');
518
519 switch ($type) {
520 case 4:
521 $this->type('first_name', $fname);
522 $this->type('last_name', $lname);
523 break;
524
525 case 5:
526 $this->type('organization_name', $fname);
527 break;
528
529 case 6:
530 $this->type('household_name', $fname);
531 break;
532 }
533
534 $this->type('email-Primary', $email);
535 $this->click('_qf_Edit_next');
536
537 // Is new contact created?
538 if ($lname) {
539 $this->assertTrue($this->isTextPresent("$fname $lname has been created."), "Status message didn't show up after saving!");
540 }
541 else {
542 $this->assertTrue($this->isTextPresent("$fname has been created."), "Status message didn't show up after saving!");
543 }
544 }
545
546 /**
547 * Generic function to check that strings are present in the page
548 *
549 * @strings array array of strings or a single string
550 *
551 * @return void
552 */
553 function assertStringsPresent($strings) {
554 foreach ((array) $strings as $string) {
555 $this->assertTrue($this->isTextPresent($string), "Could not find $string on page");
556 }
557 }
558
559 /**
560 * Generic function to parse a URL string into it's elements.extract a variable value from a string (url)
561 *
562 * @url string url to parse or retrieve current url if null
563 *
564 * @return array returns an associative array containing any of the various components
565 * of the URL that are present. Querystring elements are returned in sub-array (elements.queryString)
566 * http://php.net/manual/en/function.parse-url.php
567 *
568 */
569 function parseURL($url = NULL) {
570 if (!$url) {
571 $url = $this->getLocation();
572 }
573
574 $elements = parse_url($url);
575 if (!empty($elements['query'])) {
576 $elements['queryString'] = array();
577 parse_str($elements['query'], $elements['queryString']);
578 }
579 return $elements;
580 }
581
582 /**
583 * Returns a single argument from the url query
584 */
585 function urlArg($arg, $url = NULL) {
586 $elements = $this->parseURL($url);
587 return isset($elements['queryString'][$arg]) ? $elements['queryString'][$arg] : NULL;
588 }
589
590 /**
591 * Define a payment processor for use by a webtest. Default is to create Dummy processor
592 * which is useful for testing online public forms (online contribution pages and event registration)
593 *
594 * @param string $processorName Name assigned to new processor
595 * @param string $processorType Name for processor type (e.g. PayPal, Dummy, etc.)
596 * @param array $processorSettings Array of fieldname => value for required settings for the processor
597 *
598 * @return void
599 */
600
601 function webtestAddPaymentProcessor($processorName, $processorType = 'Dummy', $processorSettings = NULL, $financialAccount = 'Deposit Bank Account') {
602 if (!$processorName) {
603 $this->fail("webTestAddPaymentProcessor requires $processorName.");
604 }
605 if ($processorType == 'Dummy') {
606 $processorSettings = array(
607 'user_name' => 'dummy',
608 'url_site' => 'http://dummy.com',
609 'test_user_name' => 'dummytest',
610 'test_url_site' => 'http://dummytest.com',
611 );
612 }
613 elseif ($processorType == 'AuthNet') {
614 // FIXME: we 'll need to make a new separate account for testing
615 $processorSettings = array(
616 'test_user_name' => '5ULu56ex',
617 'test_password' => '7ARxW575w736eF5p',
618 );
619 }
620 elseif ($processorType == 'Google_Checkout') {
621 // FIXME: we 'll need to make a new separate account for testing
622 $processorSettings = array(
623 'test_user_name' => '559999327053114',
624 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
625 );
626 }
627 elseif ($processorType == 'PayPal') {
628 $processorSettings = array(
629 'test_user_name' => '559999327053114',
630 'test_password' => 'R2zv2g60-A7GXKJYl0nR0g',
631 'test_signature' => 'R2zv2g60-A7GXKJYl0nR0g',
632 );
633 }
634 elseif ($processorType == 'PayPal_Standard') {
635 $processorSettings = array(
636 'test_user_name' => 'V18ki@9r5Bf.org',
637 );
638 }
639 elseif (empty($processorSettings)) {
640 $this->fail("webTestAddPaymentProcessor requires $processorSettings array if processorType is not Dummy.");
641 }
642 $pid = CRM_Core_DAO::getFieldValue("CRM_Financial_DAO_PaymentProcessorType", $processorType, "id", "name");
643 if (empty($pid)) {
644 $this->fail("$processorType processortype not found.");
645 }
646 $this->open($this->sboxPath . 'civicrm/admin/paymentProcessor?action=add&reset=1&pp=' . $pid);
647 $this->waitForPageToLoad($this->getTimeoutMsec());
648 $this->type('name', $processorName);
649 $this->select('financial_account_id', "label={$financialAccount}");
650
651 foreach ($processorSettings AS $f => $v) {
652 $this->type($f, $v);
653 }
654 $this->click('_qf_PaymentProcessor_next-bottom');
655 $this->waitForPageToLoad($this->getTimeoutMsec());
656 // Is new processor created?
657 $this->assertTrue($this->isTextPresent($processorName), 'Processor name not found in selector after adding payment processor (webTestAddPaymentProcessor).');
658
659 $paymentProcessorId = explode('&id=', $this->getAttribute("xpath=//table[@class='selector']//tbody//tr/td[text()='{$processorName}']/../td[7]/span/a[1]@href"));
660 $paymentProcessorId = explode('&', $paymentProcessorId[1]);
661 return $paymentProcessorId[0];
662 }
663
664 function webtestAddCreditCardDetails() {
665 $this->waitForElementPresent('credit_card_type');
666 $this->select('credit_card_type', 'label=Visa');
667 $this->type('credit_card_number', '4807731747657838');
668 $this->type('cvv2', '123');
669 $this->select('credit_card_exp_date[M]', 'label=Feb');
670 $this->select('credit_card_exp_date[Y]', 'label=2019');
671 }
672
673 function webtestAddBillingDetails($firstName = NULL, $middleName = NULL, $lastName = NULL) {
674 if (!$firstName) {
675 $firstName = 'John';
676 }
677
678 if (!$middleName) {
679 $middleName = 'Apple';
680 }
681
682 if (!$lastName) {
683 $lastName = 'Smith_' . substr(sha1(rand()), 0, 7);
684 }
685
686 $this->type('billing_first_name', $firstName);
687 $this->type('billing_middle_name', $middleName);
688 $this->type('billing_last_name', $lastName);
689
690 $this->type('billing_street_address-5', '234 Lincoln Ave');
691 $this->type('billing_city-5', 'San Bernadino');
692 $this->click('billing_state_province_id-5');
693 $this->select('billing_state_province_id-5', 'label=California');
694 $this->select('billing_country_id-5', 'value=1228');
695 $this->type('billing_postal_code-5', '93245');
696
697 return array($firstName, $middleName, $lastName);
698 }
699
700 function webtestAttachFile($fieldLocator, $filePath = NULL) {
701 if (!$filePath) {
702 $filePath = '/tmp/testfile_' . substr(sha1(rand()), 0, 7) . '.txt';
703 $fp = @fopen($filePath, 'w');
704 fputs($fp, 'Test file created by selenium test.');
705 @fclose($fp);
706 }
707
708 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
709
710 $this->attachFile($fieldLocator, "file://{$filePath}");
711
712 return $filePath;
713 }
714
715 function webtestCreateCSV($headers, $rows, $filePath = NULL) {
716 if (!$filePath) {
717 $filePath = '/tmp/testcsv_' . substr(sha1(rand()), 0, 7) . '.csv';
718 }
719
720 $data = '"' . implode('", "', $headers) . '"' . "\r\n";
721
722 foreach ($rows as $row) {
723 $temp = array();
724 foreach ($headers as $field => $header) {
725 $temp[$field] = isset($row[$field]) ? '"' . $row[$field] . '"' : '""';
726 }
727 $data .= implode(', ', $temp) . "\r\n";
728 }
729
730 $fp = @fopen($filePath, 'w');
731 @fwrite($fp, $data);
732 @fclose($fp);
733
734 $this->assertTrue(file_exists($filePath), 'Not able to locate file: ' . $filePath);
735
736 return $filePath;
737 }
738
739 /**
740 * Create new relationship type w/ user specified params or default.
741 *
742 * @param $params array of required params.
743 *
744 * @return an array of saved params values.
745 */
746 function webtestAddRelationshipType($params = array()) {
747 $this->openCiviPage("admin/reltype", "reset=1&action=add");
748
749 //build the params if not passed.
750 if (!is_array($params) || empty($params)) {
751 $params = array(
752 'label_a_b' => 'Test Relationship Type A - B -' . rand(),
753 'label_b_a' => 'Test Relationship Type B - A -' . rand(),
754 'contact_types_a' => 'Individual',
755 'contact_types_b' => 'Individual',
756 'description' => 'Test Relationship Type Description',
757 );
758 }
759 //make sure we have minimum required params.
760 if (!isset($params['label_a_b']) || empty($params['label_a_b'])) {
761 $params['label_a_b'] = 'Test Relationship Type A - B -' . rand();
762 }
763
764 //start the form fill.
765 $this->type('label_a_b', $params['label_a_b']);
766 $this->type('label_b_a', $params['label_b_a']);
767 $this->select('contact_types_a', "value={$params['contact_type_a']}");
768 $this->select('contact_types_b', "value={$params['contact_type_b']}");
769 $this->type('description', $params['description']);
770
771 //save the data.
772 $this->click('_qf_RelationshipType_next-bottom');
773 $this->waitForPageToLoad($this->getTimeoutMsec());
774
775 //does data saved.
776 $this->assertTrue($this->isTextPresent('The Relationship Type has been saved.'),
777 "Status message didn't show up after saving!"
778 );
779
780 $this->openCiviPage("admin/reltype", "reset=1");
781
782 //validate data on selector.
783 $data = $params;
784 if (isset($data['description'])) {
785 unset($data['description']);
786 }
787 $this->assertStringsPresent($data);
788
789 return $params;
790 }
791
792 /**
793 * Create new online contribution page w/ user specified params or defaults.
794 * FIXME: this function take an absurd number of params - very unwieldy :(
795 *
796 * @param User can define pageTitle, hash and rand values for later data verification
797 *
798 * @return $pageId of newly created online contribution page.
799 */
800 function webtestAddContributionPage($hash = NULL,
801 $rand = NULL,
802 $pageTitle = NULL,
803 $processor = array('Dummy Processor' => 'Dummy'),
804 $amountSection = TRUE,
805 $payLater = TRUE,
806 $onBehalf = TRUE,
807 $pledges = TRUE,
808 $recurring = FALSE,
809 $membershipTypes = TRUE,
810 $memPriceSetId = NULL,
811 $friend = TRUE,
812 $profilePreId = 1,
813 $profilePostId = 7,
814 $premiums = TRUE,
815 $widget = TRUE,
816 $pcp = TRUE,
817 $isAddPaymentProcessor = TRUE,
818 $isPcpApprovalNeeded = FALSE,
819 $isSeparatePayment = FALSE,
820 $honoreeSection = TRUE,
821 $allowOtherAmmount = TRUE,
822 $isConfirmEnabled = TRUE,
823 $financialType = 'Donation',
824 $fixedAmount = TRUE,
825 $membershipsRequired = TRUE
826 ) {
827 if (!$hash) {
828 $hash = substr(sha1(rand()), 0, 7);
829 }
830 if (!$pageTitle) {
831 $pageTitle = 'Donate Online ' . $hash;
832 }
833
834 if (!$rand) {
835 $rand = 2 * rand(2, 50);
836 }
837
838 // Create a new payment processor if requested
839 if ($isAddPaymentProcessor) {
840 while (list($processorName, $processorType) = each($processor)) {
841 $this->webtestAddPaymentProcessor($processorName, $processorType);
842 }
843 }
844
845 // go to the New Contribution Page page
846 $this->openCiviPage('admin/contribute', 'action=add&reset=1');
847
848 // fill in step 1 (Title and Settings)
849 $this->type('title', $pageTitle);
850
851 //to select financial type
852 $this->select('financial_type_id', "label={$financialType}");
853
854 if ($onBehalf) {
855 $this->click('is_organization');
856 $this->select('onbehalf_profile_id', 'label=On Behalf Of Organization');
857 $this->type('for_organization', "On behalf $hash");
858
859 if ($onBehalf == 'required') {
860 $this->click('CIVICRM_QFID_2_4');
861 }
862 elseif ($onBehalf == 'optional') {
863 $this->click('CIVICRM_QFID_1_2');
864 }
865 }
866
867 $this->fillRichTextField('intro_text', 'This is introductory message for ' . $pageTitle, 'CKEditor');
868 $this->fillRichTextField('footer_text', 'This is footer message for ' . $pageTitle, 'CKEditor');
869
870 $this->type('goal_amount', 10 * $rand);
871
872 // FIXME: handle Start/End Date/Time
873 if ($honoreeSection) {
874 $this->click('honor_block_is_active');
875 $this->type('honor_block_title', "Honoree Section Title $hash");
876 $this->type('honor_block_text', "Honoree Introductory Message $hash");
877 }
878
879 // is confirm enabled? it starts out enabled, so uncheck it if false
880 if (!$isConfirmEnabled) {
881 $this->click("id=is_confirm_enabled");
882 }
883
884 // Submit form
885 $this->clickLink('_qf_Settings_next', "_qf_Amount_next-bottom");
886
887 // Get contribution page id
888 $pageId = $this->urlArg('id');
889
890 // fill in step 2 (Processor, Pay Later, Amounts)
891 if (!empty($processor)) {
892 reset($processor);
893 while (list($processorName) = each($processor)) {
894 // select newly created processor
895 $xpath = "xpath=//label[text() = '{$processorName}']/preceding-sibling::input[1]";
896 $this->assertTrue($this->isTextPresent($processorName));
897 $this->check($xpath);
898 }
899 }
900
901 if ($amountSection && !$memPriceSetId) {
902 if ($payLater) {
903 $this->click('is_pay_later');
904 $this->type('pay_later_text', "Pay later label $hash");
905 $this->fillRichTextField('pay_later_receipt', "Pay later instructions $hash");
906 }
907
908 if ($pledges) {
909 $this->click('is_pledge_active');
910 $this->click('pledge_frequency_unit[week]');
911 $this->click('is_pledge_interval');
912 $this->type('initial_reminder_day', 3);
913 $this->type('max_reminders', 2);
914 $this->type('additional_reminder_day', 1);
915 }
916 elseif ($recurring) {
917 $this->click('is_recur');
918 $this->click("is_recur_interval");
919 $this->click("is_recur_installments");
920 }
921 if ($allowOtherAmmount) {
922
923 $this->click('is_allow_other_amount');
924
925 // there shouldn't be minimums and maximums on test contribution forms unless you specify it
926 //$this->type('min_amount', $rand / 2);
927 //$this->type('max_amount', $rand * 10);
928 }
929 if ($fixedAmount || !$allowOtherAmmount) {
930 $this->type('label_1', "Label $hash");
931 $this->type('value_1', "$rand");
932 }
933 $this->click('CIVICRM_QFID_1_2');
934 }
935 else {
936 $this->click('amount_block_is_active');
937 }
938
939 $this->click('_qf_Amount_next');
940 $this->waitForElementPresent('_qf_Amount_next-bottom');
941 $this->waitForPageToLoad($this->getTimeoutMsec());
942 $text = "'Amount' information has been saved.";
943 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
944
945 if ($memPriceSetId || (($membershipTypes === TRUE) || (is_array($membershipTypes) && !empty($membershipTypes)))) {
946 // go to step 3 (memberships)
947 $this->click('link=Memberships');
948 $this->waitForElementPresent('_qf_MembershipBlock_next-bottom');
949
950 // fill in step 3 (Memberships)
951 $this->click('member_is_active');
952 $this->waitForElementPresent('displayFee');
953 $this->type('new_title', "Title - New Membership $hash");
954 $this->type('renewal_title', "Title - Renewals $hash");
955
956 if ($memPriceSetId) {
957 $this->click('member_price_set_id');
958 $this->select('member_price_set_id', "value={$memPriceSetId}");
959 }
960 else {
961 if ($membershipTypes === TRUE) {
962 $membershipTypes = array(array('id' => 2));
963 }
964
965 // FIXME: handle Introductory Message - New Memberships/Renewals
966 foreach ($membershipTypes as $mType) {
967 $this->click("membership_type_{$mType['id']}");
968 if (array_key_exists('default', $mType)) {
969 // FIXME:
970 }
971 if (array_key_exists('auto_renew', $mType)) {
972 $this->select("auto_renew_{$mType['id']}", "label=Give option");
973 }
974 }
975 if ($membershipsRequired) {
976 $this->click('is_required');
977 }
978 $this->waitForElementPresent('CIVICRM_QFID_2_4');
979 $this->click('CIVICRM_QFID_2_4');
980 if ($isSeparatePayment) {
981 $this->click('is_separate_payment');
982 }
983 }
984 $this->clickLink('_qf_MembershipBlock_next', '_qf_MembershipBlock_next-bottom');
985 $text = "'MembershipBlock' information has been saved.";
986 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
987 }
988
989 // go to step 4 (thank-you and receipting)
990 $this->click('link=Receipt');
991 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
992
993 // fill in step 4
994 $this->type('thankyou_title', "Thank-you Page Title $hash");
995 // FIXME: handle Thank-you Message/Page Footer
996 $this->type('receipt_from_name', "Receipt From Name $hash");
997 $this->type('receipt_from_email', "$hash@example.org");
998 $this->type('receipt_text', "Receipt Message $hash");
999 $this->type('cc_receipt', "$hash@example.net");
1000 $this->type('bcc_receipt', "$hash@example.com");
1001
1002 $this->click('_qf_ThankYou_next');
1003 $this->waitForElementPresent('_qf_ThankYou_next-bottom');
1004 $this->waitForPageToLoad($this->getTimeoutMsec());
1005 $text = "'ThankYou' information has been saved.";
1006 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1007
1008 if ($friend) {
1009 // fill in step 5 (Tell a Friend)
1010 $this->click('link=Tell a Friend');
1011 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1012 $this->click('tf_is_active');
1013 $this->type('tf_title', "TaF Title $hash");
1014 $this->type('intro', "TaF Introduction $hash");
1015 $this->type('suggested_message', "TaF Suggested Message $hash");
1016 $this->type('general_link', "TaF Info Page Link $hash");
1017 $this->type('tf_thankyou_title', "TaF Thank-you Title $hash");
1018 $this->type('tf_thankyou_text', "TaF Thank-you Message $hash");
1019
1020 //$this->click('_qf_Contribute_next');
1021 $this->click('_qf_Contribute_next-bottom');
1022 $this->waitForPageToLoad($this->getTimeoutMsec());
1023 $text = "'Friend' information has been saved.";
1024 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1025 }
1026
1027 if ($profilePreId || $profilePostId) {
1028 // fill in step 6 (Include Profiles)
1029 $this->click('css=li#tab_custom a');
1030 $this->waitForElementPresent('_qf_Custom_next-bottom');
1031
1032 if ($profilePreId) {
1033 $this->select('custom_pre_id', "value={$profilePreId}");
1034 }
1035
1036 if ($profilePostId) {
1037 $this->select('custom_post_id', "value={$profilePostId}");
1038 }
1039
1040 $this->click('_qf_Custom_next-bottom');
1041 //$this->waitForElementPresent('_qf_Custom_next-bottom');
1042
1043 $this->waitForPageToLoad($this->getTimeoutMsec());
1044 $text = "'Custom' information has been saved.";
1045 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1046 }
1047
1048 if ($premiums) {
1049 // fill in step 7 (Premiums)
1050 $this->click('link=Premiums');
1051 $this->waitForElementPresent('_qf_Premium_next-bottom');
1052 $this->click('premiums_active');
1053 $this->type('premiums_intro_title', "Prem Title $hash");
1054 $this->type('premiums_intro_text', "Prem Introductory Message $hash");
1055 $this->type('premiums_contact_email', "$hash@example.info");
1056 $this->type('premiums_contact_phone', rand(100000000, 999999999));
1057 $this->click('premiums_display_min_contribution');
1058 $this->type('premiums_nothankyou_label', 'No thank-you');
1059 $this->click('_qf_Premium_next');
1060 $this->waitForElementPresent('_qf_Premium_next-bottom');
1061
1062 $this->waitForPageToLoad($this->getTimeoutMsec());
1063 $text = "'Premium' information has been saved.";
1064 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1065 }
1066
1067 if ($widget) {
1068 // fill in step 8 (Widget Settings)
1069 $this->click('link=Widgets');
1070 $this->waitForElementPresent('_qf_Widget_next-bottom');
1071
1072 $this->click('is_active');
1073 $this->type('url_logo', "URL to Logo Image $hash");
1074 $this->type('button_title', "Button Title $hash");
1075 // Type About text in ckEditor (fieldname, text to type, editor)
1076 $this->fillRichTextField('about', 'This is for ' . $pageTitle, 'CKEditor');
1077
1078 $this->click('_qf_Widget_next');
1079 $this->waitForElementPresent('_qf_Widget_next-bottom');
1080
1081 $this->waitForPageToLoad($this->getTimeoutMsec());
1082 $text = "'Widget' information has been saved.";
1083 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1084 }
1085
1086 if ($pcp) {
1087 // fill in step 9 (Enable Personal Campaign Pages)
1088 $this->click('link=Personal Campaigns');
1089 $this->waitForElementPresent('_qf_Contribute_next-bottom');
1090 $this->click('pcp_active');
1091 if (!$isPcpApprovalNeeded) {
1092 $this->click('is_approval_needed');
1093 }
1094 $this->type('notify_email', "$hash@example.name");
1095 $this->select('supporter_profile_id', 'value=2');
1096 $this->type('tellfriend_limit', 7);
1097 $this->type('link_text', "'Create Personal Campaign Page' link text $hash");
1098
1099 $this->click('_qf_Contribute_next-bottom');
1100 //$this->waitForElementPresent('_qf_PCP_next-bottom');
1101 $this->waitForPageToLoad($this->getTimeoutMsec());
1102 $text = "'Pcp' information has been saved.";
1103 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1104 }
1105
1106 return $pageId;
1107 }
1108
1109 /**
1110 * Function to update default strict rule.
1111 *
1112 * @params string $contactType Contact type
1113 * @param array $fields Fields to be set for strict rule
1114 * @param Integer $threshold Rule's threshold value
1115 */
1116 function webtestStrictDedupeRuleDefault($contactType = 'Individual', $fields = array(), $threshold = 10) {
1117 // set default strict rule.
1118 $strictRuleId = 4;
1119 if ($contactType == 'Organization') {
1120 $strictRuleId = 5;
1121 }
1122 elseif ($contactType == 'Household') {
1123 $strictRuleId = 6;
1124 }
1125
1126 // Default dedupe fields for each Contact type.
1127 if (empty($fields)) {
1128 $fields = array('civicrm_email.email' => 10);
1129 if ($contactType == 'Organization') {
1130 $fields = array(
1131 'civicrm_contact.organization_name' => 10,
1132 'civicrm_email.email' => 10,
1133 );
1134 }
1135 elseif ($contactType == 'Household') {
1136 $fields = array(
1137 'civicrm_contact.household_name' => 10,
1138 'civicrm_email.email' => 10,
1139 );
1140 }
1141 }
1142
1143 $this->openCiviPage('contact/deduperules', "action=update&id=$strictRuleId", '_qf_DedupeRules_next-bottom');
1144
1145 $count = 0;
1146 foreach ($fields as $field => $weight) {
1147 $this->select("where_{$count}", "value={$field}");
1148 $this->type("length_{$count}", '');
1149 $this->type("weight_{$count}", $weight);
1150 $count++;
1151 }
1152
1153 if ($count > 4) {
1154 $this->type('threshold', $threshold);
1155 // click save
1156 $this->click('_qf_DedupeRules_next-bottom');
1157 $this->waitForPageToLoad($this->getTimeoutMsec());
1158 return;
1159 }
1160
1161 for ($i = $count; $i <= 4; $i++) {
1162 $this->select("where_{$i}", 'label=- none -');
1163 $this->type("length_{$i}", '');
1164 $this->type("weight_{$i}", '');
1165 }
1166
1167 $this->type('threshold', $threshold);
1168
1169 // click save
1170 $this->click('_qf_DedupeRules_next-bottom');
1171 $this->waitForPageToLoad($this->getTimeoutMsec());
1172 }
1173
1174 function webtestAddMembershipType($period_type = 'rolling', $duration_interval = 1, $duration_unit = 'year', $auto_renew = 'no') {
1175 $membershipTitle = substr(sha1(rand()), 0, 7);
1176 $membershipOrg = $membershipTitle . ' memorg';
1177 $this->webtestAddOrganization($membershipOrg, TRUE);
1178
1179 $title = 'Membership Type ' . substr(sha1(rand()), 0, 7);
1180 $memTypeParams = array(
1181 'membership_type' => $title,
1182 'member_of_contact' => $membershipOrg,
1183 'financial_type' => 2,
1184 'period_type' => $period_type,
1185 );
1186
1187 $this->openCiviPage("admin/member/membershipType/add", "action=add&reset=1", '_qf_MembershipType_cancel-bottom');
1188
1189 $this->type('name', $memTypeParams['membership_type']);
1190
1191 // if auto_renew optional or required - a valid payment processor must be created first (e.g Auth.net)
1192 // select the radio first since the element id changes after membership org search results are loaded
1193 switch ($auto_renew) {
1194 case 'optional':
1195 $this->click("xpath=//div[@id='membership_type_form']//table/tbody/tr[6]/td/label[contains(text(), 'Auto-renew Option')]/../../td[2]/label[contains(text(), 'Give option, but not required')]");
1196 break;
1197
1198 case 'required':
1199 $this->click("xpath=//div[@id='membership_type_form']//table/tbody/tr[6]/td/label[contains(text(), 'Auto-renew Option')]/../../td[2]/label[contains(text(), 'Auto-renew required')]");
1200 break;
1201
1202 default:
1203 //check if for the element presence (the Auto renew options can be absent when proper payment processor not configured)
1204 if ($this->isElementPresent("xpath=//div[@id='membership_type_form']//table/tbody/tr[6]/td/label[contains(text(), 'Auto-renew Option')]/../../td[2]/label[contains(text(), 'No auto-renew option')]")) {
1205 $this->click("xpath=//div[@id='membership_type_form']//table/tbody/tr[6]/td/label[contains(text(), 'Auto-renew Option')]/../../td[2]/label[contains(text(), 'No auto-renew option')]");
1206 }
1207 break;
1208 }
1209
1210 $this->type('member_of_contact', $membershipTitle);
1211 $this->click('member_of_contact');
1212 $this->waitForElementPresent("css=div.ac_results-inner li");
1213 $this->click("css=div.ac_results-inner li");
1214
1215 $this->type('minimum_fee', '100');
1216 $this->select('financial_type_id', "value={$memTypeParams['financial_type']}");
1217
1218 $this->type('duration_interval', $duration_interval);
1219 $this->select('duration_unit', "label={$duration_unit}");
1220
1221 $this->select('period_type', "label={$period_type}");
1222
1223 $this->click('_qf_MembershipType_upload-bottom');
1224 $this->waitForElementPresent('link=Add Membership Type');
1225 $this->assertTrue($this->isTextPresent("The membership type '$title' has been saved."));
1226
1227 return $memTypeParams;
1228 }
1229
1230 function WebtestAddGroup($groupName = NULL, $parentGroupName = NULL) {
1231 $this->openCiviPage('group/add', 'reset=1', '_qf_Edit_upload-bottom');
1232
1233 // fill group name
1234 if (!$groupName) {
1235 $groupName = 'group_' . substr(sha1(rand()), 0, 7);
1236 }
1237 $this->type('title', $groupName);
1238
1239 // fill description
1240 $this->type('description', 'Adding new group.');
1241
1242 // check Access Control
1243 $this->click('group_type[1]');
1244
1245 // check Mailing List
1246 $this->click('group_type[2]');
1247
1248 // select Visibility as Public Pages
1249 $this->select('visibility', 'value=Public Pages');
1250
1251 // select parent group
1252 if ($parentGroupName) {
1253 $this->select('parents', "*$parentGroupName");
1254 }
1255
1256 // Clicking save.
1257 $this->clickLink('_qf_Edit_upload-bottom');
1258
1259 // Is status message correct?
1260 $this->waitForText('crm-notification-container', "$groupName");
1261 return $groupName;
1262 }
1263
1264 function WebtestAddActivity($activityType = "Meeting") {
1265 // Adding Adding contact with randomized first name for test testContactContextActivityAdd
1266 // We're using Quick Add block on the main page for this.
1267 $firstName1 = substr(sha1(rand()), 0, 7);
1268 $this->webtestAddContact($firstName1, "Summerson", $firstName1 . "@summerson.name");
1269 $firstName2 = substr(sha1(rand()), 0, 7);
1270 $this->webtestAddContact($firstName2, "Anderson", $firstName2 . "@anderson.name");
1271
1272 $this->click("css=li#tab_activity a");
1273
1274 // waiting for the activity dropdown to show up
1275 $this->waitForElementPresent("other_activity");
1276
1277 // Select the activity type from the activity dropdown
1278 $this->select("other_activity", "label=Meeting");
1279
1280 $this->waitForElementPresent("_qf_Activity_upload-bottom");
1281
1282 $this->assertTrue($this->isTextPresent("Anderson, " . $firstName2), "Contact not found in line " . __LINE__);
1283
1284 // Typing contact's name into the field (using typeKeys(), not type()!)...
1285 $this->click("css=tr.crm-activity-form-block-assignee_contact_id input#token-input-assignee_contact_id");
1286 $this->type("css=tr.crm-activity-form-block-assignee_contact_id input#token-input-assignee_contact_id", $firstName1);
1287 $this->typeKeys("css=tr.crm-activity-form-block-assignee_contact_id input#token-input-assignee_contact_id", $firstName1);
1288
1289 // ...waiting for drop down with results to show up...
1290 $this->waitForElementPresent("css=div.token-input-dropdown-facebook");
1291 $this->waitForElementPresent("css=li.token-input-input-token-facebook");
1292
1293 //.need to use mouseDown on first result (which is a li element), click does not work
1294 // Note that if you are using firebug this appears at the bottom of the html source, before the closing </body> tag, not where the <li> referred to above is, which is a different <li>.
1295 $this->waitForElementPresent("css=div.token-input-dropdown-facebook li");
1296 $this->mouseDown("css=div.token-input-dropdown-facebook li");
1297
1298 // ...again, waiting for the box with contact name to show up...
1299 $this->waitForElementPresent("css=tr.crm-activity-form-block-assignee_contact_id td ul li span.token-input-delete-token-facebook");
1300
1301 // ...and verifying if the page contains properly formatted display name for chosen contact.
1302 $this->assertTrue($this->isTextPresent("Summerson, " . $firstName1), "Contact not found in line " . __LINE__);
1303
1304 // Putting the contents into subject field - assigning the text to variable, it'll come in handy later
1305 $subject = "This is subject of test activity being added through activity tab of contact summary screen.";
1306 // For simple input fields we can use field id as selector
1307 $this->type("subject", $subject);
1308 $this->type("location", "Some location needs to be put in this field.");
1309
1310 $this->webtestFillDateTime('activity_date_time', '+1 month 11:10PM');
1311
1312 // Setting duration.
1313 $this->type("duration", "30");
1314
1315 // Putting in details.
1316 $this->type("details", "Really brief details information.");
1317
1318 // Making sure that status is set to Scheduled (using value, not label).
1319 $this->select("status_id", "value=1");
1320
1321 // Setting priority.
1322 $this->select("priority_id", "value=1");
1323
1324 // Scheduling follow-up.
1325 $this->click("css=.crm-activity-form-block-schedule_followup div.crm-accordion-header");
1326 $this->select("followup_activity_type_id", "value=1");
1327 $this->webtestFillDateTime('followup_date', '+2 month 11:10PM');
1328 $this->type("followup_activity_subject", "This is subject of schedule follow-up activity");
1329
1330 // Clicking save.
1331 $this->click("_qf_Activity_upload-bottom");
1332 $this->waitForPageToLoad($this->getTimeoutMsec());
1333
1334 // Is status message correct?
1335 $this->assertTrue($this->isTextPresent("Activity '$subject' has been saved."), "Status message didn't show up after saving!");
1336
1337 $this->waitForElementPresent("xpath=//div[@id='Activities']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1338
1339 // click through to the Activity view screen
1340 $this->click("xpath=//div[@id='Activities']//table/tbody/tr[2]/td[8]/span/a[text()='View']");
1341 $this->waitForElementPresent('_qf_Activity_cancel-bottom');
1342
1343 // parse URL to grab the activity id
1344 // pass id back to any other tests that call this class
1345 return $this->urlArg('id');
1346 }
1347
1348 static
1349 function checkDoLocalDBTest() {
1350 if (defined('CIVICRM_WEBTEST_LOCAL_DB') &&
1351 CIVICRM_WEBTEST_LOCAL_DB
1352 ) {
1353 require_once 'tests/phpunit/CiviTest/CiviDBAssert.php';
1354 return TRUE;
1355 }
1356 return FALSE;
1357 }
1358
1359 /**
1360 * Generic function to compare expected values after an api call to retrieved
1361 * DB values.
1362 *
1363 * @daoName string DAO Name of object we're evaluating.
1364 * @id int Id of object
1365 * @match array Associative array of field name => expected value. Empty if asserting
1366 * that a DELETE occurred
1367 * @delete boolean True if we're checking that a DELETE action occurred.
1368 */
1369 function assertDBState($daoName, $id, $match, $delete = FALSE) {
1370 if (!self::checkDoLocalDBTest()) {
1371 return;
1372 }
1373
1374 return CiviDBAssert::assertDBState($this, $daoName, $id, $match, $delete);
1375 }
1376
1377 // Request a record from the DB by seachColumn+searchValue. Success if a record is found.
1378 function assertDBNotNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1379 if (!self::checkDoLocalDBTest()) {
1380 return;
1381 }
1382
1383 return CiviDBAssert::assertDBNotNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1384 }
1385
1386 // Request a record from the DB by seachColumn+searchValue. Success if returnColumn value is NULL.
1387 function assertDBNull($daoName, $searchValue, $returnColumn, $searchColumn, $message) {
1388 if (!self::checkDoLocalDBTest()) {
1389 return;
1390 }
1391
1392 return CiviDBAssert::assertDBNull($this, $daoName, $searchValue, $returnColumn, $searchColumn, $message);
1393 }
1394
1395 // Request a record from the DB by id. Success if row not found.
1396 function assertDBRowNotExist($daoName, $id, $message) {
1397 if (!self::checkDoLocalDBTest()) {
1398 return;
1399 }
1400
1401 return CiviDBAssert::assertDBRowNotExist($this, $daoName, $id, $message);
1402 }
1403
1404 // Compare a single column value in a retrieved DB record to an expected value
1405 function assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1406 $expectedValue, $message
1407 ) {
1408 if (!self::checkDoLocalDBTest()) {
1409 return;
1410 }
1411
1412 return CiviDBAssert::assertDBCompareValue($daoName, $searchValue, $returnColumn, $searchColumn,
1413 $expectedValue, $message
1414 );
1415 }
1416
1417 // Compare all values in a single retrieved DB record to an array of expected values
1418 function assertDBCompareValues($daoName, $searchParams, $expectedValues) {
1419 if (!self::checkDoLocalDBTest()) {
1420 return;
1421 }
1422
1423 return CiviDBAssert::assertDBCompareValues($this, $daoName, $searchParams, $expectedValues);
1424 }
1425
1426 function assertAttributesEquals(&$expectedValues, &$actualValues) {
1427 if (!self::checkDoLocalDBTest()) {
1428 return;
1429 }
1430
1431 return CiviDBAssert::assertAttributesEquals($expectedValues, $actualValues);
1432 }
1433
1434 function assertType($expected, $actual, $message = '') {
1435 return $this->assertInternalType($expected, $actual, $message);
1436 }
1437
1438 /**
1439 * Add new Financial Account
1440 */
1441 function _testAddFinancialAccount($financialAccountTitle,
1442 $financialAccountDescription = FALSE,
1443 $accountingCode = FALSE,
1444 $firstName = FALSE,
1445 $financialAccountType = FALSE,
1446 $taxDeductible = FALSE,
1447 $isActive = FALSE,
1448 $isTax = FALSE,
1449 $taxRate = FALSE,
1450 $isDefault = FALSE
1451 ) {
1452
1453 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1454
1455 $this->click("link=Add Financial Account");
1456 $this->waitForElementPresent('_qf_FinancialAccount_cancel-botttom');
1457
1458 // Financial Account Name
1459 $this->type('name', $financialAccountTitle);
1460
1461 // Financial Description
1462 if ($financialAccountDescription) {
1463 $this->type('description', $financialAccountDescription);
1464 }
1465
1466 //Accounting Code
1467 if ($accountingCode) {
1468 $this->type('accounting_code', $accountingCode);
1469 }
1470
1471 // Autofill Organization
1472 if ($firstName) {
1473 $this->webtestOrganisationAutocomplete($firstName);
1474 }
1475
1476 // Financial Account Type
1477 if ($financialAccountType) {
1478 $this->select('financial_account_type_id', "label={$financialAccountType}");
1479 }
1480
1481 // Is Tax Deductible
1482 if ($taxDeductible) {
1483 $this->check('is_deductible');
1484 }
1485 else {
1486 $this->uncheck('is_deductible');
1487 }
1488 // Is Active
1489 if (!$isActive) {
1490 $this->check('is_active');
1491 }
1492 else {
1493 $this->uncheck('is_active');
1494 }
1495 // Is Tax
1496 if ($isTax) {
1497 $this->check('is_tax');
1498 }
1499 else {
1500 $this->uncheck('is_tax');
1501 }
1502 // Tax Rate
1503 if ($taxRate) {
1504 $this->type('tax_rate', $taxRate);
1505 }
1506
1507 // Set Default
1508 if ($isDefault) {
1509 $this->check('is_default');
1510 }
1511 else {
1512 $this->uncheck('is_default');
1513 }
1514 $this->click('_qf_FinancialAccount_next-botttom');
1515 $this->waitForPageToLoad($this->getTimeoutMsec());
1516 }
1517
1518 /**
1519 * Edit Financial Account
1520 */
1521 function _testEditFinancialAccount($editfinancialAccount,
1522 $financialAccountTitle = FALSE,
1523 $financialAccountDescription = FALSE,
1524 $accountingCode = FALSE,
1525 $firstName = FALSE,
1526 $financialAccountType = FALSE,
1527 $taxDeductible = FALSE,
1528 $isActive = TRUE,
1529 $isTax = FALSE,
1530 $taxRate = FALSE,
1531 $isDefault = FALSE
1532 ) {
1533 if ($firstName) {
1534 $this->openCiviPage("admin/financial/financialAccount", "reset=1");
1535 }
1536
1537 $this->waitForElementPresent("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']");
1538 $this->clickLink("xpath=//table/tbody//tr/td[1][text()='{$editfinancialAccount}']/../td[9]/span/a[text()='Edit']", '_qf_FinancialAccount_cancel-botttom');
1539
1540 // Change Financial Account Name
1541 if ($financialAccountTitle) {
1542 $this->type('name', $financialAccountTitle);
1543 }
1544
1545 // Financial Description
1546 if ($financialAccountDescription) {
1547 $this->type('description', $financialAccountDescription);
1548 }
1549
1550 //Accounting Code
1551 if ($accountingCode) {
1552 $this->type('accounting_code', $accountingCode);
1553 }
1554
1555 // Autofill Edit Organization
1556 if ($firstName) {
1557 $this->webtestOrganisationAutocomplete($firstName);
1558 }
1559
1560 // Financial Account Type
1561 if ($financialAccountType) {
1562 $this->select('financial_account_type_id', "label={$financialAccountType}");
1563 }
1564
1565 // Is Tax Deductible
1566 if ($taxDeductible) {
1567 $this->check('is_deductible');
1568 }
1569 else {
1570 $this->uncheck('is_deductible');
1571 }
1572
1573 // Is Tax
1574 if ($isTax) {
1575 $this->check('is_tax');
1576 }
1577 else {
1578 $this->uncheck('is_tax');
1579 }
1580
1581 // Tax Rate
1582 if ($taxRate) {
1583 $this->type('tax_rate', $taxRate);
1584 }
1585
1586 // Set Default
1587 if ($isDefault) {
1588 $this->check('is_default');
1589 }
1590 else {
1591 $this->uncheck('is_default');
1592 }
1593
1594 // Is Active
1595 if ($isActive) {
1596 $this->check('is_active');
1597 }
1598 else {
1599 $this->uncheck('is_active');
1600 }
1601 $this->click('_qf_FinancialAccount_next-botttom');
1602 $this->waitForPageToLoad($this->getTimeoutMsec());
1603 }
1604
1605 /**
1606 * Delete Financial Account
1607 */
1608 function _testDeleteFinancialAccount($financialAccountTitle) {
1609 $this->click("xpath=//table/tbody//tr/td[1][text()='{$financialAccountTitle}']/../td[9]/span/a[text()='Delete']");
1610 $this->waitForElementPresent('_qf_FinancialAccount_next-botttom');
1611 $this->click('_qf_FinancialAccount_next-botttom');
1612 $this->waitForElementPresent('link=Add Financial Account');
1613 $this->assertTrue($this->isTextPresent("Selected Financial Account has been deleted."));
1614 }
1615
1616 /**
1617 * Verify data after ADD and EDIT
1618 */
1619 function _assertFinancialAccount($verifyData) {
1620 foreach ($verifyData as $key => $expectedValue) {
1621 $actualValue = $this->getValue($key);
1622 if ($key == 'parent_financial_account') {
1623 $this->assertTrue((bool) preg_match("/^{$expectedValue}/", $actualValue));
1624 }
1625 else {
1626 $this->assertEquals($expectedValue, $actualValue);
1627 }
1628 }
1629 }
1630
1631 function _assertSelectVerify($verifySelectFieldData) {
1632 foreach ($verifySelectFieldData as $key => $expectedvalue) {
1633 $actualvalue = $this->getSelectedLabel($key);
1634 $this->assertEquals($expectedvalue, $actualvalue);
1635 }
1636 }
1637
1638 function addeditFinancialType($financialType, $option = 'new') {
1639 $this->openCiviPage("admin/financial/financialType", "reset=1");
1640
1641 if ($option == 'Delete') {
1642 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]");
1643 $this->waitForElementPresent("css=span.btn-slide-active");
1644 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[name]']/../td[7]/span[2]/ul/li[2]/a");
1645 $this->waitForElementPresent("_qf_FinancialType_next");
1646 $this->click("_qf_FinancialType_next");
1647 $this->waitForPageToLoad($this->getTimeoutMsec());
1648 $this->assertTrue($this->isTextPresent('Selected financial type has been deleted.'), 'Missing text: ' . 'Selected financial type has been deleted.');
1649 return;
1650 }
1651 if ($option == 'new') {
1652 $this->click("link=Add Financial Type");
1653 }
1654 else {
1655 $this->click("xpath=id('ltype')/div/table/tbody/tr/td[1][text()='$financialType[oldname]']/../td[7]/span/a[text()='Edit']");
1656 }
1657 $this->waitForPageToLoad($this->getTimeoutMsec());
1658 $this->type('name', $financialType['name']);
1659 if ($option == 'new') {
1660 $this->type('description', $financialType['name'] . ' description');
1661 }
1662
1663 if ($financialType['is_reserved']) {
1664 $this->check('is_reserved');
1665 }
1666 else {
1667 $this->uncheck('is_reserved');
1668 }
1669
1670 if ($financialType['is_deductible']) {
1671 $this->check('is_deductible');
1672 }
1673 else {
1674 $this->uncheck('is_deductible');
1675 }
1676
1677 $this->click('_qf_FinancialType_next');
1678 $this->waitForPageToLoad($this->getTimeoutMsec());
1679 if ($option == 'new') {
1680 $text = "Your Financial '{$financialType['name']}' Type has been created, along with a corresponding income account '{$financialType['name']}'. That income account, along with standard financial accounts 'Accounts Receivable', 'Banking Fees' and 'Premiums' have been linked to the financial type. You may edit or replace those relationships here.";
1681 }
1682 else {
1683 $text = "The financial type '{$financialType['name']}' has been saved.";
1684 }
1685 $this->assertTrue($this->isTextPresent($text), 'Missing text: ' . $text);
1686 }
1687
1688 /**
1689 * Give the specified permissions
1690 * Note: this function logs in as 'admin' (logging out if necessary)
1691 */
1692 function changePermissions($permission) {
1693 $this->webtestLogin('admin');
1694 $this->open("{$this->sboxPath}admin/people/permissions");
1695 $this->waitForElementPresent('edit-submit');
1696 foreach ((array) $permission as $perm) {
1697 $this->check($perm);
1698 }
1699 $this->click('edit-submit');
1700 $this->waitForPageToLoad($this->getTimeoutMsec());
1701 $this->assertTrue($this->isTextPresent('The changes have been saved.'));
1702 }
1703
1704 function addProfile($profileTitle, $profileFields) {
1705 $this->openCiviPage('admin/uf/group', "reset=1");
1706
1707 $this->click('link=Add Profile');
1708
1709 // Add membership custom data field to profile
1710 $this->waitForElementPresent('_qf_Group_cancel-bottom');
1711 $this->type('title', $profileTitle);
1712 $this->click('_qf_Group_next-bottom');
1713
1714 $this->waitForElementPresent('_qf_Field_cancel-bottom');
1715 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile '{$profileTitle}' has been added. You can add fields to this profile now."));
1716
1717 foreach ($profileFields as $field) {
1718 $this->waitForElementPresent('field_name_0');
1719 // $this->waitForPageToLoad($this->getTimeoutMsec());
1720 $this->click("id=field_name_0");
1721 $this->select("id=field_name_0", "label=" . $field['type']);
1722 $this->waitForElementPresent('field_name_1');
1723 $this->click("id=field_name_1");
1724 $this->select("id=field_name_1", "label=" . $field['name']);
1725 $this->waitForElementPresent('label');
1726 $this->type("id=label", $field['label']);
1727 $this->click("id=_qf_Field_next_new-top");
1728 $this->waitForPageToLoad($this->getTimeoutMsec());
1729 //$this->assertTrue($this->isTextPresent("Your CiviCRM Profile Field '" . $field['name'] . "' has been saved to '" . $profileTitle . "'. You can add another profile field."));
1730 }
1731 }
1732
1733 function addPremium($name, $sku, $amount, $price, $cost, $financialType) {
1734 $this->waitForElementPresent("_qf_ManagePremiums_upload-bottom");
1735 $this->type("name", $name);
1736 $this->type("sku", $sku);
1737 $this->click("CIVICRM_QFID_noImage_16");
1738 $this->type("min_contribution", $amount);
1739 $this->type("price", $price);
1740 $this->type("cost", $cost);
1741 if ($financialType) {
1742 $this->select("financial_type_id", "label={$financialType}");
1743 }
1744 $this->click("_qf_ManagePremiums_upload-bottom");
1745 $this->waitForPageToLoad($this->getTimeoutMsec());
1746 }
1747
1748 function addPaymentInstrument($label, $financialAccount) {
1749 $this->openCiviPage('admin/options/payment_instrument', 'group=payment_instrument&action=add&reset=1', "_qf_Options_next-bottom");
1750 $this->type("label", $label);
1751 $this->select("financial_account_id", "value=$financialAccount");
1752 $this->click("_qf_Options_next-bottom");
1753 $this->waitForPageToLoad($this->getTimeoutMsec());
1754 }
1755
1756 /**
1757 * Ensure we have a default mailbox set up for CiviMail
1758 */
1759 function setupDefaultMailbox() {
1760 $this->openCiviPage('admin/mailSettings', 'action=update&id=1&reset=1');
1761 // Check if it hasn't already been set up
1762 if (!$this->getSelectedValue('protocol')) {
1763 $this->type('name', 'Test Domain');
1764 $this->select('protocol', "IMAP");
1765 $this->type('server', 'localhost');
1766 $this->type('domain', 'example.com');
1767 $this->click('_qf_MailSettings_next-top');
1768 $this->waitForPageToLoad($this->getTimeoutMsec());
1769 }
1770 }
1771
1772 /**
1773 * Determine the default time-out in milliseconds.
1774 *
1775 * @return string, timeout expressed in milliseconds
1776 */
1777 function getTimeoutMsec() {
1778 // note: existing local versions of CiviSeleniumSettings may not declare $timeout, so use @
1779 $timeout = ($this->settings && @$this->settings->timeout) ? ($this->settings->timeout * 1000) : 30000;
1780 return (string) $timeout; // don't know why, but all our old code used a string
1781 }
1782
1783 /**
1784 * CRM-12378
1785 * checks custom fields rendering / loading properly on the fly WRT entity passed as parameter
1786 *
1787 *
1788 * @param array $customSets custom sets i.e entity wise sets want to be created and checked
1789 e.g $customSets = array(array('entity' => 'Contribution', 'subEntity' => 'Donation',
1790 'triggerElement' => $triggerElement))
1791 array $triggerElement: the element which is responsible for custom group to load
1792
1793 which uses the entity info as its selection value
1794 * @param array $pageUrl the url which on which the ajax custom group load takes place
1795 * @param $beforeTriggering code to execute before actual element triggering
1796 * @return void
1797 */
1798 function customFieldSetLoadOnTheFlyCheck($customSets, $pageUrl, $beforeTriggering = NULL) {
1799 //add the custom set
1800 $return = $this->addCustomGroupField($customSets);
1801
1802 $this->openCiviPage($pageUrl['url'], $pageUrl['args']);
1803
1804 foreach($return as $values) {
1805 foreach ($values as $entityType => $customData) {
1806 //initiate necessary variables
1807 list($entity, $entityData) = explode('_', $entityType);
1808 $elementType = CRM_Utils_Array::value('type', $customData['triggerElement'], 'select');
1809 $elementName = CRM_Utils_Array::value('name', $customData['triggerElement']);
1810 if ($beforeTriggering) {
1811 call_user_func($beforeTriggering);
1812 }
1813 if ($elementType == 'select') {
1814 //reset the select box, so triggering of ajax only happens
1815 //WRT input of value in this function
1816 $this->select($elementName, "index=0");
1817 }
1818 if (!empty($entityData)) {
1819 if ($elementType == 'select') {
1820 $this->select($elementName, "label=regexp:{$entityData}");
1821 }
1822 elseif ($elementType == 'checkbox') {
1823 $val = explode(',', $entityData);
1824 foreach($val as $v) {
1825 $checkId = $this->getAttribute("xpath=//label[text()='{$v}']/@for");
1826 $this->check($checkId);
1827 }
1828 }
1829 }
1830
1831 //sleep method is used as to wait for custom field div to load -
1832 //we cant use wait for the div element as we are asserting for the same,
1833 //so wait for some time till the div loads
1834 sleep(1);
1835
1836 //checking for proper custom data which is loading through ajax
1837 $this->assertElementPresent("xpath=//div[@id='{$customData['cgtitle']}'][@class='crm-accordion-body']",
1838 "The on the fly custom group has not been rendered for entity : {$entity} => {$entityData}");
1839 $this->assertElementPresent("xpath=//div[@id='{$customData['cgtitle']}'][@class='crm-accordion-body']/table/tbody/tr/td[2]/input",
1840 "The on the fly custom group field is not present for entity : {$entity} => {$entityData}");
1841 }
1842 }
1843 }
1844
1845 function addCustomGroupField($customSets) {
1846 foreach ($customSets as $customSet) {
1847 $this->openCiviPage("admin/custom/group", "action=add&reset=1");
1848
1849 //fill custom group title
1850 $customGroupTitle = "webtest_for_ajax_cd" . substr(sha1(rand()), 0, 4);
1851 $this->click("title");
1852 $this->type("title", $customGroupTitle);
1853
1854 //custom group extends
1855 $this->click("extends_0");
1856 $this->select("extends_0", "value={$customSet['entity']}");
1857 if (!empty($customSet['subEntity'])) {
1858 $this->addSelection("extends_1", "label={$customSet['subEntity']}");
1859 }
1860
1861 // Don't collapse
1862 $this->uncheck('collapse_display');
1863
1864 // Save
1865 $this->click('_qf_Group_next-bottom');
1866 $this->waitForElementPresent('_qf_Field_cancel-bottom');
1867
1868 //Is custom group created?
1869 $this->waitForText('crm-notification-container', "Your custom field set '{$customGroupTitle}' has been added.");
1870 $gid = $this->urlArg('gid');
1871
1872 $fieldLabel = "custom_field_for_{$customSet['entity']}_{$customSet['subEntity']}" . substr(sha1(rand()), 0, 4);
1873 $this->type('label', $fieldLabel);
1874 $this->click('_qf_Field_next-bottom');
1875 $this->waitForPageToLoad($this->getTimeoutMsec());
1876 $customGroupTitle = preg_replace('/\s/', '_', trim($customGroupTitle));
1877
1878 $return[] = array(
1879 "{$customSet['entity']}_{$customSet['subEntity']}" => array('cgtitle' => $customGroupTitle, 'gid' => $gid, 'triggerElement' => $customSet['triggerElement']));
1880 }
1881 return $return;
1882 }
1883 }